diff --git a/.editorconfig b/.editorconfig index 7c166ac2..d57b44be 100644 --- a/.editorconfig +++ b/.editorconfig @@ -27,7 +27,7 @@ trim_trailing_whitespace = true # Set file behavior to: # 2 space indentation ############################################################################### -[*.{cmd,config,csproj,json,props,ps1,resx,sh,targets}] +[*.{cmd,config,csproj,json,props,ps1,resx,sh,targets,yml}] indent_size = 2 ############################################################################### @@ -39,58 +39,67 @@ indent_size = 2 end_of_line = crlf indent_style = tab +############################################################################### +# Set file header template to the specified text +############################################################################### +[*.cs] +file_header_template = Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + ############################################################################### # Set dotnet naming rules to: -# suggest async members be pascal case suffixed with Async -# suggest const declarations be pascal case -# suggest interfaces be pascal case prefixed with I -# suggest parameters be camel case -# suggest private and internal static fields be camel case -# suggest private and internal fields be camel case -# suggest public and protected declarations be pascal case -# suggest static readonly declarations be pascal case -# suggest type parameters be prefixed with T +# require async methods be pascal case suffixed with Async +# require const fields and locals be pascal case +# require interfaces be pascal case prefixed with I +# require locals be camel case +# require parameters be camel case +# require private and internal static fields be camel case and prefixed with s and underscore +# require private and internal fields be camel case and prefixed with underscore +# require public and protected declarations be pascal case +# require static readonly declarations be pascal case +# require type parameters be prefixed with T ############################################################################### [*.cs] -dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.severity = suggestion -dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.style = pascal_case_suffixed_with_async -dotnet_naming_rule.async_members_should_be_pascal_case_suffixed_with_async.symbols = async_members +dotnet_naming_rule.async_methods_should_be_pascal_case_suffixed_with_async.severity = error +dotnet_naming_rule.async_methods_should_be_pascal_case_suffixed_with_async.style = pascal_case_suffixed_with_async +dotnet_naming_rule.async_methods_should_be_pascal_case_suffixed_with_async.symbols = async_methods -dotnet_naming_rule.const_declarations_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.const_declarations_should_be_pascal_case.style = pascal_case -dotnet_naming_rule.const_declarations_should_be_pascal_case.symbols = const_declarations +dotnet_naming_rule.const_fields_and_locals_should_be_pascal_case.severity = error +dotnet_naming_rule.const_fields_and_locals_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.const_fields_and_locals_should_be_pascal_case.symbols = const_fields_and_locals -dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.severity = suggestion +dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.severity = error dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.style = pascal_case_prefixed_with_i dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.symbols = interfaces -dotnet_naming_rule.parameters_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.severity = error +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals + +dotnet_naming_rule.parameters_should_be_camel_case.severity = error dotnet_naming_rule.parameters_should_be_camel_case.style = camel_case dotnet_naming_rule.parameters_should_be_camel_case.symbols = parameters -dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case.severity = suggestion -dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case.style = camel_case -dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case.symbols = private_and_internal_static_fields +dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case_prefixed_with_s_and_underscore.severity = error +dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case_prefixed_with_s_and_underscore.style = camel_case_prefixed_with_s_and_underscore +dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case_prefixed_with_s_and_underscore.symbols = private_and_internal_static_fields -dotnet_naming_rule.private_and_internal_fields_should_be_camel_case.severity = suggestion -dotnet_naming_rule.private_and_internal_fields_should_be_camel_case.style = camel_case -dotnet_naming_rule.private_and_internal_fields_should_be_camel_case.symbols = private_and_internal_fields +dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.severity = error +dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.style = camel_case_prefixed_with_underscore +dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.symbols = private_and_internal_fields -dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.severity = error dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.style = pascal_case dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.symbols = public_and_protected_declarations -dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.style = pascal_case -dotnet_naming_rule.static_readonly_declarations_should_be_pascal_case.symbols = static_readonly_declarations - -dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.severity = suggestion +dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.severity = error dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.style = pascal_case_prefixed_with_t dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.symbols = type_parameters ############################################################################### # Set dotnet naming styles to define: # camel case +# camel case prefixed with _ +# camel case prefixed with s_ # pascal case # pascal case suffixed with Async # pascal case prefixed with I @@ -99,6 +108,12 @@ dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.symbols [*.cs] dotnet_naming_style.camel_case.capitalization = camel_case +dotnet_naming_style.camel_case_prefixed_with_s_and_underscore.capitalization = camel_case +dotnet_naming_style.camel_case_prefixed_with_s_and_underscore.required_prefix = s_ + +dotnet_naming_style.camel_case_prefixed_with_underscore.capitalization = camel_case +dotnet_naming_style.camel_case_prefixed_with_underscore.required_prefix = _ + dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_naming_style.pascal_case_suffixed_with_async.capitalization = pascal_case @@ -112,9 +127,10 @@ dotnet_naming_style.pascal_case_prefixed_with_t.required_prefix = T ############################################################################### # Set dotnet naming symbols to: -# async members -# const declarations +# async methods +# const fields and locals # interfaces +# locals # private and internal fields # private and internal static fields # public and protected declarations @@ -122,12 +138,16 @@ dotnet_naming_style.pascal_case_prefixed_with_t.required_prefix = T # type parameters ############################################################################### [*.cs] -dotnet_naming_symbols.async_members.required_modifiers = async +dotnet_naming_symbols.async_methods.applicable_kinds = method +dotnet_naming_symbols.async_methods.required_modifiers = async -dotnet_naming_symbols.const_declarations.required_modifiers = const +dotnet_naming_symbols.const_fields_and_locals.applicable_kinds = field, local +dotnet_naming_symbols.const_fields_and_locals.required_modifiers = const dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.locals.applicable_kinds = local + dotnet_naming_symbols.parameters.applicable_kinds = parameter dotnet_naming_symbols.private_and_internal_fields.applicable_accessibilities = private, internal @@ -138,8 +158,7 @@ dotnet_naming_symbols.private_and_internal_static_fields.applicable_kinds = fiel dotnet_naming_symbols.private_and_internal_static_fields.required_modifiers = static dotnet_naming_symbols.public_and_protected_declarations.applicable_accessibilities = public, protected - -dotnet_naming_symbols.static_readonly_declarations.required_modifiers = static, readonly +dotnet_naming_symbols.public_and_protected_declarations.applicable_kinds = namespace, class, struct, enum, property, method, field, event, delegate, local_function dotnet_naming_symbols.type_parameters.applicable_kinds = type_parameter @@ -154,68 +173,81 @@ dotnet_sort_system_directives_first = true ############################################################################### # Set dotnet style options to: -# suggest null-coalescing expressions, -# suggest collection-initializers, -# suggest explicit tuple names, -# suggest null-propogation -# suggest object-initializers, -# generate parentheses in arithmetic binary operators for clarity, -# generate parentheses in other binary operators for clarity, -# don't generate parentheses in other operators if unnecessary, -# generate parentheses in relational binary operators for clarity, -# warn when not using predefined-types for locals, parameters, and members, -# generate predefined-types of type names for member access, -# generate auto properties, -# suggest compound assignment, -# generate conditional expression over assignment, -# generate conditional expression over return, -# suggest inferred anonymous types, -# suggest inferred tuple names, -# suggest 'is null' checks over '== null', -# don't generate 'this.' and 'Me.' for events, -# warn when not using 'this.' and 'Me.' for fields, -# warn when not using 'this.' and 'Me.' for methods, -# warn when not using 'this.' and 'Me.' for properties, -# suggest readonly fields, and -# generate accessibility modifiers for non interface members +# require null-coalescing expressions, +# require collection-initializers, +# require explicit tuple names, +# require null-propogation +# require object-initializers, +# +# require parentheses in arithmetic binary operators for clarity, +# require parentheses in other binary operators for clarity, +# error on parentheses in other operators if unnecessary, +# require parentheses in relational binary operators for clarity, +# +# require predefined-types for locals, parameters, and members, +# require predefined-types of type names for member access, +# +# place operators at the beginning of the line when wrapping, +# error on suggest auto properties, +# require compound assignment, +# suggest conditional expression over assignment, +# suggest conditional expression over return, +# require inferred anonymous types, +# require inferred tuple names, +# require 'is null' checks over '== null', +# require simplified boolean expressions, +# require simplified interpolation, +# +# error on 'this.' and 'Me.' for events, +# error on 'this.' and 'Me.' for fields, +# error on 'this.' and 'Me.' for methods, +# error on 'this.' and 'Me.' for properties, +# +# require readonly fields, and +# require specifying accessibility modifiers ############################################################################### [*.cs] -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_object_initializer = true:suggestion - -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent - -dotnet_style_predefined_type_for_locals_parameters_members = true:silent -dotnet_style_predefined_type_for_member_access = true:silent - -dotnet_style_prefer_auto_properties = true:silent -dotnet_style_prefer_compound_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_assignment = true:silent -dotnet_style_prefer_conditional_expression_over_return = true:silent -dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion -dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion - -dotnet_style_qualification_for_event = false:silent -dotnet_style_qualification_for_field = false:silent -dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_property = false:silent - -dotnet_style_readonly_field = true:suggestion -dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_coalesce_expression = true:error +dotnet_style_collection_initializer = true:error +dotnet_style_explicit_tuple_names = true:error +dotnet_style_null_propagation = true:error +dotnet_style_object_initializer = true:error + +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:error +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:error +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:error +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:error + +dotnet_style_predefined_type_for_locals_parameters_members = true:error +dotnet_style_predefined_type_for_member_access = true:error + +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = false:error +dotnet_style_prefer_compound_assignment = true:error +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:error +dotnet_style_prefer_inferred_tuple_names = true:error +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error +dotnet_style_prefer_simplified_boolean_expressions = true:error +dotnet_style_prefer_simplified_interpolation = true:error + +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = false:error +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error + +dotnet_style_readonly_field = true:error +dotnet_style_require_accessibility_modifiers = always:error ############################################################################### # Set dotnet style options to: -# suggest removing all unused parameters +# suggest removing all unused parameters, and +# remove unnecessary supression exclusions ############################################################################### [*.cs] dotnet_code_quality_unused_parameters = all:suggestion +dotnet_remove_unnecessary_suppression_exclusions = none ############################################################################### # Set csharp indent options to: @@ -240,27 +272,42 @@ csharp_indent_switch_labels = true # insert a new-line before "else", # insert a new-line before "finally", # insert a new-line before members in anonymous-types, -# insert a new-line before members in object-initializers, and -# insert a new-line before all open braces +# insert a new-line before members in object-initializers, +# insert a new-line before all open braces except anonymous methods, anonymous types, lambdas, and object collections and +# insert a new-line within query expression clauses ############################################################################### [*.cs] csharp_new_line_before_catch = true csharp_new_line_before_else = true csharp_new_line_before_finally = true - csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = accessors, control_blocks, events, indexers, local_functions, methods, properties, types +csharp_new_line_within_query_expression_clauses = true -csharp_new_line_before_open_brace = all +############################################################################### +# Set csharp preferences to: +# require braces, +# require simple default expressions, +# require simple using statements, +# require static local functions, +# require a preferred modifier order, +############################################################################### +[*.cs] +csharp_prefer_braces = true:error +csharp_prefer_simple_default_expression = true:error +csharp_prefer_simple_using_statement = true:error +csharp_prefer_static_local_function = true:error +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:error ############################################################################### # Set csharp preserve options to: # preserve single-line blocks, and -# preserve single-line statements +# not preserve single-line statements ############################################################################### [*.cs] csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true +csharp_preserve_single_line_statements = false ############################################################################### # Set csharp space options to: @@ -294,16 +341,13 @@ csharp_space_after_comma = true csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true - csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = do_not_ignore - +csharp_space_around_declaration_statements = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false csharp_space_before_open_square_brackets = false csharp_space_before_semicolon_in_for_statement = false - csharp_space_between_empty_square_brackets = false csharp_space_between_method_call_empty_parameter_list_parentheses = false csharp_space_between_method_call_name_and_opening_parenthesis = false @@ -316,56 +360,87 @@ csharp_space_between_square_brackets = false ############################################################################### # Set csharp style options to: -# generate braces, -# suggest simple default expressions, -# generate a preferred modifier order, -# suggest conditional delegate calls, -# suggest deconstructed variable declarations, -# generate expression-bodied accessors, -# don't generate expression-bodied constructors, -# generate expression-bodied indexers, -# generate expression-bodied lambdas, -# don't generate expression-bodied methods, -# don't generate expression-bodied operators, -# generate expression-bodied properties, -# suggest inlined variable declarations, -# suggest local over anonymous functions, -# suggest pattern-matching over "as" with "null" check, -# suggest pattern-matching over "is" with "cast" check, -# suggest throw expressions, -# generate a discard variable for unused value expression statements, -# suggest a discard variable for unused assignments, -# warn when using var for built-in types, -# warn when using var when the type is not apparent, and -# warn when not using var when the type is apparent +# require conditional delegate calls, +# require deconstructed variable declarations, +# +# error on expression-bodied accessors, +# error on expression-bodied constructors, +# require expression-bodied indexers when on a single line, +# require expression-bodied lambdas, +# error on expression-bodied local functions, +# suggest expression-bodied methods when on a single line, +# require expression-bodied operators when on a single line, +# require expression-bodied properties when on a single line, +# +# error on simplified new expression, +# +# require inlined variable declarations, +# +# require local over anonymous functions, +# require pattern-matching over "as" with "null" check, +# require pattern-matching over "is" with "cast" check, +# +# require index operators where possible, +# require range operators where possible, +# require the "not" pattern where possible, +# require pattern-matching where possible, +# require switch expressions where possible, +# +# require throw expressions, +# +# require a discard variable for unused assignments, +# require a discard variable for unused value expression statements, +# +# require var when the type is not apparent, +# require var for built-in types, and +# require var when the type is apparent ############################################################################### [*.cs] -csharp_prefer_braces = true:silent -csharp_prefer_simple_default_expression = true:suggestion -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent +csharp_style_conditional_delegate_call = true:error +csharp_style_deconstructed_variable_declaration = true:error + +csharp_style_expression_bodied_accessors = false:error +csharp_style_expression_bodied_constructors = false:error +csharp_style_expression_bodied_indexers = when_on_single_line:error +csharp_style_expression_bodied_lambdas = true:error +csharp_style_expression_bodied_local_functions = false:error +csharp_style_expression_bodied_methods = when_on_single_line:suggestion +csharp_style_expression_bodied_operators = when_on_single_line:error +csharp_style_expression_bodied_properties = when_on_single_line:error -csharp_style_conditional_delegate_call = true:suggestion -csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = false:error -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_lambdas = true:silent -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent +csharp_style_inlined_variable_declaration = true:error -csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:error +csharp_style_pattern_matching_over_as_with_null_check = true:error +csharp_style_pattern_matching_over_is_with_cast_check = true:error -csharp_style_pattern_local_over_anonymous_function = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_index_operator = true:error +csharp_style_prefer_range_operator = true:error +csharp_style_prefer_not_pattern = true:error +csharp_style_prefer_pattern_matching = true:error +csharp_style_prefer_switch_expression = true:error -csharp_style_throw_expression = true:suggestion +csharp_style_throw_expression = true:error -csharp_style_unused_value_expression_statement_preference = discard_variable:silent -csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:error +csharp_style_unused_value_expression_statement_preference = discard_variable:error -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_elsewhere = false:silent -csharp_style_var_when_type_is_apparent = false:silent +csharp_style_var_elsewhere = true:error +csharp_style_var_for_built_in_types = true:error +csharp_style_var_when_type_is_apparent = true:error + +############################################################################### +# Set csharp using options to: +# require using directives outside the namespace +############################################################################### +[*.cs] +csharp_using_directive_placement = outside_namespace:error + +############################################################################### +# Supress diagnostics that don't apply to ClangSharp +############################################################################### +dotnet_diagnostic.CA1069.severity = none +dotnet_diagnostic.CA1826.severity = none +dotnet_diagnostic.IDE0060.severity = none diff --git a/README.md b/README.md index f8af2d6b..72e161d1 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,8 @@ Options: attributes. generate-macro-bindings Bindings for macro-definitions should be generated. This currently only works with value like macros and not function-like ones. + generate-template-bindings Bindings for template-definitions should be generated. This is currently + experimental. generate-native-inheritance-attribute [NativeInheritance("")] attribute should be generated to document the encountered C++ base type. generate-vtbl-index-attribute [VtblIndex(#)] attribute should be generated to document the underlying diff --git a/scripts/azure-windows.yml b/scripts/azure-windows.yml index 44f50313..c1d7269f 100644 --- a/scripts/azure-windows.yml +++ b/scripts/azure-windows.yml @@ -31,6 +31,27 @@ jobs: PathtoPublish: artifacts/pkg/${{parameters.configuration}} ArtifactName: packages publishLocation: Container + - task: CopyFiles@2 + displayName: 'Stage win32metadata bin artifacts' + condition: eq(${{parameters.testwin32metadata}}, true) + inputs: + sourceFolder: artifacts/win32metadata + contents: '**/bin/**' + targetFolder: $(Build.ArtifactStagingDirectory) + - task: CopyFiles@2 + displayName: 'Stage win32metadata obj artifacts' + condition: eq(${{parameters.testwin32metadata}}, true) + inputs: + sourceFolder: artifacts/win32metadata + contents: '**/obj/**' + targetFolder: $(Build.ArtifactStagingDirectory) + - task: PublishBuildArtifacts@1 + displayName: 'Publish win32metadata Artifacts' + condition: eq(${{parameters.testwin32metadata}}, true) + inputs: + PathtoPublish: $(Build.ArtifactStagingDirectory) + ArtifactName: win32metadata + publishLocation: Container variables: EXCLUDE_BUILDNUMBER_FROM_PACKAGE: ${{parameters.EXCLUDE_BUILDNUMBER_FROM_PACKAGE}} OVERRIDE_RUNTIME_IDENTIFIER: ${{parameters.OVERRIDE_RUNTIME_IDENTIFIER}} diff --git a/sources/ClangSharp.PInvokeGenerator/Abstractions/FunctionOrDelegateDesc.cs b/sources/ClangSharp.PInvokeGenerator/Abstractions/FunctionOrDelegateDesc.cs index 8739a3dc..3ae37654 100644 --- a/sources/ClangSharp.PInvokeGenerator/Abstractions/FunctionOrDelegateDesc.cs +++ b/sources/ClangSharp.PInvokeGenerator/Abstractions/FunctionOrDelegateDesc.cs @@ -18,98 +18,181 @@ internal struct FunctionOrDelegateDesc public bool IsVirtual { - get => (Flags & FunctionOrDelegateFlags.IsVirtual) != 0; - set => Flags = - value ? Flags | FunctionOrDelegateFlags.IsVirtual : Flags & ~FunctionOrDelegateFlags.IsVirtual; + get + { + return (Flags & FunctionOrDelegateFlags.IsVirtual) != 0; + } + + set + { + Flags = value ? Flags | FunctionOrDelegateFlags.IsVirtual : Flags & ~FunctionOrDelegateFlags.IsVirtual; + } } public bool IsDllImport { - get => (Flags & FunctionOrDelegateFlags.IsDllImport) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.IsDllImport - : Flags & ~FunctionOrDelegateFlags.IsDllImport; + get + { + return (Flags & FunctionOrDelegateFlags.IsDllImport) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.IsDllImport + : Flags & ~FunctionOrDelegateFlags.IsDllImport; + } } public bool HasFnPtrCodeGen { - get => (Flags & FunctionOrDelegateFlags.HasFnPtrCodeGen) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.HasFnPtrCodeGen - : Flags & ~FunctionOrDelegateFlags.HasFnPtrCodeGen; + get + { + return (Flags & FunctionOrDelegateFlags.HasFnPtrCodeGen) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.HasFnPtrCodeGen + : Flags & ~FunctionOrDelegateFlags.HasFnPtrCodeGen; + } } public bool IsAggressivelyInlined { - get => (Flags & FunctionOrDelegateFlags.IsAggressivelyInlined) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.IsAggressivelyInlined - : Flags & ~FunctionOrDelegateFlags.IsAggressivelyInlined; + get + { + return (Flags & FunctionOrDelegateFlags.IsAggressivelyInlined) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.IsAggressivelyInlined + : Flags & ~FunctionOrDelegateFlags.IsAggressivelyInlined; + } } public bool SetLastError { - get => (Flags & FunctionOrDelegateFlags.SetLastError) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.SetLastError - : Flags & ~FunctionOrDelegateFlags.SetLastError; + get + { + return (Flags & FunctionOrDelegateFlags.SetLastError) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.SetLastError + : Flags & ~FunctionOrDelegateFlags.SetLastError; + } } public bool IsCxx { - get => (Flags & FunctionOrDelegateFlags.IsCxx) != 0; - set => Flags = value ? Flags | FunctionOrDelegateFlags.IsCxx : Flags & ~FunctionOrDelegateFlags.IsCxx; + get + { + return (Flags & FunctionOrDelegateFlags.IsCxx) != 0; + } + + set + { + Flags = value ? Flags | FunctionOrDelegateFlags.IsCxx : Flags & ~FunctionOrDelegateFlags.IsCxx; + } } public bool NeedsNewKeyword { - get => (Flags & FunctionOrDelegateFlags.NeedsNewKeyword) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.NeedsNewKeyword - : Flags & ~FunctionOrDelegateFlags.NeedsNewKeyword; + get + { + return (Flags & FunctionOrDelegateFlags.NeedsNewKeyword) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.NeedsNewKeyword + : Flags & ~FunctionOrDelegateFlags.NeedsNewKeyword; + } } public bool IsUnsafe { - get => (Flags & FunctionOrDelegateFlags.IsUnsafe) != 0; - set => Flags = value ? Flags | FunctionOrDelegateFlags.IsUnsafe : Flags & ~FunctionOrDelegateFlags.IsUnsafe; + get + { + return (Flags & FunctionOrDelegateFlags.IsUnsafe) != 0; + } + + set + { + Flags = value ? Flags | FunctionOrDelegateFlags.IsUnsafe : Flags & ~FunctionOrDelegateFlags.IsUnsafe; + } } public bool IsCtxCxxRecord { - get => (Flags & FunctionOrDelegateFlags.IsCtxCxxRecord) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.IsCtxCxxRecord - : Flags & ~FunctionOrDelegateFlags.IsCtxCxxRecord; + get + { + return (Flags & FunctionOrDelegateFlags.IsCtxCxxRecord) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.IsCtxCxxRecord + : Flags & ~FunctionOrDelegateFlags.IsCtxCxxRecord; + } } public bool IsCxxRecordCtxUnsafe { - get => (Flags & FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe - : Flags & ~FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe; + get + { + return (Flags & FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe + : Flags & ~FunctionOrDelegateFlags.IsCxxRecordCtxUnsafe; + } } public bool IsMemberFunction { - get => (Flags & FunctionOrDelegateFlags.IsMemberFunction) != 0; - set => Flags = value - ? Flags | FunctionOrDelegateFlags.IsMemberFunction - : Flags & ~FunctionOrDelegateFlags.IsMemberFunction; + get + { + return (Flags & FunctionOrDelegateFlags.IsMemberFunction) != 0; + } + + set + { + Flags = value + ? Flags | FunctionOrDelegateFlags.IsMemberFunction + : Flags & ~FunctionOrDelegateFlags.IsMemberFunction; + } } public bool? IsStatic { - get => (Flags & FunctionOrDelegateFlags.IsStatic) != 0 ? true : - (Flags & FunctionOrDelegateFlags.IsNotStatic) != 0 ? false : null; - set => Flags = value switch - { - // true - static, false - not static, null - infer - true => Flags | FunctionOrDelegateFlags.IsStatic & ~FunctionOrDelegateFlags.IsNotStatic, - false => Flags & ~FunctionOrDelegateFlags.IsStatic | FunctionOrDelegateFlags.IsNotStatic, - null => Flags & ~FunctionOrDelegateFlags.IsStatic & ~FunctionOrDelegateFlags.IsNotStatic - }; + get + { + return (Flags & FunctionOrDelegateFlags.IsStatic) != 0 + ? true + : (Flags & FunctionOrDelegateFlags.IsNotStatic) != 0 ? false : null; + } + + set + { + Flags = value switch { + // true - static, false - not static, null - infer + true => Flags | (FunctionOrDelegateFlags.IsStatic & ~FunctionOrDelegateFlags.IsNotStatic), + false => (Flags & ~FunctionOrDelegateFlags.IsStatic) | FunctionOrDelegateFlags.IsNotStatic, + null => Flags & ~FunctionOrDelegateFlags.IsStatic & ~FunctionOrDelegateFlags.IsNotStatic + }; + } } public Action WriteCustomAttrs { get; set; } diff --git a/sources/ClangSharp.PInvokeGenerator/Abstractions/StructDesc.cs b/sources/ClangSharp.PInvokeGenerator/Abstractions/StructDesc.cs index 42cf9735..131c80ee 100644 --- a/sources/ClangSharp.PInvokeGenerator/Abstractions/StructDesc.cs +++ b/sources/ClangSharp.PInvokeGenerator/Abstractions/StructDesc.cs @@ -17,14 +17,28 @@ internal struct StructDesc public bool IsUnsafe { - get => (Flags & StructFlags.IsUnsafe) != 0; - set => Flags = value ? Flags | StructFlags.IsUnsafe : Flags & ~StructFlags.IsUnsafe; + get + { + return (Flags & StructFlags.IsUnsafe) != 0; + } + + set + { + Flags = value ? Flags | StructFlags.IsUnsafe : Flags & ~StructFlags.IsUnsafe; + } } public bool HasVtbl { - get => (Flags & StructFlags.HasVtbl) != 0; - set => Flags = value ? Flags | StructFlags.HasVtbl : Flags & ~StructFlags.HasVtbl; + get + { + return (Flags & StructFlags.HasVtbl) != 0; + } + + set + { + Flags = value ? Flags | StructFlags.HasVtbl : Flags & ~StructFlags.HasVtbl; + } } public Action WriteCustomAttrs { get; set; } diff --git a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.Visit.cs b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.Visit.cs index e52fe568..0cec6b64 100644 --- a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.Visit.cs +++ b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.Visit.cs @@ -47,10 +47,7 @@ public void WriteDivider(bool force = false) } } - public void SuppressDivider() - { - NeedsNewline = false; - } + public void SuppressDivider() => NeedsNewline = false; public void WriteIid(string iidName, string iidValue) { diff --git a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.VisitDecl.cs b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.VisitDecl.cs index f2427bc4..ec7ae586 100644 --- a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.VisitDecl.cs +++ b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.VisitDecl.cs @@ -54,10 +54,7 @@ public void BeginConstant(in ConstantDesc desc) Write(desc.EscapedName); } - public void BeginConstantValue(bool isGetOnlyProperty = false) - { - Write(isGetOnlyProperty ? " => " : " = "); - } + public void BeginConstantValue(bool isGetOnlyProperty = false) => Write(isGetOnlyProperty ? " => " : " = "); public void WriteConstantValue(long value) => Write(value); public void WriteConstantValue(ulong value) => Write(value); @@ -150,11 +147,10 @@ public void EndField(bool isBodyless = true) } } - public void BeginFunctionOrDelegate( - in FunctionOrDelegateDesc desc, - ref bool isMethodClassUnsafe) + public void BeginFunctionOrDelegate(in FunctionOrDelegateDesc desc, ref bool isMethodClassUnsafe) { desc.WriteCustomAttrs(desc.CustomAttrGeneratorData); + if (desc.IsVirtual) { Debug.Assert(!desc.HasFnPtrCodeGen); @@ -304,10 +300,7 @@ public void BeginParameter(in ParameterDesc Write(')'); public void BeginConstructorInitializer(string memberRefName, string memberInitName) { @@ -374,10 +364,7 @@ public void EndConstructorInitializers() // nop, method only exists for consistency and/or future use } - public void BeginInnerFunctionBody() - { - WriteIndentation(); - } + public void BeginInnerFunctionBody() => WriteIndentation(); public void EndInnerFunctionBody() { @@ -461,10 +448,7 @@ public void BeginExplicitVtbl() WriteBlockStart(); } - public void EmitCompatibleCodeSupport() - { - AddUsingDirective("System.Runtime.CompilerServices"); - } + public void EmitCompatibleCodeSupport() => AddUsingDirective("System.Runtime.CompilerServices"); public void EmitFnPtrSupport() { @@ -472,26 +456,15 @@ public void EmitFnPtrSupport() AddUsingDirective("System.Runtime.InteropServices"); } - public void EmitSystemSupport() - { - AddUsingDirective("System"); - } + public void EmitSystemSupport() => AddUsingDirective("System"); - public void EndStruct() - { - WriteBlockEnd(); - } + public void EndStruct() => WriteBlockEnd(); - public void EndExplicitVtbl() - { - WriteBlockEnd(); - } + public void EndExplicitVtbl() => WriteBlockEnd(); - public CSharpOutputBuilder BeginCSharpCode() - { + public CSharpOutputBuilder BeginCSharpCode() => // just write directly to this buffer - return this; - } + this; public void EndCSharpCode(CSharpOutputBuilder output) { @@ -510,10 +483,7 @@ public void BeginGetter(bool aggressivelyInlined) WriteBlockStart(); } - public void EndGetter() - { - WriteBlockEnd(); - } + public void EndGetter() => WriteBlockEnd(); public void BeginSetter(bool aggressivelyInlined) { @@ -551,25 +521,13 @@ public void WriteIndexer(string typeName) Write(" this"); } - public void BeginIndexerParameters() - { - Write('['); - } + public void BeginIndexerParameters() => Write('['); - public void EndIndexerParameters() - { - Write(']'); - } + public void EndIndexerParameters() => Write(']'); - public void EndIndexer() - { - NeedsNewline = true; - } + public void EndIndexer() => NeedsNewline = true; - public void BeginDereference() - { - Write('&'); - } + public void BeginDereference() => Write('&'); public void EndDereference() { diff --git a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.cs b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.cs index 6c48b44f..2e6c298b 100644 --- a/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.cs +++ b/sources/ClangSharp.PInvokeGenerator/CSharp/CSharpOutputBuilder.cs @@ -19,7 +19,7 @@ internal sealed partial class CSharpOutputBuilder private readonly bool _isTestOutput; private int _indentationLevel; - private MarkerMode _markerMode; + private readonly MarkerMode _markerMode; public CSharpOutputBuilder(string name, string indentationString = DefaultIndentationString, bool isTestOutput = false, MarkerMode markerMode = MarkerMode.None) { @@ -53,17 +53,7 @@ public CSharpOutputBuilder(string name, string indentationString = DefaultIndent public IEnumerable UsingDirectives => _usingDirectives; - public void AddUsingDirective(string namespaceName) - { - if (namespaceName.StartsWith("static ")) - { - _staticUsingDirectives.Add(namespaceName); - } - else - { - _usingDirectives.Add(namespaceName); - } - } + public void AddUsingDirective(string namespaceName) => _ = namespaceName.StartsWith("static ") ? _staticUsingDirectives.Add(namespaceName) : _usingDirectives.Add(namespaceName); public void DecreaseIndentation() { @@ -75,10 +65,7 @@ public void DecreaseIndentation() _indentationLevel--; } - public void IncreaseIndentation() - { - _indentationLevel++; - } + public void IncreaseIndentation() => _indentationLevel++; public void WriteBlockStart() { @@ -98,10 +85,7 @@ public void WriteBlockEnd() WriteIndentedLine('}'); } - public void Write(T value) - { - _currentLine.Append(value); - } + public void Write(T value) => _ = _currentLine.Append(value); public void WriteIndentation() { @@ -109,7 +93,7 @@ public void WriteIndentation() for (var i = 0; i < _indentationLevel; i++) { - _currentLine.Append(_indentationString); + _ = _currentLine.Append(_indentationString); } } @@ -134,7 +118,7 @@ public void WriteLine(T value) public void WriteNewline() { _contents.Add(_currentLine.ToString()); - _currentLine.Clear(); + _ = _currentLine.Clear(); NeedsNewline = false; } @@ -344,5 +328,19 @@ private void AddNativeTypeNameAttribute(string nativeTypeName, string prefix = n Write(postfix); } } + + public override string ToString() + { + var result = new StringBuilder(); + + foreach (var line in _contents) + { + _ = result.Append(line); + _ = result.Append('\n'); + } + + _ = result.Append(_currentLine); + return result.ToString(); + } } } diff --git a/sources/ClangSharp.PInvokeGenerator/Diagnostic.cs b/sources/ClangSharp.PInvokeGenerator/Diagnostic.cs index 12636c3a..38720af2 100644 --- a/sources/ClangSharp.PInvokeGenerator/Diagnostic.cs +++ b/sources/ClangSharp.PInvokeGenerator/Diagnostic.cs @@ -37,10 +37,7 @@ public Diagnostic(DiagnosticLevel level, string message, string location) public string Message => _message; - public override bool Equals(object obj) - { - return (obj is Diagnostic other) && Equals(other); - } + public override bool Equals(object obj) => (obj is Diagnostic other) && Equals(other); public bool Equals(Diagnostic other) { @@ -49,13 +46,6 @@ public bool Equals(Diagnostic other) && (_message == other.Message); } - public override string ToString() - { - if (string.IsNullOrWhiteSpace(_location)) - { - return $"{_level}: {_message}"; - } - return $"{_level} ({_location}): {_message}"; - } + public override string ToString() => string.IsNullOrWhiteSpace(_location) ? $"{_level}: {_message}" : $"{_level} ({_location}): {_message}"; } } diff --git a/sources/ClangSharp.PInvokeGenerator/Extensions/IReadOnlyListExtensions.cs b/sources/ClangSharp.PInvokeGenerator/Extensions/IReadOnlyListExtensions.cs index c9305b26..6cc4ffc7 100644 --- a/sources/ClangSharp.PInvokeGenerator/Extensions/IReadOnlyListExtensions.cs +++ b/sources/ClangSharp.PInvokeGenerator/Extensions/IReadOnlyListExtensions.cs @@ -10,7 +10,7 @@ public static int IndexOf(this IReadOnlyList self, T value) { var comparer = EqualityComparer.Default; - for (int i = 0; i < self.Count; i++) + for (var i = 0; i < self.Count; i++) { if (comparer.Equals(self[i], value)) { diff --git a/sources/ClangSharp.PInvokeGenerator/Extensions/StringExtensions.cs b/sources/ClangSharp.PInvokeGenerator/Extensions/StringExtensions.cs index 1f73a826..83417d89 100644 --- a/sources/ClangSharp.PInvokeGenerator/Extensions/StringExtensions.cs +++ b/sources/ClangSharp.PInvokeGenerator/Extensions/StringExtensions.cs @@ -10,7 +10,7 @@ internal static class StringExtensions { public static string Unquote(this string str) => str.StartsWith("\"") && str.EndsWith("\"") && !str.EndsWith("\\\"") - ? str.Substring(1, str.Length - 2) + ? str[1..^1] : str; public static string AsString(this AccessSpecifier value) => value switch diff --git a/sources/ClangSharp.PInvokeGenerator/OutputBuilderFactory.cs b/sources/ClangSharp.PInvokeGenerator/OutputBuilderFactory.cs index 47cee0e6..630b33f8 100644 --- a/sources/ClangSharp.PInvokeGenerator/OutputBuilderFactory.cs +++ b/sources/ClangSharp.PInvokeGenerator/OutputBuilderFactory.cs @@ -21,10 +21,7 @@ public OutputBuilderFactory(PInvokeGeneratorOutputMode mode) public IEnumerable OutputBuilders => _outputBuilders.Values; - public void Clear() - { - _outputBuilders.Clear(); - } + public void Clear() => _outputBuilders.Clear(); public IOutputBuilder Create(string name) { @@ -37,7 +34,7 @@ public IOutputBuilder Create(string name) { PInvokeGeneratorOutputMode.CSharp => (IOutputBuilder) new CSharpOutputBuilder(name), PInvokeGeneratorOutputMode.Xml => new XmlOutputBuilder(name), - _ => throw new ArgumentOutOfRangeException() + _ => throw new InvalidOperationException() }; _outputBuilders.Add(name, outputBuilder); @@ -57,37 +54,22 @@ public CSharpOutputBuilder CreateTests(string name) return outputBuilder; } - public IOutputBuilder GetOutputBuilder(string name) - { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentNullException(nameof(name)); - } - return _outputBuilders[name]; - } + public IOutputBuilder GetOutputBuilder(string name) => string.IsNullOrWhiteSpace(name) ? throw new ArgumentNullException(nameof(name)) : _outputBuilders[name]; public CSharpOutputBuilder GetTestOutputBuilder(string name) { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentNullException(nameof(name)); - } - - if (_outputBuilders[name] is CSharpOutputBuilder csharpOutputBuilder && csharpOutputBuilder.IsTestOutput) - { - return csharpOutputBuilder; - } - - throw new ArgumentException("A test output builder was not found with the given name", nameof(name)); + return string.IsNullOrWhiteSpace(name) + ? throw new ArgumentNullException(nameof(name)) + : _outputBuilders[name] is CSharpOutputBuilder csharpOutputBuilder && csharpOutputBuilder.IsTestOutput + ? csharpOutputBuilder + : throw new ArgumentException("A test output builder was not found with the given name", nameof(name)); } public bool TryGetOutputBuilder(string name, out IOutputBuilder outputBuilder) { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentNullException(nameof(name)); - } - return _outputBuilders.TryGetValue(name, out outputBuilder); + return string.IsNullOrWhiteSpace(name) + ? throw new ArgumentNullException(nameof(name)) + : _outputBuilders.TryGetValue(name, out outputBuilder); } } } diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitAttr.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitAttr.cs index 93f620ef..d5d81070 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitAttr.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitAttr.cs @@ -4,7 +4,7 @@ namespace ClangSharp { public partial class PInvokeGenerator { - private void VisitAttr(Attr attr) + private static void VisitAttr(Attr attr) { // We don't consider most attributes particularly important and so we do nothing } diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs index 1a05e9b3..d5968011 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs @@ -13,20 +13,9 @@ namespace ClangSharp { public partial class PInvokeGenerator { - private void VisitClassTemplateDecl(ClassTemplateDecl classTemplateDecl) - { - AddDiagnostic(DiagnosticLevel.Warning, - $"Class templates are not supported: '{GetCursorQualifiedName(classTemplateDecl)}'. Generated bindings may be incomplete.", - classTemplateDecl); - } + private void VisitClassTemplateDecl(ClassTemplateDecl classTemplateDecl) => Visit(classTemplateDecl.TemplatedDecl); - private void VisitClassTemplateSpecializationDecl( - ClassTemplateSpecializationDecl classTemplateSpecializationDecl) - { - AddDiagnostic(DiagnosticLevel.Warning, - $"Class template specializations are not supported: '{GetCursorQualifiedName(classTemplateSpecializationDecl)}'. Generated bindings may be incomplete.", - classTemplateSpecializationDecl); - } + private void VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl classTemplateSpecializationDecl) => AddDiagnostic(DiagnosticLevel.Warning, $"Class template specializations are not supported: '{GetCursorQualifiedName(classTemplateSpecializationDecl)}'. Generated bindings may be incomplete.", classTemplateSpecializationDecl); private void VisitDecl(Decl decl) { @@ -57,7 +46,13 @@ private void VisitDecl(Decl decl) // case CX_DeclKind.CX_DeclKind_Export: // case CX_DeclKind.CX_DeclKind_ExternCContext: // case CX_DeclKind.CX_DeclKind_FileScopeAsm: - // case CX_DeclKind.CX_DeclKind_Friend: + + case CX_DeclKind.CX_DeclKind_Friend: + { + // Nothing to generate for friend declarations + break; + } + // case CX_DeclKind.CX_DeclKind_FriendTemplate: // case CX_DeclKind.CX_DeclKind_Import: @@ -67,7 +62,11 @@ private void VisitDecl(Decl decl) break; } - // case CX_DeclKind.CX_DeclKind_Label: + case CX_DeclKind.CX_DeclKind_Label: + { + VisitLabelDecl((LabelDecl)decl); + break; + } case CX_DeclKind.CX_DeclKind_Namespace: { @@ -241,8 +240,7 @@ private void VisitDecl(Decl decl) default: { - AddDiagnostic(DiagnosticLevel.Error, - $"Unsupported declaration: '{decl.Kind}'. Generated bindings may be incomplete.", decl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported declaration: '{decl.DeclKindName}'. Generated bindings may be incomplete.", decl); break; } } @@ -255,8 +253,7 @@ private void VisitEnumConstantDecl(EnumConstantDecl enumConstantDecl) var escapedName = EscapeName(name); var isAnonymousEnum = false; - var typeName = string.Empty; - + string typeName; if (enumConstantDecl.DeclContext is EnumDecl enumDecl) { if (GetRemappedCursorName(enumDecl).StartsWith("__AnonymousEnum_")) @@ -265,12 +262,12 @@ private void VisitEnumConstantDecl(EnumConstantDecl enumConstantDecl) accessSpecifier = GetAccessSpecifier(enumDecl); } - typeName = GetRemappedTypeName(enumDecl, context: null, enumDecl.IntegerType, out var nativeTypeName); + typeName = GetRemappedTypeName(enumDecl, context: null, enumDecl.IntegerType, out _); } else { typeName = GetRemappedTypeName(enumConstantDecl, context: null, enumConstantDecl.Type, - out var nativeTypeName); + out _); } var desc = new ConstantDesc @@ -308,249 +305,6 @@ private void VisitEnumConstantDecl(EnumConstantDecl enumConstantDecl) _outputBuilder.EndConstant(isAnonymousEnum); } - private void VisitIndirectFieldDecl(IndirectFieldDecl indirectFieldDecl) - { - if (_config.ExcludeAnonymousFieldHelpers) - { - return; - } - - if (IsPrevContextDecl(out var prevContext) && prevContext.IsAnonymousStructOrUnion) - { - // We shouldn't process indirect fields where the prev context is an anonymous record decl - return; - } - - var fieldDecl = indirectFieldDecl.AnonField; - var anonymousRecordDecl = fieldDecl.Parent; - - var rootRecordDecl = anonymousRecordDecl; - - var contextNameParts = new Stack(); - var contextTypeParts = new Stack(); - - while (rootRecordDecl.Parent is RecordDecl parentRecordDecl) - { - var contextNamePart = GetRemappedCursorName(rootRecordDecl); - - if (contextNamePart.StartsWith("_")) - { - int suffixLength = 0; - - if (contextNamePart.EndsWith("_e__Union")) - { - suffixLength = 10; - } - else if (contextNamePart.EndsWith("_e__Struct")) - { - suffixLength = 11; - } - - if (suffixLength != 0) - { - contextNamePart = contextNamePart.Substring(1, contextNamePart.Length - suffixLength); - } - } - - contextNameParts.Push(EscapeName(contextNamePart)); - contextTypeParts.Push(GetRemappedTypeName(rootRecordDecl, context: null, rootRecordDecl.TypeForDecl, out string nativeTypeName)); - - if (!rootRecordDecl.IsAnonymousStructOrUnion) - { - break; - } - - rootRecordDecl = parentRecordDecl; - } - - var contextNameBuilder = new StringBuilder(contextNameParts.Pop()); - var contextTypeBuilder = new StringBuilder(contextTypeParts.Pop()); - - while (contextNameParts.Count != 0) - { - contextNameBuilder.Append('.'); - contextNameBuilder.Append(contextNameParts.Pop()); - - contextTypeBuilder.Append('.'); - contextTypeBuilder.Append(contextTypeParts.Pop()); - } - - var contextName = contextNameBuilder.ToString(); - var contextType = contextTypeBuilder.ToString(); - - var type = fieldDecl.Type; - - var accessSpecifier = GetAccessSpecifier(anonymousRecordDecl); - var typeName = GetRemappedTypeName(fieldDecl, context: null, type, out var fieldNativeTypeName); - var name = GetRemappedCursorName(fieldDecl); - var escapedName = EscapeName(name); - - var desc = new FieldDesc - { - AccessSpecifier = accessSpecifier, - NativeTypeName = null, - EscapedName = escapedName, - Offset = null, - NeedsNewKeyword = false - }; - - _outputBuilder.WriteDivider(true); - _outputBuilder.BeginField(in desc); - - var isFixedSizedBuffer = (type.CanonicalType is ConstantArrayType); - var generateCompatibleCode = _config.GenerateCompatibleCode; - var typeString = string.Empty; - - if (!fieldDecl.IsBitField && (!isFixedSizedBuffer || generateCompatibleCode)) - { - typeString = "ref "; - } - - if (type.CanonicalType is RecordType recordType) - { - var recordDecl = recordType.Decl; - - while ((recordDecl.DeclContext is RecordDecl parentRecordDecl) && (parentRecordDecl != rootRecordDecl)) - { - var parentRecordDeclName = GetRemappedCursorName(parentRecordDecl); - var escapedParentRecordDeclName = EscapeName(parentRecordDeclName); - - typeString += escapedParentRecordDeclName + '.'; - - recordDecl = parentRecordDecl; - } - } - - var isSupportedFixedSizedBufferType = - isFixedSizedBuffer && IsSupportedFixedSizedBufferType(typeName); - - if (isFixedSizedBuffer) - { - if (!generateCompatibleCode) - { - _outputBuilder.EmitSystemSupport(); - typeString += "Span<"; - } - else if (!isSupportedFixedSizedBufferType) - { - typeString += contextType + '.'; - typeName = GetArtificialFixedSizedBufferName(fieldDecl); - } - } - - typeString += typeName; - if (isFixedSizedBuffer && !generateCompatibleCode) - { - typeString += '>'; - } - - _outputBuilder.WriteRegularField(typeString, escapedName); - - generateCompatibleCode |= - ((type.CanonicalType is PointerType) || (type.CanonicalType is ReferenceType)) && - ((typeName != "IntPtr") && (typeName != "UIntPtr")); - - _outputBuilder.BeginBody(); - _outputBuilder.BeginGetter(_config.GenerateAggressiveInlining); - var code = _outputBuilder.BeginCSharpCode(); - - if (fieldDecl.IsBitField) - { - code.WriteIndented("return "); - code.Write(contextName); - code.Write('.'); - code.Write(escapedName); - code.WriteSemicolon(); - code.WriteNewline(); - _outputBuilder.EndCSharpCode(code); - - _outputBuilder.EndGetter(); - - _outputBuilder.BeginSetter(_config.GenerateAggressiveInlining); - - code = _outputBuilder.BeginCSharpCode(); - code.WriteIndented(contextName); - code.Write('.'); - code.Write(escapedName); - code.Write(" = value"); - code.WriteSemicolon(); - code.WriteNewline(); - _outputBuilder.EndCSharpCode(code); - - _outputBuilder.EndSetter(); - } - else if (generateCompatibleCode) - { - code.WriteIndented("fixed ("); - code.Write(contextType); - code.Write("* pField = &"); - code.Write(contextName); - code.WriteLine(')'); - code.WriteBlockStart(); - code.WriteIndented("return ref pField->"); - code.Write(escapedName); - - if (isSupportedFixedSizedBufferType) - { - code.Write("[0]"); - } - - code.WriteSemicolon(); - code.WriteNewline(); - code.WriteBlockEnd(); - _outputBuilder.EndCSharpCode(code); - - _outputBuilder.EndGetter(); - } - else - { - code.WriteIndented("return "); - - if (!isFixedSizedBuffer) - { - code.AddUsingDirective("System.Runtime.InteropServices"); - code.Write("ref MemoryMarshal.GetReference("); - } - - if (!isFixedSizedBuffer || isSupportedFixedSizedBufferType) - { - code.Write("MemoryMarshal.CreateSpan(ref "); - } - - code.Write(contextName); - code.Write('.'); - code.Write(escapedName); - - if (isFixedSizedBuffer) - { - if (isSupportedFixedSizedBufferType) - { - code.Write("[0], "); - code.Write(((ConstantArrayType)type.CanonicalType).Size); - } - else - { - code.Write(".AsSpan("); - } - } - else - { - code.Write(", 1)"); - } - - code.Write(')'); - code.WriteSemicolon(); - code.WriteNewline(); - _outputBuilder.EndCSharpCode(code); - - _outputBuilder.EndGetter(); - } - - _outputBuilder.EndBody(); - _outputBuilder.EndField(false); - _outputBuilder.WriteDivider(); - } - private void VisitEnumDecl(EnumDecl enumDecl) { var accessSpecifier = GetAccessSpecifier(enumDecl); @@ -568,9 +322,7 @@ private void VisitEnumDecl(EnumDecl enumDecl) { if (!isAnonymousEnum) { - var typeName = GetRemappedTypeName(enumDecl, context: null, enumDecl.IntegerType, - out var nativeTypeName); - + var typeName = GetRemappedTypeName(enumDecl, context: null, enumDecl.IntegerType, out var nativeTypeName); _outputBuilder.BeginEnum(accessSpecifier, typeName, escapedName, nativeTypeName); } @@ -651,6 +403,17 @@ private void VisitFunctionDecl(FunctionDecl functionDecl) return; } + if (functionDecl.DeclContext is not CXXRecordDecl cxxRecordDecl) + { + cxxRecordDecl = null; + StartUsingOutputBuilder(_config.MethodClassName); + } + else if ((Cursor)functionDecl.LexicalDeclContext != cxxRecordDecl) + { + // We shouldn't reprocess C++ functions outside the declaration + return; + } + var accessSppecifier = GetAccessSpecifier(functionDecl); var name = GetRemappedCursorName(functionDecl); @@ -660,12 +423,6 @@ private void VisitFunctionDecl(FunctionDecl functionDecl) var isVirtual = (cxxMethodDecl != null) && cxxMethodDecl.IsVirtual; var escapedName = isVirtual ? PrefixAndStripName(name, cxxMethodDecl.OverloadIndex) : EscapeAndStripName(name); - if (!(functionDecl.DeclContext is CXXRecordDecl cxxRecordDecl)) - { - cxxRecordDecl = null; - StartUsingOutputBuilder(_config.MethodClassName); - } - var returnType = functionDecl.ReturnType; var returnTypeName = GetRemappedTypeName(functionDecl, cxxRecordDecl, returnType, out var nativeTypeName); @@ -730,148 +487,382 @@ private void VisitFunctionDecl(FunctionDecl functionDecl) _outputBuilder.BeginFunctionOrDelegate(in desc, ref _isMethodClassUnsafe); - var needsReturnFixup = isVirtual && NeedsReturnFixup(cxxMethodDecl); + var needsReturnFixup = isVirtual && NeedsReturnFixup(cxxMethodDecl); + + if ((functionDecl is not CXXConstructorDecl) || (_config.OutputMode == PInvokeGeneratorOutputMode.Xml)) + { + _outputBuilder.WriteReturnType(needsReturnFixup ? $"{returnTypeName}*" : returnTypeName); + } + + _outputBuilder.BeginFunctionInnerPrototype(escapedName); + + if (isVirtual) + { + Debug.Assert(cxxRecordDecl != null); + + if (!IsPrevContextDecl(out var thisCursor)) + { + thisCursor = cxxRecordDecl; + } + + var cxxRecordDeclName = GetRemappedCursorName(thisCursor); + var cxxRecordEscapedName = EscapeName(cxxRecordDeclName); + ParameterDesc<(string Name, PInvokeGenerator This)> parameterDesc = new() + { + Name = "pThis", + Type = $"{cxxRecordEscapedName}*", + WriteCustomAttrs = static x => { }, + CustomAttrGeneratorData = default + }; + + _outputBuilder.BeginParameter(in parameterDesc); + _outputBuilder.EndParameter(); + + if (needsReturnFixup) + { + _outputBuilder.WriteParameterSeparator(); + parameterDesc = new() + { + Name = "_result", + Type = $"{returnTypeName}*", + WriteCustomAttrs = static x => { }, + CustomAttrGeneratorData = default + }; + _outputBuilder.BeginParameter(in parameterDesc); + _outputBuilder.EndParameter(); + } + + if (functionDecl.Parameters.Any()) + { + _outputBuilder.WriteParameterSeparator(); + } + } + + Visit(functionDecl.Parameters); + + _outputBuilder.EndFunctionInnerPrototype(); + + if ((body is null) || isVirtual) + { + _outputBuilder.EndFunctionOrDelegate(isVirtual, true); + } + else + { + var firstCtorInitializer = functionDecl.Parameters.Any() ? (functionDecl.CursorChildren.IndexOf(functionDecl.Parameters.Last()) + 1) : 0; + var lastCtorInitializer = (functionDecl.Body != null) ? functionDecl.CursorChildren.IndexOf(functionDecl.Body) : functionDecl.CursorChildren.Count; + + _outputBuilder.BeginBody(); + + if (functionDecl is CXXConstructorDecl cxxConstructorDecl) + { + VisitCtorInitializers(cxxConstructorDecl, firstCtorInitializer, lastCtorInitializer); + } + + if (body is CompoundStmt compoundStmt) + { + _outputBuilder.BeginConstructorInitializers(); + VisitStmts(compoundStmt.Body); + _outputBuilder.EndConstructorInitializers(); + } + else + { + _outputBuilder.BeginInnerFunctionBody(); + Visit(body); + _outputBuilder.EndInnerFunctionBody(); + } + + _outputBuilder.EndBody(); + _outputBuilder.EndFunctionOrDelegate(isVirtual, false); + } + + Visit(functionDecl.Decls, excludedCursors: functionDecl.Parameters); + + if (cxxRecordDecl is null) + { + StopUsingOutputBuilder(); + } + + void VisitCtorInitializers(CXXConstructorDecl cxxConstructorDecl, int firstCtorInitializer, int lastCtorInitializer) + { + for (var i = firstCtorInitializer; i < lastCtorInitializer; i++) + { + if (cxxConstructorDecl.CursorChildren[i] is Attr) + { + continue; + } + + var memberRef = (Ref)cxxConstructorDecl.CursorChildren[i]; + var memberInit = (Stmt)cxxConstructorDecl.CursorChildren[++i]; + + if (memberInit is ImplicitValueInitExpr) + { + continue; + } + + var memberRefName = GetRemappedCursorName(memberRef.Referenced); + var memberInitName = memberInit.Spelling; + + if (memberInit is CastExpr {SubExprAsWritten: DeclRefExpr declRefExpr}) + { + memberInitName = GetRemappedCursorName(declRefExpr.Decl); + } + + _outputBuilder.BeginConstructorInitializer(memberRefName, memberInitName); + + var memberRefTypeName = GetRemappedTypeName(memberRef, context: null, memberRef.Type, + out var memberRefNativeTypeName); + + UncheckStmt(memberRefTypeName, memberInit); + + _outputBuilder.EndConstructorInitializer(); + } + } + } + + private void VisitFunctionTemplateDecl(FunctionTemplateDecl functionTemplateDecl) => Visit(functionTemplateDecl.TemplatedDecl); + + private void VisitIndirectFieldDecl(IndirectFieldDecl indirectFieldDecl) + { + if (_config.ExcludeAnonymousFieldHelpers) + { + return; + } + + if (IsPrevContextDecl(out var prevContext) && prevContext.IsAnonymousStructOrUnion) + { + // We shouldn't process indirect fields where the prev context is an anonymous record decl + return; + } + + var fieldDecl = indirectFieldDecl.AnonField; + var anonymousRecordDecl = fieldDecl.Parent; + + var rootRecordDecl = anonymousRecordDecl; + + var contextNameParts = new Stack(); + var contextTypeParts = new Stack(); + + while (rootRecordDecl.IsAnonymousStructOrUnion && (rootRecordDecl.Parent is RecordDecl parentRecordDecl)) + { + var contextNamePart = GetRemappedCursorName(rootRecordDecl); + + if (contextNamePart.StartsWith("_")) + { + var suffixLength = 0; + + if (contextNamePart.EndsWith("_e__Union")) + { + suffixLength = 10; + } + else if (contextNamePart.EndsWith("_e__Struct")) + { + suffixLength = 11; + } + + if (suffixLength != 0) + { + contextNamePart = contextNamePart.Substring(1, contextNamePart.Length - suffixLength); + } + } + + contextNameParts.Push(EscapeName(contextNamePart)); + + contextTypeParts.Push(GetRemappedTypeName(rootRecordDecl, context: null, rootRecordDecl.TypeForDecl, out _)); + + rootRecordDecl = parentRecordDecl; + } + + var contextNameBuilder = new StringBuilder(contextNameParts.Pop()); + var contextTypeBuilder = new StringBuilder(contextTypeParts.Pop()); + + while (contextNameParts.Count != 0) + { + _ = contextNameBuilder.Append('.'); + _ = contextNameBuilder.Append(contextNameParts.Pop()); + + _ = contextTypeBuilder.Append('.'); + _ = contextTypeBuilder.Append(contextTypeParts.Pop()); + } + + var contextName = contextNameBuilder.ToString(); + var contextType = contextTypeBuilder.ToString(); + + var type = fieldDecl.Type; + + var accessSpecifier = GetAccessSpecifier(anonymousRecordDecl); + + var typeName = GetRemappedTypeName(fieldDecl, context: null, type, out _); + var name = GetRemappedCursorName(fieldDecl); + var escapedName = EscapeName(name); + + var desc = new FieldDesc { + AccessSpecifier = accessSpecifier, + NativeTypeName = null, + EscapedName = escapedName, + Offset = null, + NeedsNewKeyword = false + }; + + _outputBuilder.WriteDivider(true); + _outputBuilder.BeginField(in desc); + + var isFixedSizedBuffer = type.CanonicalType is ConstantArrayType; + var generateCompatibleCode = _config.GenerateCompatibleCode; + var typeString = string.Empty; - if ((functionDecl is not CXXConstructorDecl) || (_config.OutputMode == PInvokeGeneratorOutputMode.Xml)) + if (!fieldDecl.IsBitField && (!isFixedSizedBuffer || generateCompatibleCode)) { - _outputBuilder.WriteReturnType(needsReturnFixup ? $"{returnTypeName}*" : returnTypeName); + typeString = "ref "; } - _outputBuilder.BeginFunctionInnerPrototype(escapedName); - - if (isVirtual) + if (type.CanonicalType is RecordType recordType) { - Debug.Assert(cxxRecordDecl != null); + var recordDecl = recordType.Decl; - if (!IsPrevContextDecl(out CXXRecordDecl thisCursor)) + while ((recordDecl.DeclContext is RecordDecl parentRecordDecl) && (parentRecordDecl != rootRecordDecl)) { - thisCursor = cxxRecordDecl; - } + var parentRecordDeclName = GetRemappedCursorName(parentRecordDecl); + var escapedParentRecordDeclName = EscapeName(parentRecordDeclName); - var cxxRecordDeclName = GetRemappedCursorName(thisCursor); - var cxxRecordEscapedName = EscapeName(cxxRecordDeclName); - ParameterDesc<(string Name, PInvokeGenerator This)> parameterDesc = new() - { - Name = "pThis", - Type = $"{cxxRecordEscapedName}*", - WriteCustomAttrs = static x => { }, - CustomAttrGeneratorData = default - }; + typeString += escapedParentRecordDeclName + '.'; - _outputBuilder.BeginParameter(in parameterDesc); - _outputBuilder.EndParameter(); + recordDecl = parentRecordDecl; + } + } - if (needsReturnFixup) + var isSupportedFixedSizedBufferType = + isFixedSizedBuffer && IsSupportedFixedSizedBufferType(typeName); + + if (isFixedSizedBuffer) + { + if (!generateCompatibleCode) { - _outputBuilder.WriteParameterSeparator(); - parameterDesc = new() - { - Name = "_result", - Type = $"{returnTypeName}*", - WriteCustomAttrs = static x => { }, - CustomAttrGeneratorData = default - }; - _outputBuilder.BeginParameter(in parameterDesc); - _outputBuilder.EndParameter(); + _outputBuilder.EmitSystemSupport(); + typeString += "Span<"; } - - if (functionDecl.Parameters.Any()) + else if (!isSupportedFixedSizedBufferType) { - _outputBuilder.WriteParameterSeparator(); + typeString += contextType + '.'; + typeName = GetArtificialFixedSizedBufferName(fieldDecl); } } - Visit(functionDecl.Parameters); + typeString += typeName; + if (isFixedSizedBuffer && !generateCompatibleCode) + { + typeString += '>'; + } - _outputBuilder.EndFunctionInnerPrototype(); + _outputBuilder.WriteRegularField(typeString, escapedName); - if ((body is null) || isVirtual) + generateCompatibleCode |= + ((type.CanonicalType is PointerType) || (type.CanonicalType is ReferenceType)) && + (typeName != "IntPtr") && (typeName != "UIntPtr"); + + _outputBuilder.BeginBody(); + _outputBuilder.BeginGetter(_config.GenerateAggressiveInlining); + var code = _outputBuilder.BeginCSharpCode(); + + if (fieldDecl.IsBitField) { - _outputBuilder.EndFunctionOrDelegate(isVirtual, true); + code.WriteIndented("return "); + code.Write(contextName); + code.Write('.'); + code.Write(escapedName); + code.WriteSemicolon(); + code.WriteNewline(); + _outputBuilder.EndCSharpCode(code); + + _outputBuilder.EndGetter(); + + _outputBuilder.BeginSetter(_config.GenerateAggressiveInlining); + + code = _outputBuilder.BeginCSharpCode(); + code.WriteIndented(contextName); + code.Write('.'); + code.Write(escapedName); + code.Write(" = value"); + code.WriteSemicolon(); + code.WriteNewline(); + _outputBuilder.EndCSharpCode(code); + + _outputBuilder.EndSetter(); } - else + else if (generateCompatibleCode) { - int firstCtorInitializer = functionDecl.Parameters.Any() - ? (functionDecl.CursorChildren.IndexOf(functionDecl.Parameters.Last()) + 1) - : 0; - int lastCtorInitializer = (functionDecl.Body != null) - ? functionDecl.CursorChildren.IndexOf(functionDecl.Body) - : functionDecl.CursorChildren.Count; - - _outputBuilder.BeginBody(); + code.WriteIndented("fixed ("); + code.Write(contextType); + code.Write("* pField = &"); + code.Write(contextName); + code.WriteLine(')'); + code.WriteBlockStart(); + code.WriteIndented("return ref pField->"); + code.Write(escapedName); - if (functionDecl is CXXConstructorDecl cxxConstructorDecl) + if (isSupportedFixedSizedBufferType) { - VisitCtorInitializers(cxxConstructorDecl, firstCtorInitializer, lastCtorInitializer); + code.Write("[0]"); } - if (body is CompoundStmt compoundStmt) - { - _outputBuilder.BeginConstructorInitializers(); - VisitStmts(compoundStmt.Body); - _outputBuilder.EndConstructorInitializers(); - } - else - { - _outputBuilder.BeginInnerFunctionBody(); - Visit(body); - _outputBuilder.EndInnerFunctionBody(); - } + code.WriteSemicolon(); + code.WriteNewline(); + code.WriteBlockEnd(); + _outputBuilder.EndCSharpCode(code); - _outputBuilder.EndBody(); - _outputBuilder.EndFunctionOrDelegate(isVirtual, false); + _outputBuilder.EndGetter(); } - - Visit(functionDecl.Decls, excludedCursors: functionDecl.Parameters); - - if (cxxRecordDecl is null) + else { - StopUsingOutputBuilder(); - } + code.WriteIndented("return "); - void VisitCtorInitializers(CXXConstructorDecl cxxConstructorDecl, int firstCtorInitializer, - int lastCtorInitializer) - { - for (int i = firstCtorInitializer; i < lastCtorInitializer; i++) + if (!isFixedSizedBuffer) { - if (cxxConstructorDecl.CursorChildren[i] is Attr) - { - continue; - } + code.AddUsingDirective("System.Runtime.InteropServices"); + code.Write("ref MemoryMarshal.GetReference("); + } - var memberRef = (Ref)cxxConstructorDecl.CursorChildren[i]; - var memberInit = (Stmt)cxxConstructorDecl.CursorChildren[++i]; + if (!isFixedSizedBuffer || isSupportedFixedSizedBufferType) + { + code.Write("MemoryMarshal.CreateSpan(ref "); + } - if (memberInit is ImplicitValueInitExpr) + code.Write(contextName); + code.Write('.'); + code.Write(escapedName); + + if (isFixedSizedBuffer) + { + if (isSupportedFixedSizedBufferType) { - continue; + code.Write("[0], "); + code.Write(((ConstantArrayType)type.CanonicalType).Size); } - - var memberRefName = GetRemappedCursorName(memberRef.Referenced); - var memberInitName = memberInit.Spelling; - - if ((memberInit is CastExpr {SubExprAsWritten: DeclRefExpr declRefExpr})) + else { - memberInitName = GetRemappedCursorName(declRefExpr.Decl); + code.Write(".AsSpan("); } + } + else + { + code.Write(", 1)"); + } - _outputBuilder.BeginConstructorInitializer(memberRefName, memberInitName); - - var memberRefTypeName = GetRemappedTypeName(memberRef, context: null, memberRef.Type, - out var memberRefNativeTypeName); - - UncheckStmt(memberRefTypeName, memberInit); + code.Write(')'); + code.WriteSemicolon(); + code.WriteNewline(); + _outputBuilder.EndCSharpCode(code); - _outputBuilder.EndConstructorInitializer(); - } + _outputBuilder.EndGetter(); } + + _outputBuilder.EndBody(); + _outputBuilder.EndField(false); + _outputBuilder.WriteDivider(); } - private void VisitFunctionTemplateDecl(FunctionTemplateDecl functionTemplateDecl) + private static void VisitLabelDecl(LabelDecl labelDecl) { - AddDiagnostic(DiagnosticLevel.Warning, - $"Function templates are not supported: '{GetCursorQualifiedName(functionTemplateDecl)}'. Generated bindings may be incomplete.", - functionTemplateDecl); + // This should have already been handled as a statement } private void VisitLinkageSpecDecl(LinkageSpecDecl linkageSpecDecl) @@ -906,7 +897,7 @@ private void VisitParmVarDecl(ParmVarDecl parmVarDecl) } else { - IsPrevContextDecl(out var previousContext); + _ = IsPrevContextDecl(out var previousContext); AddDiagnostic(DiagnosticLevel.Error, $"Unsupported parameter variable declaration parent: '{previousContext.CursorKindSpelling}'. Generated bindings may be incomplete.", previousContext); @@ -1035,13 +1026,10 @@ private void VisitRecordDecl(RecordDecl recordDecl) hasVtbl = HasVtbl(cxxRecordDecl); } - var alignment = recordDecl.TypeForDecl.Handle.AlignOf; - var maxAlignm = recordDecl.Fields.Any() - ? recordDecl.Fields.Max((fieldDecl) => fieldDecl.Type.Handle.AlignOf) - : alignment; + var alignment = Math.Max(recordDecl.TypeForDecl.Handle.AlignOf, 1); + var maxAlignm = recordDecl.Fields.Any() ? recordDecl.Fields.Max((fieldDecl) => Math.Max(fieldDecl.Type.Handle.AlignOf, 1)) : alignment; - if ((_testOutputBuilder != null) && !recordDecl.IsAnonymousStructOrUnion && - !(recordDecl.DeclContext is RecordDecl)) + if ((_testOutputBuilder != null) && !recordDecl.IsAnonymousStructOrUnion && !(recordDecl.DeclContext is RecordDecl)) { _testOutputBuilder.WriteIndented("/// Provides validation of the fieldDecl.Type.Handle.AlignOf); + var alignment = Math.Max(recordDecl.TypeForDecl.Handle.AlignOf, 1); + var maxAlignm = recordDecl.Fields.Any() ? recordDecl.Fields.Max((fieldDecl) => Math.Max(fieldDecl.Type.Handle.AlignOf, 1)) : alignment; StructLayoutAttribute layout = null; if (alignment < maxAlignm) { - layout = new StructLayoutAttribute(LayoutKind.Sequential); - layout.Pack = (int) alignment; + layout = new StructLayoutAttribute(LayoutKind.Sequential) { + Pack = (int)alignment + }; } var accessSpecifier = GetAccessSpecifier(constantArray); var canonicalElementType = type.ElementType.CanonicalType; var isUnsafeElementType = ((canonicalElementType is PointerType) || (canonicalElementType is ReferenceType)) && - ((typeName != "IntPtr") && (typeName != "UIntPtr")); + (typeName != "IntPtr") && (typeName != "UIntPtr"); var name = GetArtificialFixedSizedBufferName(constantArray); var escapedName = EscapeName(name); @@ -2204,7 +2191,7 @@ void VisitConstantArrayFieldDecl(RecordDecl recordDecl, FieldDecl constantArray) sizePerDimension[0] = dimension; var separateStride = false; - for (int d = 1; d < sizePerDimension.Count; d++) + for (var d = 1; d < sizePerDimension.Count; d++) { dimension = sizePerDimension[d]; fieldName += "_" + dimension.index; @@ -2456,12 +2443,9 @@ void ForPointeeType(TypedefDecl typedefDecl, Type parentType, Type pointeeType) { ForPointeeType(typedefDecl, typedefType, typedefType.Decl.UnderlyingType); } - else if (!(pointeeType is ConstantArrayType) && !(pointeeType is BuiltinType) && - !(pointeeType is TagType)) + else if (pointeeType is not ConstantArrayType and not BuiltinType and not TagType and not TemplateTypeParmType) { - AddDiagnostic(DiagnosticLevel.Error, - $"Unsupported pointee type: '{pointeeType.TypeClass}'. Generating bindings may be incomplete.", - typedefDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported pointee type: '{pointeeType.TypeClassSpelling}'. Generating bindings may be incomplete.", typedefDecl); } } @@ -2479,6 +2463,10 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType) { // Nothing to do for builtin types } + else if (underlyingType is DependentNameType dependentNameType) + { + // Nothing to do for dependent name types + } else if (underlyingType is ElaboratedType elaboratedType) { ForUnderlyingType(typedefDecl, elaboratedType.NamedType); @@ -2501,8 +2489,7 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType) if (_config.LogPotentialTypedefRemappings) { var typedefName = typedefDecl.UnderlyingDecl.Name; - var possibleNamesToRemap = - new string[] {"_" + typedefName, "_tag" + typedefName, "tag" + typedefName}; + var possibleNamesToRemap = new string[] {"_" + typedefName, "_tag" + typedefName, "tag" + typedefName}; var underlyingName = underlyingTagType.AsString; foreach (var possibleNameToRemap in possibleNamesToRemap) @@ -2511,22 +2498,34 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType) { if (possibleNameToRemap == underlyingName) { - AddDiagnostic(DiagnosticLevel.Info, - $"Potential remap: {possibleNameToRemap}={typedefName}"); + AddDiagnostic(DiagnosticLevel.Info, $"Potential remap: {possibleNameToRemap}={typedefName}"); } } } } } + else if (underlyingType is TemplateSpecializationType templateSpecializationType) + { + if (templateSpecializationType.IsTypeAlias) + { + ForUnderlyingType(typedefDecl, templateSpecializationType.AliasedType); + } + else + { + // Nothing to do for non-aliased template specialization types + } + } + else if (underlyingType is TemplateTypeParmType templateTypeParmType) + { + // Nothing to do for template type parameter types + } else if (underlyingType is TypedefType typedefType) { ForUnderlyingType(typedefDecl, typedefType.Decl.UnderlyingType); } else { - AddDiagnostic(DiagnosticLevel.Error, - $"Unsupported underlying type: '{underlyingType.TypeClass}'. Generating bindings may be incomplete.", - typedefDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported underlying type: '{underlyingType.TypeClassSpelling}'. Generating bindings may be incomplete.", typedefDecl); } return; @@ -2534,22 +2533,13 @@ void ForUnderlyingType(TypedefDecl typedefDecl, Type underlyingType) string GetUndecoratedName(Type type) { - if (type is AttributedType attributedType) - { - return GetUndecoratedName(attributedType.ModifiedType); - } - else if (type is ElaboratedType elaboratedType) - { - return GetUndecoratedName(elaboratedType.NamedType); - } - else - { - return type.AsString; - } + return type is AttributedType attributedType + ? GetUndecoratedName(attributedType.ModifiedType) + : type is ElaboratedType elaboratedType ? GetUndecoratedName(elaboratedType.NamedType) : type.AsString; } } - private void VisitUsingShadowDecl(UsingShadowDecl usingShadowDecl) + private static void VisitUsingShadowDecl(UsingShadowDecl usingShadowDecl) { // Nothing to handle for binding generation } @@ -2575,12 +2565,12 @@ private void VisitVarDecl(VarDecl varDecl) if (nativeName.StartsWith("ClangSharpMacro_")) { type = varDecl.Init.Type; - nativeName = nativeName.Substring("ClangSharpMacro_".Length); + nativeName = nativeName["ClangSharpMacro_".Length..]; isMacroDefinitionRecord = true; } var accessSpecifier = GetAccessSpecifier(varDecl); - var name = GetRemappedName(nativeName, varDecl, tryRemapOperatorName: false); + var name = GetRemappedName(nativeName, varDecl, tryRemapOperatorName: false, out var wasRemapped); var escapedName = EscapeName(name); if (isMacroDefinitionRecord) @@ -2617,19 +2607,19 @@ private void VisitVarDecl(VarDecl varDecl) if (typeName == "Guid") { - _generatedUuids.Add(name); + _ = _generatedUuids.Add(name); } if (isMacroDefinitionRecord) { var nativeTypeNameBuilder = new StringBuilder("#define"); - nativeTypeNameBuilder.Append(' '); - nativeTypeNameBuilder.Append(nativeName); - nativeTypeNameBuilder.Append(' '); + _ = nativeTypeNameBuilder.Append(' '); + _ = nativeTypeNameBuilder.Append(nativeName); + _ = nativeTypeNameBuilder.Append(' '); var macroValue = GetSourceRangeContents(varDecl.TranslationUnit.Handle, varDecl.Init.Extent); - nativeTypeNameBuilder.Append(macroValue); + _ = nativeTypeNameBuilder.Append(macroValue); nativeTypeName = nativeTypeNameBuilder.ToString(); } @@ -2751,13 +2741,13 @@ private void VisitVarDecl(VarDecl varDecl) _outputBuilder.WriteDivider(); } } - else if (IsPrevContextDecl(out var functionDecl)) + else if (IsPrevContextDecl(out _)) { // This should be handled in the function body as part of a DeclStmt } else { - IsPrevContextDecl(out var previousContext); + _ = IsPrevContextDecl(out var previousContext); AddDiagnostic(DiagnosticLevel.Error, $"Unsupported variable declaration parent: '{previousContext.CursorKindSpelling}'. Generated bindings may be incomplete.", previousContext); @@ -2772,7 +2762,8 @@ void ForDeclStmt(VarDecl varDecl, DeclStmt declStmt) if (varDecl == declStmt.Decls.First()) { var type = varDecl.Type; - var typeName = GetRemappedTypeName(varDecl, context: null, type, out var nativeTypeName); + + var typeName = GetRemappedTypeName(varDecl, context: null, type, out _); outputBuilder.Write(typeName); @@ -2788,12 +2779,8 @@ void ForDeclStmt(VarDecl varDecl, DeclStmt declStmt) if (varDecl.HasInit) { - outputBuilder.Write(' '); - outputBuilder.Write('='); - outputBuilder.Write(' '); - - var varDeclTypeName = GetRemappedTypeName(varDecl, context: null, varDecl.Type, - out var varDeclNativeTypeName); + outputBuilder.Write(" = "); + var varDeclTypeName = GetRemappedTypeName(varDecl, context: null, varDecl.Type, out _); UncheckStmt(varDeclTypeName, varDecl.Init); } @@ -2853,7 +2840,7 @@ bool CanBeConstant(Type type, Expr initExpr) } } - bool IsConstant(Expr initExpr) + private bool IsConstant(Expr initExpr) { switch (initExpr.StmtClass) { @@ -2867,7 +2854,12 @@ bool IsConstant(Expr initExpr) // case CX_StmtClass.CX_StmtClass_AddrLabelExpr: // case CX_StmtClass.CX_StmtClass_ArrayInitIndexExpr: // case CX_StmtClass.CX_StmtClass_ArrayInitLoopExpr: - // case CX_StmtClass.CX_StmtClass_ArraySubscriptExpr: + + case CX_StmtClass.CX_StmtClass_ArraySubscriptExpr: + { + return false; + } + // case CX_StmtClass.CX_StmtClass_ArrayTypeTraitExpr: // case CX_StmtClass.CX_StmtClass_AsTypeExpr: // case CX_StmtClass.CX_StmtClass_AtomicExpr: @@ -2892,10 +2884,20 @@ bool IsConstant(Expr initExpr) // case CX_StmtClass.CX_StmtClass_CXXDefaultArgExpr: // case CX_StmtClass.CX_StmtClass_CXXDefaultInitExpr: // case CX_StmtClass.CX_StmtClass_CXXDeleteExpr: - // case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + + case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + { + return false; + } + // case CX_StmtClass.CX_StmtClass_CXXFoldExpr: // case CX_StmtClass.CX_StmtClass_CXXInheritedCtorInitExpr: - // case CX_StmtClass.CX_StmtClass_CXXNewExpr: + + case CX_StmtClass.CX_StmtClass_CXXNewExpr: + { + return false; + } + // case CX_StmtClass.CX_StmtClass_CXXNoexceptExpr: case CX_StmtClass.CX_StmtClass_CXXNullPtrLiteralExpr: @@ -2993,7 +2995,13 @@ bool IsConstant(Expr initExpr) } // case CX_StmtClass.CX_StmtClass_ConstantExpr: - // case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + + case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + { + var exprWithCleanups = (ExprWithCleanups)initExpr; + return IsConstant(exprWithCleanups.SubExpr); + } + // case CX_StmtClass.CX_StmtClass_FunctionParmPackExpr: // case CX_StmtClass.CX_StmtClass_GNUNullExpr: // case CX_StmtClass.CX_StmtClass_GenericSelectionExpr: @@ -3045,7 +3053,21 @@ bool IsConstant(Expr initExpr) return IsConstant(parenExpr.SubExpr); } - // case CX_StmtClass.CX_StmtClass_ParenListExpr: + case CX_StmtClass.CX_StmtClass_ParenListExpr: + { + var parenListExpr = (ParenListExpr)initExpr; + + foreach (var expr in parenListExpr.Exprs) + { + if (IsConstant(expr)) + { + return true; + } + } + + return false; + } + // case CX_StmtClass.CX_StmtClass_PredefinedExpr: // case CX_StmtClass.CX_StmtClass_PseudoObjectExpr: // case CX_StmtClass.CX_StmtClass_RequiresExpr: @@ -3069,26 +3091,24 @@ bool IsConstant(Expr initExpr) var unaryExprOrTypeTraitExpr = (UnaryExprOrTypeTraitExpr)initExpr; var argumentType = unaryExprOrTypeTraitExpr.TypeOfArgument; - long size32; - long size64; long alignment32 = -1; long alignment64 = -1; - GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out size32, - out size64); + GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out var size32, + out var size64); switch (unaryExprOrTypeTraitExpr.Kind) { case CX_UnaryExprOrTypeTrait.CX_UETT_SizeOf: { - return (size32 == size64); + return size32 == size64; } case CX_UnaryExprOrTypeTrait.CX_UETT_AlignOf: case CX_UnaryExprOrTypeTrait.CX_UETT_PreferredAlignOf: { - return (alignment32 == alignment64); + return alignment32 == alignment64; } default: @@ -3108,9 +3128,7 @@ bool IsConstant(Expr initExpr) default: { - AddDiagnostic(DiagnosticLevel.Warning, - $"Unsupported statement class: '{initExpr.StmtClassName}'. Generated bindings may not be constant.", - initExpr); + AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported statement class: '{initExpr.StmtClassName}'. Generated bindings may not be constant.", initExpr); return false; } } diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitPreprocessedEntity.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitPreprocessedEntity.cs index e86cf76d..4b8e5ee2 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitPreprocessedEntity.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitPreprocessedEntity.cs @@ -32,19 +32,19 @@ private unsafe void VisitMacroDefinitionRecord(MacroDefinitionRecord macroDefini var macroName = $"ClangSharpMacro_{macroDefinitionRecord.Spelling}"; - _fileContentsBuilder.Append('\n'); - _fileContentsBuilder.Append($"const auto {macroName} = "); + _ = _fileContentsBuilder.Append('\n'); + _ = _fileContentsBuilder.Append($"const auto {macroName} = "); - var sourceRangeEnd = tokens[tokens.Length - 1].GetExtent(translationUnitHandle).End; + var sourceRangeEnd = tokens[^1].GetExtent(translationUnitHandle).End; var sourceRangeStart = tokens[1].GetLocation(translationUnitHandle); var sourceRange = CXSourceRange.Create(sourceRangeStart, sourceRangeEnd); var macroValue = GetSourceRangeContents(translationUnitHandle, sourceRange); - _fileContentsBuilder.Append(macroValue); + _ = _fileContentsBuilder.Append(macroValue); - _fileContentsBuilder.Append(';'); - _fileContentsBuilder.Append('\n'); + _ = _fileContentsBuilder.Append(';'); + _ = _fileContentsBuilder.Append('\n'); } else { diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs index 8b11eae8..88a38b26 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs @@ -66,7 +66,17 @@ private void VisitCallExpr(CallExpr callExpr) var outputBuilder = StartCSharpCode(); var calleeDecl = callExpr.CalleeDecl; - if (calleeDecl is FunctionDecl functionDecl) + if (calleeDecl is null) + { + Visit(callExpr.Callee); + VisitArgs(callExpr); + } + else if (calleeDecl is FieldDecl) + { + Visit(callExpr.Callee); + VisitArgs(callExpr); + } + else if (calleeDecl is FunctionDecl functionDecl) { switch (functionDecl.Name) { @@ -94,14 +104,14 @@ private void VisitCallExpr(CallExpr callExpr) } } } - else if (calleeDecl is FieldDecl) + else if (calleeDecl is ParmVarDecl) { Visit(callExpr.Callee); VisitArgs(callExpr); } else { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl?.Kind}'. Generated bindings may be incomplete.", calleeDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl?.DeclKindName}'. Generated bindings may be incomplete.", calleeDecl); } void VisitArgs(CallExpr callExpr) @@ -109,15 +119,21 @@ void VisitArgs(CallExpr callExpr) outputBuilder.Write('('); var args = callExpr.Args; + var needsComma = false; - if (args.Count != 0) + for (var i = 0; i < args.Count; i++) { - Visit(args[0]); - - for (int i = 1; i < args.Count; i++) + if (needsComma) { outputBuilder.Write(", "); - Visit(args[i]); + } + + var arg = args[i]; + Visit(arg); + + if (arg is not CXXDefaultArgExpr) + { + needsComma = true; } } @@ -267,13 +283,11 @@ private void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr cxxBoolLiteralExpr) StopCSharpCode(); } - private void VisitCXXConstCastExpr(CXXConstCastExpr cxxConstCastExpr) - { + private void VisitCXXConstCastExpr(CXXConstCastExpr cxxConstCastExpr) => // C# doesn't have a concept of const pointers so // ignore rather than adding a cast from T* to T* Visit(cxxConstCastExpr.SubExprAsWritten); - } private void VisitCXXConstructExpr(CXXConstructExpr cxxConstructExpr) { @@ -296,7 +310,7 @@ private void VisitCXXConstructExpr(CXXConstructExpr cxxConstructExpr) { Visit(args[0]); - for (int i = 1; i < args.Count; i++) + for (var i = 1; i < args.Count; i++) { outputBuilder.Write(", "); Visit(args[i]); @@ -311,6 +325,39 @@ private void VisitCXXConstructExpr(CXXConstructExpr cxxConstructExpr) StopCSharpCode(); } + private static void VisitCXXDefaultArgExpr(CXXDefaultArgExpr cxxDefaultArgExpr) + { + // Nothing to handle as these just represent optional parameters that + // aren't properly defined + } + + private void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr cxxDependentScopeMemberExpr) + { + var outputBuilder = StartCSharpCode(); + if (!cxxDependentScopeMemberExpr.IsImplicitAccess) + { + Visit(cxxDependentScopeMemberExpr.Base); + + var type = cxxDependentScopeMemberExpr.Base is CXXThisExpr + ? null + : cxxDependentScopeMemberExpr.Base is DeclRefExpr declRefExpr + ? declRefExpr.Decl.Type.CanonicalType + : cxxDependentScopeMemberExpr.Base.Type.CanonicalType; + + if (type is not null and (PointerType or ReferenceType)) + { + outputBuilder.Write("->"); + } + else + { + outputBuilder.Write('.'); + } + } + + outputBuilder.Write(GetRemappedName(cxxDependentScopeMemberExpr.MemberName, cxxDependentScopeMemberExpr, tryRemapOperatorName: false, out _)); + StopCSharpCode(); + } + private void VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr cxxFunctionalCastExpr) { if (cxxFunctionalCastExpr.SubExpr is CXXConstructExpr cxxConstructExpr) @@ -323,6 +370,30 @@ private void VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr cxxFunctionalCastE } } + private void VisitCXXNewExpr(CXXNewExpr cxxNewExpr) + { + var outputBuilder = StartCSharpCode(); + outputBuilder.Write("cxx_new<"); + + + var allocatedTypeName = GetRemappedTypeName(cxxNewExpr, null, cxxNewExpr.AllocatedType, out _); + outputBuilder.Write(allocatedTypeName); + + outputBuilder.Write(">(sizeof("); + outputBuilder.Write(allocatedTypeName); + outputBuilder.Write("))"); + + if (cxxNewExpr.ConstructExpr is not null) + { + outputBuilder.WriteSemicolon(); + outputBuilder.WriteNewline(); + + outputBuilder.WriteIndented(" = "); + VisitCXXConstructExpr(cxxNewExpr.ConstructExpr); + } + StopCSharpCode(); + } + private void VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr cxxNullPtrLiteralExpr) { var outputBuilder = StartCSharpCode(); @@ -337,15 +408,15 @@ private void VisitCXXOperatorCallExpr(CXXOperatorCallExpr cxxOperatorCallExpr) if (calleeDecl is FunctionDecl functionDecl) { + var functionDeclName = GetCursorName(functionDecl); + var args = cxxOperatorCallExpr.Args; + if (functionDecl.DeclContext is CXXRecordDecl) { Visit(cxxOperatorCallExpr.Args[0]); outputBuilder.Write('.'); } - var functionDeclName = GetCursorName(functionDecl); - var args = cxxOperatorCallExpr.Args; - if (IsEnumOperator(functionDecl, functionDeclName)) { switch (functionDeclName) @@ -359,7 +430,7 @@ private void VisitCXXOperatorCallExpr(CXXOperatorCallExpr cxxOperatorCallExpr) { Visit(args[0]); outputBuilder.Write(' '); - outputBuilder.Write(functionDeclName.Substring(8)); + outputBuilder.Write(functionDeclName[8..]); outputBuilder.Write(' '); Visit(args[1]); StopCSharpCode(); @@ -368,7 +439,7 @@ private void VisitCXXOperatorCallExpr(CXXOperatorCallExpr cxxOperatorCallExpr) case "operator~": { - outputBuilder.Write(functionDeclName.Substring(8)); + outputBuilder.Write(functionDeclName[8..]); Visit(args[0]); StopCSharpCode(); return; @@ -385,13 +456,13 @@ private void VisitCXXOperatorCallExpr(CXXOperatorCallExpr cxxOperatorCallExpr) outputBuilder.Write(name); outputBuilder.Write('('); + var firstIndex = (functionDecl.DeclContext is CXXRecordDecl) ? 1 : 0; - if (args.Count != 0) + if (args.Count > firstIndex) { - var firstIndex = (functionDecl.DeclContext is CXXRecordDecl) ? 1 : 0; Visit(args[firstIndex]); - for (int i = firstIndex + 1; i < args.Count; i++) + for (var i = firstIndex + 1; i < args.Count; i++) { outputBuilder.Write(", "); Visit(args[i]); @@ -402,18 +473,51 @@ private void VisitCXXOperatorCallExpr(CXXOperatorCallExpr cxxOperatorCallExpr) } else { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl.Kind}'. Generated bindings may be incomplete.", calleeDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl.DeclKindName}'. Generated bindings may be incomplete.", calleeDecl); } StopCSharpCode(); } + private static void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr cxxPseudoDestructorExpr) + { + // Nothing to generate for pseudo destructors + } + + private void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr cxxTemporaryObjectExpr) => VisitCXXConstructExpr(cxxTemporaryObjectExpr); + private void VisitCXXThisExpr(CXXThisExpr cxxThisExpr) { StartCSharpCode().Write("this"); StopCSharpCode(); } + private void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr cxxUnresolvedConstructExpr) + { + var outputBuilder = StartCSharpCode(); + outputBuilder.Write("new "); + + var constructorName = GetRemappedTypeName(cxxUnresolvedConstructExpr, null, cxxUnresolvedConstructExpr.TypeAsWritten, out _); + outputBuilder.Write(constructorName); + + outputBuilder.Write('('); + var args = cxxUnresolvedConstructExpr.Args; + + if (args.Count != 0) + { + Visit(args[0]); + + for (var i = 1; i < args.Count; i++) + { + outputBuilder.Write(", "); + Visit(args[i]); + } + } + + outputBuilder.Write(')'); + StopCSharpCode(); + } + private void VisitCXXUuidofExpr(CXXUuidofExpr cxxUuidofExpr) { var outputBuilder = StartCSharpCode(); @@ -492,6 +596,16 @@ private void VisitDefaultStmt(DefaultStmt defaultStmt) StopCSharpCode(); } + private void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr dependentScopeDeclRefExpr) + { + var outputBuilder = StartCSharpCode(); + + var name = GetRemappedName(dependentScopeDeclRefExpr.DeclName, dependentScopeDeclRefExpr, tryRemapOperatorName: true, out _); + outputBuilder.Write(EscapeName(name)); + + StopCSharpCode(); + } + private void VisitDoStmt(DoStmt doStmt) { var outputBuilder = StartCSharpCode(); @@ -515,7 +629,7 @@ private void VisitDoStmt(DoStmt doStmt) private void VisitExplicitCastExpr(ExplicitCastExpr explicitCastExpr) { var outputBuilder = StartCSharpCode(); - if (IsPrevContextDecl(out var _) && explicitCastExpr.Type is EnumType enumType) + if (IsPrevContextDecl(out _) && explicitCastExpr.Type is EnumType enumType) { outputBuilder.Write('('); var enumUnderlyingTypeName = GetRemappedTypeName(explicitCastExpr, context: null, enumType.Decl.IntegerType, out _); @@ -525,7 +639,8 @@ private void VisitExplicitCastExpr(ExplicitCastExpr explicitCastExpr) var type = explicitCastExpr.Type; - var typeName = GetRemappedTypeName(explicitCastExpr, context: null, type, out var nativeTypeName); + + var typeName = GetRemappedTypeName(explicitCastExpr, context: null, type, out _); outputBuilder.Write('('); outputBuilder.Write(typeName); @@ -536,12 +651,18 @@ private void VisitExplicitCastExpr(ExplicitCastExpr explicitCastExpr) StopCSharpCode(); } + private void VisitExprWithCleanups(ExprWithCleanups exprWithCleanups) + { + Visit(exprWithCleanups.SubExpr); + Visit(exprWithCleanups.Objects); + } + private void VisitFloatingLiteral(FloatingLiteral floatingLiteral) { var outputBuilder = StartCSharpCode(); if (floatingLiteral.ValueString.EndsWith(".f")) { - outputBuilder.Write(floatingLiteral.ValueString.Substring(0, floatingLiteral.ValueString.Length - 1)); + outputBuilder.Write(floatingLiteral.ValueString[0..^1]); outputBuilder.Write("0f"); } else @@ -733,7 +854,8 @@ void ForEnumConstantDecl(ImplicitCastExpr implicitCastExpr, EnumConstantDecl enu else { var type = implicitCastExpr.Type; - var typeName = GetRemappedTypeName(implicitCastExpr, context: null, type, out var nativeTypeName); + + var typeName = GetRemappedTypeName(implicitCastExpr, context: null, type, out _); outputBuilder.Write('('); outputBuilder.Write(typeName); @@ -762,7 +884,7 @@ void ForArrayType(InitListExpr initListExpr, ArrayType arrayType) outputBuilder.Write("new "); var type = initListExpr.Type; - var typeName = GetRemappedTypeName(initListExpr, context: null, type, out var nativeTypeName); + var typeName = GetRemappedTypeName(initListExpr, context: null, type, out _); outputBuilder.Write(typeName); @@ -803,14 +925,14 @@ void ForArrayType(InitListExpr initListExpr, ArrayType arrayType) outputBuilder.WriteNewline(); outputBuilder.WriteBlockStart(); - for (int i = 0; i < initListExpr.Inits.Count; i++) + for (var i = 0; i < initListExpr.Inits.Count; i++) { outputBuilder.WriteIndentation(); Visit(initListExpr.Inits[i]); outputBuilder.WriteLine(','); } - for (int i = initListExpr.Inits.Count; i < rootSize; i++) + for (var i = initListExpr.Inits.Count; i < rootSize; i++) { outputBuilder.WriteIndentedLine("default,"); } @@ -820,12 +942,28 @@ void ForArrayType(InitListExpr initListExpr, ArrayType arrayType) outputBuilder.NeedsSemicolon = true; } + void ForBuiltinType(InitListExpr initListExpr, BuiltinType builtinType) + { + var inits = initListExpr.Inits; + + if (inits.Count == 1) + { + Visit(inits[0]); + } + else + { + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported init list expression count for builtin type: '{inits.Count}'. Generated bindings may be incomplete.", initListExpr); + } + + outputBuilder.NeedsSemicolon = true; + } + void ForRecordType(InitListExpr initListExpr, RecordType recordType) { outputBuilder.Write("new "); var type = initListExpr.Type; - var typeName = GetRemappedTypeName(initListExpr, context: null, type, out var nativeTypeName); + var typeName = GetRemappedTypeName(initListExpr, context: null, type, out _); outputBuilder.Write(typeName); @@ -844,7 +982,7 @@ void ForRecordType(InitListExpr initListExpr, RecordType recordType) Visit(initListExpr.Inits[2]); initListExpr = (InitListExpr)initListExpr.Inits[3]; - for (int i = 0; i < initListExpr.Inits.Count; i++) + for (var i = 0; i < initListExpr.Inits.Count; i++) { outputBuilder.Write(", "); @@ -860,7 +998,7 @@ void ForRecordType(InitListExpr initListExpr, RecordType recordType) var decl = recordType.Decl; - for (int i = 0; i < initListExpr.Inits.Count; i++) + for (var i = 0; i < initListExpr.Inits.Count; i++) { var init = initListExpr.Inits[i]; @@ -883,16 +1021,40 @@ void ForRecordType(InitListExpr initListExpr, RecordType recordType) } } + void ForPointerType(InitListExpr initListExpr, PointerType pointerType) + { + var inits = initListExpr.Inits; + + if (inits.Count == 1) + { + Visit(inits[0]); + } + else + { + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported init list expression count for pointer type: '{inits.Count}'. Generated bindings may be incomplete.", initListExpr); + } + + outputBuilder.NeedsSemicolon = true; + } + void ForType(InitListExpr initListExpr, Type type) { if (type is ArrayType arrayType) { ForArrayType(initListExpr, arrayType); } + else if (type is BuiltinType builtinType) + { + ForBuiltinType(initListExpr, builtinType); + } else if (type is ElaboratedType elaboratedType) { ForType(initListExpr, elaboratedType.NamedType); } + else if (type is PointerType pointerType) + { + ForPointerType(initListExpr, pointerType); + } else if (type is RecordType recordType) { ForRecordType(initListExpr, recordType); @@ -916,44 +1078,44 @@ private void VisitIntegerLiteral(IntegerLiteral integerLiteral) if (valueString.EndsWith("l", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 1); + valueString = valueString[0..^1]; } else if (valueString.EndsWith("ui8", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 3); + valueString = valueString[0..^3]; } else if (valueString.EndsWith("i8", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 2); + valueString = valueString[0..^2]; } else if (valueString.EndsWith("ui16", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 4); + valueString = valueString[0..^4]; } else if (valueString.EndsWith("i16", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 3); + valueString = valueString[0..^3]; } else if (valueString.EndsWith("i32", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 3); + valueString = valueString[0..^3]; } else if (valueString.EndsWith("i64", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 3) + "L"; + valueString = valueString[0..^3] + "L"; } if (valueString.EndsWith("ul", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 2) + "UL"; + valueString = valueString[0..^2] + "UL"; } else if (valueString.EndsWith("l", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 1) + "L"; + valueString = valueString[0..^1] + "L"; } else if (valueString.EndsWith("u", StringComparison.OrdinalIgnoreCase)) { - valueString = valueString.Substring(0, valueString.Length - 1) + "U"; + valueString = valueString[0..^1] + "U"; } StartCSharpCode().Write(valueString); @@ -963,6 +1125,7 @@ private void VisitIntegerLiteral(IntegerLiteral integerLiteral) private void VisitLabelStmt(LabelStmt labelStmt) { var outputBuilder = StartCSharpCode(); + outputBuilder.Write(labelStmt.Decl.Name); outputBuilder.WriteLine(':'); @@ -971,6 +1134,8 @@ private void VisitLabelStmt(LabelStmt labelStmt) StopCSharpCode(); } + private void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr materializeTemporaryExpr) => Visit(materializeTemporaryExpr.SubExpr); + private void VisitMemberExpr(MemberExpr memberExpr) { var outputBuilder = StartCSharpCode(); @@ -978,22 +1143,11 @@ private void VisitMemberExpr(MemberExpr memberExpr) { Visit(memberExpr.Base); - Type type; + var type = memberExpr.Base is CXXThisExpr + ? null + : memberExpr.Base is DeclRefExpr declRefExpr ? declRefExpr.Decl.Type.CanonicalType : memberExpr.Base.Type.CanonicalType; - if (memberExpr.Base is CXXThisExpr) - { - type = null; - } - else if (memberExpr.Base is DeclRefExpr declRefExpr) - { - type = declRefExpr.Decl.Type.CanonicalType; - } - else - { - type = memberExpr.Base.Type.CanonicalType; - } - - if ((type != null) && ((type is PointerType) || (type is ReferenceType))) + if (type is not null and (PointerType or ReferenceType)) { outputBuilder.Write("->"); } @@ -1007,11 +1161,13 @@ private void VisitMemberExpr(MemberExpr memberExpr) StopCSharpCode(); } - private void VisitNullStmt(NullStmt nullStmt) + private static void VisitNullStmt(NullStmt nullStmt) { // null statements are empty by definition, so nothing to do } + private void VisitPackExpansionExpr(PackExpansionExpr packExpansionExpr) => Visit(packExpansionExpr.Pattern); + private void VisitParenExpr(ParenExpr parenExpr) { var outputBuilder = StartCSharpCode(); @@ -1021,6 +1177,28 @@ private void VisitParenExpr(ParenExpr parenExpr) StopCSharpCode(); } + private void VisitParenListExpr(ParenListExpr parenListExpr) + { + var outputBuilder = StartCSharpCode(); + outputBuilder.Write('('); + + var needsComma = false; + + foreach (var expr in parenListExpr.Exprs) + { + if (needsComma) + { + outputBuilder.Write(", "); + } + + Visit(expr); + needsComma = true; + } + + outputBuilder.Write(')'); + StopCSharpCode(); + } + private void VisitReturnStmt(ReturnStmt returnStmt) { var outputBuilder = StartCSharpCode(); @@ -1247,14 +1425,36 @@ private void VisitStmt(Stmt stmt) break; } - // case CX_StmtClass.CX_StmtClass_CXXTemporaryObjectExpr: - // case CX_StmtClass.CX_StmtClass_CXXDefaultArgExpr: + case CX_StmtClass.CX_StmtClass_CXXTemporaryObjectExpr: + { + VisitCXXTemporaryObjectExpr((CXXTemporaryObjectExpr)stmt); + break; + } + + case CX_StmtClass.CX_StmtClass_CXXDefaultArgExpr: + { + VisitCXXDefaultArgExpr((CXXDefaultArgExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_CXXDefaultInitExpr: // case CX_StmtClass.CX_StmtClass_CXXDeleteExpr: - // case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + + case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + { + VisitCXXDependentScopeMemberExpr((CXXDependentScopeMemberExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_CXXFoldExpr: // case CX_StmtClass.CX_StmtClass_CXXInheritedCtorInitExpr: - // case CX_StmtClass.CX_StmtClass_CXXNewExpr: + + case CX_StmtClass.CX_StmtClass_CXXNewExpr: + { + VisitCXXNewExpr((CXXNewExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_CXXNoexceptExpr: case CX_StmtClass.CX_StmtClass_CXXNullPtrLiteralExpr: @@ -1263,7 +1463,12 @@ private void VisitStmt(Stmt stmt) break; } - // case CX_StmtClass.CX_StmtClass_CXXPseudoDestructorExpr: + case CX_StmtClass.CX_StmtClass_CXXPseudoDestructorExpr: + { + VisitCXXPseudoDestructorExpr((CXXPseudoDestructorExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_CXXScalarValueInitExpr: // case CX_StmtClass.CX_StmtClass_CXXStdInitializerListExpr: @@ -1275,7 +1480,12 @@ private void VisitStmt(Stmt stmt) // case CX_StmtClass.CX_StmtClass_CXXThrowExpr: // case CX_StmtClass.CX_StmtClass_CXXTypeidExpr: - // case CX_StmtClass.CX_StmtClass_CXXUnresolvedConstructExpr: + + case CX_StmtClass.CX_StmtClass_CXXUnresolvedConstructExpr: + { + VisitCXXUnresolvedConstructExpr((CXXUnresolvedConstructExpr)stmt); + break; + } case CX_StmtClass.CX_StmtClass_CXXUuidofExpr: { @@ -1349,7 +1559,13 @@ private void VisitStmt(Stmt stmt) } // case CX_StmtClass.CX_StmtClass_DependentCoawaitExpr: - // case CX_StmtClass.CX_StmtClass_DependentScopeDeclRefExpr: + + case CX_StmtClass.CX_StmtClass_DependentScopeDeclRefExpr: + { + VisitDependentScopeDeclRefExpr((DependentScopeDeclRefExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_DesignatedInitExpr: // case CX_StmtClass.CX_StmtClass_DesignatedInitUpdateExpr: // case CX_StmtClass.CX_StmtClass_ExpressionTraitExpr: @@ -1363,7 +1579,13 @@ private void VisitStmt(Stmt stmt) } // case CX_StmtClass.CX_StmtClass_ConstantExpr: - // case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + + case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + { + VisitExprWithCleanups((ExprWithCleanups)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_FunctionParmPackExpr: // case CX_StmtClass.CX_StmtClass_GNUNullExpr: // case CX_StmtClass.CX_StmtClass_GenericSelectionExpr: @@ -1390,7 +1612,12 @@ private void VisitStmt(Stmt stmt) // case CX_StmtClass.CX_StmtClass_LambdaExpr: // case CX_StmtClass.CX_StmtClass_MSPropertyRefExpr: // case CX_StmtClass.CX_StmtClass_MSPropertySubscriptExpr: - // case CX_StmtClass.CX_StmtClass_MaterializeTemporaryExpr: + + case CX_StmtClass.CX_StmtClass_MaterializeTemporaryExpr: + { + VisitMaterializeTemporaryExpr((MaterializeTemporaryExpr)stmt); + break; + } case CX_StmtClass.CX_StmtClass_MemberExpr: { @@ -1417,9 +1644,24 @@ private void VisitStmt(Stmt stmt) // case CX_StmtClass.CX_StmtClass_ObjCSubscriptRefExpr: // case CX_StmtClass.CX_StmtClass_OffsetOfExpr: // case CX_StmtClass.CX_StmtClass_OpaqueValueExpr: - // case CX_StmtClass.CX_StmtClass_UnresolvedLookupExpr: - // case CX_StmtClass.CX_StmtClass_UnresolvedMemberExpr: - // case CX_StmtClass.CX_StmtClass_PackExpansionExpr: + + case CX_StmtClass.CX_StmtClass_UnresolvedLookupExpr: + { + VisitUnresolvedLookupExpr((UnresolvedLookupExpr)stmt); + break; + } + + case CX_StmtClass.CX_StmtClass_UnresolvedMemberExpr: + { + VisitUnresolvedMemberExpr((UnresolvedMemberExpr)stmt); + break; + } + + case CX_StmtClass.CX_StmtClass_PackExpansionExpr: + { + VisitPackExpansionExpr((PackExpansionExpr)stmt); + break; + } case CX_StmtClass.CX_StmtClass_ParenExpr: { @@ -1427,7 +1669,12 @@ private void VisitStmt(Stmt stmt) break; } - // case CX_StmtClass.CX_StmtClass_ParenListExpr: + case CX_StmtClass.CX_StmtClass_ParenListExpr: + { + VisitParenListExpr((ParenListExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_PredefinedExpr: // case CX_StmtClass.CX_StmtClass_PseudoObjectExpr: // case CX_StmtClass.CX_StmtClass_ShuffleVectorExpr: @@ -1441,7 +1688,12 @@ private void VisitStmt(Stmt stmt) break; } - // case CX_StmtClass.CX_StmtClass_SubstNonTypeTemplateParmExpr: + case CX_StmtClass.CX_StmtClass_SubstNonTypeTemplateParmExpr: + { + VisitSubstNonTypeTemplateParmExpr((SubstNonTypeTemplateParmExpr)stmt); + break; + } + // case CX_StmtClass.CX_StmtClass_SubstNonTypeTemplateParmPackExpr: // case CX_StmtClass.CX_StmtClass_TypeTraitExpr: // case CX_StmtClass.CX_StmtClass_TypoExpr: @@ -1481,7 +1733,7 @@ private void VisitStmt(Stmt stmt) context = $" in {GetCursorQualifiedName(namedDecl)}"; } - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported statement: '{stmt.StmtClass}'{context}. Generated bindings may be incomplete.", stmt); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported statement: '{stmt.StmtClassName}'{context}. Generated bindings may be incomplete.", stmt); break; } } @@ -1493,7 +1745,7 @@ private void VisitStmts(IReadOnlyList stmts) var lastIndex = stmts.Count - 1; var previousStmt = null as Stmt; - for (int i = 0; i < lastIndex; i++) + for (var i = 0; i < lastIndex; i++) { var stmt = stmts[i]; @@ -1587,18 +1839,17 @@ private void VisitStringLiteral(StringLiteral stringLiteral) StopCSharpCode(); } + private void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr substNonTypeTemplateParmExpr) => Visit(substNonTypeTemplateParmExpr.Replacement); + private void VisitSwitchStmt(SwitchStmt switchStmt) { var outputBuilder = StartCSharpCode(); outputBuilder.Write("switch ("); - Visit(switchStmt.Cond); - outputBuilder.WriteLine(')'); VisitBody(switchStmt.Body); - StopCSharpCode(); } @@ -1607,13 +1858,11 @@ private void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr unaryExprOrT var outputBuilder = StartCSharpCode(); var argumentType = unaryExprOrTypeTraitExpr.TypeOfArgument; - long size32; - long size64; long alignment32 = -1; long alignment64 = -1; - GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out size32, out size64); + GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out var size32, out var size64); switch (unaryExprOrTypeTraitExpr.Kind) { @@ -1634,31 +1883,38 @@ private void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr unaryExprOrT if (IsPrevContextStmt(out var callExpr)) { - var index = callExpr.Args.IndexOf(unaryExprOrTypeTraitExpr); + var args = callExpr.Args; + var index = -1; - // If we didn't find the expression, try and find it under an implicit cast - if (index == -1) + for (var i = 0; i < args.Count; i++) { - for (int i = 0; i < callExpr.Args.Count; i++) + var arg = args[i]; + + if (IsStmtAsWritten(arg, unaryExprOrTypeTraitExpr)) { - var arg = callExpr.Args[i]; - if (arg is ImplicitCastExpr implicitCastExpr && implicitCastExpr.SubExprAsWritten == unaryExprOrTypeTraitExpr) - { - index = i; - break; - } + index = i; + break; } } + if (index == -1) + { + AddDiagnostic(DiagnosticLevel.Error, $"Failed to locate index of '{unaryExprOrTypeTraitExpr}' in call expression. Generated bindings may be incomplete.", callExpr); + } + var calleeDecl = callExpr.CalleeDecl; - if (calleeDecl is FunctionDecl functionDecl) + if (calleeDecl is null) + { + parentType = callExpr.Callee.Type.CanonicalType; + } + else if (calleeDecl is FunctionDecl functionDecl) { parentType = functionDecl.Parameters[index].Type.CanonicalType; } else { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl?.Kind}'. Generated bindings may be incomplete.", calleeDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported callee declaration: '{calleeDecl?.DeclKindName}'. Generated bindings may be incomplete.", calleeDecl); } } @@ -1676,10 +1932,10 @@ private void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr unaryExprOrT if (parentType != null) { - needsCast = (parentType.Kind == CXTypeKind.CXType_UInt); - needsCast |= (parentType.Kind == CXTypeKind.CXType_ULong); + needsCast = parentType.Kind == CXTypeKind.CXType_UInt; + needsCast |= parentType.Kind == CXTypeKind.CXType_ULong; needsCast &= !IsSupportedFixedSizedBufferType(typeName); - needsCast &= (argumentType.CanonicalType.Kind != CXTypeKind.CXType_Enum); + needsCast &= argumentType.CanonicalType.Kind != CXTypeKind.CXType_Enum; } if (needsCast) @@ -1719,7 +1975,7 @@ private void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr unaryExprOrT default: { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported unary or type trait expression: '{unaryExprOrTypeTraitExpr.Kind}'. Generated bindings may be incomplete.", unaryExprOrTypeTraitExpr); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported unary or type trait expression: '{unaryExprOrTypeTraitExpr.StmtClassName}'. Generated bindings may be incomplete.", unaryExprOrTypeTraitExpr); break; } } @@ -1762,7 +2018,7 @@ private void VisitUnaryOperator(UnaryOperator unaryOperator) Visit(subExpr); outputBuilder.Write(" == 0"); } - else if ((canonicalType is PointerType) || (canonicalType is ReferenceType)) + else if (canonicalType is PointerType or ReferenceType) { Visit(subExpr); outputBuilder.Write(" == null"); @@ -1799,6 +2055,38 @@ private void VisitUnaryOperator(UnaryOperator unaryOperator) StopCSharpCode(); } + private void VisitUnresolvedLookupExpr(UnresolvedLookupExpr unresolvedLookupExpr) + { + var outputBuilder = StartCSharpCode(); + outputBuilder.Write(GetRemappedName(unresolvedLookupExpr.Name, unresolvedLookupExpr, tryRemapOperatorName: false, out _)); + StopCSharpCode(); + } + + private void VisitUnresolvedMemberExpr(UnresolvedMemberExpr unresolvedMemberExpr) + { + var outputBuilder = StartCSharpCode(); + if (!unresolvedMemberExpr.IsImplicitAccess) + { + Visit(unresolvedMemberExpr.Base); + + var type = unresolvedMemberExpr.Base is CXXThisExpr + ? null + : unresolvedMemberExpr.Base is DeclRefExpr declRefExpr ? declRefExpr.Decl.Type.CanonicalType : unresolvedMemberExpr.Base.Type.CanonicalType; + + if (type is not null and (PointerType or ReferenceType)) + { + outputBuilder.Write("->"); + } + else + { + outputBuilder.Write('.'); + } + } + + outputBuilder.Write(GetRemappedName(unresolvedMemberExpr.MemberName, unresolvedMemberExpr, tryRemapOperatorName: true, out _)); + StopCSharpCode(); + } + private void VisitWhileStmt(WhileStmt whileStmt) { var outputBuilder = StartCSharpCode(); diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs index 355747f3..4e2fbce0 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.cs @@ -17,7 +17,7 @@ namespace ClangSharp public sealed partial class PInvokeGenerator : IDisposable { private const int DefaultStreamWriterBufferSize = 1024; - private static readonly Encoding defaultStreamWriterEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + private static readonly Encoding s_defaultStreamWriterEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly CXIndex _index; private readonly OutputBuilderFactory _outputBuilderFactory; @@ -53,7 +53,7 @@ public PInvokeGenerator(PInvokeGeneratorConfiguration config, Func { var directoryPath = Path.GetDirectoryName(path); - Directory.CreateDirectory(directoryPath); + _ = Directory.CreateDirectory(directoryPath); return new FileStream(path, FileMode.Create); }); _fileContentsBuilder = new StringBuilder(); @@ -84,8 +84,8 @@ public void Close() { Stream stream = null; IOutputBuilder methodClassOutputBuilder = null; - bool emitNamespaceDeclaration = true; - bool leaveStreamOpen = false; + var emitNamespaceDeclaration = true; + var leaveStreamOpen = false; foreach (var foundUuid in _uuidsToGenerate) { @@ -139,7 +139,7 @@ public void Close() if (hasAnyContents) { - using var sw = new StreamWriter(stream, defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); + using var sw = new StreamWriter(stream, s_defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); sw.NewLine = "\n"; if (_config.OutputMode == PInvokeGeneratorOutputMode.CSharp) @@ -214,7 +214,7 @@ public void Close() CloseOutputBuilder(stream, methodClassOutputBuilder, isMethodClass: true, leaveStreamOpen, emitNamespaceDeclaration); } - using var sw = new StreamWriter(stream, defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); + using var sw = new StreamWriter(stream, s_defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); sw.NewLine = "\n"; if (_config.OutputMode == PInvokeGeneratorOutputMode.CSharp) @@ -230,7 +230,7 @@ public void Close() _context.Clear(); _diagnostics.Clear(); - _fileContentsBuilder.Clear(); + _ = _fileContentsBuilder.Clear(); _generatedUuids.Clear(); _outputBuilderFactory.Clear(); _uuidsToGenerate.Clear(); @@ -261,7 +261,7 @@ public void GenerateBindings(TranslationUnit translationUnit, string filePath, s { using var diagnostic = translationUnit.Handle.GetDiagnostic(i); - if ((diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Error) || (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Fatal)) + if (diagnostic.Severity is CXDiagnosticSeverity.CXDiagnostic_Error or CXDiagnosticSeverity.CXDiagnostic_Fatal) { invalidTranslationUnitHandle = true; errorDiagnostics.Append(' ', 4); @@ -358,7 +358,7 @@ private void CloseOutputBuilder(Stream stream, IOutputBuilder outputBuilder, boo throw new ArgumentNullException(nameof(outputBuilder)); } - using var sw = new StreamWriter(stream, defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); + using var sw = new StreamWriter(stream, s_defaultStreamWriterEncoding, DefaultStreamWriterBufferSize, leaveStreamOpen); sw.NewLine = "\n"; if (_config.GenerateMultipleFiles) @@ -480,8 +480,8 @@ void ForCSharp(CSharpOutputBuilder csharpOutputBuilder) void ForXml(XmlOutputBuilder xmlOutputBuilder) { - const string indent = " "; - var indentationString = indent; + const string Indent = " "; + var indentationString = Indent; if (emitNamespaceDeclaration) { @@ -491,7 +491,7 @@ void ForXml(XmlOutputBuilder xmlOutputBuilder) sw.WriteLine("\">"); } - indentationString += indent; + indentationString += Indent; if (isMethodClass) { @@ -506,7 +506,7 @@ void ForXml(XmlOutputBuilder xmlOutputBuilder) } sw.WriteLine('>'); - indentationString += indent; + indentationString += Indent; } foreach (var line in xmlOutputBuilder.Contents) @@ -524,14 +524,14 @@ void ForXml(XmlOutputBuilder xmlOutputBuilder) if (isMethodClass) { - indentationString = indentationString.Substring(0, indentationString.Length - indent.Length); + indentationString = indentationString.Substring(0, indentationString.Length - Indent.Length); sw.Write(indentationString); sw.WriteLine(""); } if (_config.GenerateMultipleFiles) { - indentationString = indentationString.Substring(0, indentationString.Length - indent.Length); + indentationString = indentationString.Substring(0, indentationString.Length - Indent.Length); sw.Write(indentationString); sw.WriteLine(""); sw.WriteLine(""); @@ -556,7 +556,7 @@ private void Dispose(bool isDisposing) _index.Dispose(); } - private string EscapeName(string name) + private static string EscapeName(string name) { switch (name) { @@ -653,7 +653,7 @@ private string EscapeAndStripName(string name) { if (name.StartsWith(_config.MethodPrefixToStrip)) { - name = name.Substring(_config.MethodPrefixToStrip.Length); + name = name[_config.MethodPrefixToStrip.Length..]; } return EscapeName(name); @@ -709,7 +709,7 @@ private AccessSpecifier GetAccessSpecifier(NamedDecl namedDecl) return name; } - private string GetAnonymousName(Cursor cursor, string kind) + private static string GetAnonymousName(Cursor cursor, string kind) { cursor.Location.GetFileLocation(out var file, out var line, out var column, out _); var fileName = Path.GetFileNameWithoutExtension(file.Name.ToString()); @@ -767,7 +767,7 @@ private Type[] GetBitfieldCount(RecordDecl recordDecl) type = enumType.Decl.IntegerType; } - types[types.Count - 1] = type; + types[^1] = type; } remainingBits -= fieldDecl.BitWidthValue; @@ -779,7 +779,7 @@ private Type[] GetBitfieldCount(RecordDecl recordDecl) private CallingConvention GetCallingConvention(Cursor cursor, CXCallingConv callingConvention, string remappedName) { - if (_config.WithCallConvs.TryGetValue(remappedName, out string callConv) || _config.WithCallConvs.TryGetValue("*", out callConv)) + if (_config.WithCallConvs.TryGetValue(remappedName, out var callConv) || _config.WithCallConvs.TryGetValue("*", out callConv)) { if (Enum.TryParse(callConv, true, out CallingConvention callConvEnum)) { @@ -818,9 +818,9 @@ private CallingConvention GetCallingConvention(Cursor cursor, CXCallingConv call default: { - const CallingConvention name = CallingConvention.Winapi; - AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported calling convention: '{callingConvention}'. Falling back to '{name}'.", cursor); - return name; + const CallingConvention Name = CallingConvention.Winapi; + AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported calling convention: '{callingConvention}'. Falling back to '{Name}'.", cursor); + return Name; } } } @@ -829,19 +829,21 @@ private string GetCursorName(NamedDecl namedDecl) { var name = namedDecl.Name.Replace('\\', '/'); - if (string.IsNullOrWhiteSpace(name)) + if (namedDecl is CXXConstructorDecl cxxConstructorDecl) + { + name = GetCursorName(cxxConstructorDecl.Parent); + } + else if (namedDecl is CXXDestructorDecl) + { + name = "Dispose"; + } + else if (string.IsNullOrWhiteSpace(name)) { if (namedDecl is TypeDecl typeDecl) { - if ((typeDecl is TagDecl tagDecl) && tagDecl.Handle.IsAnonymous) - { - name = GetAnonymousName(tagDecl, tagDecl.TypeForDecl.KindSpelling); - - } - else - { - name = GetTypeName(namedDecl, context: null, typeDecl.TypeForDecl, out var nativeTypeName); - } + name = (typeDecl is TagDecl tagDecl) && tagDecl.Handle.IsAnonymous + ? GetAnonymousName(tagDecl, tagDecl.TypeForDecl.KindSpelling) + : GetTypeName(namedDecl, context: null, typeDecl.TypeForDecl, out _); } else if (namedDecl is ParmVarDecl) { @@ -851,24 +853,11 @@ private string GetCursorName(NamedDecl namedDecl) { name = GetAnonymousName(fieldDecl, fieldDecl.CursorKindSpelling); } - else if (namedDecl is CXXConstructorDecl cxxConstructorDecl) - { - name = GetCursorName(cxxConstructorDecl.Parent); - } - else if (namedDecl is CXXDestructorDecl cxxDestructorDecl) - { - name = "~"; - name += GetCursorName(cxxDestructorDecl.Parent); - } else { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported anonymous named declaration: '{namedDecl.Kind}'.", namedDecl); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported anonymous named declaration: '{namedDecl.DeclKindName}'.", namedDecl); } } - else if (namedDecl is CXXDestructorDecl) - { - name = "Finalize"; - } Debug.Assert(!string.IsNullOrWhiteSpace(name)); return name; @@ -877,23 +866,29 @@ private string GetCursorName(NamedDecl namedDecl) private string GetCursorQualifiedName(NamedDecl namedDecl, bool truncateFunctionParameters = false) { var parts = new Stack(); + Decl decl = namedDecl; - for (Decl decl = namedDecl; decl.DeclContext != null; decl = (Decl)decl.DeclContext) + do { - if (decl is NamedDecl) + if (decl is NamedDecl parentNamedDecl) { - parts.Push((NamedDecl)decl); + parts.Push(parentNamedDecl); } + + decl = (decl.DeclContext is null) && (decl is CXXMethodDecl cxxMethodDecl) + ? cxxMethodDecl.ThisObjectType.AsCXXRecordDecl + : (Decl)decl.DeclContext; } + while (decl != null); var qualifiedName = new StringBuilder(); - NamedDecl part = parts.Pop(); + var part = parts.Pop(); while (parts.Count != 0) { AppendNamedDecl(part, GetCursorName(part), qualifiedName); - qualifiedName.Append("::"); + _ = qualifiedName.Append("::"); part = parts.Pop(); } @@ -908,35 +903,35 @@ void AppendFunctionParameters(CXType functionType, StringBuilder qualifiedName) return; } - qualifiedName.Append('('); + _ = qualifiedName.Append('('); if (functionType.NumArgTypes != 0) { - qualifiedName.Append(functionType.GetArgType(0).Spelling); + _ = qualifiedName.Append(functionType.GetArgType(0).Spelling); for (uint i = 1; i < functionType.NumArgTypes; i++) { - qualifiedName.Append(','); - qualifiedName.Append(' '); - qualifiedName.Append(functionType.GetArgType(i).Spelling); + _ = qualifiedName.Append(','); + _ = qualifiedName.Append(' '); + _ = qualifiedName.Append(functionType.GetArgType(i).Spelling); } } - qualifiedName.Append(')'); - qualifiedName.Append(':'); + _ = qualifiedName.Append(')'); + _ = qualifiedName.Append(':'); - qualifiedName.Append(functionType.ResultType.Spelling); + _ = qualifiedName.Append(functionType.ResultType.Spelling); if (functionType.ExceptionSpecificationType == CXCursor_ExceptionSpecificationKind.CXCursor_ExceptionSpecificationKind_NoThrow) { - qualifiedName.Append(' '); - qualifiedName.Append("nothrow"); + _ = qualifiedName.Append(' '); + _ = qualifiedName.Append("nothrow"); } } void AppendNamedDecl(NamedDecl namedDecl, string name, StringBuilder qualifiedName) { - qualifiedName.Append(name); + _ = qualifiedName.Append(name); if (namedDecl is FunctionDecl functionDecl) { @@ -963,19 +958,19 @@ void AppendTemplateArgument(TemplateArgument templateArgument, Decl parentDecl, { case CXTemplateArgumentKind.CXTemplateArgumentKind_Type: { - qualifiedName.Append(templateArgument.AsType.AsString); + _ = qualifiedName.Append(templateArgument.AsType.AsString); break; } case CXTemplateArgumentKind.CXTemplateArgumentKind_Integral: { - qualifiedName.Append(templateArgument.AsIntegral); + _ = qualifiedName.Append(templateArgument.AsIntegral); break; } default: { - qualifiedName.Append('?'); + _ = qualifiedName.Append('?'); break; } } @@ -983,7 +978,7 @@ void AppendTemplateArgument(TemplateArgument templateArgument, Decl parentDecl, void AppendTemplateArguments(ClassTemplateSpecializationDecl classTemplateSpecializationDecl, StringBuilder qualifiedName) { - qualifiedName.Append('<'); + _ = qualifiedName.Append('<'); var templateArgs = classTemplateSpecializationDecl.TemplateArgs; @@ -991,40 +986,40 @@ void AppendTemplateArguments(ClassTemplateSpecializationDecl classTemplateSpecia { AppendTemplateArgument(templateArgs[0], classTemplateSpecializationDecl, qualifiedName); - for (int i = 1; i < templateArgs.Count; i++) + for (var i = 1; i < templateArgs.Count; i++) { - qualifiedName.Append(','); - qualifiedName.Append(' '); + _ = qualifiedName.Append(','); + _ = qualifiedName.Append(' '); AppendTemplateArgument(templateArgs[i], classTemplateSpecializationDecl, qualifiedName); } } - qualifiedName.Append('>'); + _ = qualifiedName.Append('>'); } void AppendTemplateParameters(TemplateDecl templateDecl, StringBuilder qualifiedName) { - qualifiedName.Append('<'); + _ = qualifiedName.Append('<'); var templateParameters = templateDecl.TemplateParameters; if (templateParameters.Any()) { - qualifiedName.Append(templateParameters[0].Name); + _ = qualifiedName.Append(templateParameters[0].Name); - for (int i = 1; i < templateParameters.Count; i++) + for (var i = 1; i < templateParameters.Count; i++) { - qualifiedName.Append(','); - qualifiedName.Append(' '); - qualifiedName.Append(templateParameters[i].Name); + _ = qualifiedName.Append(','); + _ = qualifiedName.Append(' '); + _ = qualifiedName.Append(templateParameters[i].Name); } } - qualifiedName.Append('>'); + _ = qualifiedName.Append('>'); } } - private Expr GetExprAsWritten(Expr expr, bool removeParens) + private static Expr GetExprAsWritten(Expr expr, bool removeParens) { do { @@ -1046,9 +1041,9 @@ private Expr GetExprAsWritten(Expr expr, bool removeParens) private static CXXRecordDecl GetRecordDeclForBaseSpecifier(CXXBaseSpecifier cxxBaseSpecifier) { - Type baseType = cxxBaseSpecifier.Type; + var baseType = cxxBaseSpecifier.Type; - while (!(baseType is RecordType)) + while (baseType is not RecordType) { if (baseType is AttributedType attributedType) { @@ -1079,41 +1074,41 @@ private static CXXRecordDecl GetRecordDeclForBaseSpecifier(CXXBaseSpecifier cxxB private string GetRemappedCursorName(NamedDecl namedDecl) { var name = GetCursorQualifiedName(namedDecl); - var remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true); + var remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true, out var wasRemapped); - if (remappedName != name) + if (wasRemapped) { return remappedName; } name = name.Replace("::", "."); - remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true); + remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true, out wasRemapped); - if (remappedName != name) + if (wasRemapped) { return remappedName; } name = GetCursorQualifiedName(namedDecl, truncateFunctionParameters: true); - remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true); + remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true, out wasRemapped); - if (remappedName != name) + if (wasRemapped) { return remappedName; } name = name.Replace("::", "."); - remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true); + remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true, out wasRemapped); - if (remappedName != name) + if (wasRemapped) { return remappedName; } name = GetCursorName(namedDecl); - remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true); + remappedName = GetRemappedName(name, namedDecl, tryRemapOperatorName: true, out wasRemapped); - if (remappedName != name) + if (wasRemapped) { return remappedName; } @@ -1154,15 +1149,17 @@ private string GetRemappedCursorName(NamedDecl namedDecl) return remappedName; } - private string GetRemappedName(string name, Cursor cursor, bool tryRemapOperatorName) + private string GetRemappedName(string name, Cursor cursor, bool tryRemapOperatorName, out bool wasRemapped) { - if (_config.RemappedNames.TryGetValue(name, out string remappedName)) + if (_config.RemappedNames.TryGetValue(name, out var remappedName)) { + wasRemapped = true; return AddUsingDirectiveIfNeeded(remappedName); } - if (name.StartsWith("const ") && _config.RemappedNames.TryGetValue(name.Substring(6), out remappedName)) + if (name.StartsWith("const ") && _config.RemappedNames.TryGetValue(name[6..], out remappedName)) { + wasRemapped = true; return AddUsingDirectiveIfNeeded(remappedName); } @@ -1170,9 +1167,11 @@ private string GetRemappedName(string name, Cursor cursor, bool tryRemapOperator if ((cursor is FunctionDecl functionDecl) && tryRemapOperatorName && TryRemapOperatorName(ref remappedName, functionDecl)) { + wasRemapped = true; return AddUsingDirectiveIfNeeded(remappedName); } + wasRemapped = false; return AddUsingDirectiveIfNeeded(remappedName); string AddUsingDirectiveIfNeeded(string remappedName) @@ -1189,83 +1188,86 @@ string AddUsingDirectiveIfNeeded(string remappedName) private string GetRemappedTypeName(Cursor cursor, Cursor context, Type type, out string nativeTypeName) { var name = GetTypeName(cursor, context, type, out nativeTypeName); - name = GetRemappedName(name, cursor, tryRemapOperatorName: false); - - var canonicalType = type.CanonicalType; + var remappedName = GetRemappedName(name, cursor, tryRemapOperatorName: false, out var wasRemapped); - if ((canonicalType is ConstantArrayType constantArrayType) && (constantArrayType.ElementType is RecordType)) + if (!wasRemapped) { - canonicalType = constantArrayType.ElementType; - } + var canonicalType = type.CanonicalType; - if ((canonicalType is RecordType recordType) && name.StartsWith("__AnonymousRecord_")) - { - var recordDecl = recordType.Decl; - name = "_Anonymous"; + if ((canonicalType is ConstantArrayType constantArrayType) && (constantArrayType.ElementType is RecordType)) + { + canonicalType = constantArrayType.ElementType; + } - if (recordDecl.Parent is RecordDecl parentRecordDecl) + if ((canonicalType is RecordType recordType) && remappedName.StartsWith("__AnonymousRecord_")) { - var matchingField = parentRecordDecl.Fields.Where((fieldDecl) => fieldDecl.Type.CanonicalType == recordType).FirstOrDefault(); + var recordDecl = recordType.Decl; + remappedName = "_Anonymous"; - if (matchingField != null) + if (recordDecl.Parent is RecordDecl parentRecordDecl) { - name = "_"; - name += GetRemappedCursorName(matchingField); - } - else - { - var index = 0; + var matchingField = parentRecordDecl.Fields.Where((fieldDecl) => fieldDecl.Type.CanonicalType == recordType).FirstOrDefault(); - if (parentRecordDecl.AnonymousRecords.Count > 1) + if (matchingField != null) { - index = parentRecordDecl.AnonymousRecords.IndexOf(cursor) + 1; + remappedName = "_"; + remappedName += GetRemappedCursorName(matchingField); } - - while ((parentRecordDecl.IsAnonymousStructOrUnion) && (parentRecordDecl.IsUnion == recordType.Decl.IsUnion)) + else { - index += 1; + var index = 0; + + if (parentRecordDecl.AnonymousRecords.Count > 1) + { + index = parentRecordDecl.AnonymousRecords.IndexOf(cursor) + 1; + } - if (parentRecordDecl.Parent is RecordDecl parentRecordDeclParent) + while (parentRecordDecl.IsAnonymousStructOrUnion && (parentRecordDecl.IsUnion == recordType.Decl.IsUnion)) { - if (parentRecordDeclParent.AnonymousRecords.Count > 0) + index += 1; + + if (parentRecordDecl.Parent is RecordDecl parentRecordDeclParent) { - index += parentRecordDeclParent.AnonymousRecords.Count - 1; + if (parentRecordDeclParent.AnonymousRecords.Count > 0) + { + index += parentRecordDeclParent.AnonymousRecords.Count - 1; + } + parentRecordDecl = parentRecordDeclParent; } - parentRecordDecl = parentRecordDeclParent; } - } - if (index != 0) - { - name += index.ToString(); + if (index != 0) + { + remappedName += index.ToString(); + } } - } - } - - name += $"_e__{(recordDecl.IsUnion ? "Union" : "Struct")}"; - } - else if ((canonicalType is EnumType enumType) && name.StartsWith("__AnonymousEnum_")) - { - name = GetRemappedTypeName(enumType.Decl, context: null, enumType.Decl.IntegerType, out _); - } - else if (cursor is EnumDecl enumDecl) - { - var enumDeclName = GetRemappedCursorName(enumDecl); + } - if (enumDecl.Enumerators.Any((enumConstantDecl) => IsForceDwordOrForceUInt(enumDeclName, enumConstantDecl))) + remappedName += $"_e__{(recordDecl.IsUnion ? "Union" : "Struct")}"; + } + else if ((canonicalType is EnumType enumType) && remappedName.StartsWith("__AnonymousEnum_")) { - name = "uint"; + remappedName = GetRemappedTypeName(enumType.Decl, context: null, enumType.Decl.IntegerType, out _); } + else if (cursor is EnumDecl enumDecl) + { + var enumDeclName = GetRemappedCursorName(enumDecl); + + if (enumDecl.Enumerators.Any((enumConstantDecl) => IsForceDwordOrForceUInt(enumDeclName, enumConstantDecl))) + { + remappedName = "uint"; + } - WithType("*", ref name, ref nativeTypeName); - WithType(enumDeclName, ref name, ref nativeTypeName); + WithType("*", ref remappedName, ref nativeTypeName); + WithType(enumDeclName, ref remappedName, ref nativeTypeName); + } } - if (nativeTypeName.Equals(name)) + if (nativeTypeName.Equals(remappedName) || nativeTypeName.Replace(" ", "").Equals(remappedName)) { nativeTypeName = string.Empty; } - return name; + return remappedName; bool IsForceDwordOrForceUInt(string enumDeclName, EnumConstantDecl enumConstantDecl) { @@ -1274,7 +1276,7 @@ bool IsForceDwordOrForceUInt(string enumDeclName, EnumConstantDecl enumConstantD } } - private string GetSourceRangeContents(CXTranslationUnit translationUnit, CXSourceRange sourceRange) + private static string GetSourceRangeContents(CXTranslationUnit translationUnit, CXSourceRange sourceRange) { sourceRange.Start.GetFileLocation(out var startFile, out var startLine, out var startColumn, out var startOffset); sourceRange.End.GetFileLocation(out var endFile, out var endLine, out var endColumn, out var endOffset); @@ -1301,17 +1303,17 @@ private string GetTypeName(Cursor cursor, Cursor context, Type type, out string if (type is ArrayType arrayType) { - name = GetTypeName(cursor, context, arrayType.ElementType, out var nativeElementTypeName); + name = GetTypeName(cursor, context, arrayType.ElementType, out _); - if ((cursor is FunctionDecl) || (cursor is ParmVarDecl)) + if (cursor is FunctionDecl or ParmVarDecl) { - name = GetRemappedName(name, cursor, tryRemapOperatorName: false); + name = GetRemappedName(name, cursor, tryRemapOperatorName: false, out _); name += '*'; } } else if (type is AttributedType attributedType) { - name = GetTypeName(cursor, context, attributedType.ModifiedType, out var nativeModifiedTypeName); + name = GetTypeName(cursor, context, attributedType.ModifiedType, out _); } else if (type is BuiltinType) { @@ -1430,53 +1432,133 @@ private string GetTypeName(Cursor cursor, Cursor context, Type type, out string break; } + case CXTypeKind.CXType_NullPtr: + { + name = "null"; + break; + } + default: { - AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported builtin type: '{type.TypeClass}'. Falling back '{name}'.", cursor); + AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported builtin type: '{type.KindSpelling}'. Falling back '{name}'.", cursor); break; } } } else if (type is DeducedType deducedType) { - name = GetTypeName(cursor, context, deducedType.CanonicalType, out var nativeDeducedTypeName); + name = GetTypeName(cursor, context, deducedType.CanonicalType, out _); + } + else if (type is DependentNameType dependentNameType) + { + if (dependentNameType.IsSugared) + { + name = GetTypeName(cursor, context, dependentNameType.Desugar, out _); + } + else + { + // The default name should be correct + } } else if (type is ElaboratedType elaboratedType) { - name = GetTypeName(cursor, context, elaboratedType.NamedType, out var nativeNamedTypeName); + name = GetTypeName(cursor, context, elaboratedType.NamedType, out _); } else if (type is FunctionType functionType) { - name = GetTypeNameForPointeeType(cursor, context, functionType, out var nativeFunctionTypeName); + name = GetTypeNameForPointeeType(cursor, context, functionType, out _); + } + else if (type is InjectedClassNameType injectedClassNameType) + { + name = GetTypeName(cursor, context, injectedClassNameType.InjectedTST, out _); + } + else if (type is PackExpansionType packExpansionType) + { + name = GetTypeName(cursor, context, packExpansionType.Pattern, out _); } else if (type is PointerType pointerType) { - name = GetTypeNameForPointeeType(cursor, context, pointerType.PointeeType, out var nativePointeeTypeName); + name = GetTypeNameForPointeeType(cursor, context, pointerType.PointeeType, out _); } else if (type is ReferenceType referenceType) { - name = GetTypeNameForPointeeType(cursor, context, referenceType.PointeeType, out var nativePointeeTypeName); + name = GetTypeNameForPointeeType(cursor, context, referenceType.PointeeType, out _); + } + else if (type is SubstTemplateTypeParmType substTemplateTypeParmType) + { + name = GetTypeName(cursor, context, substTemplateTypeParmType.ReplacementType, out _); + } + else if (type is TagType tagType) + { + if (tagType.Decl.Handle.IsAnonymous) + { + name = GetAnonymousName(tagType.Decl, tagType.KindSpelling); + } + else if (tagType.Handle.IsConstQualified) + { + name = GetTypeName(cursor, context, tagType.Decl.TypeForDecl, out _); + } + else + { + // The default name should be correct + } + + if (name.Contains("::")) + { + name = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).Last(); + name = GetRemappedName(name, cursor, tryRemapOperatorName: false, out _); + } } else if (type is TemplateSpecializationType templateSpecializationType) { var nameBuilder = new StringBuilder(); - var templateTypeDecl = ((RecordType)templateSpecializationType.CanonicalType).Decl; - nameBuilder.Append(GetRemappedName(templateTypeDecl.Name, templateTypeDecl, tryRemapOperatorName: false)); + var templateTypeDecl = templateSpecializationType.CanonicalType is RecordType recordType + ? recordType.Decl + : (NamedDecl)templateSpecializationType.TemplateName.AsTemplateDecl; - nameBuilder.Append('<'); + _ = nameBuilder.Append(GetRemappedName(templateTypeDecl.Name, templateTypeDecl, tryRemapOperatorName: false, out _)); + _ = nameBuilder.Append('<'); - bool shouldWritePrecedingComma = false; + var shouldWritePrecedingComma = false; foreach (var arg in templateSpecializationType.Args) { if (shouldWritePrecedingComma) { - nameBuilder.Append(','); - nameBuilder.Append(' '); + _ = nameBuilder.Append(','); + _ = nameBuilder.Append(' '); } - var typeName = GetRemappedTypeName(cursor, context: null, arg.AsType, out _); + var typeName = ""; + + switch (arg.Kind) + { + case CXTemplateArgumentKind.CXTemplateArgumentKind_Type: + { + typeName = GetRemappedTypeName(cursor, context: null, arg.AsType, out var nativeAsTypeName); + break; + } + + case CXTemplateArgumentKind.CXTemplateArgumentKind_Expression: + { + var oldOutputBuilder = _outputBuilder; + _outputBuilder = new CSharpOutputBuilder("ClangSharp_TemplateSpecializationType_AsExpr"); + + Visit(arg.AsExpr); + typeName = _outputBuilder.ToString(); + + _outputBuilder = oldOutputBuilder; + break; + } + + default: + { + typeName = name; + AddDiagnostic(DiagnosticLevel.Warning, $"Unsupported template argument kind: '{arg.Kind}'. Falling back '{name}'.", cursor); + break; + } + } if (typeName == "bool") { @@ -1491,35 +1573,25 @@ private string GetTypeName(Cursor cursor, Cursor context, Type type, out string _outputBuilder.EmitSystemSupport(); } - nameBuilder.Append(typeName); + _ = nameBuilder.Append(typeName); shouldWritePrecedingComma = true; } - nameBuilder.Append('>'); + _ = nameBuilder.Append('>'); name = nameBuilder.ToString(); } - else if (type is TagType tagType) + else if (type is TemplateTypeParmType templateTypeParmType) { - if (tagType.Decl.Handle.IsAnonymous) + if (templateTypeParmType.IsSugared) { - name = GetAnonymousName(tagType.Decl, tagType.KindSpelling); - } - else if (tagType.Handle.IsConstQualified) - { - name = GetTypeName(cursor, context, tagType.Decl.TypeForDecl, out var nativeDeclTypeName); + name = GetTypeName(cursor, context, templateTypeParmType.Desugar, out _); } else { // The default name should be correct } - - if (name.Contains("::")) - { - name = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).Last(); - name = GetRemappedName(name, cursor, tryRemapOperatorName: false); - } } else if (type is TypedefType typedefType) { @@ -1527,16 +1599,8 @@ private string GetTypeName(Cursor cursor, Cursor context, Type type, out string // can be treated correctly. Otherwise, they will resolve to a particular // platform size, based on whatever parameters were passed into clang. - var remappedName = GetRemappedName(name, cursor, tryRemapOperatorName: false); - - if (remappedName.Equals(name)) - { - name = GetTypeName(cursor, context, typedefType.Decl.UnderlyingType, out var nativeUnderlyingTypeName); - } - else - { - name = remappedName; - } + var remappedName = GetRemappedName(name, cursor, tryRemapOperatorName: false, out var wasRemapped); + name = wasRemapped ? remappedName : GetTypeName(cursor, context, typedefType.Decl.UnderlyingType, out _); } else { @@ -1566,7 +1630,7 @@ private string GetTypeNameForPointeeType(Cursor cursor, Cursor context, Type poi { if (!_config.ExcludeFnptrCodegen && (functionType is FunctionProtoType functionProtoType)) { - var remappedName = GetRemappedName(name, cursor, tryRemapOperatorName: false); + var remappedName = GetRemappedName(name, cursor, tryRemapOperatorName: false, out var wasRemapped); var callConv = GetCallingConvention(cursor, functionType.CallConv, remappedName); var needsReturnFixup = false; @@ -1579,41 +1643,41 @@ private string GetTypeNameForPointeeType(Cursor cursor, Cursor context, Type poi } var nameBuilder = new StringBuilder(); - nameBuilder.Append("delegate"); - nameBuilder.Append('*'); + _ = nameBuilder.Append("delegate"); + _ = nameBuilder.Append('*'); var isMacroDefinitionRecord = (cursor is VarDecl varDecl) && GetCursorName(varDecl).StartsWith("ClangSharpMacro_"); if (!isMacroDefinitionRecord) { - nameBuilder.Append(" unmanaged"); + _ = nameBuilder.Append(" unmanaged"); if (callConv != CallingConvention.Winapi) { - nameBuilder.Append('['); - nameBuilder.Append(callConv.AsString(true)); - nameBuilder.Append(']'); + _ = nameBuilder.Append('['); + _ = nameBuilder.Append(callConv.AsString(true)); + _ = nameBuilder.Append(']'); } } - nameBuilder.Append('<'); + _ = nameBuilder.Append('<'); if ((cursor is CXXMethodDecl cxxMethodDecl) && (context is CXXRecordDecl cxxRecordDecl)) { var cxxRecordDeclName = GetRemappedCursorName(cxxRecordDecl); needsReturnFixup = cxxMethodDecl.IsVirtual && NeedsReturnFixup(cxxMethodDecl); - nameBuilder.Append(EscapeName(cxxRecordDeclName)); - nameBuilder.Append('*'); - nameBuilder.Append(','); - nameBuilder.Append(' '); + _ = nameBuilder.Append(EscapeName(cxxRecordDeclName)); + _ = nameBuilder.Append('*'); + _ = nameBuilder.Append(','); + _ = nameBuilder.Append(' '); if (needsReturnFixup) { - nameBuilder.Append(returnTypeName); - nameBuilder.Append('*'); - nameBuilder.Append(','); - nameBuilder.Append(' '); + _ = nameBuilder.Append(returnTypeName); + _ = nameBuilder.Append('*'); + _ = nameBuilder.Append(','); + _ = nameBuilder.Append(' '); } } @@ -1641,19 +1705,19 @@ private string GetTypeNameForPointeeType(Cursor cursor, Cursor context, Type poi typeName = "byte"; } - nameBuilder.Append(typeName); - nameBuilder.Append(','); - nameBuilder.Append(' '); + _ = nameBuilder.Append(typeName); + _ = nameBuilder.Append(','); + _ = nameBuilder.Append(' '); } - nameBuilder.Append(returnTypeName); + _ = nameBuilder.Append(returnTypeName); if (needsReturnFixup) { - nameBuilder.Append('*'); + _ = nameBuilder.Append('*'); } - nameBuilder.Append('>'); + _ = nameBuilder.Append('>'); name = nameBuilder.ToString(); } else @@ -1695,7 +1759,7 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon alignment64 = elementSize64; } } - else if (type is IncompleteArrayType incompleteArrayType) + else if (type is IncompleteArrayType) { GetTypeSize(cursor, arrayType.ElementType, ref alignment32, ref alignment64, out var elementSize32, out var elementSize64); @@ -1812,7 +1876,7 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon default: { - AddDiagnostic(DiagnosticLevel.Error, $"Unsupported builtin type: '{type.TypeClass}.", cursor); + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported builtin type: '{type.KindSpelling}.", cursor); break; } } @@ -1825,22 +1889,34 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon { GetTypeSize(cursor, enumType.Decl.IntegerType, ref alignment32, ref alignment64, out size32, out size64); } - else if ((type is FunctionType functionType) || (type is PointerType) || (type is ReferenceType)) + else if (type is FunctionType or PointerType or ReferenceType) { size32 = 4; size64 = 8; + if (alignment32 == -1) + { + alignment32 = 4; + } + if (alignment64 == -1) { alignment64 = 8; } } + else if (type is InjectedClassNameType) + { + Debug.Assert(size32 == 0); + Debug.Assert(size64 == 0); + } else if (type is RecordType recordType) { + var recordTypeAlignOf = recordType.Handle.AlignOf; + if (alignment32 == -1) { - alignment32 = recordType.Handle.AlignOf; - alignment64 = recordType.Handle.AlignOf; + alignment32 = recordTypeAlignOf; + alignment64 = recordTypeAlignOf; } long maxFieldAlignment32 = -1; @@ -1871,22 +1947,19 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon { foreach (var baseCXXRecordDecl in cxxRecordDecl.Bases) { - long fieldSize32; - long fieldSize64; - long fieldAlignment32 = -1; long fieldAlignment64 = -1; - GetTypeSize(baseCXXRecordDecl, baseCXXRecordDecl.Type, ref fieldAlignment32, ref fieldAlignment64, out fieldSize32, out fieldSize64); + GetTypeSize(baseCXXRecordDecl, baseCXXRecordDecl.Type, ref fieldAlignment32, ref fieldAlignment64, out var fieldSize32, out var fieldSize64); if ((fieldAlignment32 == -1) || (alignment32 < 4)) { - fieldAlignment32 = Math.Min(alignment32, fieldSize32); + fieldAlignment32 = Math.Max(Math.Min(alignment32, fieldSize32), 1); } if ((fieldAlignment64 == -1) || (alignment64 < 4)) { - fieldAlignment64 = Math.Min(alignment64, fieldSize64); + fieldAlignment64 = Math.Max(Math.Min(alignment64, fieldSize64), 1); } if ((size32 % fieldAlignment32) != 0) @@ -1942,10 +2015,6 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon } } } - else if ((declaration is RecordDecl nestedRecordDecl) && nestedRecordDecl.IsAnonymousStructOrUnion) - { - GetTypeSize(nestedRecordDecl, nestedRecordDecl.TypeForDecl, ref fieldAlignment32, ref fieldAlignment64, out fieldSize32, out fieldSize64); - } else { continue; @@ -1953,12 +2022,12 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon if ((fieldAlignment32 == -1) || (alignment32 < 4)) { - fieldAlignment32 = Math.Min(alignment32, fieldSize32); + fieldAlignment32 = Math.Max(Math.Min(alignment32, fieldSize32), 1); } if ((fieldAlignment64 == -1) || (alignment64 < 4)) { - fieldAlignment64 = Math.Min(alignment64, fieldSize64); + fieldAlignment64 = Math.Max(Math.Min(alignment64, fieldSize64), 1); } if ((size32 % fieldAlignment32) != 0) @@ -2015,7 +2084,7 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon var name = GetTypeName(cursor, context: null, type, out _); - if (!_config.RemappedNames.TryGetValue(name, out string remappedName)) + if (!_config.RemappedNames.TryGetValue(name, out var remappedName)) { remappedName = name; } @@ -2025,6 +2094,11 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon size32 = 4; size64 = 8; + if (alignment32 == -1) + { + alignment32 = 4; + } + if (alignment64 == -1) { alignment64 = 8; @@ -2035,6 +2109,41 @@ private void GetTypeSize(Cursor cursor, Type type, ref long alignment32, ref lon GetTypeSize(cursor, typedefType.Decl.UnderlyingType, ref alignment32, ref alignment64, out size32, out size64); } } + else if (type is SubstTemplateTypeParmType substTemplateTypeParmType) + { + GetTypeSize(cursor, substTemplateTypeParmType.ReplacementType, ref alignment32, ref alignment64, out size32, out size64); + } + else if (type is TemplateSpecializationType templateSpecializationType) + { + if (templateSpecializationType.IsTypeAlias) + { + GetTypeSize(cursor, templateSpecializationType.AliasedType, ref alignment32, ref alignment64, out size32, out size64); + } + else if (templateSpecializationType.IsSugared) + { + GetTypeSize(cursor, templateSpecializationType.Desugar, ref alignment32, ref alignment64, out size32, out size64); + } + else if (templateSpecializationType.TemplateName.AsTemplateDecl is TemplateDecl templateDecl) + { + if (templateDecl.TemplatedDecl is TypeDecl typeDecl) + { + GetTypeSize(cursor, typeDecl.TypeForDecl, ref alignment32, ref alignment64, out size32, out size64); + } + else + { + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported template specialization declaration kind: '{templateDecl.TemplatedDecl.DeclKindName}'.", cursor); + } + } + else + { + AddDiagnostic(DiagnosticLevel.Error, $"Unsupported template specialization type: '{templateSpecializationType}'.", cursor); + } + } + else if (type is TemplateTypeParmType) + { + Debug.Assert(size32 == 0); + Debug.Assert(size64 == 0); + } else { AddDiagnostic(DiagnosticLevel.Error, $"Unsupported type: '{type.TypeClass}'.", cursor); @@ -2064,7 +2173,7 @@ private bool HasVtbl(CXXRecordDecl cxxRecordDecl) return hasDirectVtbl || (indirectVtblCount != 0); } - private bool IsEnumOperator(FunctionDecl functionDecl, string name) + private static bool IsEnumOperator(FunctionDecl functionDecl, string name) { if (name.StartsWith("operator") && ((functionDecl.Parameters.Count == 1) || (functionDecl.Parameters.Count == 2))) { @@ -2082,7 +2191,7 @@ private bool IsEnumOperator(FunctionDecl functionDecl, string name) if (functionDecl.Parameters.Count == 1) { - return (parmVarDecl1Type.Kind == CXTypeKind.CXType_Enum); + return parmVarDecl1Type.Kind == CXTypeKind.CXType_Enum; } var parmVarDecl2 = functionDecl.Parameters[1]; @@ -2111,24 +2220,18 @@ private bool IsExcluded(Cursor cursor, out bool isExcludedByConflictingDefinitio { isExcludedByConflictingDefinition = false; - if (IsAlwaysIncluded(cursor)) - { - return false; - } + return !IsAlwaysIncluded(cursor) + && (IsExcludedByConfig(cursor) || IsExcludedByFile(cursor) || IsExcludedByName(cursor, out isExcludedByConflictingDefinition)); - if (_config.ExcludeFunctionsWithBody && - cursor is FunctionDecl functionDecl && - cursor.CursorKind == CXCursorKind.CXCursor_FunctionDecl && - functionDecl.HasBody) + bool IsAlwaysIncluded(Cursor cursor) { - return true; + return (cursor is TranslationUnitDecl) || (cursor is LinkageSpecDecl) || ((cursor is VarDecl varDecl) && varDecl.Name.StartsWith("ClangSharpMacro_")); } - return IsExcludedByFile(cursor) || IsExcludedByName(cursor, out isExcludedByConflictingDefinition); - - bool IsAlwaysIncluded(Cursor cursor) + bool IsExcludedByConfig(Cursor cursor) { - return (cursor is TranslationUnitDecl) || (cursor is LinkageSpecDecl) || ((cursor is VarDecl varDecl) && varDecl.Name.StartsWith("ClangSharpMacro_")); + return (_config.ExcludeFunctionsWithBody && (cursor is FunctionDecl functionDecl) && functionDecl.HasBody) + || (!_config.GenerateTemplateBindings && (cursor is TemplateDecl)); } bool IsExcludedByFile(Cursor cursor) @@ -2142,7 +2245,7 @@ bool IsExcludedByFile(Cursor cursor) } var declLocation = cursor.Location; - declLocation.GetFileLocation(out CXFile file, out uint line, out uint column, out _); + declLocation.GetFileLocation(out var file, out var line, out var column, out _); if (IsIncludedFileOrLocation(cursor, file, declLocation)) { @@ -2153,7 +2256,7 @@ bool IsExcludedByFile(Cursor cursor) // defined in an imported header file. We want to also check if the expansion location is // in the main file to catch these cases and ensure we still generate bindings for them. - declLocation.GetExpansionLocation(out CXFile expansionFile, out uint expansionLine, out uint expansionColumn, out _); + declLocation.GetExpansionLocation(out var expansionFile, out var expansionLine, out var expansionColumn, out _); if ((expansionFile == file) && (expansionLine == line) && (expansionColumn == column) && (_config.TraversalNames.Length != 0)) { @@ -2166,12 +2269,7 @@ bool IsExcludedByFile(Cursor cursor) var expansionLocation = cursor.TranslationUnit.Handle.GetLocation(expansionFile, expansionLine, expansionColumn); - if (IsIncludedFileOrLocation(cursor, file, expansionLocation)) - { - return false; - } - - return true; + return !IsIncludedFileOrLocation(cursor, file, expansionLocation); } bool IsExcludedByName(Cursor cursor, out bool isExcludedByConflictingDefinition) @@ -2344,7 +2442,7 @@ bool IsComProxy(FunctionDecl functionDecl, string name) if ((parmVarDecl != null) && (parmVarDecl.Type is PointerType pointerType)) { - var typeName = GetTypeName(parmVarDecl, context: null, pointerType.PointeeType, out string nativeTypeName); + var typeName = GetTypeName(parmVarDecl, context: null, pointerType.PointeeType, out var nativeTypeName); return name.StartsWith($"{nativeTypeName}_") || name.StartsWith($"{typeName}_") || (typeName == "IRpcStubBuffer"); } return false; @@ -2355,7 +2453,7 @@ bool IsConflictingMethodDecl(CXXMethodDecl cxxMethodDecl, CXXRecordDecl cxxRecor var cxxMethodName = GetRemappedCursorName(cxxMethodDecl); var cxxMethodDeclIndex = -1; - for (int i = 0; i < cxxRecordDecl.Methods.Count; i++) + for (var i = 0; i < cxxRecordDecl.Methods.Count; i++) { var methodDecl = cxxRecordDecl.Methods[i]; var methodName = GetRemappedCursorName(methodDecl); @@ -2378,7 +2476,7 @@ bool IsConflictingMethodDecl(CXXMethodDecl cxxMethodDecl, CXXRecordDecl cxxRecor var allMatch = true; - for (int n = 0; n < cxxMethodDecl.Parameters.Count; n++) + for (var n = 0; n < cxxMethodDecl.Parameters.Count; n++) { var baseParameterType = cxxMethodDecl.Parameters[n].Type.CanonicalType; var thisParameterType = methodDecl.Parameters[n].Type.CanonicalType; @@ -2411,7 +2509,7 @@ bool IsConflictingMethodDecl(CXXMethodDecl cxxMethodDecl, CXXRecordDecl cxxRecor // An index of -1 means we found a conflict before encountering // ourselves. Since we generally want to prefer the first declaration, // we want to classify ourselves as the conflicting instance. - return (cxxMethodDeclIndex == -1); + return cxxMethodDeclIndex == -1; } } @@ -2419,9 +2517,9 @@ bool IsConflictingMethodDecl(CXXMethodDecl cxxMethodDecl, CXXRecordDecl cxxRecor { CXXRecordDecl baseRecordDecl; - if (@base.Referenced is CXXRecordDecl) + if (@base.Referenced is CXXRecordDecl baseCXXRecordDecl) { - baseRecordDecl = (CXXRecordDecl)@base.Referenced; + baseRecordDecl = baseCXXRecordDecl; } else if (@base.Referenced is TypedefDecl typedefDecl) { @@ -2523,7 +2621,7 @@ private bool IsFixedSize(Cursor cursor, Type type) var recordDecl = recordType.Decl; return recordDecl.Fields.All((fieldDecl) => IsFixedSize(fieldDecl, fieldDecl.Type)) - && (!(recordDecl is CXXRecordDecl cxxRecordDecl) || cxxRecordDecl.Methods.All((cxxMethodDecl) => !cxxMethodDecl.IsVirtual)); + && (recordDecl is not CXXRecordDecl cxxRecordDecl || cxxRecordDecl.Methods.All((cxxMethodDecl) => !cxxMethodDecl.IsVirtual)); } else if (type is ReferenceType) { @@ -2533,7 +2631,7 @@ private bool IsFixedSize(Cursor cursor, Type type) { var name = GetTypeName(cursor, context: null, type, out _); - if (!_config.RemappedNames.TryGetValue(name, out string remappedName)) + if (!_config.RemappedNames.TryGetValue(name, out var remappedName)) { remappedName = name; } @@ -2556,14 +2654,14 @@ private bool IsPrevContextDecl(out T value) { var previousContext = _context.Last.Previous; - while (!(previousContext.Value is Decl)) + while (previousContext.Value is not Decl) { previousContext = previousContext.Previous; } - if (previousContext.Value is T) + if (previousContext.Value is T t) { - value = (T)previousContext.Value; + value = t; return true; } else @@ -2578,14 +2676,14 @@ private bool IsPrevContextStmt(out T value) { var previousContext = _context.Last.Previous; - while ((previousContext.Value is ParenExpr) || (previousContext.Value is ImplicitCastExpr)) + while (previousContext.Value is ParenExpr or ImplicitCastExpr) { previousContext = previousContext.Previous; } - if (previousContext.Value is T) + if (previousContext.Value is T t) { - value = (T)previousContext.Value; + value = t; return true; } else @@ -2595,7 +2693,7 @@ private bool IsPrevContextStmt(out T value) } } - private bool IsStmtAsWritten(Cursor cursor, out T value, bool removeParens = false) + private static bool IsStmtAsWritten(Cursor cursor, out T value, bool removeParens = false) where T : Stmt { if (cursor is Expr expr) @@ -2603,9 +2701,9 @@ private bool IsStmtAsWritten(Cursor cursor, out T value, bool removeParens = cursor = GetExprAsWritten(expr, removeParens); } - if (cursor is T) + if (cursor is T t) { - value = (T)cursor; + value = t; return true; } else @@ -2615,6 +2713,22 @@ private bool IsStmtAsWritten(Cursor cursor, out T value, bool removeParens = } } + private static bool IsStmtAsWritten(Stmt stmt, Stmt expectedStmt, bool removeParens = false) + { + if (stmt == expectedStmt) + { + return true; + } + + if (stmt is not Expr expr) + { + return false; + } + + expr = GetExprAsWritten(expr, removeParens); + return expr == expectedStmt; + } + internal static bool IsSupportedFixedSizedBufferType(string typeName) { switch (typeName) @@ -2659,7 +2773,14 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt) // case CX_StmtClass.CX_StmtClass_AddrLabelExpr: // case CX_StmtClass.CX_StmtClass_ArrayInitIndexExpr: // case CX_StmtClass.CX_StmtClass_ArrayInitLoopExpr: - // case CX_StmtClass.CX_StmtClass_ArraySubscriptExpr: + + case CX_StmtClass.CX_StmtClass_ArraySubscriptExpr: + { + var arraySubscriptExpr = (ArraySubscriptExpr)stmt; + return IsUnchecked(targetTypeName, arraySubscriptExpr.LHS) + || IsUnchecked(targetTypeName, arraySubscriptExpr.RHS); + } + // case CX_StmtClass.CX_StmtClass_ArrayTypeTraitExpr: // case CX_StmtClass.CX_StmtClass_AsTypeExpr: // case CX_StmtClass.CX_StmtClass_AtomicExpr: @@ -2691,10 +2812,20 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt) // case CX_StmtClass.CX_StmtClass_CXXDefaultArgExpr: // case CX_StmtClass.CX_StmtClass_CXXDefaultInitExpr: // case CX_StmtClass.CX_StmtClass_CXXDeleteExpr: - // case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + + case CX_StmtClass.CX_StmtClass_CXXDependentScopeMemberExpr: + { + return false; + } + // case CX_StmtClass.CX_StmtClass_CXXFoldExpr: // case CX_StmtClass.CX_StmtClass_CXXInheritedCtorInitExpr: - // case CX_StmtClass.CX_StmtClass_CXXNewExpr: + + case CX_StmtClass.CX_StmtClass_CXXNewExpr: + { + return false; + } + // case CX_StmtClass.CX_StmtClass_CXXNoexceptExpr: case CX_StmtClass.CX_StmtClass_CXXNullPtrLiteralExpr: @@ -2797,7 +2928,13 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt) } // case CX_StmtClass.CX_StmtClass_ConstantExpr: - // case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + + case CX_StmtClass.CX_StmtClass_ExprWithCleanups: + { + var exprWithCleanups = (ExprWithCleanups)stmt; + return IsUnchecked(targetTypeName, exprWithCleanups.SubExpr); + } + // case CX_StmtClass.CX_StmtClass_FunctionParmPackExpr: // case CX_StmtClass.CX_StmtClass_GNUNullExpr: // case CX_StmtClass.CX_StmtClass_GenericSelectionExpr: @@ -2856,7 +2993,21 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt) || IsUnchecked(targetTypeName, parenExpr.Handle.Evaluate); } - // case CX_StmtClass.CX_StmtClass_ParenListExpr: + case CX_StmtClass.CX_StmtClass_ParenListExpr: + { + var parenListExpr = (ParenListExpr)stmt; + + foreach (var expr in parenListExpr.Exprs) + { + if (IsUnchecked(targetTypeName, expr) || IsUnchecked(targetTypeName, expr.Handle.Evaluate)) + { + return true; + } + } + + return false; + } + // case CX_StmtClass.CX_StmtClass_PredefinedExpr: // case CX_StmtClass.CX_StmtClass_PseudoObjectExpr: // case CX_StmtClass.CX_StmtClass_RequiresExpr: @@ -2881,13 +3032,10 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt) var argumentType = unaryExprOrTypeTraitExpr.TypeOfArgument; - long size32; - long size64; - long alignment32 = -1; long alignment64 = -1; - GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out size32, out size64); + GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out var size32, out var size64); switch (unaryExprOrTypeTraitExpr.Kind) { @@ -2969,26 +3117,16 @@ bool IsOverflow(BinaryOperator binaryOperator) { case CX_BinaryOperatorKind.CX_BO_Add: { - if (isUnsigned) - { - return unchecked((ulong)lhsIntegerLiteral.Value + (ulong)rhsIntegerLiteral.Value < (ulong)lhsIntegerLiteral.Value); - } - else - { - return unchecked(lhsIntegerLiteral.Value + rhsIntegerLiteral.Value < lhsIntegerLiteral.Value); - } + return isUnsigned + ? (ulong)lhsIntegerLiteral.Value + (ulong)rhsIntegerLiteral.Value < (ulong)lhsIntegerLiteral.Value + : lhsIntegerLiteral.Value + rhsIntegerLiteral.Value < lhsIntegerLiteral.Value; } case CX_BinaryOperatorKind.CX_BO_Sub: { - if (isUnsigned) - { - return unchecked((ulong)lhsIntegerLiteral.Value - (ulong)rhsIntegerLiteral.Value > (ulong)lhsIntegerLiteral.Value); - } - else - { - return unchecked(lhsIntegerLiteral.Value - rhsIntegerLiteral.Value > lhsIntegerLiteral.Value); - } + return isUnsigned + ? (ulong)lhsIntegerLiteral.Value - (ulong)rhsIntegerLiteral.Value > (ulong)lhsIntegerLiteral.Value + : lhsIntegerLiteral.Value - rhsIntegerLiteral.Value > lhsIntegerLiteral.Value; } default: @@ -2999,7 +3137,7 @@ bool IsOverflow(BinaryOperator binaryOperator) } } - private bool IsUnchecked(string typeName, CXEvalResult evalResult) + private static bool IsUnchecked(string typeName, CXEvalResult evalResult) { if (evalResult.Kind != CXEvalResultKind.CXEval_Int) { @@ -3007,40 +3145,38 @@ private bool IsUnchecked(string typeName, CXEvalResult evalResult) } var signedValue = evalResult.AsLongLong; - return IsUnchecked(typeName, signedValue, (signedValue < 0), isHex: false); + return IsUnchecked(typeName, signedValue, signedValue < 0, isHex: false); } - private bool IsUnchecked(string typeName, long signedValue, bool isNegative, bool isHex) + private static bool IsUnchecked(string typeName, long signedValue, bool isNegative, bool isHex) { switch (typeName) { case "byte": case "Byte": { - var unsignedValue = unchecked((uint)signedValue); - return (unsignedValue < byte.MinValue) || (byte.MaxValue < unsignedValue); + var unsignedValue = unchecked((ulong)signedValue); + return unsignedValue is < byte.MinValue or > byte.MaxValue; } case "ushort": case "UInt16": { - var unsignedValue = unchecked((uint)signedValue); - return (unsignedValue < ushort.MinValue) || (ushort.MaxValue < unsignedValue); + var unsignedValue = unchecked((ulong)signedValue); + return unsignedValue is < ushort.MinValue or > ushort.MaxValue; } case "uint": case "UInt32": case "nuint": { - var unsignedValue = unchecked((uint)signedValue); - return (unsignedValue < uint.MinValue) || (uint.MaxValue < unsignedValue); + return false; } case "ulong": case "UInt64": { - var unsignedValue = unchecked((ulong)signedValue); - return (unsignedValue < ulong.MinValue) || (ulong.MaxValue < unsignedValue); + return false; } case "sbyte": @@ -3083,7 +3219,7 @@ private bool IsUnsafe(FieldDecl fieldDecl) { var name = GetTypeName(fieldDecl, context: null, type, out _); - if (!_config.RemappedNames.TryGetValue(name, out string remappedName)) + if (!_config.RemappedNames.TryGetValue(name, out var remappedName)) { remappedName = name; } @@ -3158,7 +3294,7 @@ private bool IsUnsafe(NamedDecl namedDecl, Type type) { var name = GetTypeName(namedDecl, context: null, type, out _); - if (!_config.RemappedNames.TryGetValue(name, out string remappedName)) + if (!_config.RemappedNames.TryGetValue(name, out var remappedName)) { remappedName = name; } @@ -3240,7 +3376,7 @@ private bool NeedsReturnFixup(CXXMethodDecl cxxMethodDecl) return needsReturnFixup; } - private bool NeedsNewKeyword(string name) + private static bool NeedsNewKeyword(string name) { return name.Equals("Equals") || name.Equals("GetHashCode") @@ -3250,17 +3386,13 @@ private bool NeedsNewKeyword(string name) || name.Equals("ToString"); } - private bool NeedsNewKeyword(string name, IReadOnlyList parmVarDecls) + private static bool NeedsNewKeyword(string name, IReadOnlyList parmVarDecls) { - if (name.Equals("GetHashCode") + return (name.Equals("GetHashCode") || name.Equals("GetType") || name.Equals("MemberwiseClone") || name.Equals("ToString")) - { - return parmVarDecls.Count == 0; - } - - return false; +&& parmVarDecls.Count == 0; } private void ParenthesizeStmt(Stmt stmt) @@ -3292,7 +3424,7 @@ private string PrefixAndStripName(string name, uint overloadIndex) { if (name.StartsWith(_config.MethodPrefixToStrip)) { - name = name.Substring(_config.MethodPrefixToStrip.Length); + name = name[_config.MethodPrefixToStrip.Length..]; } return $"_{name}{((overloadIndex != 0) ? overloadIndex.ToString() : "")}"; @@ -3370,7 +3502,7 @@ private bool TryGetUuid(RecordDecl recordDecl, out Guid uuid) { var uuidAttrs = recordDecl.Attrs.Where((attr) => attr.Kind == CX_AttrKind.CX_AttrKind_Uuid); - if (uuidAttrs.Count() == 0) + if (!uuidAttrs.Any()) { uuid = Guid.Empty; return false; @@ -3396,7 +3528,7 @@ private bool TryRemapOperatorName(ref string name, FunctionDecl functionDecl) { var numArgs = functionDecl.Parameters.Count; - if (functionDecl.DeclContext is CXXRecordDecl) + if (functionDecl.IsInstance) { numArgs++; } @@ -3551,26 +3683,24 @@ private void UncheckStmt(string targetTypeName, Stmt stmt) { var argumentType = unaryExprOrTypeTraitExpr.TypeOfArgument; - long size32; - long size64; long alignment32 = -1; long alignment64 = -1; - GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out size32, out size64); + GetTypeSize(unaryExprOrTypeTraitExpr, argumentType, ref alignment32, ref alignment64, out var size32, out var size64); switch (unaryExprOrTypeTraitExpr.Kind) { case CX_UnaryExprOrTypeTrait.CX_UETT_SizeOf: { - needsCast |= (size32 != size64); + needsCast |= size32 != size64; break; } case CX_UnaryExprOrTypeTrait.CX_UETT_AlignOf: case CX_UnaryExprOrTypeTrait.CX_UETT_PreferredAlignOf: { - needsCast |= (alignment32 != alignment64); + needsCast |= alignment32 != alignment64; break; } @@ -3643,14 +3773,11 @@ private void Visit(IEnumerable cursors) } } - private void Visit(IEnumerable cursors, IEnumerable excludedCursors) - { - Visit(cursors.Except(excludedCursors)); - } + private void Visit(IEnumerable cursors, IEnumerable excludedCursors) => Visit(cursors.Except(excludedCursors)); private void WithAttributes(string remappedName) { - if (_config.WithAttributes.TryGetValue(remappedName, out IReadOnlyList attributes)) + if (_config.WithAttributes.TryGetValue(remappedName, out var attributes)) { foreach (var attribute in attributes) { @@ -3661,14 +3788,9 @@ private void WithAttributes(string remappedName) private string GetLibraryPath(string remappedName) { - if (!_config.WithLibraryPaths.TryGetValue(remappedName, out string libraryPath) && !_config.WithLibraryPaths.TryGetValue("*", out libraryPath)) - { - return _config.LibraryPath; - } - else - { - return libraryPath; - } + return !_config.WithLibraryPaths.TryGetValue(remappedName, out var libraryPath) && !_config.WithLibraryPaths.TryGetValue("*", out libraryPath) + ? _config.LibraryPath + : libraryPath; } private bool GetSetLastError(string remappedName) => _config.WithSetLastErrors.Contains("*") || @@ -3693,13 +3815,9 @@ private void WithTestAssertEqual(string expected, string actual) _testOutputBuilder.WriteIndented("Assert.That"); _testOutputBuilder.Write('('); _testOutputBuilder.Write(actual); - _testOutputBuilder.Write(','); - _testOutputBuilder.Write(' '); - _testOutputBuilder.Write("Is.EqualTo"); - _testOutputBuilder.Write('('); + _testOutputBuilder.Write(", Is.EqualTo("); _testOutputBuilder.Write(expected); - _testOutputBuilder.Write(')'); - _testOutputBuilder.Write(')'); + _testOutputBuilder.Write("))"); _testOutputBuilder.WriteSemicolon(); _testOutputBuilder.WriteNewline(); } @@ -3708,8 +3826,7 @@ private void WithTestAssertEqual(string expected, string actual) _testOutputBuilder.WriteIndented("Assert.Equal"); _testOutputBuilder.Write('('); _testOutputBuilder.Write(expected); - _testOutputBuilder.Write(','); - _testOutputBuilder.Write(' '); + _testOutputBuilder.Write(", ");; _testOutputBuilder.Write(actual); _testOutputBuilder.Write(')'); _testOutputBuilder.WriteSemicolon(); @@ -3724,10 +3841,7 @@ private void WithTestAssertTrue(string actual) _testOutputBuilder.WriteIndented("Assert.That"); _testOutputBuilder.Write('('); _testOutputBuilder.Write(actual); - _testOutputBuilder.Write(','); - _testOutputBuilder.Write(' '); - _testOutputBuilder.Write("Is.True"); - _testOutputBuilder.Write(')'); + _testOutputBuilder.Write(", Is.True)"); _testOutputBuilder.WriteSemicolon(); _testOutputBuilder.WriteNewline(); } @@ -3744,7 +3858,7 @@ private void WithTestAssertTrue(string actual) private void WithType(string remappedName, ref string integerTypeName, ref string nativeTypeName) { - if (_config.WithTypes.TryGetValue(remappedName, out string type)) + if (_config.WithTypes.TryGetValue(remappedName, out var type)) { if (string.IsNullOrWhiteSpace(nativeTypeName)) { @@ -3762,7 +3876,7 @@ private void WithType(string remappedName, ref string integerTypeName, ref strin private void WithUsings(string remappedName) { - if (_config.WithUsings.TryGetValue(remappedName, out IReadOnlyList usings)) + if (_config.WithUsings.TryGetValue(remappedName, out var usings)) { foreach (var @using in usings) { diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs index 5b08f440..52906998 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfiguration.cs @@ -46,7 +46,7 @@ public PInvokeGeneratorConfiguration(string libraryPath, string namespaceName, s throw new ArgumentNullException(nameof(namespaceName)); } - if (outputMode != PInvokeGeneratorOutputMode.CSharp && outputMode != PInvokeGeneratorOutputMode.Xml) + if (outputMode is not PInvokeGeneratorOutputMode.CSharp and not PInvokeGeneratorOutputMode.Xml) { throw new ArgumentOutOfRangeException(nameof(options)); } @@ -177,6 +177,8 @@ public PInvokeGeneratorConfiguration(string libraryPath, string namespaceName, s public bool GenerateNativeInheritanceAttribute => _options.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateNativeInheritanceAttribute); + public bool GenerateTemplateBindings => _options.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateTemplateBindings); + public bool GenerateVtblIndexAttribute => _options.HasFlag(PInvokeGeneratorConfigurationOptions.GenerateVtblIndexAttribute); public string MethodClassName { get; } diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfigurationOptions.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfigurationOptions.cs index cd005432..555b431f 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfigurationOptions.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGeneratorConfigurationOptions.cs @@ -56,5 +56,7 @@ public enum PInvokeGeneratorConfigurationOptions GenerateVtblIndexAttribute = 0x00400000, GeneratePreviewCode = 0x00800000, + + GenerateTemplateBindings = 0x01000000, } } diff --git a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.Visit.cs b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.Visit.cs index e055cc06..36613506 100644 --- a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.Visit.cs +++ b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.Visit.cs @@ -8,11 +8,11 @@ public void WriteCustomAttribute(string attribute) => _sb.Append($"{attribute}\n"); public void WriteIid(string iidName, string iidValue) { - _sb.Append(""); + _ = _sb.Append(""); } public void WriteDivider(bool force = false) diff --git a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.VisitDecl.cs b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.VisitDecl.cs index 8cc2ca9a..cfcb6a2f 100644 --- a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.VisitDecl.cs +++ b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.VisitDecl.cs @@ -10,7 +10,7 @@ namespace ClangSharp.XML { internal partial class XmlOutputBuilder { - private StringBuilder _sb = new(); + private readonly StringBuilder _sb = new(); public void BeginInnerValue() => _sb.Append(""); public void EndInnerValue() => _sb.Append(""); @@ -23,12 +23,12 @@ internal partial class XmlOutputBuilder public void BeginConstant(in ConstantDesc desc) { - _sb.Append((desc.Kind & ConstantKind.Enumerator) == 0 + _ = _sb.Append((desc.Kind & ConstantKind.Enumerator) == 0 ? $"" : $""); - _sb.Append($""); - _sb.Append(EscapeText(desc.TypeName)); - _sb.Append(""); + _ = _sb.Append($""); + _ = _sb.Append(EscapeText(desc.TypeName)); + _ = _sb.Append(""); } public void BeginConstantValue(bool isGetOnlyProperty = false) => _sb.Append(""); @@ -39,33 +39,33 @@ public void BeginConstant(in ConstantDesc desc) public void BeginEnum(AccessSpecifier accessSpecifier, string typeName, string escapedName, string nativeTypeName) { - _sb.Append($""); - _sb.Append($"{typeName}"); + _ = _sb.Append($""); + _ = _sb.Append($"{typeName}"); } public void EndEnum() => _sb.Append(""); public void BeginField(in FieldDesc desc) { - _sb.Append($"'); - _sb.Append("'); + _ = _sb.Append("( if (desc.IsVirtual) { Debug.Assert(!desc.HasFnPtrCodeGen); - _sb.Append($"'); + _ = _sb.Append('>'); desc.WriteCustomAttrs(desc.CustomAttrGeneratorData); - _sb.Append("'); + _ = _sb.Append('>'); } public void WriteReturnType(string typeString) { - _sb.Append(EscapeText(typeString)); - _sb.Append(""); + _ = _sb.Append(EscapeText(typeString)); + _ = _sb.Append(""); } public void BeginFunctionInnerPrototype(string escapedName) @@ -157,27 +157,18 @@ public void BeginFunctionInnerPrototype(string escapedName) public void BeginParameter(in ParameterDesc info) { - _sb.Append($""); + _ = _sb.Append($""); info.WriteCustomAttrs(info.CustomAttrGeneratorData); - _sb.Append(""); - _sb.Append(EscapeText(info.Type)); - _sb.Append(""); + _ = _sb.Append(""); + _ = _sb.Append(EscapeText(info.Type)); + _ = _sb.Append(""); } - public void BeginParameterDefault() - { - _sb.Append(""); - } + public void BeginParameterDefault() => _ = _sb.Append(""); - public void EndParameterDefault() - { - _sb.Append(""); - } + public void EndParameterDefault() => _ = _sb.Append(""); - public void EndParameter() - { - _sb.Append(""); - } + public void EndParameter() => _ = _sb.Append(""); public void WriteParameterSeparator() { @@ -199,12 +190,10 @@ public void BeginConstructorInitializers() // nop, method only exists for consistency and/or future use } - public void BeginConstructorInitializer(string memberRefName, string memberInitName) - { + public void BeginConstructorInitializer(string memberRefName, string memberInitName) => // "hint" is the name we're initializing using, but should only be used as a "hint" rather than a definitive // value, which is contained within the init block. - _sb.Append($""); - } + _ = _sb.Append($""); public void EndConstructorInitializer() => _sb.Append(""); @@ -213,15 +202,9 @@ public void EndConstructorInitializers() // nop, method only exists for consistency and/or future use } - public void BeginInnerFunctionBody() - { - _sb.Append(""); - } + public void BeginInnerFunctionBody() => _ = _sb.Append(""); - public void EndInnerFunctionBody() - { - _sb.Append(""); - } + public void EndInnerFunctionBody() => _ = _sb.Append(""); public void EndBody(bool isExpressionBody = false) { @@ -233,56 +216,56 @@ public void EndFunctionOrDelegate(bool isVirtual, bool _) public void BeginStruct(in StructDesc info) { - _sb.Append("'); + _ = _sb.Append('>'); info.WriteCustomAttrs(info.CustomAttrGeneratorData); } @@ -308,7 +291,7 @@ public void EmitSystemSupport() public CSharpOutputBuilder BeginCSharpCode() { - _sb.Append(""); + _ = _sb.Append(""); return new CSharpOutputBuilder("__Internal", markerMode: MarkerMode.Xml); } @@ -322,62 +305,56 @@ public void EndCSharpCode(CSharpOutputBuilder output) { if (needsNewline) { - _sb.Append('\n'); + _ = _sb.Append('\n'); } - _sb.Append(EscapeText(s).Replace("/*M*/<", "<") + _ = _sb.Append(EscapeText(s).Replace("/*M*/<", "<") .Replace("/*M*/>", ">")); needsNewline = true; } - _sb.Append(""); + _ = _sb.Append(""); } public void BeginGetter(bool aggressivelyInlined) { - _sb.Append("'); + _ = _sb.Append('>'); } - public void EndGetter() - { - _sb.Append(""); - } + public void EndGetter() => _ = _sb.Append(""); public void BeginSetter(bool aggressivelyInlined) { - _sb.Append("'); + _ = _sb.Append('>'); } - public void EndSetter() - { - _sb.Append(""); - } + public void EndSetter() => _ = _sb.Append(""); public void BeginIndexer(AccessSpecifier accessSpecifier, bool isUnsafe) { - _sb.Append("" : "\">"); + _ = _sb.Append("" : "\">"); } public void WriteIndexer(string typeName) { - _sb.Append(""); - _sb.Append(EscapeText(typeName)); - _sb.Append(""); + _ = _sb.Append(""); + _ = _sb.Append(EscapeText(typeName)); + _ = _sb.Append(""); } public void BeginIndexerParameters() diff --git a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.cs b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.cs index 703db424..2f9e0415 100644 --- a/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.cs +++ b/sources/ClangSharp.PInvokeGenerator/XML/XmlOutputBuilder.cs @@ -24,7 +24,7 @@ public IEnumerable Contents get { StringWriter sw = new(); - XmlWriter writer = XmlWriter.Create(sw, new() + var writer = XmlWriter.Create(sw, new() { Indent = true, IndentChars = " ", @@ -42,6 +42,6 @@ public IEnumerable Contents } } - private string EscapeText(string value) => new XText(value).ToString(); + private static string EscapeText(string value) => new XText(value).ToString(); } } diff --git a/sources/ClangSharp/ClangSharp.csproj b/sources/ClangSharp/ClangSharp.csproj index d52dee5c..410c085d 100644 --- a/sources/ClangSharp/ClangSharp.csproj +++ b/sources/ClangSharp/ClangSharp.csproj @@ -7,6 +7,12 @@ + + + + + + diff --git a/sources/ClangSharp/Cursors/Attrs/Attr.cs b/sources/ClangSharp/Cursors/Attrs/Attr.cs index b44d2148..b6b7fe23 100644 --- a/sources/ClangSharp/Cursors/Attrs/Attr.cs +++ b/sources/ClangSharp/Cursors/Attrs/Attr.cs @@ -11,7 +11,7 @@ private protected Attr(CXCursor handle) : base(handle, handle.Kind) { if (handle.AttrKind == CX_AttrKind.CX_AttrKind_Invalid) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } diff --git a/sources/ClangSharp/Cursors/Attrs/InheritableAttr.cs b/sources/ClangSharp/Cursors/Attrs/InheritableAttr.cs index 4902aca4..ba071808 100644 --- a/sources/ClangSharp/Cursors/Attrs/InheritableAttr.cs +++ b/sources/ClangSharp/Cursors/Attrs/InheritableAttr.cs @@ -9,9 +9,9 @@ public class InheritableAttr : Attr { internal InheritableAttr(CXCursor handle) : base(handle) { - if ((CX_AttrKind.CX_AttrKind_LastInheritableAttr < handle.AttrKind) || (handle.AttrKind < CX_AttrKind.CX_AttrKind_FirstInheritableAttr)) + if (handle.AttrKind is > CX_AttrKind.CX_AttrKind_LastInheritableAttr or < CX_AttrKind.CX_AttrKind_FirstInheritableAttr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Attrs/InheritableParamAttr.cs b/sources/ClangSharp/Cursors/Attrs/InheritableParamAttr.cs index 169333fa..aee72544 100644 --- a/sources/ClangSharp/Cursors/Attrs/InheritableParamAttr.cs +++ b/sources/ClangSharp/Cursors/Attrs/InheritableParamAttr.cs @@ -9,9 +9,9 @@ public class InheritableParamAttr : InheritableAttr { internal InheritableParamAttr(CXCursor handle) : base(handle) { - if ((CX_AttrKind.CX_AttrKind_LastInheritableParamAttr < handle.AttrKind) || (handle.AttrKind < CX_AttrKind.CX_AttrKind_FirstInheritableParamAttr)) + if (handle.AttrKind is > CX_AttrKind.CX_AttrKind_LastInheritableParamAttr or < CX_AttrKind.CX_AttrKind_FirstInheritableParamAttr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Attrs/ParameterABIAttr.cs b/sources/ClangSharp/Cursors/Attrs/ParameterABIAttr.cs index ebc4ecda..eee656a8 100644 --- a/sources/ClangSharp/Cursors/Attrs/ParameterABIAttr.cs +++ b/sources/ClangSharp/Cursors/Attrs/ParameterABIAttr.cs @@ -9,9 +9,9 @@ public sealed class ParameterABIAttr : InheritableParamAttr { internal ParameterABIAttr(CXCursor handle) : base(handle) { - if ((CX_AttrKind.CX_AttrKind_LastParameterABIAttr < handle.AttrKind) || (handle.AttrKind < CX_AttrKind.CX_AttrKind_FirstParameterABIAttr)) + if (handle.AttrKind is > CX_AttrKind.CX_AttrKind_LastParameterABIAttr or < CX_AttrKind.CX_AttrKind_FirstParameterABIAttr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Attrs/StmtAttr.cs b/sources/ClangSharp/Cursors/Attrs/StmtAttr.cs index a2bcf390..60874367 100644 --- a/sources/ClangSharp/Cursors/Attrs/StmtAttr.cs +++ b/sources/ClangSharp/Cursors/Attrs/StmtAttr.cs @@ -9,9 +9,9 @@ public sealed class StmtAttr : Attr { internal StmtAttr(CXCursor handle) : base(handle) { - if ((CX_AttrKind.CX_AttrKind_LastStmtAttr < handle.AttrKind) || (handle.AttrKind < CX_AttrKind.CX_AttrKind_FirstStmtAttr)) + if (handle.AttrKind is > CX_AttrKind.CX_AttrKind_LastStmtAttr or < CX_AttrKind.CX_AttrKind_FirstStmtAttr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Attrs/TypeAttr.cs b/sources/ClangSharp/Cursors/Attrs/TypeAttr.cs index 1f53cb66..85a77009 100644 --- a/sources/ClangSharp/Cursors/Attrs/TypeAttr.cs +++ b/sources/ClangSharp/Cursors/Attrs/TypeAttr.cs @@ -9,9 +9,9 @@ public sealed class TypeAttr : Attr { internal TypeAttr(CXCursor handle) : base(handle) { - if ((CX_AttrKind.CX_AttrKind_LastTypeAttr < handle.AttrKind) || (handle.AttrKind < CX_AttrKind.CX_AttrKind_FirstTypeAttr)) + if (handle.AttrKind is > CX_AttrKind.CX_AttrKind_LastTypeAttr or < CX_AttrKind.CX_AttrKind_FirstTypeAttr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Cursor.cs b/sources/ClangSharp/Cursors/Cursor.cs index 9763845b..528efd5e 100644 --- a/sources/ClangSharp/Cursors/Cursor.cs +++ b/sources/ClangSharp/Cursors/Cursor.cs @@ -11,20 +11,22 @@ namespace ClangSharp public unsafe class Cursor : IEquatable { private readonly Lazy> _cursorChildren; + private readonly Lazy _lexicalParentCursor; + private readonly Lazy _semanticParentCursor; private readonly Lazy _translationUnit; private protected Cursor(CXCursor handle, CXCursorKind expectedCursorKind) { if (handle.kind != expectedCursorKind) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Handle = handle; _cursorChildren = new Lazy>(() => { var cursors = new List(); - Handle.VisitChildren((cursor, parent, clientData) => { + _ = Handle.VisitChildren((cursor, parent, clientData) => { var cursorChild = TranslationUnit.GetOrCreate(cursor); cursors.Add(cursorChild); return CXChildVisitResult.CXChildVisit_Continue; @@ -33,6 +35,8 @@ private protected Cursor(CXCursor handle, CXCursorKind expectedCursorKind) return cursors; }); + _lexicalParentCursor = new Lazy(() => TranslationUnit.GetOrCreate(Handle.LexicalParent)); + _semanticParentCursor = new Lazy(() => TranslationUnit.GetOrCreate(Handle.SemanticParent)); _translationUnit = new Lazy(() => TranslationUnit.GetOrCreate(Handle.TranslationUnit)); } @@ -46,8 +50,12 @@ private protected Cursor(CXCursor handle, CXCursorKind expectedCursorKind) public CXCursor Handle { get; } + public Cursor LexicalParentCursor => _lexicalParentCursor.Value; + public CXSourceLocation Location => Handle.Location; + public Cursor SemanticParentCursor => _semanticParentCursor.Value; + public string Spelling => Handle.Spelling.ToString(); public TranslationUnit TranslationUnit => _translationUnit.Value; diff --git a/sources/ClangSharp/Cursors/Decls/BlockDecl.cs b/sources/ClangSharp/Cursors/Decls/BlockDecl.cs index d00a8a3e..273c513c 100644 --- a/sources/ClangSharp/Cursors/Decls/BlockDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/BlockDecl.cs @@ -19,7 +19,7 @@ internal BlockDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unexpos var captureCount = Handle.NumCaptures; var captures = new List(captureCount); - for (int i = 0; i < captureCount; i++) + for (var i = 0; i < captureCount; i++) { var capture = new Capture(this, unchecked((uint)i)); captures.Add(capture); @@ -31,7 +31,7 @@ internal BlockDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unexpos var parameterCount = Handle.NumArguments; var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/CXXConstructorDecl.cs b/sources/ClangSharp/Cursors/Decls/CXXConstructorDecl.cs index 9656577b..318fc3d8 100644 --- a/sources/ClangSharp/Cursors/Decls/CXXConstructorDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/CXXConstructorDecl.cs @@ -62,14 +62,9 @@ public CXXConstructorDecl TargetConstructor return null; } - Expr E = InitExprs.FirstOrDefault()?.IgnoreImplicit; + var e = InitExprs.FirstOrDefault()?.IgnoreImplicit; - if (E is CXXConstructExpr Construct) - { - return Construct.Constructor; - } - - return null; + return e is CXXConstructExpr construct ? construct.Constructor : null; } } } diff --git a/sources/ClangSharp/Cursors/Decls/CXXMethodDecl.cs b/sources/ClangSharp/Cursors/Decls/CXXMethodDecl.cs index 082dbe98..e5bf4185 100644 --- a/sources/ClangSharp/Cursors/Decls/CXXMethodDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/CXXMethodDecl.cs @@ -20,9 +20,9 @@ internal CXXMethodDecl(CXCursor handle) : this(handle, CXCursorKind.CXCursor_CXX private protected CXXMethodDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastCXXMethod < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstCXXMethod)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastCXXMethod or < CX_DeclKind.CX_DeclKind_FirstCXXMethod) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _overloadIndex = new Lazy(() => { @@ -48,7 +48,7 @@ private protected CXXMethodDecl(CXCursor handle, CXCursorKind expectedCursorKind var numOverriddenMethods = Handle.NumMethods; var overriddenMethods = new List(numOverriddenMethods); - for (int i = 0; i < numOverriddenMethods; i++) + for (var i = 0; i < numOverriddenMethods; i++) { var overriddenMethod = TranslationUnit.GetOrCreate(Handle.GetMethod(unchecked((uint)i))); overriddenMethods.Add(overriddenMethod); @@ -65,8 +65,6 @@ private protected CXXMethodDecl(CXCursor handle, CXCursorKind expectedCursorKind public bool IsConst => Handle.CXXMethod_IsConst; - public bool IsInstance => !IsStatic; - public bool IsVirtual => Handle.CXXMethod_IsVirtual; public new CXXMethodDecl MostRecentDecl => (CXXMethodDecl)base.MostRecentDecl; @@ -75,7 +73,7 @@ private protected CXXMethodDecl(CXCursor handle, CXCursorKind expectedCursorKind public IReadOnlyList OverriddenMethods => _overriddenMethods.Value; - public new CXXRecordDecl Parent => (CXXRecordDecl)base.Parent; + public new CXXRecordDecl Parent => (CXXRecordDecl)(base.Parent ?? ThisObjectType.AsCXXRecordDecl); public uint SizeOverriddenMethods => unchecked((uint)Handle.NumMethods); diff --git a/sources/ClangSharp/Cursors/Decls/CXXRecordDecl.cs b/sources/ClangSharp/Cursors/Decls/CXXRecordDecl.cs index 425c8596..5cb2d983 100644 --- a/sources/ClangSharp/Cursors/Decls/CXXRecordDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/CXXRecordDecl.cs @@ -28,9 +28,9 @@ internal CXXRecordDecl(CXCursor handle) : this(handle, handle.Kind, CX_DeclKind. private protected CXXRecordDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastCXXRecord < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstCXXRecord)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastCXXRecord or < CX_DeclKind.CX_DeclKind_FirstCXXRecord) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _bases = new Lazy>(() => { @@ -162,13 +162,13 @@ public CXXRecordDecl MostRecentNonInjectedDecl { get { - CXXRecordDecl Recent = MostRecentDecl; + var recent = MostRecentDecl; - while ((Recent != null) && Recent.IsInjectedClassName) + while ((recent != null) && recent.IsInjectedClassName) { - Recent = Recent.PreviousDecl; + recent = recent.PreviousDecl; } - return Recent; + return recent; } } diff --git a/sources/ClangSharp/Cursors/Decls/CapturedDecl.cs b/sources/ClangSharp/Cursors/Decls/CapturedDecl.cs index e9e4e1a3..4775f2bf 100644 --- a/sources/ClangSharp/Cursors/Decls/CapturedDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/CapturedDecl.cs @@ -18,7 +18,7 @@ internal CapturedDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unex var parameterCount = Handle.NumArguments; var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/ClassScopeFunctionSpecializationDecl.cs b/sources/ClangSharp/Cursors/Decls/ClassScopeFunctionSpecializationDecl.cs index b69c624d..075c61fb 100644 --- a/sources/ClangSharp/Cursors/Decls/ClassScopeFunctionSpecializationDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ClassScopeFunctionSpecializationDecl.cs @@ -18,7 +18,7 @@ internal ClassScopeFunctionSpecializationDecl(CXCursor handle) : base(handle, CX var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgumentLoc(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Decls/ClassTemplatePartialSpecializationDecl.cs b/sources/ClangSharp/Cursors/Decls/ClassTemplatePartialSpecializationDecl.cs index 097e0e6e..ea45f276 100644 --- a/sources/ClangSharp/Cursors/Decls/ClassTemplatePartialSpecializationDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ClassTemplatePartialSpecializationDecl.cs @@ -19,7 +19,7 @@ internal ClassTemplatePartialSpecializationDecl(CXCursor handle) : base(handle, var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List(associatedConstraintCount); - for (int i = 0; i < associatedConstraintCount; i++) + for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); @@ -35,7 +35,7 @@ internal ClassTemplatePartialSpecializationDecl(CXCursor handle) : base(handle, var parameterCount = Handle.GetNumTemplateParameters(0); var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetTemplateParameter(0, unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/ClassTemplateSpecializationDecl.cs b/sources/ClangSharp/Cursors/Decls/ClassTemplateSpecializationDecl.cs index e3f12345..1ebd1e67 100644 --- a/sources/ClangSharp/Cursors/Decls/ClassTemplateSpecializationDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ClassTemplateSpecializationDecl.cs @@ -19,7 +19,7 @@ internal ClassTemplateSpecializationDecl(CXCursor handle) : this(handle, handle. var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); @@ -31,9 +31,9 @@ internal ClassTemplateSpecializationDecl(CXCursor handle) : this(handle, handle. private protected ClassTemplateSpecializationDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastClassTemplateSpecialization < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstClassTemplateSpecialization)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastClassTemplateSpecialization or < CX_DeclKind.CX_DeclKind_FirstClassTemplateSpecialization) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _specializedTemplate = new Lazy(() => TranslationUnit.GetOrCreate(Handle.SpecializedCursorTemplate)); @@ -41,7 +41,7 @@ private protected ClassTemplateSpecializationDecl(CXCursor handle, CXCursorKind var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Decls/Decl.cs b/sources/ClangSharp/Cursors/Decls/Decl.cs index d1808328..80ac4800 100644 --- a/sources/ClangSharp/Cursors/Decls/Decl.cs +++ b/sources/ClangSharp/Cursors/Decls/Decl.cs @@ -13,9 +13,7 @@ public class Decl : Cursor private readonly Lazy _body; private readonly Lazy _canonicalDecl; private readonly Lazy> _decls; - private readonly Lazy _declContext; private readonly Lazy _describedTemplate; - private readonly Lazy _lexicalDeclContext; private readonly Lazy _mostRecentDecl; private readonly Lazy _nextDeclInContext; private readonly Lazy _nonClosureContext; @@ -28,7 +26,7 @@ private protected Decl(CXCursor handle, CXCursorKind expectedCursorKind, CX_Decl { if ((handle.DeclKind == CX_DeclKind.CX_DeclKind_Invalid) || (handle.DeclKind != expectedDeclKind)) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _asFunction = new Lazy(() => TranslationUnit.GetOrCreate(Handle.AsFunction)); @@ -37,7 +35,7 @@ private protected Decl(CXCursor handle, CXCursorKind expectedCursorKind, CX_Decl var attrCount = Handle.NumAttrs; var attrs = new List(attrCount); - for (int i = 0; i < attrCount; i++) + for (var i = 0; i < attrCount; i++) { var attr = TranslationUnit.GetOrCreate(Handle.GetAttr(unchecked((uint)i))); attrs.Add(attr); @@ -53,7 +51,7 @@ private protected Decl(CXCursor handle, CXCursorKind expectedCursorKind, CX_Decl var declCount = Handle.NumDecls; var decls = new List(declCount); - for (int i = 0; i < declCount; i++) + for (var i = 0; i < declCount; i++) { var decl = TranslationUnit.GetOrCreate(Handle.GetDecl(unchecked((uint)i))); decls.Add(decl); @@ -61,10 +59,8 @@ private protected Decl(CXCursor handle, CXCursorKind expectedCursorKind, CX_Decl return decls; }); - - _declContext = new Lazy(() => TranslationUnit.GetOrCreate(Handle.SemanticParent) as IDeclContext); +; _describedTemplate = new Lazy(() => TranslationUnit.GetOrCreate(Handle.DescribedTemplate)); - _lexicalDeclContext = new Lazy(() => TranslationUnit.GetOrCreate(Handle.LexicalParent) as IDeclContext); _mostRecentDecl = new Lazy(() => TranslationUnit.GetOrCreate(Handle.MostRecentDecl)); _nextDeclInContext = new Lazy(() => TranslationUnit.GetOrCreate(Handle.NextDeclInContext)); _nonClosureContext = new Lazy(() => TranslationUnit.GetOrCreate(Handle.NonClosureContext)); @@ -86,7 +82,7 @@ private protected Decl(CXCursor handle, CXCursorKind expectedCursorKind, CX_Decl public Decl CanonicalDecl => _canonicalDecl.Value; - public IDeclContext DeclContext => _declContext.Value; + public IDeclContext DeclContext => SemanticParentCursor as IDeclContext; public string DeclKindName => Handle.DeclKindSpelling; @@ -110,22 +106,8 @@ public bool IsStdNamespace { get { - if (this is not NamespaceDecl ND) - { - return false; - } - - if (ND.IsInline) - { - return ND.Parent.IsStdNamespace; - } - - if (!ND.Parent.RedeclContext.IsTranslationUnit) - { - return false; - } - - return ND.Name == "std"; + return this is NamespaceDecl nd + && (nd.IsInline ? nd.Parent.IsStdNamespace : nd.Parent.RedeclContext.IsTranslationUnit && nd.Name == "std"); } } @@ -139,7 +121,7 @@ public bool IsStdNamespace public CX_DeclKind Kind => Handle.DeclKind; - public IDeclContext LexicalDeclContext => _lexicalDeclContext.Value; + public IDeclContext LexicalDeclContext => LexicalParentCursor as IDeclContext; public IDeclContext LexicalParent => (this is IDeclContext) ? LexicalDeclContext : null; diff --git a/sources/ClangSharp/Cursors/Decls/DeclaratorDecl.cs b/sources/ClangSharp/Cursors/Decls/DeclaratorDecl.cs index c108addb..cb5bcafb 100644 --- a/sources/ClangSharp/Cursors/Decls/DeclaratorDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/DeclaratorDecl.cs @@ -13,9 +13,9 @@ public class DeclaratorDecl : ValueDecl private protected DeclaratorDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastDeclarator < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstDeclarator)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastDeclarator or < CX_DeclKind.CX_DeclKind_FirstDeclarator) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _templateParameterLists = new Lazy>>(() => { diff --git a/sources/ClangSharp/Cursors/Decls/FieldDecl.cs b/sources/ClangSharp/Cursors/Decls/FieldDecl.cs index b4fe1133..1934d9c7 100644 --- a/sources/ClangSharp/Cursors/Decls/FieldDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/FieldDecl.cs @@ -16,9 +16,9 @@ internal FieldDecl(CXCursor handle) : this(handle, CXCursorKind.CXCursor_FieldDe private protected FieldDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastField < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstField)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastField or < CX_DeclKind.CX_DeclKind_FirstField) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _bitWidth = new Lazy(() => TranslationUnit.GetOrCreate(Handle.BitWidth)); @@ -45,6 +45,6 @@ private protected FieldDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX public bool IsUnnamedBitfield => Handle.IsUnnamedBitfield; - public new RecordDecl Parent => (RecordDecl)DeclContext; + public new RecordDecl Parent => (RecordDecl)DeclContext ?? ((SemanticParentCursor is ClassTemplateDecl classTemplateDecl) ? (RecordDecl)classTemplateDecl.TemplatedDecl : null); } } diff --git a/sources/ClangSharp/Cursors/Decls/FunctionDecl.cs b/sources/ClangSharp/Cursors/Decls/FunctionDecl.cs index 11dfca42..622d4fda 100644 --- a/sources/ClangSharp/Cursors/Decls/FunctionDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/FunctionDecl.cs @@ -25,9 +25,9 @@ internal FunctionDecl(CXCursor handle) : this(handle, CXCursorKind.CXCursor_Func private protected FunctionDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastFunction < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstFunction)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastFunction or < CX_DeclKind.CX_DeclKind_FirstFunction) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _callResultType = new Lazy(() => TranslationUnit.GetOrCreate(Handle.CallResultType)); @@ -40,7 +40,7 @@ private protected FunctionDecl(CXCursor handle, CXCursorKind expectedCursorKind, var parameterCount = Handle.NumArguments; var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); parameters.Add(parameter); @@ -57,7 +57,7 @@ private protected FunctionDecl(CXCursor handle, CXCursorKind expectedCursorKind, var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); @@ -99,6 +99,8 @@ private protected FunctionDecl(CXCursor handle, CXCursorKind expectedCursorKind, public bool IsInlined => Handle.IsFunctionInlined; + public bool IsInstance => !IsStatic; + public bool IsNoReturn => Handle.IsNoReturn; public bool IsOverloadedOperator => Handle.IsOverloadedOperator; diff --git a/sources/ClangSharp/Cursors/Decls/FunctionTemplateDecl.cs b/sources/ClangSharp/Cursors/Decls/FunctionTemplateDecl.cs index 6dc448e4..c7944791 100644 --- a/sources/ClangSharp/Cursors/Decls/FunctionTemplateDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/FunctionTemplateDecl.cs @@ -17,7 +17,7 @@ internal FunctionTemplateDecl(CXCursor handle) : base(handle, CXCursorKind.CXCur var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Decls/LinkageSpecDecl.cs b/sources/ClangSharp/Cursors/Decls/LinkageSpecDecl.cs index da37ddb8..6e9cb061 100644 --- a/sources/ClangSharp/Cursors/Decls/LinkageSpecDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/LinkageSpecDecl.cs @@ -9,9 +9,9 @@ public sealed class LinkageSpecDecl : Decl, IDeclContext { internal LinkageSpecDecl(CXCursor handle) : base(handle, handle.Kind, CX_DeclKind.CX_DeclKind_LinkageSpec) { - if ((handle.Kind != CXCursorKind.CXCursor_LinkageSpec) && (handle.Kind != CXCursorKind.CXCursor_UnexposedDecl)) + if (handle.Kind is not CXCursorKind.CXCursor_LinkageSpec and not CXCursorKind.CXCursor_UnexposedDecl) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } diff --git a/sources/ClangSharp/Cursors/Decls/NamedDecl.cs b/sources/ClangSharp/Cursors/Decls/NamedDecl.cs index b83aa8c2..a1aacc4a 100644 --- a/sources/ClangSharp/Cursors/Decls/NamedDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/NamedDecl.cs @@ -11,9 +11,9 @@ public class NamedDecl : Decl private protected NamedDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastNamed < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstNamed)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastNamed or < CX_DeclKind.CX_DeclKind_FirstNamed) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _underlyingDecl = new Lazy(() => TranslationUnit.GetOrCreate(Handle.UnderlyingDecl)); diff --git a/sources/ClangSharp/Cursors/Decls/NonTypeTemplateParmDecl.cs b/sources/ClangSharp/Cursors/Decls/NonTypeTemplateParmDecl.cs index 76e07a6b..7820fbbb 100644 --- a/sources/ClangSharp/Cursors/Decls/NonTypeTemplateParmDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/NonTypeTemplateParmDecl.cs @@ -19,7 +19,7 @@ internal NonTypeTemplateParmDecl(CXCursor handle) : base(handle, CXCursorKind.CX var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List(associatedConstraintCount); - for (int i = 0; i < associatedConstraintCount; i++) + for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); @@ -34,7 +34,7 @@ internal NonTypeTemplateParmDecl(CXCursor handle) : base(handle, CXCursorKind.CX var numExpansionTypes = Handle.NumExpansionTypes; var expansionTypes = new List(numExpansionTypes); - for (int i = 0; i < numExpansionTypes; i++) + for (var i = 0; i < numExpansionTypes; i++) { var expansionType = TranslationUnit.GetOrCreate(Handle.GetExpansionType(unchecked((uint)i))); expansionTypes.Add(expansionType); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCCategoryDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCCategoryDecl.cs index 8388eb80..72ae745c 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCCategoryDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCCategoryDecl.cs @@ -29,7 +29,7 @@ internal ObjCCategoryDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_ var numProtocols = Handle.NumProtocols; var protocols = new List(numProtocols); - for (int i = 0; i < numProtocols; i++) + for (var i = 0; i < numProtocols; i++) { var protocol = TranslationUnit.GetOrCreate(Handle.GetProtocol(unchecked((uint)i))); protocols.Add(protocol); @@ -42,7 +42,7 @@ internal ObjCCategoryDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_ var numTypeParams = Handle.NumArguments; var typeParams = new List(numTypeParams); - for (int i = 0; i < numTypeParams; i++) + for (var i = 0; i < numTypeParams; i++) { var typeParam = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); typeParams.Add(typeParam); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCContainerDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCContainerDecl.cs index ae0f6705..49fbddba 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCContainerDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCContainerDecl.cs @@ -18,9 +18,9 @@ public class ObjCContainerDecl : NamedDecl, IDeclContext private protected ObjCContainerDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastObjCContainer < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstObjCContainer)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastObjCContainer or < CX_DeclKind.CX_DeclKind_FirstObjCContainer) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _classMethods = new Lazy>(() => Methods.Where((method) => method.IsClassMethod).ToList()); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCImplDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCImplDecl.cs index 090a927f..7b646d2c 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCImplDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCImplDecl.cs @@ -14,9 +14,9 @@ public class ObjCImplDecl : ObjCContainerDecl private protected ObjCImplDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastObjCImpl < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstObjCImpl)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastObjCImpl or < CX_DeclKind.CX_DeclKind_FirstObjCImpl) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _classInterface = new Lazy(() => TranslationUnit.GetOrCreate(Handle.GetSubDecl(0))); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCInterfaceDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCInterfaceDecl.cs index fe1bf832..0a9c3cca 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCInterfaceDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCInterfaceDecl.cs @@ -27,7 +27,7 @@ internal ObjCInterfaceDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor _categoryList = new Lazy>(() => { var categories = new List(); - ObjCCategoryDecl category = TranslationUnit.GetOrCreate(handle.GetSubDecl(0)); + var category = TranslationUnit.GetOrCreate(handle.GetSubDecl(0)); while (category != null) { @@ -47,7 +47,7 @@ internal ObjCInterfaceDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor var numProtocols = Handle.NumProtocols; var protocols = new List(numProtocols); - for (int i = 0; i < numProtocols; i++) + for (var i = 0; i < numProtocols; i++) { var protocol = TranslationUnit.GetOrCreate(Handle.GetProtocol(unchecked((uint)i))); protocols.Add(protocol); @@ -64,7 +64,7 @@ internal ObjCInterfaceDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor var numTypeParams = Handle.NumArguments; var typeParams = new List(numTypeParams); - for (int i = 0; i < numTypeParams; i++) + for (var i = 0; i < numTypeParams; i++) { var typeParam = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); typeParams.Add(typeParam); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCMethodDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCMethodDecl.cs index 7e3e0c8f..4c876547 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCMethodDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCMethodDecl.cs @@ -17,9 +17,9 @@ public sealed class ObjCMethodDecl : NamedDecl, IDeclContext internal ObjCMethodDecl(CXCursor handle) : base(handle, handle.Kind, CX_DeclKind.CX_DeclKind_ObjCMethod) { - if ((handle.Kind != CXCursorKind.CXCursor_ObjCInstanceMethodDecl) && (handle.Kind != CXCursorKind.CXCursor_ObjCClassMethodDecl)) + if (handle.Kind is not CXCursorKind.CXCursor_ObjCInstanceMethodDecl and not CXCursorKind.CXCursor_ObjCClassMethodDecl) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _classInterface = new Lazy(() => TranslationUnit.GetOrCreate(Handle.GetSubDecl(0))); @@ -29,7 +29,7 @@ internal ObjCMethodDecl(CXCursor handle) : base(handle, handle.Kind, CX_DeclKind var parameterCount = Handle.NumArguments; var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCPropertyDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCPropertyDecl.cs index e08d4958..c7257980 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCPropertyDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCPropertyDecl.cs @@ -26,7 +26,7 @@ internal ObjCPropertyDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_ public bool IsInstanceProperty => !IsClassProperty; - CXObjCPropertyAttrKind PropertyAttributes => Handle.GetObjCPropertyAttributes(0); + public CXObjCPropertyAttrKind PropertyAttributes => Handle.GetObjCPropertyAttributes(0); public ObjCIvarDecl PropertyIvarDecl => _propertyIvarDecl.Value; diff --git a/sources/ClangSharp/Cursors/Decls/ObjCPropertyImplDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCPropertyImplDecl.cs index 1d5a4b89..dcc6d82a 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCPropertyImplDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCPropertyImplDecl.cs @@ -16,9 +16,9 @@ public sealed class ObjCPropertyImplDecl : Decl internal ObjCPropertyImplDecl(CXCursor handle) : base(handle, handle.Kind, CX_DeclKind.CX_DeclKind_ObjCPropertyImpl) { - if ((handle.Kind != CXCursorKind.CXCursor_ObjCSynthesizeDecl) && (handle.Kind != CXCursorKind.CXCursor_ObjCDynamicDecl)) + if (handle.Kind is not CXCursorKind.CXCursor_ObjCSynthesizeDecl and not CXCursorKind.CXCursor_ObjCDynamicDecl) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _getterCXXConstructor = new Lazy(() => TranslationUnit.GetOrCreate(Handle.GetExpr(0))); diff --git a/sources/ClangSharp/Cursors/Decls/ObjCProtocolDecl.cs b/sources/ClangSharp/Cursors/Decls/ObjCProtocolDecl.cs index 6a713c26..6f8d0635 100644 --- a/sources/ClangSharp/Cursors/Decls/ObjCProtocolDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ObjCProtocolDecl.cs @@ -19,7 +19,7 @@ internal ObjCProtocolDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_ var numProtocols = Handle.NumProtocols; var protocols = new List(numProtocols); - for (int i = 0; i < numProtocols; i++) + for (var i = 0; i < numProtocols; i++) { var protocol = TranslationUnit.GetOrCreate(Handle.GetProtocol(unchecked((uint)i))); protocols.Add(protocol); diff --git a/sources/ClangSharp/Cursors/Decls/RecordDecl.cs b/sources/ClangSharp/Cursors/Decls/RecordDecl.cs index e102dcd3..c701a6f2 100644 --- a/sources/ClangSharp/Cursors/Decls/RecordDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/RecordDecl.cs @@ -22,14 +22,14 @@ internal RecordDecl(CXCursor handle) : this(handle, handle.Kind, CX_DeclKind.CX_ private protected RecordDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastRecord < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstRecord)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastRecord or < CX_DeclKind.CX_DeclKind_FirstRecord) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } - if ((handle.Kind != CXCursorKind.CXCursor_StructDecl) && (handle.Kind != CXCursorKind.CXCursor_UnionDecl) && (handle.Kind != CXCursorKind.CXCursor_ClassDecl) && (handle.Kind != CXCursorKind.CXCursor_ClassTemplatePartialSpecialization)) + if (handle.Kind is not CXCursorKind.CXCursor_StructDecl and not CXCursorKind.CXCursor_UnionDecl and not CXCursorKind.CXCursor_ClassDecl and not CXCursorKind.CXCursor_ClassTemplatePartialSpecialization) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _fields = new Lazy>(() => { diff --git a/sources/ClangSharp/Cursors/Decls/RedeclarableTemplateDecl.cs b/sources/ClangSharp/Cursors/Decls/RedeclarableTemplateDecl.cs index ac392a1f..3627910f 100644 --- a/sources/ClangSharp/Cursors/Decls/RedeclarableTemplateDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/RedeclarableTemplateDecl.cs @@ -11,9 +11,9 @@ public class RedeclarableTemplateDecl : TemplateDecl, IRedeclarable CX_DeclKind.CX_DeclKind_LastRedeclarableTemplate or < CX_DeclKind.CX_DeclKind_FirstRedeclarableTemplate) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _instantiatedFromMemberTemplate = new Lazy(() => TranslationUnit.GetOrCreate(Handle.SpecializedCursorTemplate)); diff --git a/sources/ClangSharp/Cursors/Decls/TagDecl.cs b/sources/ClangSharp/Cursors/Decls/TagDecl.cs index a3a54bb3..4c8a60c8 100644 --- a/sources/ClangSharp/Cursors/Decls/TagDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/TagDecl.cs @@ -14,9 +14,9 @@ public unsafe class TagDecl : TypeDecl, IDeclContext, IRedeclarable private protected TagDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastTag < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstTag)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastTag or < CX_DeclKind.CX_DeclKind_FirstTag) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _definition = new Lazy(() => TranslationUnit.GetOrCreate(Handle.Definition)); diff --git a/sources/ClangSharp/Cursors/Decls/TemplateDecl.cs b/sources/ClangSharp/Cursors/Decls/TemplateDecl.cs index fb81a23c..1978fae5 100644 --- a/sources/ClangSharp/Cursors/Decls/TemplateDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/TemplateDecl.cs @@ -14,16 +14,16 @@ public class TemplateDecl : NamedDecl private protected TemplateDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastTemplate < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstTemplate)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastTemplate or < CX_DeclKind.CX_DeclKind_FirstTemplate) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _associatedConstraints = new Lazy>(() => { var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List(associatedConstraintCount); - for (int i = 0; i < associatedConstraintCount; i++) + for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); @@ -31,12 +31,12 @@ private protected TemplateDecl(CXCursor handle, CXCursorKind expectedCursorKind, return associatedConstraints; }); - _templatedDecl = new Lazy(() => TranslationUnit.GetOrCreate(Handle.TemplatedDecl)); + _templatedDecl = new Lazy(() => TranslationUnit.GetOrCreate(Handle.TemplatedDecl)); _templateParameters = new Lazy>(() => { var parameterCount = Handle.GetNumTemplateParameters(0); var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetTemplateParameter(0, unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs b/sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs index 020db59c..6c832f5b 100644 --- a/sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs @@ -17,7 +17,7 @@ internal TemplateTypeParmDecl(CXCursor handle) : base(handle, CXCursorKind.CXCur var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List(associatedConstraintCount); - for (int i = 0; i < associatedConstraintCount; i++) + for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/TypeDecl.cs b/sources/ClangSharp/Cursors/Decls/TypeDecl.cs index 291e3f2a..e5b85015 100644 --- a/sources/ClangSharp/Cursors/Decls/TypeDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/TypeDecl.cs @@ -11,9 +11,9 @@ public class TypeDecl : NamedDecl private protected TypeDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastType < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstType)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastType or < CX_DeclKind.CX_DeclKind_FirstType) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _typeForDecl = new Lazy(() => TranslationUnit.GetOrCreate(Handle.Type)); diff --git a/sources/ClangSharp/Cursors/Decls/TypedefNameDecl.cs b/sources/ClangSharp/Cursors/Decls/TypedefNameDecl.cs index 2fa5bf61..4808bf38 100644 --- a/sources/ClangSharp/Cursors/Decls/TypedefNameDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/TypedefNameDecl.cs @@ -11,9 +11,9 @@ public class TypedefNameDecl : TypeDecl, IRedeclarable private protected TypedefNameDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastTypedefName < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstTypedefName)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastTypedefName or < CX_DeclKind.CX_DeclKind_FirstTypedefName) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _underlyingType = new Lazy(() => TranslationUnit.GetOrCreate(Handle.TypedefDeclUnderlyingType)); diff --git a/sources/ClangSharp/Cursors/Decls/UsingShadowDecl.cs b/sources/ClangSharp/Cursors/Decls/UsingShadowDecl.cs index 2f9f5f6d..60b7f973 100644 --- a/sources/ClangSharp/Cursors/Decls/UsingShadowDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/UsingShadowDecl.cs @@ -13,9 +13,9 @@ internal UsingShadowDecl(CXCursor handle) : this(handle, CXCursorKind.CXCursor_U private protected UsingShadowDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastUsingShadow < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstUsingShadow)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastUsingShadow or < CX_DeclKind.CX_DeclKind_FirstUsingShadow) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Decls/ValueDecl.cs b/sources/ClangSharp/Cursors/Decls/ValueDecl.cs index f41addd5..9c92a80d 100644 --- a/sources/ClangSharp/Cursors/Decls/ValueDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/ValueDecl.cs @@ -11,9 +11,9 @@ public class ValueDecl : NamedDecl private protected ValueDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastValue < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstValue)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastValue or < CX_DeclKind.CX_DeclKind_FirstValue) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _type = new Lazy(() => TranslationUnit.GetOrCreate(Handle.Type)); diff --git a/sources/ClangSharp/Cursors/Decls/VarDecl.cs b/sources/ClangSharp/Cursors/Decls/VarDecl.cs index 7e64081a..7a0096a0 100644 --- a/sources/ClangSharp/Cursors/Decls/VarDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/VarDecl.cs @@ -17,9 +17,9 @@ internal VarDecl(CXCursor handle) : this(handle, CXCursorKind.CXCursor_VarDecl, private protected VarDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastVar < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstVar)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastVar or < CX_DeclKind.CX_DeclKind_FirstVar) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _definition = new Lazy(() => TranslationUnit.GetOrCreate(Handle.Definition)); diff --git a/sources/ClangSharp/Cursors/Decls/VarTemplatePartialSpecializationDecl.cs b/sources/ClangSharp/Cursors/Decls/VarTemplatePartialSpecializationDecl.cs index 00e2cfe0..f7baf401 100644 --- a/sources/ClangSharp/Cursors/Decls/VarTemplatePartialSpecializationDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/VarTemplatePartialSpecializationDecl.cs @@ -18,7 +18,7 @@ internal VarTemplatePartialSpecializationDecl(CXCursor handle) : base(handle, CX var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List(associatedConstraintCount); - for (int i = 0; i < associatedConstraintCount; i++) + for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); @@ -31,7 +31,7 @@ internal VarTemplatePartialSpecializationDecl(CXCursor handle) : base(handle, CX var parameterCount = Handle.GetNumTemplateParameters(0); var parameters = new List(parameterCount); - for (int i = 0; i < parameterCount; i++) + for (var i = 0; i < parameterCount; i++) { var parameter = TranslationUnit.GetOrCreate(Handle.GetTemplateParameter(0, unchecked((uint)i))); parameters.Add(parameter); diff --git a/sources/ClangSharp/Cursors/Decls/VarTemplateSpecializationDecl.cs b/sources/ClangSharp/Cursors/Decls/VarTemplateSpecializationDecl.cs index 6e9df6ca..0fc31783 100644 --- a/sources/ClangSharp/Cursors/Decls/VarTemplateSpecializationDecl.cs +++ b/sources/ClangSharp/Cursors/Decls/VarTemplateSpecializationDecl.cs @@ -17,9 +17,9 @@ internal VarTemplateSpecializationDecl(CXCursor handle) : this(handle, CXCursorK private protected VarTemplateSpecializationDecl(CXCursor handle, CXCursorKind expectedCursorKind, CX_DeclKind expectedDeclKind) : base(handle, expectedCursorKind, expectedDeclKind) { - if ((CX_DeclKind.CX_DeclKind_LastVarTemplateSpecialization < handle.DeclKind) || (handle.DeclKind < CX_DeclKind.CX_DeclKind_FirstVarTemplateSpecialization)) + if (handle.DeclKind is > CX_DeclKind.CX_DeclKind_LastVarTemplateSpecialization or < CX_DeclKind.CX_DeclKind_FirstVarTemplateSpecialization) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _specializedTemplate = new Lazy(() => TranslationUnit.GetOrCreate(Handle.SpecializedCursorTemplate)); @@ -27,7 +27,7 @@ private protected VarTemplateSpecializationDecl(CXCursor handle, CXCursorKind ex var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/AbstractConditionalOperator.cs b/sources/ClangSharp/Cursors/Exprs/AbstractConditionalOperator.cs index 45169db8..f98d4db9 100644 --- a/sources/ClangSharp/Cursors/Exprs/AbstractConditionalOperator.cs +++ b/sources/ClangSharp/Cursors/Exprs/AbstractConditionalOperator.cs @@ -9,46 +9,16 @@ public class AbstractConditionalOperator : Expr { private protected AbstractConditionalOperator(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastAbstractConditionalOperator < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstAbstractConditionalOperator)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastAbstractConditionalOperator or < CX_StmtClass.CX_StmtClass_FirstAbstractConditionalOperator) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } - public Expr Cond - { - get - { - if (this is ConditionalOperator co) - { - return co.Cond; - } - return ((BinaryConditionalOperator)this).Cond; - } - } + public Expr Cond => this is ConditionalOperator co ? co.Cond : ((BinaryConditionalOperator)this).Cond; - public Expr FalseExpr - { - get - { - if (this is ConditionalOperator co) - { - return co.FalseExpr; - } - return ((BinaryConditionalOperator)this).FalseExpr; - } - } + public Expr FalseExpr => this is ConditionalOperator co ? co.FalseExpr : ((BinaryConditionalOperator)this).FalseExpr; - public Expr TrueExpr - { - get - { - if (this is ConditionalOperator co) - { - return co.TrueExpr; - } - return ((BinaryConditionalOperator)this).TrueExpr; - } - } + public Expr TrueExpr => this is ConditionalOperator co ? co.TrueExpr : ((BinaryConditionalOperator)this).TrueExpr; } } diff --git a/sources/ClangSharp/Cursors/Exprs/AtomicExpr.cs b/sources/ClangSharp/Cursors/Exprs/AtomicExpr.cs index 1dae90ff..91f86499 100644 --- a/sources/ClangSharp/Cursors/Exprs/AtomicExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/AtomicExpr.cs @@ -28,7 +28,7 @@ internal AtomicExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unexpo public Expr Ptr => SubExprs[0]; - public Expr Scope => (Op >= CX_AtomicOperatorKind.CX_AO__opencl_atomic_load && Op <= CX_AtomicOperatorKind.CX_AO__opencl_atomic_fetch_max) ? SubExprs[(int)(NumSubExprs - 1)] : null; + public Expr Scope => (Op is >= CX_AtomicOperatorKind.CX_AO__opencl_atomic_load and <= CX_AtomicOperatorKind.CX_AO__opencl_atomic_fetch_max) ? SubExprs[(int)(NumSubExprs - 1)] : null; public IReadOnlyList SubExprs => _subExprs.Value; @@ -36,25 +36,13 @@ public Expr Val1 { get { - if (Op == CX_AtomicOperatorKind.CX_AO__c11_atomic_init || Op == CX_AtomicOperatorKind.CX_AO__opencl_atomic_init) - { - return Order; - } - return (NumSubExprs > 2) ? SubExprs[2] : null; + return Op is CX_AtomicOperatorKind.CX_AO__c11_atomic_init or CX_AtomicOperatorKind.CX_AO__opencl_atomic_init + ? Order + : (NumSubExprs > 2) ? SubExprs[2] : null; } } - public Expr Val - { - get - { - if (Op == CX_AtomicOperatorKind.CX_AO__atomic_exchange) - { - return OrderFail; - } - return (NumSubExprs > 4) ? SubExprs[4] : null; - } - } + public Expr Val => Op == CX_AtomicOperatorKind.CX_AO__atomic_exchange ? OrderFail : (NumSubExprs > 4) ? SubExprs[4] : null; public Type ValueType => _valueType.Value; diff --git a/sources/ClangSharp/Cursors/Exprs/BinaryOperator.cs b/sources/ClangSharp/Cursors/Exprs/BinaryOperator.cs index 28521e58..42891dcb 100644 --- a/sources/ClangSharp/Cursors/Exprs/BinaryOperator.cs +++ b/sources/ClangSharp/Cursors/Exprs/BinaryOperator.cs @@ -14,39 +14,39 @@ internal BinaryOperator(CXCursor handle) : this(handle, CXCursorKind.CXCursor_Bi private protected BinaryOperator(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastBinaryOperator < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstBinaryOperator)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastBinaryOperator or < CX_StmtClass.CX_StmtClass_FirstBinaryOperator) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren is 2); } - public bool IsAdditiveOp => (Opcode == CX_BinaryOperatorKind.CX_BO_Add) || (Opcode == CX_BinaryOperatorKind.CX_BO_Sub); + public bool IsAdditiveOp => Opcode is CX_BinaryOperatorKind.CX_BO_Add or CX_BinaryOperatorKind.CX_BO_Sub; - public bool IsAssignmentOp => (Opcode >= CX_BinaryOperatorKind.CX_BO_Assign) && (Opcode <= CX_BinaryOperatorKind.CX_BO_OrAssign); + public bool IsAssignmentOp => Opcode is >= CX_BinaryOperatorKind.CX_BO_Assign and <= CX_BinaryOperatorKind.CX_BO_OrAssign; - public bool IsBitwiseOp => (Opcode >= CX_BinaryOperatorKind.CX_BO_And) && (Opcode <= CX_BinaryOperatorKind.CX_BO_Or); + public bool IsBitwiseOp => Opcode is >= CX_BinaryOperatorKind.CX_BO_And and <= CX_BinaryOperatorKind.CX_BO_Or; public bool IsCommaOp => Opcode == CX_BinaryOperatorKind.CX_BO_Comma; - public bool IsComparisonOp => (Opcode >= CX_BinaryOperatorKind.CX_BO_Cmp) && (Opcode <= CX_BinaryOperatorKind.CX_BO_NE); + public bool IsComparisonOp => Opcode is >= CX_BinaryOperatorKind.CX_BO_Cmp and <= CX_BinaryOperatorKind.CX_BO_NE; - public bool IsCompoundAssignmentOp=> (Opcode > CX_BinaryOperatorKind.CX_BO_Assign) && (Opcode <= CX_BinaryOperatorKind.CX_BO_OrAssign); + public bool IsCompoundAssignmentOp=> Opcode is > CX_BinaryOperatorKind.CX_BO_Assign and <= CX_BinaryOperatorKind.CX_BO_OrAssign; - public bool IsEqualityOp => (Opcode == CX_BinaryOperatorKind.CX_BO_EQ) || (Opcode == CX_BinaryOperatorKind.CX_BO_NE); + public bool IsEqualityOp => Opcode is CX_BinaryOperatorKind.CX_BO_EQ or CX_BinaryOperatorKind.CX_BO_NE; - public bool IsLogicalOp => (Opcode == CX_BinaryOperatorKind.CX_BO_LAnd) || (Opcode == CX_BinaryOperatorKind.CX_BO_LOr); + public bool IsLogicalOp => Opcode is CX_BinaryOperatorKind.CX_BO_LAnd or CX_BinaryOperatorKind.CX_BO_LOr; - public bool IsMultiplicativeOp => (Opcode >= CX_BinaryOperatorKind.CX_BO_Mul) && (Opcode <= CX_BinaryOperatorKind.CX_BO_Rem); + public bool IsMultiplicativeOp => Opcode is >= CX_BinaryOperatorKind.CX_BO_Mul and <= CX_BinaryOperatorKind.CX_BO_Rem; - public bool IsPtrMemOp => (Opcode == CX_BinaryOperatorKind.CX_BO_PtrMemD) || (Opcode == CX_BinaryOperatorKind.CX_BO_PtrMemI); + public bool IsPtrMemOp => Opcode is CX_BinaryOperatorKind.CX_BO_PtrMemD or CX_BinaryOperatorKind.CX_BO_PtrMemI; - public bool IsRelationalOp => (Opcode >= CX_BinaryOperatorKind.CX_BO_LT) && (Opcode <= CX_BinaryOperatorKind.CX_BO_GE); + public bool IsRelationalOp => Opcode is >= CX_BinaryOperatorKind.CX_BO_LT and <= CX_BinaryOperatorKind.CX_BO_GE; - public bool IsShiftAssignOp=> (Opcode == CX_BinaryOperatorKind.CX_BO_ShlAssign) || (Opcode == CX_BinaryOperatorKind.CX_BO_ShrAssign); + public bool IsShiftAssignOp=> Opcode is CX_BinaryOperatorKind.CX_BO_ShlAssign or CX_BinaryOperatorKind.CX_BO_ShrAssign; - public bool IsShiftOp => (Opcode == CX_BinaryOperatorKind.CX_BO_Shl) || (Opcode == CX_BinaryOperatorKind.CX_BO_Shr); + public bool IsShiftOp => Opcode is CX_BinaryOperatorKind.CX_BO_Shl or CX_BinaryOperatorKind.CX_BO_Shr; public Expr LHS => (Expr)Children[0]; diff --git a/sources/ClangSharp/Cursors/Exprs/CXXConstructExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXConstructExpr.cs index 5cb51f94..1a3885fe 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXConstructExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXConstructExpr.cs @@ -19,9 +19,9 @@ internal CXXConstructExpr(CXCursor handle) : this(handle, CXCursorKind.CXCursor_ private protected CXXConstructExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastCXXConstructExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstCXXConstructExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastCXXConstructExpr or < CX_StmtClass.CX_StmtClass_FirstCXXConstructExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren == NumArgs); diff --git a/sources/ClangSharp/Cursors/Exprs/CXXDefaultInitExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXDefaultInitExpr.cs index b1f0e369..84bb0c29 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXDefaultInitExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXDefaultInitExpr.cs @@ -8,8 +8,8 @@ namespace ClangSharp { public sealed class CXXDefaultInitExpr : Expr { - private Lazy _field; - private Lazy _usedContext; + private readonly Lazy _field; + private readonly Lazy _usedContext; internal CXXDefaultInitExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_UnexposedExpr, CX_StmtClass.CX_StmtClass_CXXDefaultInitExpr) { diff --git a/sources/ClangSharp/Cursors/Exprs/CXXDeleteExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXDeleteExpr.cs index 0f876844..6483e528 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXDeleteExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXDeleteExpr.cs @@ -8,8 +8,8 @@ namespace ClangSharp { public sealed class CXXDeleteExpr : Expr { - private Lazy _destroyedType; - private Lazy _operatorDelete; + private readonly Lazy _destroyedType; + private readonly Lazy _operatorDelete; internal CXXDeleteExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_CXXDeleteExpr, CX_StmtClass.CX_StmtClass_CXXDeleteExpr) { diff --git a/sources/ClangSharp/Cursors/Exprs/CXXDependentScopeMemberExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXDependentScopeMemberExpr.cs index b0e59246..1bd7d3b6 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXDependentScopeMemberExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXDependentScopeMemberExpr.cs @@ -24,7 +24,7 @@ internal CXXDependentScopeMemberExpr(CXCursor handle) : base(handle, CXCursorKin var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgumentLoc(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/CXXMemberCallExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXMemberCallExpr.cs index 196b87ca..9d2e66bd 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXMemberCallExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXMemberCallExpr.cs @@ -14,18 +14,18 @@ public Expr ImplicitObjectArgument { get { - Expr callee = Callee.IgnoreParens; + var callee = Callee.IgnoreParens; - if (callee is MemberExpr MemExpr) + if (callee is MemberExpr memExpr) { - return MemExpr.Base; + return memExpr.Base; } - if (callee is BinaryOperator BO) + if (callee is BinaryOperator bo) { - if (BO.IsPtrMemOp) + if (bo.IsPtrMemOp) { - return BO.LHS; + return bo.LHS; } } @@ -33,30 +33,19 @@ public Expr ImplicitObjectArgument } } - public CXXMethodDecl MethodDecl - { - get - { - if (Callee.IgnoreParens is MemberExpr MemExpr) - { - return (CXXMethodDecl)MemExpr.MemberDecl; - } - - return null; - } - } + public CXXMethodDecl MethodDecl => Callee.IgnoreParens is MemberExpr memExpr ? (CXXMethodDecl)memExpr.MemberDecl : null; public Type ObjectType { get { - Type Ty = ImplicitObjectArgument.Type; + var ty = ImplicitObjectArgument.Type; - if (Ty.IsPointerType) + if (ty.IsPointerType) { - Ty = Ty.PointeeType; + ty = ty.PointeeType; } - return Ty; + return ty; } } @@ -64,19 +53,11 @@ public CXXRecordDecl RecordDecl { get { - Expr ThisArg = ImplicitObjectArgument; - - if (ThisArg is null) - { - return null; - } - - if (ThisArg.Type.IsAnyPointerType) - { - return ThisArg.Type.PointeeType.AsCXXRecordDecl; - } + var thisArg = ImplicitObjectArgument; - return ThisArg.Type.AsCXXRecordDecl; + return thisArg is null + ? null + : thisArg.Type.IsAnyPointerType ? thisArg.Type.PointeeType.AsCXXRecordDecl : thisArg.Type.AsCXXRecordDecl; } } } diff --git a/sources/ClangSharp/Cursors/Exprs/CXXNamedCastExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXNamedCastExpr.cs index 026d4b0e..b3a8eea0 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXNamedCastExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXNamedCastExpr.cs @@ -9,9 +9,9 @@ public class CXXNamedCastExpr : ExplicitCastExpr { private protected CXXNamedCastExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastCXXNamedCastExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstCXXNamedCastExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastCXXNamedCastExpr or < CX_StmtClass.CX_StmtClass_FirstCXXNamedCastExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } diff --git a/sources/ClangSharp/Cursors/Exprs/CXXNewExpr.cs b/sources/ClangSharp/Cursors/Exprs/CXXNewExpr.cs index faf6f834..1569716b 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXNewExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXNewExpr.cs @@ -44,7 +44,7 @@ internal CXXNewExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_CXXNew public IReadOnlyList PlacementArgs => _placementArgs.Value; - private int ArraySizeOffset => 0; + private static int ArraySizeOffset => 0; private int InitExprOffset => ArraySizeOffset + (IsArray ? 1 : 0); diff --git a/sources/ClangSharp/Cursors/Exprs/CXXRewrittenBinaryOperator.cs b/sources/ClangSharp/Cursors/Exprs/CXXRewrittenBinaryOperator.cs index 2b7a1a99..4b0ef5b8 100644 --- a/sources/ClangSharp/Cursors/Exprs/CXXRewrittenBinaryOperator.cs +++ b/sources/ClangSharp/Cursors/Exprs/CXXRewrittenBinaryOperator.cs @@ -21,9 +21,9 @@ internal CXXRewrittenBinaryOperator(CXCursor handle) : base(handle, CXCursorKind public Expr LHS => _lhs.Value; - public bool IsAssignmentOp => false; + public static bool IsAssignmentOp => false; - public bool IsComparisonOp => true; + public static bool IsComparisonOp => true; public CX_BinaryOperatorKind Opcode => Operator; diff --git a/sources/ClangSharp/Cursors/Exprs/CallExpr.cs b/sources/ClangSharp/Cursors/Exprs/CallExpr.cs index c7b6196f..ed66542f 100644 --- a/sources/ClangSharp/Cursors/Exprs/CallExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CallExpr.cs @@ -19,9 +19,9 @@ internal CallExpr(CXCursor handle) : this(handle, CXCursorKind.CXCursor_CallExpr private protected CallExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastCallExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstCallExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastCallExpr or < CX_StmtClass.CX_StmtClass_FirstCallExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren >= 1); @@ -38,7 +38,7 @@ private protected CallExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_ public FunctionDecl DirectCallee => CalleeDecl as FunctionDecl; - public bool IsCallToStdMove => (NumArgs == 1) && (DirectCallee is FunctionDecl FD) && FD.IsInStdNamespace && (FD.Name == "move"); + public bool IsCallToStdMove => (NumArgs == 1) && (DirectCallee is FunctionDecl fd) && fd.IsInStdNamespace && (fd.Name == "move"); public uint NumArgs => (uint)Handle.NumArguments; } diff --git a/sources/ClangSharp/Cursors/Exprs/CastExpr.cs b/sources/ClangSharp/Cursors/Exprs/CastExpr.cs index 4c4067a8..304883f7 100644 --- a/sources/ClangSharp/Cursors/Exprs/CastExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CastExpr.cs @@ -14,9 +14,9 @@ public class CastExpr : Expr private protected CastExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastCastExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstCastExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastCastExpr or < CX_StmtClass.CX_StmtClass_FirstCastExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren is 1); @@ -25,7 +25,7 @@ private protected CastExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_ var pathSize = Handle.NumArguments; var path = new List(pathSize); - for (int i = 0; i < pathSize; i++) + for (var i = 0; i < pathSize; i++) { var item = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); path.Add(item); @@ -44,22 +44,22 @@ public NamedDecl ConversionFunction { get { - Expr SubExpr; + Expr subExpr; - for (CastExpr E = this; E is not null; E = SubExpr as ImplicitCastExpr) + for (var e = this; e is not null; e = subExpr as ImplicitCastExpr) { - SubExpr = SkipImplicitTemporary(E.SubExpr); + subExpr = SkipImplicitTemporary(e.SubExpr); - if (E.CastKind == CX_CastKind.CX_CK_ConstructorConversion) + if (e.CastKind == CX_CastKind.CX_CK_ConstructorConversion) { - return ((CXXConstructExpr)SubExpr).Constructor; + return ((CXXConstructExpr)subExpr).Constructor; } - if (E.CastKind == CX_CastKind.CX_CK_UserDefinedConversion) + if (e.CastKind == CX_CastKind.CX_CK_UserDefinedConversion) { - if (SubExpr is CXXMemberCallExpr MCE) + if (subExpr is CXXMemberCallExpr mce) { - return MCE.MethodDecl; + return mce.MethodDecl; } } } @@ -80,33 +80,33 @@ public Expr SubExprAsWritten { get { - Expr SubExpr; - CastExpr E = this; + Expr subExpr; + var e = this; do { - SubExpr = SkipImplicitTemporary(E.SubExpr); + subExpr = SkipImplicitTemporary(e.SubExpr); // Conversions by constructor and conversion functions have a subexpression describing the call; strip it off. - if (E.CastKind == CX_CastKind.CX_CK_ConstructorConversion) + if (e.CastKind == CX_CastKind.CX_CK_ConstructorConversion) { - SubExpr = SkipImplicitTemporary(((CXXConstructExpr)SubExpr).Args[0]); + subExpr = SkipImplicitTemporary(((CXXConstructExpr)subExpr).Args[0]); } - else if (E.CastKind == CX_CastKind.CX_CK_UserDefinedConversion) + else if (e.CastKind == CX_CastKind.CX_CK_UserDefinedConversion) { - Debug.Assert((SubExpr is CXXMemberCallExpr) || (SubExpr is BlockExpr), "Unexpected SubExpr for CK_UserDefinedConversion."); + Debug.Assert(subExpr is CXXMemberCallExpr or BlockExpr, "Unexpected SubExpr for CK_UserDefinedConversion."); - if (SubExpr is CXXMemberCallExpr MCE) + if (subExpr is CXXMemberCallExpr mce) { - SubExpr = MCE.ImplicitObjectArgument; + subExpr = mce.ImplicitObjectArgument; } } // If the subexpression we're left with is an implicit cast, look // through that, too. - } while ((E = SubExpr as ImplicitCastExpr) is not null); + } while ((e = subExpr as ImplicitCastExpr) is not null); - return SubExpr; + return subExpr; } } diff --git a/sources/ClangSharp/Cursors/Exprs/CoroutineSuspendExpr.cs b/sources/ClangSharp/Cursors/Exprs/CoroutineSuspendExpr.cs index f7891e3c..e6eb91b8 100644 --- a/sources/ClangSharp/Cursors/Exprs/CoroutineSuspendExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/CoroutineSuspendExpr.cs @@ -9,9 +9,9 @@ public class CoroutineSuspendExpr : Expr { private protected CoroutineSuspendExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastCoroutineSuspendExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstCoroutineSuspendExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastCoroutineSuspendExpr or < CX_StmtClass.CX_StmtClass_FirstCoroutineSuspendExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Exprs/DeclRefExpr.cs b/sources/ClangSharp/Cursors/Exprs/DeclRefExpr.cs index af157a5a..365be07a 100644 --- a/sources/ClangSharp/Cursors/Exprs/DeclRefExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/DeclRefExpr.cs @@ -15,9 +15,9 @@ public sealed class DeclRefExpr : Expr internal DeclRefExpr(CXCursor handle) : base(handle, handle.Kind, CX_StmtClass.CX_StmtClass_DeclRefExpr) { - if ((handle.Kind != CXCursorKind.CXCursor_DeclRefExpr) && (handle.Kind != CXCursorKind.CXCursor_ObjCSelfExpr)) + if (handle.Kind is not CXCursorKind.CXCursor_DeclRefExpr and not CXCursorKind.CXCursor_ObjCSelfExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren is 0); @@ -29,7 +29,7 @@ internal DeclRefExpr(CXCursor handle) : base(handle, handle.Kind, CX_StmtClass.C var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgumentLoc(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/ExplicitCastExpr.cs b/sources/ClangSharp/Cursors/Exprs/ExplicitCastExpr.cs index 83b01574..3efbeabe 100644 --- a/sources/ClangSharp/Cursors/Exprs/ExplicitCastExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/ExplicitCastExpr.cs @@ -11,9 +11,9 @@ public class ExplicitCastExpr : CastExpr private protected ExplicitCastExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastExplicitCastExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstExplicitCastExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastExplicitCastExpr or < CX_StmtClass.CX_StmtClass_FirstExplicitCastExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _typeAsWritten = new Lazy(() => TranslationUnit.GetOrCreate(Handle.TypeOperand)); diff --git a/sources/ClangSharp/Cursors/Exprs/Expr.cs b/sources/ClangSharp/Cursors/Exprs/Expr.cs index 69aa8a74..005d58d8 100644 --- a/sources/ClangSharp/Cursors/Exprs/Expr.cs +++ b/sources/ClangSharp/Cursors/Exprs/Expr.cs @@ -7,82 +7,54 @@ namespace ClangSharp { public class Expr : ValueStmt { - private static readonly Func IgnoreImplicitCastsSingleStep = (E) => - { - if (E is ImplicitCastExpr ICE) - { - return ICE.SubExpr; - } - - if (E is FullExpr FE) - { - return FE.SubExpr; - } - - return E; - }; + private static readonly Func s_ignoreImplicitCastsSingleStep = (e) => e is ImplicitCastExpr ice ? ice.SubExpr : e is FullExpr fe ? fe.SubExpr : e; - private static readonly Func IgnoreImplicitSingleStep = (E) => + private static readonly Func s_ignoreImplicitSingleStep = (e) => { - Expr SubE = IgnoreImplicitCastsSingleStep(E); - - if (SubE != E) - { - return SubE; - } - - if (E is MaterializeTemporaryExpr MTE) - { - return MTE.SubExpr; - } - - if (E is CXXBindTemporaryExpr BTE) - { - return BTE.SubExpr; - } + var subE = s_ignoreImplicitCastsSingleStep(e); - return E; + return subE != e ? subE : e is MaterializeTemporaryExpr mte ? mte.SubExpr : e is CXXBindTemporaryExpr bte ? bte.SubExpr : e; }; - private static readonly Func IgnoreParensSingleStep = (E) => + private static readonly Func s_ignoreParensSingleStep = (e) => { - if (E is ParenExpr PE) + if (e is ParenExpr pe) { - return PE.SubExpr; + return pe.SubExpr; } - if (E is UnaryOperator UO) + if (e is UnaryOperator uo) { - if (UO.Opcode == CX_UnaryOperatorKind.CX_UO_Extension) + if (uo.Opcode == CX_UnaryOperatorKind.CX_UO_Extension) { - return UO.SubExpr; + return uo.SubExpr; } } - else if (E is GenericSelectionExpr GSE) + else if (e is GenericSelectionExpr gse) { - if (!GSE.IsResultDependent) + if (!gse.IsResultDependent) { - return GSE.ResultExpr; + return gse.ResultExpr; } } - else if (E is ChooseExpr CE) + else if (e is ChooseExpr ce) { - if (!CE.IsConditionDependent) + if (!ce.IsConditionDependent) { - return CE.ChosenSubExpr; + return ce.ChosenSubExpr; } } - return E; + return e; }; private readonly Lazy _type; private protected Expr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastExpr or < CX_StmtClass.CX_StmtClass_FirstExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _type = new Lazy(() => TranslationUnit.GetOrCreate(Handle.Type)); @@ -94,57 +66,52 @@ private protected Expr(CXCursor handle, CXCursorKind expectedCursorKind, CX_Stmt public CX_ExprDependence Dependence => Handle.ExprDependence; - public Expr IgnoreImplicit => IgnoreExprNodes(this, IgnoreImplicitSingleStep); + public Expr IgnoreImplicit => IgnoreExprNodes(this, s_ignoreImplicitSingleStep); - public Expr IgnoreParens => IgnoreExprNodes(this, IgnoreParensSingleStep); + public Expr IgnoreParens => IgnoreExprNodes(this, s_ignoreParensSingleStep); public bool IsImplicitCXXThis { get { - Expr E = this; + var e = this; while (true) { - if (E is ParenExpr Paren) + if (e is ParenExpr paren) { - E = Paren.SubExpr; + e = paren.SubExpr; continue; } - if (E is ImplicitCastExpr ICE) + if (e is ImplicitCastExpr ice) { - if ((ICE.CastKind == CX_CastKind.CX_CK_NoOp) || (ICE.CastKind == CX_CastKind.CX_CK_LValueToRValue) || (ICE.CastKind == CX_CastKind.CX_CK_DerivedToBase) || (ICE.CastKind == CX_CastKind.CX_CK_UncheckedDerivedToBase)) + if (ice.CastKind is CX_CastKind.CX_CK_NoOp or CX_CastKind.CX_CK_LValueToRValue or CX_CastKind.CX_CK_DerivedToBase or CX_CastKind.CX_CK_UncheckedDerivedToBase) { - E = ICE.SubExpr; + e = ice.SubExpr; continue; } } - if (E is UnaryOperator UnOp) + if (e is UnaryOperator unOp) { - if (UnOp.Opcode == CX_UnaryOperatorKind.CX_UO_Extension) + if (unOp.Opcode == CX_UnaryOperatorKind.CX_UO_Extension) { - E = UnOp.SubExpr; + e = unOp.SubExpr; continue; } } - if (E is MaterializeTemporaryExpr M) + if (e is MaterializeTemporaryExpr m) { - E = M.SubExpr; + e = m.SubExpr; continue; } break; } - if (E is CXXThisExpr This) - { - return This.IsImplicit; - } - - return false; + return e is CXXThisExpr self && self.IsImplicit; } } @@ -156,34 +123,34 @@ public bool IsImplicitCXXThis public Type Type => _type.Value; - private static Expr IgnoreExprNodes(Expr E, Func Fn) + private static Expr IgnoreExprNodes(Expr e, Func fn) { - Expr LastE = null; + Expr lastE = null; - while (E != LastE) + while (e != lastE) { - LastE = E; - E = Fn(E); + lastE = e; + e = fn(e); } - return E; + return e; } - protected static Expr SkipImplicitTemporary(Expr E) + protected static Expr SkipImplicitTemporary(Expr e) { // Skip through reference binding to temporary. - if (E is MaterializeTemporaryExpr Materialize) + if (e is MaterializeTemporaryExpr materialize) { - E = Materialize.SubExpr; + e = materialize.SubExpr; } // Skip any temporary bindings; they're implicit. - if (E is CXXBindTemporaryExpr Binder) + if (e is CXXBindTemporaryExpr binder) { - E = Binder.SubExpr; + e = binder.SubExpr; } - return E; + return e; } } } diff --git a/sources/ClangSharp/Cursors/Exprs/FullExpr.cs b/sources/ClangSharp/Cursors/Exprs/FullExpr.cs index facd5d52..c6dfd3cd 100644 --- a/sources/ClangSharp/Cursors/Exprs/FullExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/FullExpr.cs @@ -10,9 +10,9 @@ public class FullExpr : Expr { private protected FullExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastFullExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstFullExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastFullExpr or < CX_StmtClass.CX_StmtClass_FirstFullExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Debug.Assert(NumChildren is 1); diff --git a/sources/ClangSharp/Cursors/Exprs/IntegerLiteral.cs b/sources/ClangSharp/Cursors/Exprs/IntegerLiteral.cs index 35a12206..0fb9a0f0 100644 --- a/sources/ClangSharp/Cursors/Exprs/IntegerLiteral.cs +++ b/sources/ClangSharp/Cursors/Exprs/IntegerLiteral.cs @@ -16,7 +16,7 @@ internal IntegerLiteral(CXCursor handle) : base(handle, CXCursorKind.CXCursor_In var tokens = Handle.TranslationUnit.Tokenize(Handle.SourceRange); Debug.Assert(tokens.Length == 1); - Debug.Assert(tokens[0].Kind == CXTokenKind.CXToken_Literal); + Debug.Assert(tokens[0].Kind is CXTokenKind.CXToken_Literal or CXTokenKind.CXToken_Identifier); var spelling = tokens[0].GetSpelling(Handle.TranslationUnit).ToString(); spelling = spelling.Trim('\\', '\r', '\n'); diff --git a/sources/ClangSharp/Cursors/Exprs/MemberExpr.cs b/sources/ClangSharp/Cursors/Exprs/MemberExpr.cs index 14c8766e..f078a514 100644 --- a/sources/ClangSharp/Cursors/Exprs/MemberExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/MemberExpr.cs @@ -21,7 +21,7 @@ internal MemberExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Member var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgumentLoc(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/ObjCMessageExpr.cs b/sources/ClangSharp/Cursors/Exprs/ObjCMessageExpr.cs index dae607e5..81c0bd25 100644 --- a/sources/ClangSharp/Cursors/Exprs/ObjCMessageExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/ObjCMessageExpr.cs @@ -21,7 +21,7 @@ internal ObjCMessageExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_O var numArgs = Handle.NumArguments; var args = new List(numArgs); - for (int i = 0; i < numArgs; i++) + for (var i = 0; i < numArgs; i++) { var arg = TranslationUnit.GetOrCreate(Handle.GetArgument(unchecked((uint)i))); args.Add(arg); diff --git a/sources/ClangSharp/Cursors/Exprs/OverloadExpr.cs b/sources/ClangSharp/Cursors/Exprs/OverloadExpr.cs index d80086b4..721c5c08 100644 --- a/sources/ClangSharp/Cursors/Exprs/OverloadExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/OverloadExpr.cs @@ -14,16 +14,16 @@ public class OverloadExpr : Expr private protected OverloadExpr(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastOverloadExpr < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstOverloadExpr)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastOverloadExpr or < CX_StmtClass.CX_StmtClass_FirstOverloadExpr) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _decls = new Lazy>(() => { var numDecls = Handle.NumDecls; var decls = new List(numDecls); - for (int i = 0; i < numDecls; i++) + for (var i = 0; i < numDecls; i++) { var decl = TranslationUnit.GetOrCreate(Handle.GetDecl(unchecked((uint)i))); decls.Add(decl); @@ -38,7 +38,7 @@ private protected OverloadExpr(CXCursor handle, CXCursorKind expectedCursorKind, var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgumentLoc(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/SizeOfPackExpr.cs b/sources/ClangSharp/Cursors/Exprs/SizeOfPackExpr.cs index 077ccc86..2ac1c5cc 100644 --- a/sources/ClangSharp/Cursors/Exprs/SizeOfPackExpr.cs +++ b/sources/ClangSharp/Cursors/Exprs/SizeOfPackExpr.cs @@ -18,7 +18,7 @@ internal SizeOfPackExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Si var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Cursors/Exprs/UnaryOperator.cs b/sources/ClangSharp/Cursors/Exprs/UnaryOperator.cs index 95880457..055e3c0e 100644 --- a/sources/ClangSharp/Cursors/Exprs/UnaryOperator.cs +++ b/sources/ClangSharp/Cursors/Exprs/UnaryOperator.cs @@ -12,17 +12,17 @@ internal UnaryOperator(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Una Debug.Assert(NumChildren is 1); } - public bool IsArithmetic => (Opcode >= CX_UnaryOperatorKind.CX_UO_Plus) && (Opcode <= CX_UnaryOperatorKind.CX_UO_LNot); + public bool IsArithmetic => Opcode is >= CX_UnaryOperatorKind.CX_UO_Plus and <= CX_UnaryOperatorKind.CX_UO_LNot; - public bool IsDecrementOp => (Opcode == CX_UnaryOperatorKind.CX_UO_PreDec) || (Opcode == CX_UnaryOperatorKind.CX_UO_PostDec); + public bool IsDecrementOp => Opcode is CX_UnaryOperatorKind.CX_UO_PreDec or CX_UnaryOperatorKind.CX_UO_PostDec; - public bool IsIncrementOp => (Opcode == CX_UnaryOperatorKind.CX_UO_PreInc) || (Opcode == CX_UnaryOperatorKind.CX_UO_PostInc); + public bool IsIncrementOp => Opcode is CX_UnaryOperatorKind.CX_UO_PreInc or CX_UnaryOperatorKind.CX_UO_PostInc; - public bool IsIncrementDecrementOp => (Opcode <= CX_UnaryOperatorKind.CX_UO_PreDec); + public bool IsIncrementDecrementOp => Opcode <= CX_UnaryOperatorKind.CX_UO_PreDec; - public bool IsPrefix => (Opcode == CX_UnaryOperatorKind.CX_UO_PreInc) || (Opcode == CX_UnaryOperatorKind.CX_UO_PreDec); + public bool IsPrefix => Opcode is CX_UnaryOperatorKind.CX_UO_PreInc or CX_UnaryOperatorKind.CX_UO_PreDec; - public bool IsPostfix => (Opcode == CX_UnaryOperatorKind.CX_UO_PostInc) || (Opcode == CX_UnaryOperatorKind.CX_UO_PostDec); + public bool IsPostfix => Opcode is CX_UnaryOperatorKind.CX_UO_PostInc or CX_UnaryOperatorKind.CX_UO_PostDec; public CX_UnaryOperatorKind Opcode => Handle.UnaryOperatorKind; diff --git a/sources/ClangSharp/Cursors/Stmts/AsmStmt.cs b/sources/ClangSharp/Cursors/Stmts/AsmStmt.cs index fdaf6714..68ad75fc 100644 --- a/sources/ClangSharp/Cursors/Stmts/AsmStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/AsmStmt.cs @@ -9,9 +9,9 @@ public class AsmStmt : Stmt { private protected AsmStmt(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastAsmStmt < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstAsmStmt)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastAsmStmt or < CX_StmtClass.CX_StmtClass_FirstAsmStmt) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Stmts/CapturedStmt.cs b/sources/ClangSharp/Cursors/Stmts/CapturedStmt.cs index f07aba5b..c36cedc9 100644 --- a/sources/ClangSharp/Cursors/Stmts/CapturedStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/CapturedStmt.cs @@ -41,7 +41,7 @@ internal CapturedStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unex public RecordDecl CapturedRecordDecl => _capturedRecordDecl.Value; - CX_CapturedRegionKind CapturedRegionKind => Handle.CapturedRegionKind; + public CX_CapturedRegionKind CapturedRegionKind => Handle.CapturedRegionKind; public Stmt CaptureStmt => _captureStmt.Value; @@ -53,14 +53,14 @@ internal CapturedStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Unex public bool CapturesVariable(VarDecl var) { - foreach (var I in Captures) + foreach (var i in Captures) { - if (!I.CapturesVariable && !I.CapturesVariableByCopy) + if (!i.CapturesVariable && !i.CapturesVariableByCopy) { continue; } - if (I.CapturedVar.CanonicalDecl == var.CanonicalDecl) + if (i.CapturedVar.CanonicalDecl == var.CanonicalDecl) { return true; } diff --git a/sources/ClangSharp/Cursors/Stmts/CaseStmt.cs b/sources/ClangSharp/Cursors/Stmts/CaseStmt.cs index e528bded..dbcbca33 100644 --- a/sources/ClangSharp/Cursors/Stmts/CaseStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/CaseStmt.cs @@ -20,7 +20,7 @@ internal CaseStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_CaseStmt public new Stmt SubStmt => Children[SubStmtOffset]; - private int LHSOffset => 0; + private static int LHSOffset => 0; private int RHSOffset => LHSOffset + (CaseStmtIsGNURange ? 1 : 0); diff --git a/sources/ClangSharp/Cursors/Stmts/CompoundStmt.cs b/sources/ClangSharp/Cursors/Stmts/CompoundStmt.cs index 841d3d7e..9e66ebfb 100644 --- a/sources/ClangSharp/Cursors/Stmts/CompoundStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/CompoundStmt.cs @@ -24,11 +24,11 @@ public Stmt StmtExprResult { get { - foreach (var B in Body.Reverse()) + foreach (var b in Body.Reverse()) { - if (B is not NullStmt) + if (b is not NullStmt) { - return B; + return b; } } return BodyBack; diff --git a/sources/ClangSharp/Cursors/Stmts/IfStmt.cs b/sources/ClangSharp/Cursors/Stmts/IfStmt.cs index 7a75bce6..ec597f2f 100644 --- a/sources/ClangSharp/Cursors/Stmts/IfStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/IfStmt.cs @@ -38,7 +38,7 @@ internal IfStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_IfStmt, CX private int ElseOffset => CondOffset + 2; - private int InitOffset => 0; + private static int InitOffset => 0; private int ThenOffset => CondOffset + 1; diff --git a/sources/ClangSharp/Cursors/Stmts/OMPExecutableDirective.cs b/sources/ClangSharp/Cursors/Stmts/OMPExecutableDirective.cs index 53244b68..1dde0175 100644 --- a/sources/ClangSharp/Cursors/Stmts/OMPExecutableDirective.cs +++ b/sources/ClangSharp/Cursors/Stmts/OMPExecutableDirective.cs @@ -9,9 +9,9 @@ public class OMPExecutableDirective : Stmt { private protected OMPExecutableDirective(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastOMPExecutableDirective < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstOMPExecutableDirective)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastOMPExecutableDirective or < CX_StmtClass.CX_StmtClass_FirstOMPExecutableDirective) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Stmts/OMPLoopDirective.cs b/sources/ClangSharp/Cursors/Stmts/OMPLoopDirective.cs index 17243ef1..1b6ac8a9 100644 --- a/sources/ClangSharp/Cursors/Stmts/OMPLoopDirective.cs +++ b/sources/ClangSharp/Cursors/Stmts/OMPLoopDirective.cs @@ -9,9 +9,9 @@ public class OMPLoopDirective : OMPExecutableDirective { private protected OMPLoopDirective(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastOMPLoopDirective < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstOMPLoopDirective)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastOMPLoopDirective or < CX_StmtClass.CX_StmtClass_FirstOMPLoopDirective) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } } diff --git a/sources/ClangSharp/Cursors/Stmts/ObjCAtTryStmt.cs b/sources/ClangSharp/Cursors/Stmts/ObjCAtTryStmt.cs index a21a823f..3d79099f 100644 --- a/sources/ClangSharp/Cursors/Stmts/ObjCAtTryStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/ObjCAtTryStmt.cs @@ -31,12 +31,7 @@ internal ObjCAtTryStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Obj _finallyStmt = new Lazy(() => { var children = Children; - if (children.Last() is ObjCAtFinallyStmt finallyStmt) - { - return finallyStmt; - } - - return null; + return children.Last() is ObjCAtFinallyStmt finallyStmt ? finallyStmt : null; }); } diff --git a/sources/ClangSharp/Cursors/Stmts/Stmt.cs b/sources/ClangSharp/Cursors/Stmts/Stmt.cs index f8104a6a..9e623017 100644 --- a/sources/ClangSharp/Cursors/Stmts/Stmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/Stmt.cs @@ -15,14 +15,14 @@ private protected Stmt(CXCursor handle, CXCursorKind expectedCursorKind, CX_Stmt { if ((handle.StmtClass == CX_StmtClass.CX_StmtClass_Invalid) || (handle.StmtClass != expectedStmtClass)) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _children = new Lazy>(() => { var numChildren = Handle.NumChildren; var children = new List(numChildren); - for (int i = 0; i < numChildren; i++) + for (var i = 0; i < numChildren; i++) { var child = TranslationUnit.GetOrCreate(Handle.GetChild(unchecked((uint)i))); children.Add(child); @@ -34,7 +34,7 @@ private protected Stmt(CXCursor handle, CXCursorKind expectedCursorKind, CX_Stmt _declContext = new Lazy(() => { var semanticParent = TranslationUnit.GetOrCreate(Handle.SemanticParent); - while (!(semanticParent is IDeclContext) && (semanticParent != null)) + while (semanticParent is not IDeclContext and not null) { semanticParent = TranslationUnit.GetOrCreate(semanticParent.Handle.SemanticParent); } @@ -53,62 +53,62 @@ private protected Stmt(CXCursor handle, CXCursorKind expectedCursorKind, CX_Stmt public string StmtClassName => Handle.StmtClassSpelling; - public Stmt IgnoreContainers(bool IgnoreCaptured = false) + public Stmt IgnoreContainers(bool ignoreCaptured = false) { - Stmt S = this; + var s = this; - if (IgnoreCaptured) + if (ignoreCaptured) { - if (S is CapturedStmt CapS) + if (s is CapturedStmt capS) { - S = CapS.CaptureStmt; + s = capS.CaptureStmt; } } while (true) { - if (S is AttributedStmt AS) + if (s is AttributedStmt @as) { - S = AS.SubStmt; + s = @as.SubStmt; } - else if (S is CompoundStmt CS) + else if (s is CompoundStmt cs) { - if (CS.Size != 1) + if (cs.Size != 1) { break; } - S = CS.BodyBack; + s = cs.BodyBack; } else { break; } } - return S; + return s; } public Stmt StripLabelLikeStatements() { - Stmt S = this; + var s = this; while (true) { - if (S is LabelStmt LS) + if (s is LabelStmt ls) { - S = LS.SubStmt; + s = ls.SubStmt; } - else if (S is SwitchCase SC) + else if (s is SwitchCase sc) { - S = SC.SubStmt; + s = sc.SubStmt; } - else if (S is AttributedStmt AS) + else if (s is AttributedStmt @as) { - S = AS.SubStmt; + s = @as.SubStmt; } else { - return S; + return s; } } } diff --git a/sources/ClangSharp/Cursors/Stmts/SwitchCase.cs b/sources/ClangSharp/Cursors/Stmts/SwitchCase.cs index bc03062b..cbf5923d 100644 --- a/sources/ClangSharp/Cursors/Stmts/SwitchCase.cs +++ b/sources/ClangSharp/Cursors/Stmts/SwitchCase.cs @@ -12,9 +12,9 @@ public class SwitchCase : Stmt private protected SwitchCase(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastSwitchCase < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstSwitchCase)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastSwitchCase or < CX_StmtClass.CX_StmtClass_FirstSwitchCase) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } _nextSwitchCase = new Lazy(() => TranslationUnit.GetOrCreate(Handle.NextSwitchCase)); @@ -26,13 +26,13 @@ public Stmt SubStmt { get { - if (this is CaseStmt CS) + if (this is CaseStmt cs) { - return CS.SubStmt; + return cs.SubStmt; } - else if (this is DefaultStmt DS) + else if (this is DefaultStmt ds) { - return DS.SubStmt; + return ds.SubStmt; } Debug.Fail("SwitchCase is neither a CaseStmt nor a DefaultStmt!"); diff --git a/sources/ClangSharp/Cursors/Stmts/SwitchStmt.cs b/sources/ClangSharp/Cursors/Stmts/SwitchStmt.cs index b68481a7..dfdc88ff 100644 --- a/sources/ClangSharp/Cursors/Stmts/SwitchStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/SwitchStmt.cs @@ -38,7 +38,7 @@ internal SwitchStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_Switch private int CondOffset => VarOffset + (HasVarStorage ? 1 : 0); - private int InitOffset => 0; + private static int InitOffset => 0; private int VarOffset => InitOffset + (HasInitStorage ? 1 : 0); diff --git a/sources/ClangSharp/Cursors/Stmts/ValueStmt.cs b/sources/ClangSharp/Cursors/Stmts/ValueStmt.cs index f1489b16..c9b0ccf9 100644 --- a/sources/ClangSharp/Cursors/Stmts/ValueStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/ValueStmt.cs @@ -10,9 +10,9 @@ public class ValueStmt : Stmt { private protected ValueStmt(CXCursor handle, CXCursorKind expectedCursorKind, CX_StmtClass expectedStmtClass) : base(handle, expectedCursorKind, expectedStmtClass) { - if ((CX_StmtClass.CX_StmtClass_LastValueStmt < handle.StmtClass) || (handle.StmtClass < CX_StmtClass.CX_StmtClass_FirstValueStmt)) + if (handle.StmtClass is > CX_StmtClass.CX_StmtClass_LastValueStmt or < CX_StmtClass.CX_StmtClass_FirstValueStmt) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } } @@ -20,27 +20,28 @@ public Expr ExprStmt { get { - Stmt S = this; + Stmt s = this; + do { - if (S is Expr E) + if (s is Expr e) { - return E; + return e; } - if (S is LabelStmt LS) + if (s is LabelStmt ls) { - S = LS.SubStmt; + s = ls.SubStmt; } - else if (S is AttributedStmt AS) + else if (s is AttributedStmt @as) { - S = AS.SubStmt; + s = @as.SubStmt; } else { Debug.Fail("unknown kind of ValueStmt"); } - } while (S is ValueStmt); + } while (s is ValueStmt); return null; } diff --git a/sources/ClangSharp/Cursors/Stmts/WhileStmt.cs b/sources/ClangSharp/Cursors/Stmts/WhileStmt.cs index 65052f1d..187e143b 100644 --- a/sources/ClangSharp/Cursors/Stmts/WhileStmt.cs +++ b/sources/ClangSharp/Cursors/Stmts/WhileStmt.cs @@ -26,6 +26,6 @@ internal WhileStmt(CXCursor handle) : base(handle, CXCursorKind.CXCursor_WhileSt private int CondOffset => VarOffset + (HasVarStorage ? 1 : 0); - private int VarOffset => 0; + private static int VarOffset => 0; } } diff --git a/sources/ClangSharp/Internals/Index.cs b/sources/ClangSharp/Internals/Index.cs new file mode 100644 index 00000000..8abfd8f4 --- /dev/null +++ b/sources/ClangSharp/Internals/Index.cs @@ -0,0 +1,67 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if NETSTANDARD2_0 +using System.Runtime.CompilerServices; + +namespace System +{ + internal readonly struct Index : IEquatable + { + private readonly int _value; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _value = fromEnd ? ~value : value; + } + + private Index(int value) + { + _value = value; + } + + public static Index Start => new Index(0); + + public static Index End => new Index(~0); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value)) : new Index(value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value)) : new Index(~value); + + public int Value => _value < 0 ? ~_value : _value; + + public bool IsFromEnd => _value < 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + var offset = _value; + if (IsFromEnd) + { + offset += length + 1; + } + return offset; + } + + public override bool Equals(object value) => value is Index index && _value == index._value; + + public bool Equals(Index other) => _value == other._value; + + public override int GetHashCode() => _value; + + public static implicit operator Index(int value) => FromStart(value); + + public override string ToString() => IsFromEnd ? ToStringFromEnd() : ((uint)Value).ToString(); + + private string ToStringFromEnd() => '^' + Value.ToString(); + } +} +#endif diff --git a/sources/ClangSharp/Internals/MarshaledStringArray.cs b/sources/ClangSharp/Internals/MarshaledStringArray.cs index 75945cf3..cdedfcb1 100644 --- a/sources/ClangSharp/Internals/MarshaledStringArray.cs +++ b/sources/ClangSharp/Internals/MarshaledStringArray.cs @@ -18,7 +18,7 @@ public MarshaledStringArray(ReadOnlySpan inputs) { _values = new MarshaledString[inputs.Length]; - for (int i = 0; i < inputs.Length; i++) + for (var i = 0; i < inputs.Length; i++) { _values[i] = new MarshaledString(inputs[i]); } @@ -31,7 +31,7 @@ public void Dispose() { if (_values != null) { - for (int i = 0; i < _values.Length; i++) + for (var i = 0; i < _values.Length; i++) { _values[i].Dispose(); } @@ -44,7 +44,7 @@ public void Fill(sbyte** pDestination) { if (_values != null) { - for (int i = 0; i < _values.Length; i++) + for (var i = 0; i < _values.Length; i++) { pDestination[i] = Values[i]; } diff --git a/sources/ClangSharp/Internals/Range.cs b/sources/ClangSharp/Internals/Range.cs new file mode 100644 index 00000000..86f5a888 --- /dev/null +++ b/sources/ClangSharp/Internals/Range.cs @@ -0,0 +1,55 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if NETSTANDARD2_0 +using System.Runtime.CompilerServices; + +namespace System +{ + internal readonly struct Range : IEquatable + { + public Index Start { get; } + + public Index End { get; } + + public Range(Index start, Index end) + { + Start = start; + End = end; + } + + public override bool Equals(object value) => + value is Range r && + r.Start.Equals(Start) && + r.End.Equals(End); + + public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End); + + public override int GetHashCode() => HashCode.Combine(Start.GetHashCode(), End.GetHashCode()); + + public override string ToString() => Start.ToString() + ".." + End.ToString(); + + public static Range StartAt(Index start) => new Range(start, Index.End); + + public static Range EndAt(Index end) => new Range(Index.Start, end); + + public static Range All => new Range(Index.Start, Index.End); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + int start; + var startIndex = Start; + start = startIndex.IsFromEnd ? length - startIndex.Value : startIndex.Value; + + int end; + var endIndex = End; + end = endIndex.IsFromEnd ? length - endIndex.Value : endIndex.Value; + + return (uint)end > (uint)length || (uint)start > (uint)end + ? throw new ArgumentOutOfRangeException(nameof(length)) + : (start, end - start); + } + } +} +#endif diff --git a/sources/ClangSharp/Interop.Extensions/CXCursor.cs b/sources/ClangSharp/Interop.Extensions/CXCursor.cs index f822d243..e0b23e68 100644 --- a/sources/ClangSharp/Interop.Extensions/CXCursor.cs +++ b/sources/ClangSharp/Interop.Extensions/CXCursor.cs @@ -346,7 +346,7 @@ public string AttrKindSpelling CX_AttrKind.CX_AttrKind_Overloadable => "Overloadable", CX_AttrKind.CX_AttrKind_RenderScriptKernel => "RenderScriptKernel", CX_AttrKind.CX_AttrKind_Thread => "Thread", - _ => Kind.ToString().Substring(12), + _ => Kind.ToString()[12..], }; } } @@ -458,7 +458,7 @@ public string CastKindSpelling CX_CastKind.CX_CK_ZeroToOCLOpaqueType => "ZeroToOCLOpaqueType", CX_CastKind.CX_CK_AddressSpaceConversion => "AddressSpaceConversion", CX_CastKind.CX_CK_IntToOCLSampler => "IntToOCLSampler", - _ => CastKind.ToString().Substring(6), + _ => CastKind.ToString()[6..], }; } } @@ -649,7 +649,7 @@ public string DeclKindSpelling CX_DeclKind.CX_DeclKind_RequiresExprBody => "RequiresExprBody", CX_DeclKind.CX_DeclKind_StaticAssert => "StaticAssert", CX_DeclKind.CX_DeclKind_TranslationUnit => "TranslationUnit", - _ => Kind.ToString().Substring(12), + _ => Kind.ToString()[12..], }; } } @@ -1363,7 +1363,7 @@ public string StmtClassSpelling CX_StmtClass.CX_StmtClass_VAArgExpr => "VAArgExpr", CX_StmtClass.CX_StmtClass_LabelStmt => "LabelStmt", CX_StmtClass.CX_StmtClass_WhileStmt => "WhileStmt", - _ => StmtClass.ToString().Substring(13), + _ => StmtClass.ToString()[13..], }; } } @@ -1448,18 +1448,18 @@ internal string DebuggerDisplayString if (BinaryOperatorKind != CX_BinaryOperatorKind.CX_BO_Invalid) { - additionalInfo = $"({BinaryOperatorKindSpelling})"; + additionalInfo = $" ({BinaryOperatorKindSpelling})"; } else if (CastKind != CX_CastKind.CX_CK_Invalid) { - additionalInfo = $"({CastKindSpelling})"; + additionalInfo = $" ({CastKindSpelling})"; } else if (UnaryOperatorKind != CX_UnaryOperatorKind.CX_UO_Invalid) { - additionalInfo = $"({UnaryOperatorKindSpelling})"; + additionalInfo = $" ({UnaryOperatorKindSpelling})"; } - return $"{StmtClassSpelling}: {this}"; + return $"{StmtClassSpelling}: {this}{additionalInfo}"; } else { @@ -1474,7 +1474,7 @@ internal string DebuggerDisplayString public bool CapturesVariable(CXCursor var) => clangsharp.Cursor_getCapturesVariable(this, var) != 0; - public void DisposeOverriddenCursors(ReadOnlySpan overridden) + public static void DisposeOverriddenCursors(ReadOnlySpan overridden) { fixed (CXCursor* pOverridden = overridden) { diff --git a/sources/ClangSharp/Interop.Extensions/CXIndex.cs b/sources/ClangSharp/Interop.Extensions/CXIndex.cs index 9703120e..ce4b1538 100644 --- a/sources/ClangSharp/Interop.Extensions/CXIndex.cs +++ b/sources/ClangSharp/Interop.Extensions/CXIndex.cs @@ -13,8 +13,15 @@ public CXIndex(IntPtr handle) public CXGlobalOptFlags GlobalOptions { - get => (CXGlobalOptFlags)clang.CXIndex_getGlobalOptions(this); - set => clang.CXIndex_setGlobalOptions(this, (uint)value); + get + { + return (CXGlobalOptFlags)clang.CXIndex_getGlobalOptions(this); + } + + set + { + clang.CXIndex_setGlobalOptions(this, (uint)value); + } } public IntPtr Handle { get; set; } diff --git a/sources/ClangSharp/Interop.Extensions/CXType.cs b/sources/ClangSharp/Interop.Extensions/CXType.cs index 152cc203..2d9e2f15 100644 --- a/sources/ClangSharp/Interop.Extensions/CXType.cs +++ b/sources/ClangSharp/Interop.Extensions/CXType.cs @@ -125,7 +125,15 @@ public unsafe partial struct CXType : IEquatable public CXString Spelling => clang.getTypeSpelling(this); - public CX_TemplateName TemplateName => clangsharp.Type_getTemplateName(this); + public CX_TemplateName TemplateName + { + get + { + var TN = clangsharp.Type_getTemplateName(this); + TN.tu = (CXTranslationUnitImpl*)data[1]; + return TN; + } + } public CX_TypeClass TypeClass => clangsharp.Type_getTypeClass(this); @@ -192,7 +200,7 @@ public string TypeClassSpelling CX_TypeClass.CX_TypeClass_UnresolvedUsing => "UnresolvedUsing", CX_TypeClass.CX_TypeClass_Vector => "Vector", CX_TypeClass.CX_TypeClass_ExtVector => "ExtVector", - _ => TypeClass.ToString().Substring(13), + _ => TypeClass.ToString()[13..], }; } } @@ -205,13 +213,7 @@ public string TypeClassSpelling public CXType ValueType => clang.Type_getValueType(this); - internal string DebuggerDisplayString - { - get - { - return $"{TypeClassSpelling}: {this}"; - } - } + internal string DebuggerDisplayString => $"{TypeClassSpelling}: {this}"; public static bool operator ==(CXType left, CXType right) => clang.equalTypes(left, right) != 0; diff --git a/sources/ClangSharp/Interop.Extensions/CXUnsavedFile.cs b/sources/ClangSharp/Interop.Extensions/CXUnsavedFile.cs index b1fbc25e..b24a098d 100644 --- a/sources/ClangSharp/Interop.Extensions/CXUnsavedFile.cs +++ b/sources/ClangSharp/Interop.Extensions/CXUnsavedFile.cs @@ -15,7 +15,6 @@ public static CXUnsavedFile Create(string filename, string contents) if ((filename is null) || (filename.Length == 0)) { - filenameLength = 0; pFilename = IntPtr.Zero; } else diff --git a/sources/ClangSharp/Interop.Extensions/clang.ResolveLibrary.cs b/sources/ClangSharp/Interop.Extensions/clang.ResolveLibrary.cs index b19f0860..e5df7b77 100644 --- a/sources/ClangSharp/Interop.Extensions/clang.ResolveLibrary.cs +++ b/sources/ClangSharp/Interop.Extensions/clang.ResolveLibrary.cs @@ -17,55 +17,25 @@ static clang() private static IntPtr OnDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { - IntPtr nativeLibrary; - if (TryResolveLibrary(libraryName, assembly, searchPath, out nativeLibrary)) - { - return nativeLibrary; - } - - if (libraryName.Equals("libclang") && TryResolveClang(assembly, searchPath, out nativeLibrary)) - { - return nativeLibrary; - } - - if (libraryName.Equals("libClangSharp") && TryResolveClangSharp(assembly, searchPath, out nativeLibrary)) - { - return nativeLibrary; - } - - return IntPtr.Zero; + return TryResolveLibrary(libraryName, assembly, searchPath, out var nativeLibrary) + ? nativeLibrary + : libraryName.Equals("libclang") && TryResolveClang(assembly, searchPath, out nativeLibrary) + ? nativeLibrary + : libraryName.Equals("libClangSharp") && TryResolveClangSharp(assembly, searchPath, out nativeLibrary) + ? nativeLibrary + : IntPtr.Zero; } private static bool TryResolveClang(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang.so.10", assembly, searchPath, out nativeLibrary)) - { - return true; - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang-10", assembly, searchPath, out nativeLibrary)) - { - return true; - } - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang.so.1", assembly, searchPath, out nativeLibrary)) - { - return true; - } - - if (NativeLibrary.TryLoad("libclang", assembly, searchPath, out nativeLibrary)) - { - return true; - } - - return false; + return (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang.so.10", assembly, searchPath, out nativeLibrary)) + || (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang-10", assembly, searchPath, out nativeLibrary)) + || (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && NativeLibrary.TryLoad("libclang.so.1", assembly, searchPath, out nativeLibrary)) + || NativeLibrary.TryLoad("libclang", assembly, searchPath, out nativeLibrary); } - private static bool TryResolveClangSharp(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) - { - return NativeLibrary.TryLoad("libClangSharp", assembly, searchPath, out nativeLibrary); - } + private static bool TryResolveClangSharp(Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) => NativeLibrary.TryLoad("libClangSharp", assembly, searchPath, out nativeLibrary); private static bool TryResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr nativeLibrary) { diff --git a/sources/ClangSharp/Interop/.editorconfig b/sources/ClangSharp/Interop/.editorconfig new file mode 100644 index 00000000..ec18c8f6 --- /dev/null +++ b/sources/ClangSharp/Interop/.editorconfig @@ -0,0 +1,28 @@ +############################################################################### +# EditorConfig is awesome: http://EditorConfig.org +############################################################################### + +############################################################################### +# Not top-most EditorConfig file +############################################################################### +root = false + +############################################################################### +# Set dotnet naming rules to: +# disable any parent naming rules since they are not applicable to interop +############################################################################### +[*.cs] +dotnet_naming_rule.async_methods_should_be_pascal_case_suffixed_with_async.severity = none +dotnet_naming_rule.const_fields_and_locals_should_be_pascal_case.severity = none +dotnet_naming_rule.interfaces_should_be_pascal_case_prefixed_with_i.severity = none +dotnet_naming_rule.locals_should_be_camel_case.severity = none +dotnet_naming_rule.parameters_should_be_camel_case.severity = none +dotnet_naming_rule.private_and_internal_static_fields_should_be_camel_case_prefixed_with_s_and_underscore.severity = none +dotnet_naming_rule.private_and_internal_fields_should_be_camel_case_prefixed_with_underscore.severity = none +dotnet_naming_rule.public_and_protected_declarations_should_be_pascal_case.severity = none +dotnet_naming_rule.type_parameters_should_be_pascal_case_prefixed_with_t.severity = none + +############################################################################### +# Supress diagnostics that don't apply to ClangSharp P/Invokes +############################################################################### +dotnet_diagnostic.CA1401.severity = none diff --git a/sources/ClangSharp/Interop/CXCompletionContext.cs b/sources/ClangSharp/Interop/CXCompletionContext.cs index ce231d08..ad6d3022 100644 --- a/sources/ClangSharp/Interop/CXCompletionContext.cs +++ b/sources/ClangSharp/Interop/CXCompletionContext.cs @@ -31,6 +31,6 @@ public enum CXCompletionContext CXCompletionContext_MacroName = 1 << 20, CXCompletionContext_NaturalLanguage = 1 << 21, CXCompletionContext_IncludedFile = 1 << 22, - CXCompletionContext_Unknown = ((1 << 23) - 1), + CXCompletionContext_Unknown = (1 << 23) - 1, } } diff --git a/sources/ClangSharp/Interop/clang.cs b/sources/ClangSharp/Interop/clang.cs index 42fcffc8..4641287c 100644 --- a/sources/ClangSharp/Interop/clang.cs +++ b/sources/ClangSharp/Interop/clang.cs @@ -1353,7 +1353,7 @@ public static unsafe partial class clang public const int CINDEX_VERSION_MINOR = 60; [NativeTypeName("#define CINDEX_VERSION CINDEX_VERSION_ENCODE(CINDEX_VERSION_MAJOR, CINDEX_VERSION_MINOR)")] - public const int CINDEX_VERSION = (((0) * 10000) + ((60) * 1)); + public const int CINDEX_VERSION = (0 * 10000) + (60 * 1); [NativeTypeName("#define CINDEX_VERSION_STRING CINDEX_VERSION_STRINGIZE(CINDEX_VERSION_MAJOR, CINDEX_VERSION_MINOR)")] public static ReadOnlySpan CINDEX_VERSION_STRING => new byte[] { 0x30, 0x2E, 0x36, 0x30, 0x00 }; diff --git a/sources/ClangSharp/TemplateArgument.cs b/sources/ClangSharp/TemplateArgument.cs index 9aa81106..d82a7790 100644 --- a/sources/ClangSharp/TemplateArgument.cs +++ b/sources/ClangSharp/TemplateArgument.cs @@ -138,9 +138,6 @@ public void Dispose() GC.SuppressFinalize(this); } - private void Dispose(bool isDisposing) - { - Handle.Dispose(); - } + private void Dispose(bool isDisposing) => Handle.Dispose(); } } diff --git a/sources/ClangSharp/TranslationUnit.cs b/sources/ClangSharp/TranslationUnit.cs index ea894b5b..13923847 100644 --- a/sources/ClangSharp/TranslationUnit.cs +++ b/sources/ClangSharp/TranslationUnit.cs @@ -9,8 +9,8 @@ namespace ClangSharp { public sealed unsafe class TranslationUnit : IDisposable, IEquatable { - private static readonly ConcurrentDictionary> _createdTranslationUnits = new ConcurrentDictionary>(); - private static readonly object _createTranslationUnitLock = new object(); + private static readonly ConcurrentDictionary> s_createdTranslationUnits = new ConcurrentDictionary>(); + private static readonly object s_createTranslationUnitLock = new object(); private readonly Dictionary> _createdCursors; private readonly Dictionary> _createdTemplateArguments; @@ -54,11 +54,11 @@ public static TranslationUnit GetOrCreate(CXTranslationUnit handle) return null; } - var translationUnitRef = _createdTranslationUnits.GetOrAdd(handle, (handle) => new WeakReference(null)); + var translationUnitRef = s_createdTranslationUnits.GetOrAdd(handle, (handle) => new WeakReference(null)); - if (!translationUnitRef.TryGetTarget(out TranslationUnit translationUnit)) + if (!translationUnitRef.TryGetTarget(out var translationUnit)) { - lock (_createTranslationUnitLock) + lock (s_createTranslationUnitLock) { if (!translationUnitRef.TryGetTarget(out translationUnit)) { @@ -97,7 +97,7 @@ internal TCursor GetOrCreate(CXCursor handle) _createdCursors.Add(handle, cursorRef); } - if (!cursorRef.TryGetTarget(out Cursor cursor)) + if (!cursorRef.TryGetTarget(out var cursor)) { cursor = Cursor.Create(handle); cursorRef.SetTarget(cursor); @@ -119,7 +119,7 @@ internal TemplateArgument GetOrCreate(CX_TemplateArgument handle) _createdTemplateArguments.Add(handle, templateArgumentRef); } - if (!templateArgumentRef.TryGetTarget(out TemplateArgument templateArgument)) + if (!templateArgumentRef.TryGetTarget(out var templateArgument)) { templateArgument = new TemplateArgument(handle); templateArgumentRef.SetTarget(templateArgument); @@ -141,7 +141,7 @@ internal TemplateArgumentLoc GetOrCreate(CX_TemplateArgumentLoc handle) _createdTemplateArgumentLocs.Add(handle, templateArgumentLocRef); } - if (!templateArgumentLocRef.TryGetTarget(out TemplateArgumentLoc templateArgumentLoc)) + if (!templateArgumentLocRef.TryGetTarget(out var templateArgumentLoc)) { templateArgumentLoc = new TemplateArgumentLoc(handle); templateArgumentLocRef.SetTarget(templateArgumentLoc); @@ -163,7 +163,7 @@ internal TemplateName GetOrCreate(CX_TemplateName handle) _createdTemplateNames.Add(handle, templateNameRef); } - if (!templateNameRef.TryGetTarget(out TemplateName templateName)) + if (!templateNameRef.TryGetTarget(out var templateName)) { templateName = new TemplateName(handle); templateNameRef.SetTarget(templateName); @@ -186,7 +186,7 @@ internal TType GetOrCreate(CXType handle) _createdTypes.Add(handle, typeRef); } - if (!typeRef.TryGetTarget(out Type type)) + if (!typeRef.TryGetTarget(out var type)) { type = Type.Create(handle); typeRef.SetTarget(type); @@ -207,7 +207,7 @@ private void Dispose(bool isDisposing) Handle.Dispose(); } - _createdTranslationUnits.TryRemove(Handle, out _); + _ = s_createdTranslationUnits.TryRemove(Handle, out _); } } } diff --git a/sources/ClangSharp/Types/AutoType.cs b/sources/ClangSharp/Types/AutoType.cs index 8f59aaa2..5453ed51 100644 --- a/sources/ClangSharp/Types/AutoType.cs +++ b/sources/ClangSharp/Types/AutoType.cs @@ -16,7 +16,7 @@ internal AutoType(CXType handle) : base(handle, CXTypeKind.CXType_Auto, CX_TypeC var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Types/DependentTemplateSpecializationType.cs b/sources/ClangSharp/Types/DependentTemplateSpecializationType.cs index f497f5f3..ce258cd6 100644 --- a/sources/ClangSharp/Types/DependentTemplateSpecializationType.cs +++ b/sources/ClangSharp/Types/DependentTemplateSpecializationType.cs @@ -16,7 +16,7 @@ internal DependentTemplateSpecializationType(CXType handle) : base(handle, CXTyp var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Types/FunctionProtoType.cs b/sources/ClangSharp/Types/FunctionProtoType.cs index 2368d41b..311c1a81 100644 --- a/sources/ClangSharp/Types/FunctionProtoType.cs +++ b/sources/ClangSharp/Types/FunctionProtoType.cs @@ -16,7 +16,7 @@ internal FunctionProtoType(CXType handle) : base(handle, CXTypeKind.CXType_Funct var paramTypeCount = Handle.NumArgTypes; var paramTypes = new List(paramTypeCount); - for (int i = 0; i < paramTypeCount; i++) + for (var i = 0; i < paramTypeCount; i++) { var paramType = TranslationUnit.GetOrCreate(Handle.GetArgType(unchecked((uint)i))); paramTypes.Add(paramType); diff --git a/sources/ClangSharp/Types/SubstTemplateTypeParmPackType.cs b/sources/ClangSharp/Types/SubstTemplateTypeParmPackType.cs index 63466cc5..aa5cd239 100644 --- a/sources/ClangSharp/Types/SubstTemplateTypeParmPackType.cs +++ b/sources/ClangSharp/Types/SubstTemplateTypeParmPackType.cs @@ -15,5 +15,9 @@ internal SubstTemplateTypeParmPackType(CXType handle) : base(handle, CXTypeKind. _argumentPack = new Lazy(() => TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(0))); _replacedParameter = new Lazy(() => TranslationUnit.GetOrCreate(Handle.OriginalType)); } + + public TemplateArgument ArgumentPack => _argumentPack.Value; + + public TemplateTypeParmType ReplacedParameter => _replacedParameter.Value; } } diff --git a/sources/ClangSharp/Types/TemplateSpecializationType.cs b/sources/ClangSharp/Types/TemplateSpecializationType.cs index 832461ca..bf7e87df 100644 --- a/sources/ClangSharp/Types/TemplateSpecializationType.cs +++ b/sources/ClangSharp/Types/TemplateSpecializationType.cs @@ -17,7 +17,7 @@ internal TemplateSpecializationType(CXType handle) : base(handle, CXTypeKind.CXT var templateArgCount = Handle.NumTemplateArguments; var templateArgs = new List(templateArgCount); - for (int i = 0; i < templateArgCount; i++) + for (var i = 0; i < templateArgCount; i++) { var templateArg = TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(unchecked((uint)i))); templateArgs.Add(templateArg); diff --git a/sources/ClangSharp/Types/Type.cs b/sources/ClangSharp/Types/Type.cs index fa4b5955..8fe315df 100644 --- a/sources/ClangSharp/Types/Type.cs +++ b/sources/ClangSharp/Types/Type.cs @@ -18,12 +18,12 @@ protected Type(CXType handle, CXTypeKind expectedKind, CX_TypeClass expectedType { if (handle.kind != expectedKind) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } if ((handle.TypeClass == CX_TypeClass.CX_TypeClass_Invalid) || (handle.TypeClass != expectedTypeClass)) { - throw new ArgumentException(nameof(handle)); + throw new ArgumentOutOfRangeException(nameof(handle)); } Handle = handle; @@ -41,17 +41,9 @@ public TagDecl AsTagDecl { get { - if (GetAs() is TagType TT) - { - return TT.Decl; - } - - if (GetAs() is InjectedClassNameType Injected) - { - return Injected.Decl; - } - - return null; + return GetAs() is TagType tt + ? tt.Decl + : (global::ClangSharp.TagDecl)(GetAs() is InjectedClassNameType injected ? injected.Decl : null); } } @@ -65,34 +57,15 @@ public TagDecl AsTagDecl public bool IsExtIntType => CanonicalType is ExtIntType; - public bool IsIntegerType - { - get - { - if (this is BuiltinType builtinType) - { - return (CXTypeKind.CXType_Bool <= Kind) && (Kind <= CXTypeKind.CXType_Int128); - } - - return false; - } - } + public bool IsIntegerType => (CanonicalType is BuiltinType builtinType) && builtinType.Kind is >= CXTypeKind.CXType_Bool and <= CXTypeKind.CXType_Int128; public bool IsIntegralOrEnumerationType { get { - if (CanonicalType is BuiltinType BT) - { - return (BT.Kind >= CXTypeKind.CXType_Bool) && (BT.Kind <= CXTypeKind.CXType_Int128); - } - - if (CanonicalType is EnumType ET) - { - return ET.Decl.IsComplete; - } - - return IsExtIntType; + return CanonicalType is BuiltinType bt + ? bt.Kind is >= CXTypeKind.CXType_Bool and <= CXTypeKind.CXType_Int128 + : CanonicalType is EnumType et ? et.Decl.IsComplete : IsExtIntType; } } @@ -120,15 +93,15 @@ public Type UnqualifiedDesugaredType { get { - Type Cur = this; + var cur = this; while (true) { - if (!Cur.IsSugared) + if (!cur.IsSugared) { - return Cur; + return cur; } - Cur = Cur.Desugar; + cur = cur.Desugar; } } } @@ -197,7 +170,7 @@ public Type UnqualifiedDesugaredType public T CastAs() where T : Type { - Debug.Assert(typeof(ArrayType).IsAssignableFrom(typeof(T)), "ArrayType cannot be used with castAs!"); + Debug.Assert(!typeof(ArrayType).IsAssignableFrom(typeof(T)), "ArrayType cannot be used with castAs!"); if (this is T ty) { @@ -211,19 +184,9 @@ public T CastAs() public T GetAs() where T : Type { - Debug.Assert(typeof(ArrayType).IsAssignableFrom(typeof(T)), "ArrayType cannot be used with getAs!"); + Debug.Assert(!typeof(ArrayType).IsAssignableFrom(typeof(T)), "ArrayType cannot be used with getAs!"); - if (this is T Ty) - { - return Ty; - } - - if (CanonicalType is not T) - { - return null; - } - - return (T)UnqualifiedDesugaredType; + return this is T ty ? ty : CanonicalType is not T ? null : (T)UnqualifiedDesugaredType; } public override int GetHashCode() => Handle.GetHashCode(); diff --git a/sources/ClangSharpPInvokeGenerator/CustomHelpBuilder.cs b/sources/ClangSharpPInvokeGenerator/CustomHelpBuilder.cs index 9cf3d433..c477f439 100644 --- a/sources/ClangSharpPInvokeGenerator/CustomHelpBuilder.cs +++ b/sources/ClangSharpPInvokeGenerator/CustomHelpBuilder.cs @@ -41,10 +41,7 @@ public void Write(IReadOnlyCollection<(string Name, string Description)> options AppendBlankLine(); } - private void AppendBlankLine() - { - Console.Out.WriteLine(); - } + private void AppendBlankLine() => Console.Out.WriteLine(); private void AppendHeading(string heading) { @@ -70,33 +67,33 @@ private void AppendLine(string text, int? offset = null) private void AppendPadding(int? offset = null) { - string padding = GetPadding(offset ?? CurrentIndentation); + var padding = GetPadding(offset ?? CurrentIndentation); Console.Out.Write(padding); } private void AppendRow(IEnumerable row, IReadOnlyList columnWidths) { var array = row.Select((string element, int index) => SplitText(element, columnWidths[index])).ToArray(); - int num = array.Max((IReadOnlyList lines) => lines.Count); + var num = array.Max((IReadOnlyList lines) => lines.Count); - for (int i = 0; i < num; i++) + for (var i = 0; i < num; i++) { - int num2 = 0; - int num3 = 0; + var num2 = 0; + var num3 = 0; AppendPadding(CurrentIndentation); - for (int j = 0; j < array.Length; j++) + for (var j = 0; j < array.Length; j++) { var readOnlyList = array[j]; if (i < readOnlyList.Count) { - string text = readOnlyList[i]; + var text = readOnlyList[i]; if (!string.IsNullOrEmpty(text)) { - int num4 = num2 - num3; + var num4 = num2 - num3; AppendText(text, num4); num3 += num4 + text.Length; } @@ -112,7 +109,7 @@ private void AppendRow(IEnumerable row, IReadOnlyList columnWidths) private void AppendTable(IEnumerable> table, IReadOnlyList columnWidths) { - foreach (IEnumerable item in table) + foreach (var item in table) { AppendRow(item, columnWidths); } @@ -131,40 +128,40 @@ private IReadOnlyList ColumnWidths(IEnumerable> table return Array.Empty(); } - int count = table.First().Count; - int num = -1; - int[] array = new int[count]; - for (int j = 0; j < count; j++) + var count = table.First().Count; + var num = -1; + var array = new int[count]; + for (var j = 0; j < count; j++) { array[j] = num; } - int[] array2 = new int[count]; + var array2 = new int[count]; int i; for (i = 0; i < count; i++) { array2[i] = table.Max((IReadOnlyList row) => row[i].Length); } - int num2 = array2.Count((int width) => width > 0); - int num3 = GetAvailableWidth() - ColumnGutter * (num2 - 1); + var num2 = array2.Count((int width) => width > 0); + var num3 = GetAvailableWidth() - (ColumnGutter * (num2 - 1)); if (num3 - num2 < 0 || num2 == 0) { return array2; } - int num4 = num2; - int num5 = 0; - int num6 = 5; + var num4 = num2; + var num5 = 0; + var num6 = 5; while (num4 > 0) { - int num7 = (num3 - array.Where((int width) => width > 0).Sum()) / num4; - bool flag = num4 == num5 || num6 <= 1; - for (int k = 0; k < count; k++) + var num7 = (num3 - array.Where((int width) => width > 0).Sum()) / num4; + var flag = num4 == num5 || num6 <= 1; + for (var k = 0; k < count; k++) { if (array[k] == num) { - int num8 = array2[k]; + var num8 = array2[k]; if (flag) { num8 = Math.Min(num8, num7); diff --git a/sources/ClangSharpPInvokeGenerator/Program.cs b/sources/ClangSharpPInvokeGenerator/Program.cs index dc37edec..e38775e3 100644 --- a/sources/ClangSharpPInvokeGenerator/Program.cs +++ b/sources/ClangSharpPInvokeGenerator/Program.cs @@ -67,6 +67,7 @@ public class Program ("generate-cpp-attributes", "[CppAttributeList(\"\")] should be generated to document the encountered C++ attributes."), ("generate-macro-bindings", "Bindings for macro-definitions should be generated. This currently only works with value like macros and not function-like ones."), ("generate-native-inheritance-attribute", "[NativeInheritance(\"\")] attribute should be generated to document the encountered C++ base type."), + ("generate-template-bindings", "Bindings for template-definitions should be generated. This is currently experimental."), ("generate-vtbl-index-attribute", "[VtblIndex(#)] attribute should be generated to document the underlying VTBL index for a helper method."), ("", ""), // Logging Options @@ -76,6 +77,7 @@ public class Program ("log-visited-files", "A list of the visited files should be generated. This can help identify traversal issues."), }; +#pragma warning disable IDE1006 public static async Task Main(params string[] args) { s_rootCommand = new RootCommand("ClangSharp P/Invoke Binding Generator") @@ -111,6 +113,7 @@ public static async Task Main(params string[] args) return await s_rootCommand.InvokeAsync(args); } +#pragma warning restore IDE1006 public static int Run(InvocationContext context) { @@ -360,6 +363,12 @@ public static int Run(InvocationContext context) break; } + case "generate-template-bindings": + { + configOptions |= PInvokeGeneratorConfigurationOptions.GenerateTemplateBindings; + break; + } + case "generate-vtbl-index-attribute": { configOptions |= PInvokeGeneratorConfigurationOptions.GenerateVtblIndexAttribute; @@ -456,7 +465,7 @@ public static int Run(InvocationContext context) translationFlags |= CXTranslationUnit_Flags.CXTranslationUnit_DetailedPreprocessingRecord; } - int exitCode = 0; + var exitCode = 0; using (var pinvokeGenerator = new PInvokeGenerator(config)) { @@ -464,7 +473,7 @@ public static int Run(InvocationContext context) { var filePath = Path.Combine(fileDirectory, file); - var translationUnitError = CXTranslationUnit.TryParse(pinvokeGenerator.IndexHandle, filePath, clangCommandLineArgs, Array.Empty(), translationFlags, out CXTranslationUnit handle); + var translationUnitError = CXTranslationUnit.TryParse(pinvokeGenerator.IndexHandle, filePath, clangCommandLineArgs, Array.Empty(), translationFlags, out var handle); var skipProcessing = false; if (translationUnitError != CXErrorCode.CXError_Success) @@ -483,8 +492,8 @@ public static int Run(InvocationContext context) Console.Write(" "); Console.WriteLine(diagnostic.Format(CXDiagnostic.DefaultDisplayOptions).ToString()); - skipProcessing |= (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Error); - skipProcessing |= (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Fatal); + skipProcessing |= diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Error; + skipProcessing |= diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Fatal; } } diff --git a/sources/libClangSharp/ClangSharp.cpp b/sources/libClangSharp/ClangSharp.cpp index baf68fe2..0ffd435f 100644 --- a/sources/libClangSharp/ClangSharp.cpp +++ b/sources/libClangSharp/ClangSharp.cpp @@ -5405,20 +5405,20 @@ CX_TemplateName clangsharp_Type_getTemplateName(CXType CT) { if (const DeducedTemplateSpecializationType* DTST = dyn_cast(TP)) { TemplateName TN = DTST->getTemplateName(); - return { static_cast(TN.getKind() + 1), TN.getAsVoidPointer() }; + return MakeCXTemplateName(TN, GetTypeTU(CT)); } if (const InjectedClassNameType* ICNT = dyn_cast(TP)) { TemplateName TN = ICNT->getTemplateName(); - return { static_cast(TN.getKind() + 1), TN.getAsVoidPointer() }; + return MakeCXTemplateName(TN, GetTypeTU(CT)); } if (const TemplateSpecializationType* TST = dyn_cast(TP)) { TemplateName TN = TST->getTemplateName(); - return { static_cast(TN.getKind() + 1), TN.getAsVoidPointer() }; + return MakeCXTemplateName(TN, GetTypeTU(CT)); } - return { }; + return MakeCXTemplateName(TemplateName::getFromVoidPointer(nullptr), GetTypeTU(CT)); } CX_TypeClass clangsharp_Type_getTypeClass(CXType CT) { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/CXXMethodDeclarationTest.cs index 934ff19c..eae3a7eb 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/CXXMethodDeclarationTest.cs @@ -137,7 +137,7 @@ public override Task DestructorTest() { public partial struct MyStruct { - public void Finalize() + public void Dispose() { } } @@ -194,7 +194,6 @@ public int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() {{ return null; @@ -268,7 +267,7 @@ public static int MyFunctionA(MyStruct x) return x.MyFunction1(); } - public static int MyFunctionB([NativeTypeName(""MyStruct *"")] MyStruct* x) + public static int MyFunctionB(MyStruct* x) { return x->MyFunction2(); } @@ -315,8 +314,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -343,12 +342,12 @@ public int Equals(int obj) return 0; }} - public int Finalize() + public int Dispose() {{ return 0; }} - public int Finalize(int obj) + public int Dispose(int obj) {{ return 0; }} @@ -714,7 +713,6 @@ public static int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public static unsafe void* MyVoidStarMethod() {{ return null; @@ -774,7 +772,6 @@ namespace ClangSharp.Test { public partial struct MyStruct { - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() { return null; @@ -836,7 +833,6 @@ public unsafe partial struct MyStruct public delegate int _MyInt32Method(MyStruct* pThis); [UnmanagedFunctionPointer(CallingConvention.{callConv})] - [return: NativeTypeName(""void *"")] public delegate void* _MyVoidStarMethod(MyStruct* pThis); public void MyVoidMethod() @@ -864,7 +860,6 @@ public int MyInt32Method() }} }} - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ fixed (MyStruct* pThis = &this) @@ -923,7 +918,6 @@ public unsafe partial struct MyStruct public delegate int _MyInt32Method(MyStruct* pThis); [UnmanagedFunctionPointer(CallingConvention.{callConv})] - [return: NativeTypeName(""void *"")] public delegate void* _MyVoidStarMethod(MyStruct* pThis); [VtblIndex(0)] @@ -955,7 +949,6 @@ public int MyInt32Method() }} [VtblIndex(3)] - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ fixed (MyStruct* pThis = &this) diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationBodyImportTest.cs index 47c2fac2..1b0764df 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationBodyImportTest.cs @@ -20,7 +20,7 @@ public override Task ArraySubscriptTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* pData, int index) + public static int MyFunction(int* pData, int index) { return pData[index]; } @@ -469,7 +469,6 @@ public override Task CxxConstCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction([NativeTypeName(""const void *"")] void* input) { return input; @@ -543,8 +542,7 @@ public void MyMethod() public static unsafe partial class Methods {{ - [return: NativeTypeName(""MyStructB *"")] - public static MyStructB* MyFunction([NativeTypeName(""MyStructA *"")] MyStructA* input) + public static MyStructB* MyFunction(MyStructA* input) {{ return (MyStructB*)(input); }} @@ -567,8 +565,7 @@ public override Task CxxReinterpretCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -591,8 +588,7 @@ public override Task CxxStaticCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -1257,7 +1253,7 @@ public static int MyFunction1(MyStruct instance) return instance.value; } - public static int MyFunction2([NativeTypeName(""MyStruct *"")] MyStruct* instance) + public static int MyFunction2(MyStruct* instance) { return instance->value; } @@ -1312,7 +1308,6 @@ public override Task ReturnCXXNullPtrTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction() { return null; @@ -1630,7 +1625,6 @@ public override Task UnaryOperatorAddrOfTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] public static int* MyFunction(int value) { return &value; @@ -1654,7 +1648,7 @@ public override Task UnaryOperatorDerefTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* value) + public static int MyFunction(int* value) { return *value; } diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationDllImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationDllImportTest.cs index b8303b95..a4fb55a6 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationDllImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/FunctionDeclarationDllImportTest.cs @@ -208,7 +208,7 @@ namespace ClangSharp.Test public static unsafe partial class Methods {{ [DllImport(""ClangSharpPInvokeGenerator"", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] - public static extern void MyFunction([NativeTypeName(""{nativeType}"")] {expectedManagedType} value = {expectedManagedInit}); + public static extern void MyFunction({expectedManagedType} value = {expectedManagedInit}); }} }} "; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/StructDeclarationTest.cs index 3f17e175..e47852bf 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/StructDeclarationTest.cs @@ -1255,7 +1255,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1269,7 +1269,7 @@ public partial struct MyStruct {{ public new int Equals; - public int Finalize; + public int Dispose; public new int GetHashCode; @@ -1312,10 +1312,8 @@ public override Task PointerToSelfTest() {{ public unsafe partial struct example_s {{ - [NativeTypeName(""example_s *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1340,7 +1338,6 @@ public unsafe partial struct example_s [NativeTypeName(""example_t *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/UnionDeclarationTest.cs index e62d14d5..d69e6a47 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/UnionDeclarationTest.cs @@ -133,7 +133,7 @@ union MyUnion3 unsigned int o0_b1_1 : 1; }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; var expectedOutputContents = $@"using System.Runtime.InteropServices; @@ -1133,7 +1133,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1152,7 +1152,7 @@ public partial struct MyUnion public new int Equals; [FieldOffset(0)] - public int Finalize; + public int Dispose; [FieldOffset(0)] public new int GetHashCode; @@ -1207,11 +1207,9 @@ namespace ClangSharp.Test public unsafe partial struct example_s {{ [FieldOffset(0)] - [NativeTypeName(""example_s *"")] public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1241,7 +1239,6 @@ public unsafe partial struct example_s public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/VarDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/VarDeclarationTest.cs index 85ff204a..2bc0ab0a 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/VarDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleUnix/VarDeclarationTest.cs @@ -151,11 +151,9 @@ public static partial class Methods return ValidateGeneratedCSharpCompatibleUnixBindingsAsync(inputContents, expectedOutputContents); } - public override Task WideStringLiteralConstTest() - { + public override Task WideStringLiteralConstTest() => // Unsupported string literal kind: 'CX_CLK_Wide' - return Task.CompletedTask; - } + Task.CompletedTask; public override Task StringLiteralConstTest() { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/CXXMethodDeclarationTest.cs index 054d12b5..794ac2b0 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/CXXMethodDeclarationTest.cs @@ -137,7 +137,7 @@ public override Task DestructorTest() { public partial struct MyStruct { - public void Finalize() + public void Dispose() { } } @@ -194,7 +194,6 @@ public int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() {{ return null; @@ -268,7 +267,7 @@ public static int MyFunctionA(MyStruct x) return x.MyFunction1(); } - public static int MyFunctionB([NativeTypeName(""MyStruct *"")] MyStruct* x) + public static int MyFunctionB(MyStruct* x) { return x->MyFunction2(); } @@ -315,8 +314,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -343,12 +342,12 @@ public int Equals(int obj) return 0; }} - public int Finalize() + public int Dispose() {{ return 0; }} - public int Finalize(int obj) + public int Dispose(int obj) {{ return 0; }} @@ -714,7 +713,6 @@ public static int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public static unsafe void* MyVoidStarMethod() {{ return null; @@ -774,7 +772,6 @@ namespace ClangSharp.Test { public partial struct MyStruct { - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() { return null; @@ -836,7 +833,6 @@ public unsafe partial struct MyStruct public delegate int _MyInt32Method(MyStruct* pThis); [UnmanagedFunctionPointer(CallingConvention.{callConv})] - [return: NativeTypeName(""void *"")] public delegate void* _MyVoidStarMethod(MyStruct* pThis); public void MyVoidMethod() @@ -864,7 +860,6 @@ public int MyInt32Method() }} }} - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ fixed (MyStruct* pThis = &this) @@ -923,7 +918,6 @@ public unsafe partial struct MyStruct public delegate int _MyInt32Method(MyStruct* pThis); [UnmanagedFunctionPointer(CallingConvention.{callConv})] - [return: NativeTypeName(""void *"")] public delegate void* _MyVoidStarMethod(MyStruct* pThis); [VtblIndex(0)] @@ -955,7 +949,6 @@ public int MyInt32Method() }} [VtblIndex(3)] - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ fixed (MyStruct* pThis = &this) diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationBodyImportTest.cs index 494899ce..e1fc2a99 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationBodyImportTest.cs @@ -20,7 +20,7 @@ public override Task ArraySubscriptTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* pData, int index) + public static int MyFunction(int* pData, int index) { return pData[index]; } @@ -469,7 +469,6 @@ public override Task CxxConstCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction([NativeTypeName(""const void *"")] void* input) { return input; @@ -543,8 +542,7 @@ public void MyMethod() public static unsafe partial class Methods {{ - [return: NativeTypeName(""MyStructB *"")] - public static MyStructB* MyFunction([NativeTypeName(""MyStructA *"")] MyStructA* input) + public static MyStructB* MyFunction(MyStructA* input) {{ return (MyStructB*)(input); }} @@ -567,8 +565,7 @@ public override Task CxxReinterpretCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -591,8 +588,7 @@ public override Task CxxStaticCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -1257,7 +1253,7 @@ public static int MyFunction1(MyStruct instance) return instance.value; } - public static int MyFunction2([NativeTypeName(""MyStruct *"")] MyStruct* instance) + public static int MyFunction2(MyStruct* instance) { return instance->value; } @@ -1312,7 +1308,6 @@ public override Task ReturnCXXNullPtrTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction() { return null; @@ -1630,7 +1625,6 @@ public override Task UnaryOperatorAddrOfTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] public static int* MyFunction(int value) { return &value; @@ -1654,7 +1648,7 @@ public override Task UnaryOperatorDerefTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* value) + public static int MyFunction(int* value) { return *value; } diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationDllImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationDllImportTest.cs index 2a02ecdb..6d9b3e79 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationDllImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/FunctionDeclarationDllImportTest.cs @@ -208,7 +208,7 @@ namespace ClangSharp.Test public static unsafe partial class Methods {{ [DllImport(""ClangSharpPInvokeGenerator"", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] - public static extern void MyFunction([NativeTypeName(""{nativeType}"")] {expectedManagedType} value = {expectedManagedInit}); + public static extern void MyFunction({expectedManagedType} value = {expectedManagedInit}); }} }} "; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/StructDeclarationTest.cs index d9790d69..61d45bc4 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/StructDeclarationTest.cs @@ -1259,7 +1259,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1273,7 +1273,7 @@ public partial struct MyStruct {{ public new int Equals; - public int Finalize; + public int Dispose; public new int GetHashCode; @@ -1316,10 +1316,8 @@ public override Task PointerToSelfTest() {{ public unsafe partial struct example_s {{ - [NativeTypeName(""example_s *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1344,7 +1342,6 @@ public unsafe partial struct example_s [NativeTypeName(""example_t *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/UnionDeclarationTest.cs index 70eaa389..08164d43 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpCompatibleWindows/UnionDeclarationTest.cs @@ -134,7 +134,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; var expectedOutputContents = $@"using System.Runtime.InteropServices; @@ -1140,7 +1140,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1159,7 +1159,7 @@ public partial struct MyUnion public new int Equals; [FieldOffset(0)] - public int Finalize; + public int Dispose; [FieldOffset(0)] public new int GetHashCode; @@ -1214,11 +1214,9 @@ namespace ClangSharp.Test public unsafe partial struct example_s {{ [FieldOffset(0)] - [NativeTypeName(""example_s *"")] public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1248,7 +1246,6 @@ public unsafe partial struct example_s public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/CXXMethodDeclarationTest.cs index e488d504..8768eadb 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/CXXMethodDeclarationTest.cs @@ -137,7 +137,7 @@ public override Task DestructorTest() { public partial struct MyStruct { - public void Finalize() + public void Dispose() { } } @@ -194,7 +194,6 @@ public int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() {{ return null; @@ -268,7 +267,7 @@ public static int MyFunctionA(MyStruct x) return x.MyFunction1(); } - public static int MyFunctionB([NativeTypeName(""MyStruct *"")] MyStruct* x) + public static int MyFunctionB(MyStruct* x) { return x->MyFunction2(); } @@ -315,8 +314,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -343,12 +342,12 @@ public int Equals(int obj) return 0; }} - public int Finalize() + public int Dispose() {{ return 0; }} - public int Finalize(int obj) + public int Dispose(int obj) {{ return 0; }} @@ -676,7 +675,6 @@ public static int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public static unsafe void* MyVoidStarMethod() {{ return null; @@ -736,7 +734,6 @@ namespace ClangSharp.Test { public partial struct MyStruct { - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() { return null; @@ -802,7 +799,6 @@ public int MyInt32Method() return ((delegate* unmanaged[{callConv}])(lpVtbl[2]))((MyStruct*)Unsafe.AsPointer(ref this)); }} - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ return ((delegate* unmanaged[{callConv}])(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); @@ -866,7 +862,6 @@ public int MyInt32Method() }} [VtblIndex(3)] - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ return ((delegate* unmanaged[{callConv}])(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationBodyImportTest.cs index 3a4b67cd..08716af3 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationBodyImportTest.cs @@ -20,7 +20,7 @@ public override Task ArraySubscriptTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* pData, int index) + public static int MyFunction(int* pData, int index) { return pData[index]; } @@ -469,7 +469,6 @@ public override Task CxxConstCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction([NativeTypeName(""const void *"")] void* input) { return input; @@ -530,8 +529,7 @@ public void MyMethod() public static unsafe partial class Methods {{ - [return: NativeTypeName(""MyStructB *"")] - public static MyStructB* MyFunction([NativeTypeName(""MyStructA *"")] MyStructA* input) + public static MyStructB* MyFunction(MyStructA* input) {{ return (MyStructB*)(input); }} @@ -554,8 +552,7 @@ public override Task CxxReinterpretCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -578,8 +575,7 @@ public override Task CxxStaticCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -1244,7 +1240,7 @@ public static int MyFunction1(MyStruct instance) return instance.value; } - public static int MyFunction2([NativeTypeName(""MyStruct *"")] MyStruct* instance) + public static int MyFunction2(MyStruct* instance) { return instance->value; } @@ -1299,7 +1295,6 @@ public override Task ReturnCXXNullPtrTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction() { return null; @@ -1614,7 +1609,6 @@ public override Task UnaryOperatorAddrOfTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] public static int* MyFunction(int value) { return &value; @@ -1638,7 +1632,7 @@ public override Task UnaryOperatorDerefTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* value) + public static int MyFunction(int* value) { return *value; } diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationDllImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationDllImportTest.cs index d3650eea..2bbd5aea 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationDllImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/FunctionDeclarationDllImportTest.cs @@ -207,7 +207,7 @@ namespace ClangSharp.Test public static unsafe partial class Methods {{ [DllImport(""ClangSharpPInvokeGenerator"", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] - public static extern void MyFunction([NativeTypeName(""{nativeType}"")] {expectedManagedType} value = {expectedManagedInit}); + public static extern void MyFunction({expectedManagedType} value = {expectedManagedInit}); }} }} "; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/StructDeclarationTest.cs index 3e7cc7dd..7a162105 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/StructDeclarationTest.cs @@ -1235,7 +1235,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1249,7 +1249,7 @@ public partial struct MyStruct {{ public new int Equals; - public int Finalize; + public int Dispose; public new int GetHashCode; @@ -1292,10 +1292,8 @@ public override Task PointerToSelfTest() {{ public unsafe partial struct example_s {{ - [NativeTypeName(""example_s *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1320,7 +1318,6 @@ public unsafe partial struct example_s [NativeTypeName(""example_t *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/UnionDeclarationTest.cs index 3e511320..5bcd49a4 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/UnionDeclarationTest.cs @@ -134,7 +134,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; var expectedOutputContents = $@"using System.Runtime.InteropServices; @@ -1120,7 +1120,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1139,7 +1139,7 @@ public partial struct MyUnion public new int Equals; [FieldOffset(0)] - public int Finalize; + public int Dispose; [FieldOffset(0)] public new int GetHashCode; @@ -1194,11 +1194,9 @@ namespace ClangSharp.Test public unsafe partial struct example_s {{ [FieldOffset(0)] - [NativeTypeName(""example_s *"")] public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1228,7 +1226,6 @@ public unsafe partial struct example_s public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/VarDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/VarDeclarationTest.cs index 646f01e8..44a2214e 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/VarDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestUnix/VarDeclarationTest.cs @@ -151,11 +151,9 @@ public static partial class Methods return ValidateGeneratedCSharpLatestUnixBindingsAsync(inputContents, expectedOutputContents); } - public override Task WideStringLiteralConstTest() -{ + public override Task WideStringLiteralConstTest() => // Unsupported string literal kind: 'CX_CLK_Wide' - return Task.CompletedTask; - } + Task.CompletedTask; public override Task StringLiteralConstTest() { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/CXXMethodDeclarationTest.cs index ecaebcf5..06e589fd 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/CXXMethodDeclarationTest.cs @@ -137,7 +137,7 @@ public override Task DestructorTest() { public partial struct MyStruct { - public void Finalize() + public void Dispose() { } } @@ -194,7 +194,6 @@ public int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() {{ return null; @@ -268,7 +267,7 @@ public static int MyFunctionA(MyStruct x) return x.MyFunction1(); } - public static int MyFunctionB([NativeTypeName(""MyStruct *"")] MyStruct* x) + public static int MyFunctionB(MyStruct* x) { return x->MyFunction2(); } @@ -315,8 +314,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -343,12 +342,12 @@ public int Equals(int obj) return 0; }} - public int Finalize() + public int Dispose() {{ return 0; }} - public int Finalize(int obj) + public int Dispose(int obj) {{ return 0; }} @@ -676,7 +675,6 @@ public static int MyInt32Method() return 0; }} - [return: NativeTypeName(""void *"")] public static unsafe void* MyVoidStarMethod() {{ return null; @@ -736,7 +734,6 @@ namespace ClangSharp.Test { public partial struct MyStruct { - [return: NativeTypeName(""void *"")] public unsafe void* MyVoidStarMethod() { return null; @@ -802,7 +799,6 @@ public int MyInt32Method() return ((delegate* unmanaged[{callConv}])(lpVtbl[2]))((MyStruct*)Unsafe.AsPointer(ref this)); }} - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ return ((delegate* unmanaged[{callConv}])(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); @@ -866,7 +862,6 @@ public int MyInt32Method() }} [VtblIndex(3)] - [return: NativeTypeName(""void *"")] public void* MyVoidStarMethod() {{ return ((delegate* unmanaged[{callConv}])(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationBodyImportTest.cs index 6584c70c..6b5a00f5 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationBodyImportTest.cs @@ -20,7 +20,7 @@ public override Task ArraySubscriptTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* pData, int index) + public static int MyFunction(int* pData, int index) { return pData[index]; } @@ -469,7 +469,6 @@ public override Task CxxConstCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction([NativeTypeName(""const void *"")] void* input) { return input; @@ -530,8 +529,7 @@ public void MyMethod() public static unsafe partial class Methods {{ - [return: NativeTypeName(""MyStructB *"")] - public static MyStructB* MyFunction([NativeTypeName(""MyStructA *"")] MyStructA* input) + public static MyStructB* MyFunction(MyStructA* input) {{ return (MyStructB*)(input); }} @@ -554,8 +552,7 @@ public override Task CxxReinterpretCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -578,8 +575,7 @@ public override Task CxxStaticCastTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] - public static int* MyFunction([NativeTypeName(""void *"")] void* input) + public static int* MyFunction(void* input) { return (int*)(input); } @@ -1244,7 +1240,7 @@ public static int MyFunction1(MyStruct instance) return instance.value; } - public static int MyFunction2([NativeTypeName(""MyStruct *"")] MyStruct* instance) + public static int MyFunction2(MyStruct* instance) { return instance->value; } @@ -1299,7 +1295,6 @@ public override Task ReturnCXXNullPtrTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""void *"")] public static void* MyFunction() { return null; @@ -1614,7 +1609,6 @@ public override Task UnaryOperatorAddrOfTest() { public static unsafe partial class Methods { - [return: NativeTypeName(""int *"")] public static int* MyFunction(int value) { return &value; @@ -1638,7 +1632,7 @@ public override Task UnaryOperatorDerefTest() { public static unsafe partial class Methods { - public static int MyFunction([NativeTypeName(""int *"")] int* value) + public static int MyFunction(int* value) { return *value; } diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationDllImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationDllImportTest.cs index 73824c49..0a2d2b2c 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationDllImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/FunctionDeclarationDllImportTest.cs @@ -207,7 +207,7 @@ namespace ClangSharp.Test public static unsafe partial class Methods {{ [DllImport(""ClangSharpPInvokeGenerator"", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] - public static extern void MyFunction([NativeTypeName(""{nativeType}"")] {expectedManagedType} value = {expectedManagedInit}); + public static extern void MyFunction({expectedManagedType} value = {expectedManagedInit}); }} }} "; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/StructDeclarationTest.cs index ee864cfd..81dc4fb4 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/StructDeclarationTest.cs @@ -1239,7 +1239,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1253,7 +1253,7 @@ public partial struct MyStruct {{ public new int Equals; - public int Finalize; + public int Dispose; public new int GetHashCode; @@ -1296,10 +1296,8 @@ public override Task PointerToSelfTest() {{ public unsafe partial struct example_s {{ - [NativeTypeName(""example_s *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1324,7 +1322,6 @@ public unsafe partial struct example_s [NativeTypeName(""example_t *"")] public example_s* next; - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/UnionDeclarationTest.cs index 212d3a32..b4616620 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/CSharpLatestWindows/UnionDeclarationTest.cs @@ -134,7 +134,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ", Pack = 1" : ""; var expectedOutputContents = $@"using System.Runtime.InteropServices; @@ -1126,7 +1126,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1145,7 +1145,7 @@ public partial struct MyUnion public new int Equals; [FieldOffset(0)] - public int Finalize; + public int Dispose; [FieldOffset(0)] public new int GetHashCode; @@ -1200,11 +1200,9 @@ namespace ClangSharp.Test public unsafe partial struct example_s {{ [FieldOffset(0)] - [NativeTypeName(""example_s *"")] public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} @@ -1234,7 +1232,6 @@ public unsafe partial struct example_s public example_s* next; [FieldOffset(0)] - [NativeTypeName(""void *"")] public void* data; }} }} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/PInvokeGeneratorTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/PInvokeGeneratorTest.cs index 766344ea..5b8f9164 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/PInvokeGeneratorTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/PInvokeGeneratorTest.cs @@ -28,52 +28,25 @@ public abstract class PInvokeGeneratorTest "-Wno-c++11-narrowing" }; - protected string EscapeXml(string value) - { - return new XText(value).ToString(); - } + protected static string EscapeXml(string value) => new XText(value).ToString(); - protected Task ValidateGeneratedCSharpLatestWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.None | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedCSharpLatestWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.None | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedCSharpLatestUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedCSharpLatestUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedCSharpCompatibleWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedCSharpCompatibleWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedCSharpCompatibleUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedCSharpCompatibleUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.CSharp, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedXmlLatestWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null, [CallerFilePath] string filePath = "") - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.None | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs, filePath); - } + protected static Task ValidateGeneratedXmlLatestWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null, [CallerFilePath] string filePath = "") => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.None | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs, filePath); - protected Task ValidateGeneratedXmlLatestUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedXmlLatestUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedXmlCompatibleWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedXmlCompatibleWindowsBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - protected Task ValidateGeneratedXmlCompatibleUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) - { - return ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - } + protected static Task ValidateGeneratedXmlCompatibleUnixBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorConfigurationOptions additionalConfigOptions = PInvokeGeneratorConfigurationOptions.None, string[] excludedNames = null, IReadOnlyDictionary remappedNames = null, IReadOnlyDictionary> withAttributes = null, IReadOnlyDictionary withCallConvs = null, IReadOnlyDictionary withLibraryPaths = null, string[] withSetLastErrors = null, IReadOnlyDictionary withTypes = null, IReadOnlyDictionary> withUsings = null, IEnumerable expectedDiagnostics = null, string libraryPath = DefaultLibraryPath, string[] commandlineArgs = null) => ValidateGeneratedBindingsAsync(inputContents, expectedOutputContents, PInvokeGeneratorOutputMode.Xml, PInvokeGeneratorConfigurationOptions.GenerateCompatibleCode | PInvokeGeneratorConfigurationOptions.GenerateUnixTypes | additionalConfigOptions, excludedNames, remappedNames, withAttributes, withCallConvs, withLibraryPaths, withSetLastErrors, withTypes, withUsings, expectedDiagnostics, libraryPath, commandlineArgs); - private async Task ValidateGeneratedBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorOutputMode outputMode, PInvokeGeneratorConfigurationOptions configOptions, string[] excludedNames, IReadOnlyDictionary remappedNames, IReadOnlyDictionary> withAttributes, IReadOnlyDictionary withCallConvs, IReadOnlyDictionary withLibraryPaths, string[] withSetLastErrors, IReadOnlyDictionary withTypes, IReadOnlyDictionary> withUsings, IEnumerable expectedDiagnostics, string libraryPath, string[] commandlineArgs, [CallerFilePath] string filePath = "") + private static async Task ValidateGeneratedBindingsAsync(string inputContents, string expectedOutputContents, PInvokeGeneratorOutputMode outputMode, PInvokeGeneratorConfigurationOptions configOptions, string[] excludedNames, IReadOnlyDictionary remappedNames, IReadOnlyDictionary> withAttributes, IReadOnlyDictionary withCallConvs, IReadOnlyDictionary withLibraryPaths, string[] withSetLastErrors, IReadOnlyDictionary withTypes, IReadOnlyDictionary> withUsings, IEnumerable expectedDiagnostics, string libraryPath, string[] commandlineArgs, [CallerFilePath] string filePath = "") { Assert.True(File.Exists(DefaultInputFileName)); diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/CXXMethodDeclarationTest.cs index dd1fec06..8a94b296 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/CXXMethodDeclarationTest.cs @@ -177,7 +177,7 @@ public override Task DestructorTest() - + void @@ -234,7 +234,7 @@ int MyInt32Method() return 0; - void* + void* return null; @@ -359,8 +359,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -388,11 +388,11 @@ public override Task NewKeywordTest() return 0; - + int return 0; - + int int @@ -862,7 +862,7 @@ static int MyInt32Method() return 0; - void* + void* return null; @@ -922,7 +922,7 @@ public override Task UnsafeDoesNotImpactDllImportTest() - void* + void* return null; @@ -988,7 +988,7 @@ virtual char MyInt8Method() - void* + void* MyStruct* @@ -1021,7 +1021,7 @@ virtual char MyInt8Method() - void* + void* fixed (MyStruct* pThis = &this) {{ @@ -1087,7 +1087,7 @@ virtual char MyInt8Method() - void* + void* MyStruct* @@ -1120,7 +1120,7 @@ virtual char MyInt8Method() - void* + void* fixed (MyStruct* pThis = &this) {{ diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/FunctionDeclarationBodyImportTest.cs index 581a782c..16b78dbf 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/FunctionDeclarationBodyImportTest.cs @@ -549,7 +549,7 @@ public override Task CxxConstCastTest() - void* + void* void* @@ -630,7 +630,7 @@ struct MyStructB : MyStructA { }; - MyStructB* + MyStructB* MyStructA* @@ -657,7 +657,7 @@ public override Task CxxReinterpretCastTest() - int* + int* void* @@ -684,7 +684,7 @@ public override Task CxxStaticCastTest() - int* + int* void* @@ -1488,7 +1488,7 @@ public override Task ReturnCXXNullPtrTest() - void* + void* return null; @@ -1816,7 +1816,7 @@ public override Task UnaryOperatorAddrOfTest() - int* + int* int diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/StructDeclarationTest.cs index cbf25abb..ccb6e6b5 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/StructDeclarationTest.cs @@ -1226,7 +1226,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1241,7 +1241,7 @@ public override Task NewKeywordTest() int - + int @@ -1293,10 +1293,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1323,7 +1323,7 @@ struct example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/UnionDeclarationTest.cs index d2560c12..4816b4e0 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/UnionDeclarationTest.cs @@ -128,7 +128,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; var expectedOutputContents = $@" @@ -1050,7 +1050,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1065,7 +1065,7 @@ public override Task NewKeywordTest() int - + int @@ -1117,10 +1117,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1147,7 +1147,7 @@ union example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/VarDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/VarDeclarationTest.cs index cd8354e2..6b2737b2 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/VarDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleUnix/VarDeclarationTest.cs @@ -186,11 +186,9 @@ public override Task Utf16StringLiteralMacroTest() return ValidateGeneratedXmlCompatibleUnixBindingsAsync(inputContents, expectedOutputContents); } - public override Task WideStringLiteralConstTest() - { + public override Task WideStringLiteralConstTest() => // Unsupported string literal kind: 'CX_CLK_Wide' - return Task.CompletedTask; - } + Task.CompletedTask; public override Task StringLiteralConstTest() { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/CXXMethodDeclarationTest.cs index 3700e014..863e6461 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/CXXMethodDeclarationTest.cs @@ -177,7 +177,7 @@ public override Task DestructorTest() - + void @@ -234,7 +234,7 @@ int MyInt32Method() return 0; - void* + void* return null; @@ -359,8 +359,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -388,11 +388,11 @@ public override Task NewKeywordTest() return 0; - + int return 0; - + int int @@ -862,7 +862,7 @@ static int MyInt32Method() return 0; - void* + void* return null; @@ -922,7 +922,7 @@ public override Task UnsafeDoesNotImpactDllImportTest() - void* + void* return null; @@ -988,7 +988,7 @@ virtual char MyInt8Method() - void* + void* MyStruct* @@ -1021,7 +1021,7 @@ virtual char MyInt8Method() - void* + void* fixed (MyStruct* pThis = &this) {{ @@ -1087,7 +1087,7 @@ virtual char MyInt8Method() - void* + void* MyStruct* @@ -1120,7 +1120,7 @@ virtual char MyInt8Method() - void* + void* fixed (MyStruct* pThis = &this) {{ diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/FunctionDeclarationBodyImportTest.cs index 93539671..88a3d8ad 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/FunctionDeclarationBodyImportTest.cs @@ -549,7 +549,7 @@ public override Task CxxConstCastTest() - void* + void* void* @@ -630,7 +630,7 @@ struct MyStructB : MyStructA { }; - MyStructB* + MyStructB* MyStructA* @@ -657,7 +657,7 @@ public override Task CxxReinterpretCastTest() - int* + int* void* @@ -684,7 +684,7 @@ public override Task CxxStaticCastTest() - int* + int* void* @@ -1488,7 +1488,7 @@ public override Task ReturnCXXNullPtrTest() - void* + void* return null; @@ -1816,7 +1816,7 @@ public override Task UnaryOperatorAddrOfTest() - int* + int* int diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/StructDeclarationTest.cs index 1cd88479..2b87b354 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/StructDeclarationTest.cs @@ -1232,7 +1232,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1247,7 +1247,7 @@ public override Task NewKeywordTest() int - + int @@ -1299,10 +1299,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1329,7 +1329,7 @@ struct example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/UnionDeclarationTest.cs index c269a363..3f7e1e1d 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlCompatibleWindows/UnionDeclarationTest.cs @@ -128,7 +128,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; var expectedOutputContents = $@" @@ -1056,7 +1056,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1071,7 +1071,7 @@ public override Task NewKeywordTest() int - + int @@ -1123,10 +1123,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1153,7 +1153,7 @@ union example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/CXXMethodDeclarationTest.cs index d16726cc..e9392f33 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/CXXMethodDeclarationTest.cs @@ -177,7 +177,7 @@ public override Task DestructorTest() - + void @@ -234,7 +234,7 @@ int MyInt32Method() return 0; - void* + void* return null; @@ -359,8 +359,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -388,11 +388,11 @@ public override Task NewKeywordTest() return 0; - + int return 0; - + int int @@ -790,7 +790,7 @@ static int MyInt32Method() return 0; - void* + void* return null; @@ -850,7 +850,7 @@ public override Task UnsafeDoesNotImpactDllImportTest() - void* + void* return null; @@ -916,7 +916,7 @@ virtual char MyInt8Method() - void* + void* return ((delegate* unmanaged[{callConv}]<MyStruct*, void*>)(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); @@ -979,7 +979,7 @@ virtual char MyInt8Method() - void* + void* return ((delegate* unmanaged[{callConv}]<MyStruct*, void*>)(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/FunctionDeclarationBodyImportTest.cs index 21322de3..ca3ae167 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/FunctionDeclarationBodyImportTest.cs @@ -549,7 +549,7 @@ public override Task CxxConstCastTest() - void* + void* void* @@ -612,7 +612,7 @@ struct MyStructB : MyStructA { }; - MyStructB* + MyStructB* MyStructA* @@ -639,7 +639,7 @@ public override Task CxxReinterpretCastTest() - int* + int* void* @@ -666,7 +666,7 @@ public override Task CxxStaticCastTest() - int* + int* void* @@ -1470,7 +1470,7 @@ public override Task ReturnCXXNullPtrTest() - void* + void* return null; @@ -1795,7 +1795,7 @@ public override Task UnaryOperatorAddrOfTest() - int* + int* int diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/StructDeclarationTest.cs index d4a894ed..6d1d98d4 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/StructDeclarationTest.cs @@ -1210,7 +1210,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1225,7 +1225,7 @@ public override Task NewKeywordTest() int - + int @@ -1277,10 +1277,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1307,7 +1307,7 @@ struct example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/UnionDeclarationTest.cs index e7078dcc..dc4fde0b 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/UnionDeclarationTest.cs @@ -128,7 +128,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; var expectedOutputContents = $@" @@ -1039,7 +1039,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1054,7 +1054,7 @@ public override Task NewKeywordTest() int - + int @@ -1106,10 +1106,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1136,7 +1136,7 @@ union example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/VarDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/VarDeclarationTest.cs index 42cae630..e1fc29bd 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/VarDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestUnix/VarDeclarationTest.cs @@ -186,11 +186,9 @@ public override Task Utf16StringLiteralMacroTest() return ValidateGeneratedXmlLatestUnixBindingsAsync(inputContents, expectedOutputContents); } - public override Task WideStringLiteralConstTest() - { + public override Task WideStringLiteralConstTest() => // Unsupported string literal kind: 'CX_CLK_Wide' - return Task.CompletedTask; - } + Task.CompletedTask; public override Task StringLiteralConstTest() { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/CXXMethodDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/CXXMethodDeclarationTest.cs index 9bb0d332..02969902 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/CXXMethodDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/CXXMethodDeclarationTest.cs @@ -177,7 +177,7 @@ public override Task DestructorTest() - + void @@ -234,7 +234,7 @@ int MyInt32Method() return 0; - void* + void* return null; @@ -359,8 +359,8 @@ public override Task NewKeywordTest() { int Equals() { return 0; } int Equals(int obj) { return 0; } - int Finalize() { return 0; } - int Finalize(int obj) { return 0; } + int Dispose() { return 0; } + int Dispose(int obj) { return 0; } int GetHashCode() { return 0; } int GetHashCode(int obj) { return 0; } int GetType() { return 0; } @@ -388,11 +388,11 @@ public override Task NewKeywordTest() return 0; - + int return 0; - + int int @@ -790,7 +790,7 @@ static int MyInt32Method() return 0; - void* + void* return null; @@ -850,7 +850,7 @@ public override Task UnsafeDoesNotImpactDllImportTest() - void* + void* return null; @@ -916,7 +916,7 @@ virtual char MyInt8Method() - void* + void* return ((delegate* unmanaged[{callConv}]<MyStruct*, void*>)(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); @@ -979,7 +979,7 @@ virtual char MyInt8Method() - void* + void* return ((delegate* unmanaged[{callConv}]<MyStruct*, void*>)(lpVtbl[3]))((MyStruct*)Unsafe.AsPointer(ref this)); diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/FunctionDeclarationBodyImportTest.cs index df5e80dd..3439e5b2 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/FunctionDeclarationBodyImportTest.cs @@ -549,7 +549,7 @@ public override Task CxxConstCastTest() - void* + void* void* @@ -612,7 +612,7 @@ struct MyStructB : MyStructA { }; - MyStructB* + MyStructB* MyStructA* @@ -639,7 +639,7 @@ public override Task CxxReinterpretCastTest() - int* + int* void* @@ -666,7 +666,7 @@ public override Task CxxStaticCastTest() - int* + int* void* @@ -1470,7 +1470,7 @@ public override Task ReturnCXXNullPtrTest() - void* + void* return null; @@ -1795,7 +1795,7 @@ public override Task UnaryOperatorAddrOfTest() - int* + int* int diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/StructDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/StructDeclarationTest.cs index ac118e4d..2ec254dc 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/StructDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/StructDeclarationTest.cs @@ -1216,7 +1216,7 @@ public override Task NewKeywordTest() var inputContents = @"struct MyStruct { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1231,7 +1231,7 @@ public override Task NewKeywordTest() int - + int @@ -1283,10 +1283,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1313,7 +1313,7 @@ struct example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/UnionDeclarationTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/UnionDeclarationTest.cs index 85449f76..068bd366 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/UnionDeclarationTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/XmlLatestWindows/UnionDeclarationTest.cs @@ -128,7 +128,7 @@ union MyUnion3 }; "; - string expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; + var expectedPack = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @" pack=""1""" : ""; var expectedOutputContents = $@" @@ -1045,7 +1045,7 @@ public override Task NewKeywordTest() var inputContents = @"union MyUnion { int Equals; - int Finalize; + int Dispose; int GetHashCode; int GetType; int MemberwiseClone; @@ -1060,7 +1060,7 @@ public override Task NewKeywordTest() int - + int @@ -1112,10 +1112,10 @@ public override Task PointerToSelfTest() - example_s* + example_s* - void* + void* @@ -1142,7 +1142,7 @@ union example_s { example_s* - void* + void* diff --git a/tests/ClangSharp.UnitTests/CXModuleMapDescriptorTest.cs b/tests/ClangSharp.UnitTests/CXModuleMapDescriptorTest.cs index c4c12548..8c117bba 100644 --- a/tests/ClangSharp.UnitTests/CXModuleMapDescriptorTest.cs +++ b/tests/ClangSharp.UnitTests/CXModuleMapDescriptorTest.cs @@ -19,15 +19,13 @@ public void Basic() + " module * { export * }\n" + "}\n"; - using (var mmd = CXModuleMapDescriptor.Create(options: 0)) - { - mmd.SetFrameworkModuleName("TestFrame"); - mmd.SetUmbrellaHeader("TestFrame.h"); + using var mmd = CXModuleMapDescriptor.Create(options: 0); + _ = mmd.SetFrameworkModuleName("TestFrame"); + _ = mmd.SetUmbrellaHeader("TestFrame.h"); - Span buffer = mmd.WriteToBuffer(options: 0, errorCode: out _); - Assert.Equal(contents, buffer.AsString()); - buffer.ClangFree(); - } + var buffer = mmd.WriteToBuffer(options: 0, errorCode: out _); + Assert.Equal(contents, buffer.AsString()); + buffer.ClangFree(); } } } diff --git a/tests/ClangSharp.UnitTests/CXTranslationUnitTest.cs b/tests/ClangSharp.UnitTests/CXTranslationUnitTest.cs index c1837ee8..8dfc040e 100644 --- a/tests/ClangSharp.UnitTests/CXTranslationUnitTest.cs +++ b/tests/ClangSharp.UnitTests/CXTranslationUnitTest.cs @@ -18,7 +18,7 @@ public void Basic(string name) { // Create a unique directory var dir = Path.GetRandomFileName(); - Directory.CreateDirectory(dir); + _ = Directory.CreateDirectory(dir); try { @@ -26,12 +26,10 @@ public void Basic(string name) var file = new FileInfo(Path.Combine(dir, name + ".c")); File.WriteAllText(file.FullName, "int main() { return 0; }"); - using (var index = CXIndex.Create()) - using (var translationUnit = CXTranslationUnit.Parse(index, file.FullName, Array.Empty(), Array.Empty(), CXTranslationUnit_Flags.CXTranslationUnit_None)) - { - var clangFile = translationUnit.GetFile(file.FullName); - Assert.Equal(file.FullName, clangFile.Name.CString); - } + using var index = CXIndex.Create(); + using var translationUnit = CXTranslationUnit.Parse(index, file.FullName, Array.Empty(), Array.Empty(), CXTranslationUnit_Flags.CXTranslationUnit_None); + var clangFile = translationUnit.GetFile(file.FullName); + Assert.Equal(file.FullName, clangFile.Name.CString); } finally { @@ -47,7 +45,7 @@ public void BasicWrapper(string name) { // Create a unique directory var dir = Path.GetRandomFileName(); - Directory.CreateDirectory(dir); + _ = Directory.CreateDirectory(dir); try { diff --git a/tests/ClangSharp.UnitTests/CXVirtualFileOverlayTest.cs b/tests/ClangSharp.UnitTests/CXVirtualFileOverlayTest.cs index 04a31baf..30543aec 100644 --- a/tests/ClangSharp.UnitTests/CXVirtualFileOverlayTest.cs +++ b/tests/ClangSharp.UnitTests/CXVirtualFileOverlayTest.cs @@ -14,17 +14,17 @@ namespace ClangSharp.UnitTests // on Windows, but clang doesn't seem to support this) public class CXVirtualFileOverlayTest { - class TestVFO : IDisposable + public class TestVFO : IDisposable { public CXVirtualFileOverlay VFO; - private string Contents; - private bool isDisposed = false; + private readonly string _contents; + private bool _isDisposed = false; public TestVFO(string contents) { VFO = CXVirtualFileOverlay.Create(options: 0); - Contents = Fix(contents); + _contents = Fix(contents); } ~TestVFO() @@ -50,7 +50,7 @@ public void MapError(string vPath, string rPath, CXErrorCode expErr) Assert.Equal(expErr, err); } - private string Fix(string text) + private static string Fix(string text) { if (text is null) { @@ -69,16 +69,16 @@ public void Dispose() protected virtual void Dispose(bool isDisposing) { - if (isDisposed) + if (_isDisposed) { return; } - isDisposed = true; + _isDisposed = true; - if (Contents != null) + if (_contents != null) { - Span buffer = VFO.WriteToBuffer(options: 0, errorCode: out _); - Assert.Equal(Contents, buffer.AsString()); + var buffer = VFO.WriteToBuffer(options: 0, errorCode: out _); + Assert.Equal(_contents, buffer.AsString()); buffer.ClangFree(); } @@ -107,10 +107,8 @@ public void Basic() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map(@"$ROOT$/path/virtual/foo.h", @"$ROOT$/real/foo.h"); - } + using var t = new TestVFO(contents); + t.Map(@"$ROOT$/path/virtual/foo.h", @"$ROOT$/real/foo.h"); } [Fact] @@ -134,20 +132,16 @@ public void Unicode() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/path/♫/☂.h", "$ROOT$/real/☂.h"); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/path/♫/☂.h", "$ROOT$/real/☂.h"); } [Fact] public void InvalidArgs() { - using (TestVFO T = new TestVFO(null)) - { - T.MapError("$ROOT$/path/./virtual/../foo.h", "$ROOT$/real/foo.h", - CXErrorCode.CXError_InvalidArguments); - } + using var t = new TestVFO(null); + t.MapError("$ROOT$/path/./virtual/../foo.h", "$ROOT$/real/foo.h", + CXErrorCode.CXError_InvalidArguments); } [Fact] @@ -198,13 +192,11 @@ public void RemapDirectories() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/path/virtual/dir/foo1.h", "$ROOT$/real/foo1.h"); - T.Map("$ROOT$/another/dir/foo2.h", "$ROOT$/real/foo2.h"); - T.Map("$ROOT$/path/virtual/dir/foo3.h", "$ROOT$/real/foo3.h"); - T.Map("$ROOT$/path/virtual/dir/in/subdir/foo4.h", "$ROOT$/real/foo4.h"); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/path/virtual/dir/foo1.h", "$ROOT$/real/foo1.h"); + t.Map("$ROOT$/another/dir/foo2.h", "$ROOT$/real/foo2.h"); + t.Map("$ROOT$/path/virtual/dir/foo3.h", "$ROOT$/real/foo3.h"); + t.Map("$ROOT$/path/virtual/dir/in/subdir/foo4.h", "$ROOT$/real/foo4.h"); } [Fact] @@ -229,11 +221,9 @@ public void CaseInsensitive() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/path/virtual/foo.h", "$ROOT$/real/foo.h"); - T.VFO.SetCaseSensitivity(false); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/path/virtual/foo.h", "$ROOT$/real/foo.h"); + _ = t.VFO.SetCaseSensitivity(false); } [Fact] @@ -284,13 +274,11 @@ public void SharedPrefix() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/path/foo/bar.h", "$ROOT$/real/bar.h"); - T.Map("$ROOT$/path/foo/bar", "$ROOT$/real/bar"); - T.Map("$ROOT$/path/foobar/baz.h", "$ROOT$/real/baz.h"); - T.Map("$ROOT$/path/foobarbaz.h", "$ROOT$/real/foobarbaz.h"); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/path/foo/bar.h", "$ROOT$/real/bar.h"); + t.Map("$ROOT$/path/foo/bar", "$ROOT$/real/bar"); + t.Map("$ROOT$/path/foobar/baz.h", "$ROOT$/real/baz.h"); + t.Map("$ROOT$/path/foobarbaz.h", "$ROOT$/real/foobarbaz.h"); } [Fact] @@ -336,12 +324,10 @@ public void AdjacentDirectory() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/path/dir1/foo.h", "$ROOT$/real/foo.h"); - T.Map("$ROOT$/path/dir1/subdir/bar.h", "$ROOT$/real/bar.h"); - T.Map("$ROOT$/path/dir2/baz.h", "$ROOT$/real/baz.h"); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/path/dir1/foo.h", "$ROOT$/real/foo.h"); + t.Map("$ROOT$/path/dir1/subdir/bar.h", "$ROOT$/real/bar.h"); + t.Map("$ROOT$/path/dir2/baz.h", "$ROOT$/real/baz.h"); } [Fact] @@ -365,10 +351,8 @@ public void TopLevel() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - T.Map("$ROOT$/foo.h", "$ROOT$/real/foo.h"); - } + using var t = new TestVFO(contents); + t.Map("$ROOT$/foo.h", "$ROOT$/real/foo.h"); } [Fact] @@ -381,9 +365,7 @@ public void Empty() + " ]\n" + "}\n"; - using (TestVFO T = new TestVFO(contents)) - { - } + using var t = new TestVFO(contents); } } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCodeCompleteResultsTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCodeCompleteResultsTests.cs index bc044758..0cdf557b 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCodeCompleteResultsTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCodeCompleteResultsTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXCodeCompleteResultsTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXCodeCompleteResults), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXCodeCompleteResults), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXCodeCompleteResults).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXCodeCompleteResults).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCommentTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCommentTests.cs index dd8c750f..8e370eb3 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCommentTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCommentTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXCommentTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXComment), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXComment), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXComment).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXComment).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCompletionResultTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCompletionResultTests.cs index 8f9ec80b..e18cf8eb 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCompletionResultTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCompletionResultTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXCompletionResultTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXCompletionResult), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXCompletionResult), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXCompletionResult).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXCompletionResult).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCursorAndRangeVisitorTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCursorAndRangeVisitorTests.cs index 4c6a5d3d..203c321a 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCursorAndRangeVisitorTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCursorAndRangeVisitorTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXCursorAndRangeVisitorTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXCursorAndRangeVisitor), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXCursorAndRangeVisitor), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXCursorAndRangeVisitor).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXCursorAndRangeVisitor).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCursorSetImplTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCursorSetImplTests.cs index fe1c8629..bca0865a 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCursorSetImplTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCursorSetImplTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXCursorSetImplTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXCursorSetImpl), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXCursorSetImpl), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXCursorSetImpl).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXCursorSetImpl).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(1, sizeof(CXCursorSetImpl)); - } + public static void SizeOfTest() => Assert.Equal(1, sizeof(CXCursorSetImpl)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXCursorTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXCursorTests.cs index 093e6016..b763a79b 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXCursorTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXCursorTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXCursorTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXCursor), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXCursor), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXCursor).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXCursor).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXFileUniqueIDTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXFileUniqueIDTests.cs index 0f915a02..d5186520 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXFileUniqueIDTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXFileUniqueIDTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXFileUniqueIDTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXFileUniqueID), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXFileUniqueID), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXFileUniqueID).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXFileUniqueID).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(24, sizeof(CXFileUniqueID)); - } + public static void SizeOfTest() => Assert.Equal(24, sizeof(CXFileUniqueID)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxAttrInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxAttrInfoTests.cs index 389bb4d4..4337a4d6 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxAttrInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxAttrInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxAttrInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxAttrInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxAttrInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxAttrInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxAttrInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxBaseClassInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxBaseClassInfoTests.cs index 9b64fedf..057c56a9 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxBaseClassInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxBaseClassInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxBaseClassInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxBaseClassInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxBaseClassInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxBaseClassInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxBaseClassInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxCXXClassDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxCXXClassDeclInfoTests.cs index b3a80721..8cd323bc 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxCXXClassDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxCXXClassDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxCXXClassDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxCXXClassDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxCXXClassDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxCXXClassDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxCXXClassDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxContainerInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxContainerInfoTests.cs index be8fac8f..27adb815 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxContainerInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxContainerInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxContainerInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxContainerInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxContainerInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxContainerInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxContainerInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxDeclInfoTests.cs index e7cebbee..485a625f 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityInfoTests.cs index c2752dfb..ec97fb2a 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxEntityInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxEntityInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxEntityInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxEntityInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxEntityInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityRefInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityRefInfoTests.cs index 45c8420a..4f6b23cc 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityRefInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxEntityRefInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxEntityRefInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxEntityRefInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxEntityRefInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxEntityRefInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxEntityRefInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxIBOutletCollectionAttrInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxIBOutletCollectionAttrInfoTests.cs index d13e5cef..aaab8c97 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxIBOutletCollectionAttrInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxIBOutletCollectionAttrInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxIBOutletCollectionAttrInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxIBOutletCollectionAttrInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxIBOutletCollectionAttrInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxIBOutletCollectionAttrInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxIBOutletCollectionAttrInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxImportedASTFileInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxImportedASTFileInfoTests.cs index 38614037..b996fc62 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxImportedASTFileInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxImportedASTFileInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxImportedASTFileInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxImportedASTFileInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxImportedASTFileInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxImportedASTFileInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxImportedASTFileInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxIncludedFileInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxIncludedFileInfoTests.cs index b229587c..8d3f2b51 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxIncludedFileInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxIncludedFileInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxIncludedFileInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxIncludedFileInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxIncludedFileInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxIncludedFileInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxIncludedFileInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxLocTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxLocTests.cs index cb9ee8f3..b3244e0a 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxLocTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxLocTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxLocTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxLoc), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxLoc), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxLoc).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxLoc).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCCategoryDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCCategoryDeclInfoTests.cs index afa4d688..084bd9fe 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCCategoryDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCCategoryDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCCategoryDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCCategoryDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCCategoryDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCCategoryDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCCategoryDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCContainerDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCContainerDeclInfoTests.cs index 9cca9a7c..a0fa9c59 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCContainerDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCContainerDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCContainerDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCContainerDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCContainerDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCContainerDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCContainerDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCInterfaceDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCInterfaceDeclInfoTests.cs index 50e4c633..439dc820 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCInterfaceDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCInterfaceDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCInterfaceDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCInterfaceDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCInterfaceDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCInterfaceDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCInterfaceDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCPropertyDeclInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCPropertyDeclInfoTests.cs index 4329d586..cb59d148 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCPropertyDeclInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCPropertyDeclInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCPropertyDeclInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCPropertyDeclInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCPropertyDeclInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCPropertyDeclInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCPropertyDeclInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefInfoTests.cs index 52df204b..7be1f6cb 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCProtocolRefInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCProtocolRefInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCProtocolRefInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCProtocolRefInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCProtocolRefInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefListInfoTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefListInfoTests.cs index 3dbb311a..a53a67ba 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefListInfoTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXIdxObjCProtocolRefListInfoTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXIdxObjCProtocolRefListInfoTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXIdxObjCProtocolRefListInfo), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXIdxObjCProtocolRefListInfo), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXIdxObjCProtocolRefListInfo).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXIdxObjCProtocolRefListInfo).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXModuleMapDescriptorImplTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXModuleMapDescriptorImplTests.cs index d743d258..3d64d51c 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXModuleMapDescriptorImplTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXModuleMapDescriptorImplTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXModuleMapDescriptorImplTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXModuleMapDescriptorImpl), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXModuleMapDescriptorImpl), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXModuleMapDescriptorImpl).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXModuleMapDescriptorImpl).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(1, sizeof(CXModuleMapDescriptorImpl)); - } + public static void SizeOfTest() => Assert.Equal(1, sizeof(CXModuleMapDescriptorImpl)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXPlatformAvailabilityTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXPlatformAvailabilityTests.cs index 3b0628fb..baa4789b 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXPlatformAvailabilityTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXPlatformAvailabilityTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXPlatformAvailabilityTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXPlatformAvailability), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXPlatformAvailability), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXPlatformAvailability).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXPlatformAvailability).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXSourceLocationTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXSourceLocationTests.cs index 1e02d918..de618e7e 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXSourceLocationTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXSourceLocationTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXSourceLocationTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXSourceLocation), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXSourceLocation), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXSourceLocation).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXSourceLocation).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeListTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeListTests.cs index 0d794764..03e69616 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeListTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeListTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXSourceRangeListTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXSourceRangeList), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXSourceRangeList), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXSourceRangeList).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXSourceRangeList).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeTests.cs index af54f61b..e8e2cca6 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXSourceRangeTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXSourceRangeTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXSourceRange), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXSourceRange), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXSourceRange).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXSourceRange).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXStringSetTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXStringSetTests.cs index 731b10fd..a23d8ede 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXStringSetTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXStringSetTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXStringSetTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXStringSet), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXStringSet), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXStringSet).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXStringSet).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXStringTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXStringTests.cs index 159de069..b28c5b32 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXStringTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXStringTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXStringTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXString), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXString), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXString).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXString).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageEntryTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageEntryTests.cs index 74908b53..079758d0 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageEntryTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageEntryTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXTUResourceUsageEntryTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXTUResourceUsageEntry), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXTUResourceUsageEntry), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXTUResourceUsageEntry).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXTUResourceUsageEntry).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageTests.cs index cb45786a..27093aae 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTUResourceUsageTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXTUResourceUsageTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXTUResourceUsage), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXTUResourceUsage), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXTUResourceUsage).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXTUResourceUsage).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTargetInfoImplTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTargetInfoImplTests.cs index 047e52ff..cc7e9f45 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTargetInfoImplTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTargetInfoImplTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXTargetInfoImplTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXTargetInfoImpl), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXTargetInfoImpl), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXTargetInfoImpl).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXTargetInfoImpl).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(1, sizeof(CXTargetInfoImpl)); - } + public static void SizeOfTest() => Assert.Equal(1, sizeof(CXTargetInfoImpl)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTokenTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTokenTests.cs index df7edd53..ed57bec3 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTokenTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTokenTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXTokenTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXToken), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXToken), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXToken).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXToken).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTranslationUnitImplTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTranslationUnitImplTests.cs index f5e54b91..64c7c5f4 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTranslationUnitImplTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTranslationUnitImplTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXTranslationUnitImplTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXTranslationUnitImpl), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXTranslationUnitImpl), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXTranslationUnitImpl).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXTranslationUnitImpl).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(1, sizeof(CXTranslationUnitImpl)); - } + public static void SizeOfTest() => Assert.Equal(1, sizeof(CXTranslationUnitImpl)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXTypeTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXTypeTests.cs index 41240665..4ba8b704 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXTypeTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXTypeTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXTypeTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXType), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXType), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXType).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXType).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXUnsavedFileTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXUnsavedFileTests.cs index 3ec0613c..430aad2e 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXUnsavedFileTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXUnsavedFileTests.cs @@ -14,17 +14,11 @@ public static unsafe class CXUnsavedFileTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXUnsavedFile), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXUnsavedFile), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXUnsavedFile).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXUnsavedFile).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXVersionTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXVersionTests.cs index 12f25c83..657019f8 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXVersionTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXVersionTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXVersionTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXVersion), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXVersion), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXVersion).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXVersion).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(12, sizeof(CXVersion)); - } + public static void SizeOfTest() => Assert.Equal(12, sizeof(CXVersion)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/CXVirtualFileOverlayImplTests.cs b/tests/ClangSharp.UnitTests/InteropTests/CXVirtualFileOverlayImplTests.cs index 381778f5..28ca825e 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/CXVirtualFileOverlayImplTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/CXVirtualFileOverlayImplTests.cs @@ -13,23 +13,14 @@ public static unsafe class CXVirtualFileOverlayImplTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(CXVirtualFileOverlayImpl), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(CXVirtualFileOverlayImpl), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(CXVirtualFileOverlayImpl).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(CXVirtualFileOverlayImpl).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] - public static void SizeOfTest() - { - Assert.Equal(1, sizeof(CXVirtualFileOverlayImpl)); - } + public static void SizeOfTest() => Assert.Equal(1, sizeof(CXVirtualFileOverlayImpl)); } } diff --git a/tests/ClangSharp.UnitTests/InteropTests/IndexerCallbacksTests.cs b/tests/ClangSharp.UnitTests/InteropTests/IndexerCallbacksTests.cs index 1a60e5d0..f0fac36c 100644 --- a/tests/ClangSharp.UnitTests/InteropTests/IndexerCallbacksTests.cs +++ b/tests/ClangSharp.UnitTests/InteropTests/IndexerCallbacksTests.cs @@ -14,17 +14,11 @@ public static unsafe class IndexerCallbacksTests { /// Validates that the struct is blittable. [Fact] - public static void IsBlittableTest() - { - Assert.Equal(sizeof(IndexerCallbacks), Marshal.SizeOf()); - } + public static void IsBlittableTest() => Assert.Equal(sizeof(IndexerCallbacks), Marshal.SizeOf()); /// Validates that the struct has the right . [Fact] - public static void IsLayoutSequentialTest() - { - Assert.True(typeof(IndexerCallbacks).IsLayoutSequential); - } + public static void IsLayoutSequentialTest() => Assert.True(typeof(IndexerCallbacks).IsLayoutSequential); /// Validates that the struct has the correct size. [Fact] diff --git a/tests/ClangSharp.UnitTests/TranslationUnitTest.cs b/tests/ClangSharp.UnitTests/TranslationUnitTest.cs index 0207b4ff..9e19aefa 100644 --- a/tests/ClangSharp.UnitTests/TranslationUnitTest.cs +++ b/tests/ClangSharp.UnitTests/TranslationUnitTest.cs @@ -21,7 +21,7 @@ public abstract class TranslationUnitTest "-Wno-pragma-once-outside-header" // We are processing files which may be header files }; - protected TranslationUnit CreateTranslationUnit(string inputContents) + protected static TranslationUnit CreateTranslationUnit(string inputContents) { Assert.True(File.Exists(DefaultInputFileName)); @@ -34,18 +34,18 @@ protected TranslationUnit CreateTranslationUnit(string inputContents) if (translationUnit.NumDiagnostics != 0) { var errorDiagnostics = new StringBuilder(); - errorDiagnostics.AppendLine($"The provided {nameof(CXTranslationUnit)} has the following diagnostics which prevent its use:"); + _ = errorDiagnostics.AppendLine($"The provided {nameof(CXTranslationUnit)} has the following diagnostics which prevent its use:"); var invalidTranslationUnitHandle = false; for (uint i = 0; i < translationUnit.NumDiagnostics; ++i) { using var diagnostic = translationUnit.GetDiagnostic(i); - if ((diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Error) || (diagnostic.Severity == CXDiagnosticSeverity.CXDiagnostic_Fatal)) + if (diagnostic.Severity is CXDiagnosticSeverity.CXDiagnostic_Error or CXDiagnosticSeverity.CXDiagnostic_Fatal) { invalidTranslationUnitHandle = true; - errorDiagnostics.Append(' ', 4); - errorDiagnostics.AppendLine(diagnostic.Format(CXDiagnosticDisplayOptions.CXDiagnostic_DisplayOption).ToString()); + _ = errorDiagnostics.Append(' ', 4); + _ = errorDiagnostics.AppendLine(diagnostic.Format(CXDiagnosticDisplayOptions.CXDiagnostic_DisplayOption).ToString()); } }