From f3da2f60fd28d6655dcba25299d066b29e176b2f Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Thu, 18 Jun 2026 21:20:43 -0500 Subject: [PATCH] feat: implement analyzer and code fixer for identifying and fixing when a sync flag is not propagated correctly. --- .editorconfig | 389 ++++++++++++++ .gitea/workflows/ci.yml | 23 + .gitea/workflows/release.yml | 56 ++ .gitignore | 491 ++++++++++++++++++ .vscode/settings.json | 7 + Directory.Build.props | 14 + LICENSE.md | 19 + README.md | 99 ++++ StevanFreeborn.AsyncSyncFlagAnalyzer.slnx | 10 + .../.editorconfig | 10 + .../Program.cs | 70 +++ ...Freeborn.AsyncSyncFlagAnalyzer.Demo.csproj | 15 + scripts/determine-version.sh | 67 +++ scripts/update-version.sh | 19 + src/Directory.Build.props | 18 + src/Directory.packages.props | 11 + ...orn.AsyncSyncFlagAnalyzer.CodeFixes.csproj | 16 + .../SyncParameterCodeFixProvider.cs | 138 +++++ .../DiagnosticProperties.cs | 11 + ...eeborn.AsyncSyncFlagAnalyzer.Common.csproj | 8 + .../AnalyzerReleases.Shipped.md | 7 + .../AnalyzerReleases.Unshipped.md | 0 ...tevanFreeborn.AsyncSyncFlagAnalyzer.csproj | 52 ++ .../SyncParameterAnalyzer.cs | 130 +++++ tests/.editorconfig | 4 + tests/Directory.Packages.props | 14 + ...reeborn.AsyncSyncFlagAnalyzer.Tests.csproj | 39 ++ .../SyncParameterAnalyzerTests.cs | 159 ++++++ .../TestData/WhenOuterMethodHasNoSyncParam.cs | 17 + .../TestData/WhenSyncIsHardcodedFalse.cs | 17 + .../WhenSyncIsHardcodedFalse_Fixed.cs | 17 + .../WhenSyncIsNotLastTargetParameter.cs | 17 + .../WhenSyncIsNotLastTargetParameter_Fixed.cs | 17 + .../TestData/WhenSyncIsOmitted.cs | 17 + .../TestData/WhenSyncIsOmitted_CustomName.cs | 17 + .../WhenSyncIsOmitted_CustomName_Fixed.cs | 17 + .../TestData/WhenSyncIsOmitted_Fixed.cs | 17 + .../WhenSyncIsOmitted_MultipleAwaits.cs | 20 + .../WhenSyncIsOmitted_MultipleAwaits_Fixed.cs | 20 + .../TestData/WhenSyncIsPassedAsNamed.cs | 17 + .../WhenSyncIsPassedAsNamedHardcoded.cs | 17 + .../WhenSyncIsPassedAsNamedHardcoded_Fixed.cs | 17 + .../TestData/WhenSyncIsPassedCorrectly.cs | 17 + .../TestData/WhenSyncIsPassedPositionally.cs | 17 + .../TestData/WhenTargetHasNoSyncParam.cs | 10 + 45 files changed, 2184 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitea/workflows/release.yml create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 Directory.Build.props create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 StevanFreeborn.AsyncSyncFlagAnalyzer.slnx create mode 100644 samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/.editorconfig create mode 100644 samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/Program.cs create mode 100644 samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo.csproj create mode 100644 scripts/determine-version.sh create mode 100644 scripts/update-version.sh create mode 100644 src/Directory.Build.props create mode 100644 src/Directory.packages.props create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes.csproj create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/SyncParameterCodeFixProvider.cs create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/DiagnosticProperties.cs create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/StevanFreeborn.AsyncSyncFlagAnalyzer.Common.csproj create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Shipped.md create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Unshipped.md create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer/StevanFreeborn.AsyncSyncFlagAnalyzer.csproj create mode 100644 src/StevanFreeborn.AsyncSyncFlagAnalyzer/SyncParameterAnalyzer.cs create mode 100644 tests/.editorconfig create mode 100644 tests/Directory.Packages.props create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests.csproj create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/SyncParameterAnalyzerTests.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenOuterMethodHasNoSyncParam.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded_Fixed.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedCorrectly.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedPositionally.cs create mode 100644 tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenTargetHasNoSyncParam.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..63962ab --- /dev/null +++ b/.editorconfig @@ -0,0 +1,389 @@ +root = true + +# All files +[*] +indent_style = space + +# Xml files +[*.xml] +indent_size = 2 + +# Xml project files +[*.{csproj,fsproj,vbproj,proj,slnx}] +indent_size = 2 + +# Xml config files +[*.{props,targets,config,nuspec}] +indent_size = 2 + +[*.json] +indent_size = 2 + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 2 +tab_width = 2 + +# New line preferences +insert_final_newline = false + +#### .NET Coding Conventions #### +[*.{cs,vb}] + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +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 + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent + +# Parentheses preferences +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 + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent + +# Expression-level preferences +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed:suggestion +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_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:suggestion + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +#### C# Coding Conventions #### +[*.cs] + +# var preferences +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion + +# Expression-bodied members +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:suggestion +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +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_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_anonymous_function = true:suggestion +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,file,const,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:suggestion +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +#### C# Formatting Rules #### + +# New line preferences +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 = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +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 = 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 +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### +[*.{cs,vb}] + +# Naming rules + +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion +dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces +dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase + +dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion +dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters +dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase + +dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods +dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties +dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.events_should_be_pascalcase.symbols = events +dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables +dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase + +dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants +dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase + +dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion +dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters +dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase + +dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields +dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion +dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields +dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase + +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase + +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums +dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase + +# Symbol specifications + +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interfaces.required_modifiers = + +dotnet_naming_symbols.enums.applicable_kinds = enum +dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enums.required_modifiers = + +dotnet_naming_symbols.events.applicable_kinds = event +dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.events.required_modifiers = + +dotnet_naming_symbols.methods.applicable_kinds = method +dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.methods.required_modifiers = + +dotnet_naming_symbols.properties.applicable_kinds = property +dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.properties.required_modifiers = + +dotnet_naming_symbols.public_fields.applicable_kinds = field +dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_fields.required_modifiers = + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_fields.required_modifiers = + +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum +dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types_and_namespaces.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.type_parameters.applicable_kinds = namespace +dotnet_naming_symbols.type_parameters.applicable_accessibilities = * +dotnet_naming_symbols.type_parameters.required_modifiers = + +dotnet_naming_symbols.private_constant_fields.applicable_kinds = field +dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_constant_fields.required_modifiers = const + +dotnet_naming_symbols.local_variables.applicable_kinds = local +dotnet_naming_symbols.local_variables.applicable_accessibilities = local +dotnet_naming_symbols.local_variables.required_modifiers = + +dotnet_naming_symbols.local_constants.applicable_kinds = local +dotnet_naming_symbols.local_constants.applicable_accessibilities = local +dotnet_naming_symbols.local_constants.required_modifiers = const + +dotnet_naming_symbols.parameters.applicable_kinds = parameter +dotnet_naming_symbols.parameters.applicable_accessibilities = * +dotnet_naming_symbols.parameters.required_modifiers = + +dotnet_naming_symbols.public_constant_fields.applicable_kinds = field +dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_constant_fields.required_modifiers = const + +dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function +dotnet_naming_symbols.local_functions.applicable_accessibilities = * +dotnet_naming_symbols.local_functions.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascalcase.required_prefix = +dotnet_naming_style.pascalcase.required_suffix = +dotnet_naming_style.pascalcase.word_separator = +dotnet_naming_style.pascalcase.capitalization = pascal_case + +dotnet_naming_style.ipascalcase.required_prefix = I +dotnet_naming_style.ipascalcase.required_suffix = +dotnet_naming_style.ipascalcase.word_separator = +dotnet_naming_style.ipascalcase.capitalization = pascal_case + +dotnet_naming_style.tpascalcase.required_prefix = T +dotnet_naming_style.tpascalcase.required_suffix = +dotnet_naming_style.tpascalcase.word_separator = +dotnet_naming_style.tpascalcase.capitalization = pascal_case + +dotnet_naming_style._camelcase.required_prefix = _ +dotnet_naming_style._camelcase.required_suffix = +dotnet_naming_style._camelcase.word_separator = +dotnet_naming_style._camelcase.capitalization = camel_case + +dotnet_naming_style.camelcase.required_prefix = +dotnet_naming_style.camelcase.required_suffix = +dotnet_naming_style.camelcase.word_separator = +dotnet_naming_style.camelcase.capitalization = camel_case + +dotnet_naming_style.s_camelcase.required_prefix = s_ +dotnet_naming_style.s_camelcase.required_suffix = +dotnet_naming_style.s_camelcase.word_separator = +dotnet_naming_style.s_camelcase.capitalization = camel_case + diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..7c2dbbd --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI +on: + pull_request: + branches: [main] +jobs: + ci: + name: Build, Format, and Test + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: 11.0.x + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build --no-restore + - name: Check formatting + run: dotnet format --verify-no-changes + - name: Run tests + run: dotnet test --no-build --verbosity normal diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..108d1b8 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,56 @@ +name: Release +on: + push: + branches: [main] +jobs: + release: + name: Version, Build, and Release + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Make scripts executable + run: chmod +x scripts/*.sh + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: 11.0.x + - name: Determine version + id: version + run: ./scripts/determine-version.sh main + - name: Update version in csproj + if: steps.version.outputs.VERSION + run: ./scripts/update-version.sh "${{ steps.version.outputs.VERSION }}" + - name: Create commit + if: steps.version.outputs.VERSION + run: | + git config user.name "gitea-actions[bot]" + git config user.email "gitea-actions[bot]@users.noreply.gitea.io" + git add -A + git commit -m "Bump version to ${{ steps.version.outputs.VERSION }}" || echo "No changes to commit" + - name: Create tag + if: steps.version.outputs.VERSION + run: | + git tag "v${{ steps.version.outputs.VERSION }}" + - name: Push changes and tags + if: steps.version.outputs.VERSION + run: | + git push origin main + git push origin v${{ steps.version.outputs.VERSION }} + - name: Restore dependencies + if: steps.version.outputs.VERSION + run: dotnet restore + - name: Build + if: steps.version.outputs.VERSION + run: dotnet build --configuration Release --no-restore + - name: Run tests + if: steps.version.outputs.VERSION + run: dotnet test --configuration Release --no-build --verbosity normal + - name: Pack + if: steps.version.outputs.VERSION + run: dotnet pack --configuration Release --no-build --output ./artifacts + - name: Push to NuGet + if: steps.version.outputs.VERSION + run: dotnet nuget push ./artifacts/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..034b62f --- /dev/null +++ b/.gitignore @@ -0,0 +1,491 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# appsettings +appsettings*.json +!appsettings.Example.json + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e +# but not directories ending in .e2e +!*.e2e/ + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Official VS Code C# Dev Kit Extension exclusion +*.lscache + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a158100 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "cSpell.words": [ + "Frob", + "GITEA", + "netstandard" + ] +} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..dae7934 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,14 @@ + + + enable + enable + latest + latest + All + true + true + true + true + CS1591; + + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..307cc61 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,19 @@ +# Copyright (c) 2026 Stevan Freeborn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4a23f52 --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# StevanFreeborn.AsyncSyncFlagAnalyzer + +[![NuGet](https://img.shields.io/nuget/v/StevanFreeborn.AsyncSyncFlagAnalyzer.svg)](https://www.nuget.org/packages/StevanFreeborn.AsyncSyncFlagAnalyzer) +[![NuGet](https://img.shields.io/nuget/dt/StevanFreeborn.AsyncSyncFlagAnalyzer.svg)](https://www.nuget.org/packages/StevanFreeborn.AsyncSyncFlagAnalyzer) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) + +A Roslyn analyzer and code fix that enforces the **Flag Argument Hack** pattern — forwarding a `sync` boolean parameter through optionally-asynchronous call chains instead of hardcoding `false` or omitting the argument. + +## The Problem + +Consider a service interface with an optional async path: + +```csharp +interface IDataService +{ + Task GetDataAsync(bool sync = false); +} +``` + +Callers in the same async infrastructure should forward their own `sync` flag: + +```csharp +// ✅ Good: signal is propagated +Task Good_ForwardSync(bool sync) => _dataService.GetDataAsync(sync); + +// ❌ Bad: sync signal is lost +Task Bad_HardcodedValue(bool sync) => _dataService.GetDataAsync(false); + +// ❌ Bad: relies on the default (false), sync signal is lost +Task Bad_OmittedFlag(bool sync) => _dataService.GetDataAsync(); +``` + +This analyzer flags every case where the sync parameter is dropped, and provides a code fix to forward it automatically. + +## How It Works + +The analyzer registers a `SyntaxNodeAction` on `AwaitExpression` nodes: + +1. Finds the enclosing method and checks if it has a parameter matching a known sync name +2. If yes, resolves the invoked method's symbol and checks whether it also has a sync parameter +3. Walks the invocation's arguments — if none of them reference the enclosing method's sync parameter by name, reports SYNC001 +4. Passes the enclosing parameter name, target parameter name, and target ordinal via `Diagnostic.Properties` so the code fix knows what variable to pass and where to place it + +The code fix reads `EnclosingSyncName`, `TargetSyncName`, and `TargetSyncOrdinal` from the diagnostic properties. It first checks whether a named argument already exists for the target parameter — if so, it replaces only the expression while preserving the name colon. Otherwise, it counts existing positional arguments and inserts the sync flag at the correct ordinal position, replacing any positional argument at that slot. + +## Diagnostic Rules + +| ID | Severity | Description | +|-------------|----------|-------------------------------------------------| +| **SYNC001** | Error | Missing sync parameter in optionally async call | + +> The severity is configurable via `.editorconfig` if error-level is too strict: +> +> `dotnet_diagnostic.SYNC001.severity = warning` + +## Installation + +Add the NuGet package to projects that need the analyzer: + +```xml + +``` + +The analyzer and code fix are bundled together in the same package. + +## Configuration + +By default, the analyzer recognizes `sync` as the parameter name. To define additional names, add an entry to your `.editorconfig`: + +```ini +[*.cs] +dotnet_diagnostic.SYNC001.additional_sync_names = runSynchronously, isSync +``` + +All names are matched case-insensitively. The default name `sync` is always included and does not need to be listed. + +## Code Fix + +The analyzer ships with a code fix provider (registered as SYNC001). When the lightbulb appears, it offers **"Pass 'sync' parameter"** which inserts the sync flag at the correct position in the argument list. + +The fix uses the enclosing method's parameter name as the argument value (the variable in scope) and the target method's parameter name for named argument matching. It handles three scenarios: + +- **Sync fully omitted:** the argument is inserted as a positional argument at the correct ordinal position + - `GetDataAsync(17)` → `GetDataAsync(17, sync)` +- **Sync passed positionally with a hardcoded value:** the existing argument is replaced in-place + - `GetDataAsync(17, false)` → `GetDataAsync(17, sync)` +- **Sync passed as a named argument with a hardcoded value:** the expression is replaced while preserving the name colon + - `GetDataAsync(17, sync: false)` → `GetDataAsync(17, sync: sync)` + +## Demo + +The demo project at `samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo` exercises the analyzer with both good and bad patterns. It also configures custom sync names (`runSynchronously`, `isSync`) via its `.editorconfig` to demonstrate the override feature. + +To see the analyzer in action within an IDE, open and build the demo project — SYNC001 violations will appear on the `Bad_` methods. diff --git a/StevanFreeborn.AsyncSyncFlagAnalyzer.slnx b/StevanFreeborn.AsyncSyncFlagAnalyzer.slnx new file mode 100644 index 0000000..a860c85 --- /dev/null +++ b/StevanFreeborn.AsyncSyncFlagAnalyzer.slnx @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/.editorconfig b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/.editorconfig new file mode 100644 index 0000000..abe1e83 --- /dev/null +++ b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*.cs] +dotnet_diagnostic.SYNC001.additional_sync_names = runSynchronously, isSync + +dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.CA1707.severity = none + +indent_size = 2 +tab_width = 2 \ No newline at end of file diff --git a/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/Program.cs b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/Program.cs new file mode 100644 index 0000000..959adbd --- /dev/null +++ b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/Program.cs @@ -0,0 +1,70 @@ +internal static class Program +{ + public static async Task Main() + { + await Task.CompletedTask; + } +} + +internal interface IDataService +{ + Task GetDataAsync(string name, bool sync = false); + Task GetMoreDataAsync(bool runSynchronously, string name); + Task FetchAsync(int id, bool sync = false, bool cache = true); +} + +internal class BusinessLogic(IDataService dataService) +{ + private readonly IDataService _dataService = dataService; + + // ── Good patterns (no SYNC001) ────────────────────────── + + /// Passes the default 'sync' variable positionally. + public async Task Good_ForwardSync(bool sync) + { + return await _dataService.GetDataAsync("Stevan", sync); + } + + /// Passes a custom 'runSynchronously' variable positionally. + public async Task Good_ForwardCustomFlag(bool runSynchronously) + { + return await _dataService.GetMoreDataAsync(runSynchronously, "Freeborn"); + } + + // ── Bad patterns (SYNC001, demonstrating code fix) ────── + + /// Omits the sync argument entirely. + /// Code fix: inserts `sync` at ordinal 1. + public async Task Bad_OmittedSync(bool sync) + { + return await _dataService.GetDataAsync("Stevan"); + } + + /// Hardcodes `false` as a positional argument. + /// Code fix: replaces arg at ordinal 1 with `sync`. + public async Task Bad_HardcodedValue(bool sync) + { + return await _dataService.GetDataAsync("Stevan", false); + } + + /// Hardcodes a value using a named argument. + /// Code fix: replaces expression in the named arg, keeping `sync:`. + public async Task Bad_NamedHardcoded(bool sync) + { + return await _dataService.GetDataAsync("Stevan", sync: false); + } + + /// Omits sync when it's not the last parameter. + /// Code fix: inserts `sync` at ordinal 1 (before `cache`). + public async Task Bad_OmittedSyncNotLast(bool sync) + { + return await _dataService.FetchAsync(17); + } + + /// Hardcodes `false` at ordinal 0 where the target expects `runSynchronously`. + /// Code fix: replaces arg at ordinal 0 with `sync` (value = enclosing name). + public async Task Bad_HardcodedAtOrdinalZero(bool sync) + { + return await _dataService.GetMoreDataAsync(false, "Freeborn"); + } +} \ No newline at end of file diff --git a/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo.csproj b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo.csproj new file mode 100644 index 0000000..ecf654a --- /dev/null +++ b/samples/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo/StevanFreeborn.AsyncSyncFlagAnalyzer.Demo.csproj @@ -0,0 +1,15 @@ + + + + Exe + net11.0 + enable + enable + + + + + + + + diff --git a/scripts/determine-version.sh b/scripts/determine-version.sh new file mode 100644 index 0000000..4081842 --- /dev/null +++ b/scripts/determine-version.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +branch="${1:-main}" + +tag=$(git describe --tags --abbrev=0 2>/dev/null) +base="${tag:-$branch}" + +commits=$(git log "$base..HEAD" --format="%s") +major=0 +minor=0 +patch=0 + +while IFS= read -r message; do + if [[ -n "$message" ]] && [[ "$message" =~ " BREAKING CHANGE|!:" ]]; then + major=1 + elif [[ -n "$message" ]] && [[ "$message" =~ feat(\(.*\))?: ]]; then + minor=1 + elif [[ -n "$message" ]] && [[ "$message" =~ fix(\(.*\))?: ]]; then + patch=1 + fi +done <<< "$commits" + +if [[ "$major" -eq 1 ]]; then + minor=0 + patch=0 +elif [[ "$minor" -eq 1 ]]; then + patch=0 +elif [[ "$patch" -eq 0 ]] && [[ -n "$commits" ]]; then + patch=1 +fi + +currentVersion="0.0.0" +hasExistingTag=false + +if [[ -n "$tag" ]]; then + hasExistingTag=true + currentVersion="${tag#v}" +fi + +IFS='.' read -r majorCurrent minorCurrent patchCurrent <<< "$currentVersion" + +majorNew=$((majorCurrent + major)) + +if [[ "$major" -eq 1 ]]; then + minorNew=0 +else + minorNew=$((minorCurrent + minor)) +fi + +if [[ "$major" -eq 1 ]] || [[ "$minor" -eq 1 ]]; then + patchNew=0 +else + patchNew=$((patchCurrent + patch)) +fi + +if [[ "$majorNew" -eq "$majorCurrent" ]] && [[ "$minorNew" -eq "$minorCurrent" ]] && [[ "$patchNew" -eq "$patchCurrent" ]]; then + if [[ "$hasExistingTag" == "false" ]]; then + version="0.0.0" + [[ -n "$GITHUB_OUTPUT" ]] && echo "VERSION=$version" >> "$GITHUB_OUTPUT" || echo "VERSION=$version" + echo "First release: publishing version 0.0.0" + else + exit 0 + fi +else + version="$majorNew.$minorNew.$patchNew" + [[ -n "$GITHUB_OUTPUT" ]] && echo "VERSION=$version" >> "$GITHUB_OUTPUT" || echo "VERSION=$version" +fi diff --git a/scripts/update-version.sh b/scripts/update-version.sh new file mode 100644 index 0000000..6e0260a --- /dev/null +++ b/scripts/update-version.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +version="${1:-}" +csprojPath="${2:-src/StevanFreeborn.AsyncSyncFlagAnalyzer/StevanFreeborn.AsyncSyncFlagAnalyzer.csproj}" + +if [[ -z "$version" ]]; then + echo "Error: Version is required" + exit 1 +fi + +content=$(cat "$csprojPath") + +if [[ "$content" =~ \.*?\ ]]; then + content=$(echo "$content" | sed "s|.*|$version|") +elif [[ "$content" =~ \ ]]; then + content=$(echo "$content" | sed "s||\\n $version|") +fi + +echo "$content" > "$csprojPath" diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 0000000..6b18fc9 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,18 @@ + + + + https://gitea.freeborn.cloud/Stevan/stevanfreeborn.asyncsyncflaganalyzer + https://gitea.freeborn.cloud/Stevan/stevanfreeborn.asyncsyncflaganalyzer + git + true + true + snupkg + embedded + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + \ No newline at end of file diff --git a/src/Directory.packages.props b/src/Directory.packages.props new file mode 100644 index 0000000..2f25626 --- /dev/null +++ b/src/Directory.packages.props @@ -0,0 +1,11 @@ + + + true + + + + + + + + \ No newline at end of file diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes.csproj b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes.csproj new file mode 100644 index 0000000..05c11b1 --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes.csproj @@ -0,0 +1,16 @@ + + + + netstandard2.0 + false + + + + + + + + + + + diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/SyncParameterCodeFixProvider.cs b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/SyncParameterCodeFixProvider.cs new file mode 100644 index 0000000..e88f0ec --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes/SyncParameterCodeFixProvider.cs @@ -0,0 +1,138 @@ +using System.Collections.Immutable; +using System.Composition; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +using StevanFreeborn.AsyncSyncFlagAnalyzer.Common; + +namespace StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes; + +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SyncParameterCodeFixProvider)), Shared] +public class SyncParameterCodeFixProvider : CodeFixProvider +{ + public sealed override ImmutableArray FixableDiagnosticIds => [DiagnosticProperties.DiagnosticId]; + + public sealed override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document + .GetSyntaxRootAsync(context.CancellationToken) + .ConfigureAwait(false); + + var diagnostic = context.Diagnostics.FirstOrDefault(); + + if (diagnostic is null) + { + return; + } + + var diagnosticSpan = diagnostic.Location.SourceSpan; + + var invocation = root?.FindToken(diagnosticSpan.Start).Parent?.AncestorsAndSelf() + .OfType() + .FirstOrDefault(); + + if (invocation is null) + { + return; + } + + _ = diagnostic.Properties.TryGetValue(DiagnosticProperties.EnclosingSyncName, out var enclosingSyncName); + + if (string.IsNullOrEmpty(enclosingSyncName)) + { + enclosingSyncName = DiagnosticProperties.DefaultSyncName; + } + + _ = diagnostic.Properties.TryGetValue(DiagnosticProperties.TargetSyncName, out var targetSyncName); + + if (string.IsNullOrEmpty(targetSyncName)) + { + targetSyncName = enclosingSyncName; + } + + _ = diagnostic.Properties.TryGetValue(DiagnosticProperties.TargetSyncOrdinal, out var targetSyncOrdinalStr); + + if (!int.TryParse(targetSyncOrdinalStr, out var targetSyncOrdinal)) + { + targetSyncOrdinal = -1; + } + + var codeAction = CodeAction.Create( + title: $"Pass '{enclosingSyncName}' parameter", + createChangedDocument: c => AddSyncParameterAsync( + context.Document, + invocation, + enclosingSyncName!, + targetSyncName!, + targetSyncOrdinal, + c + ), + equivalenceKey: "PassSyncParameterFix" + ); + + context.RegisterCodeFix(codeAction, diagnostic); + } + + private static async Task AddSyncParameterAsync( + Document document, + InvocationExpressionSyntax invocation, + string enclosingSyncName, + string targetSyncName, + int targetSyncOrdinal, + CancellationToken cancellationToken + ) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + if (root is null) + { + return document; + } + + var arguments = invocation.ArgumentList.Arguments; + var syncIdentifier = SyntaxFactory.IdentifierName(enclosingSyncName); + + var existingNamedArg = arguments.FirstOrDefault( + a => a.NameColon?.Name.Identifier.Text == targetSyncName + ); + + if (existingNamedArg is not null) + { + var newNamedArg = existingNamedArg.WithExpression(syncIdentifier); + var newArguments = arguments.Replace(existingNamedArg, newNamedArg); + var newInvocation = invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments)); + var newRoot = root.ReplaceNode(invocation, newInvocation); + return document.WithSyntaxRoot(newRoot); + } + + var positionalCount = 0; + + foreach (var arg in arguments) + { + if (arg.NameColon is not null) + { + break; + } + + positionalCount++; + } + + var newArg = SyntaxFactory.Argument(syncIdentifier); + var updatedArguments = targetSyncOrdinal >= positionalCount + ? arguments.Insert(positionalCount, newArg) + : arguments.Replace(arguments[targetSyncOrdinal], newArg); + + var resultInvocation = invocation.WithArgumentList(invocation.ArgumentList.WithArguments(updatedArguments)); + var resultRoot = root.ReplaceNode(invocation, resultInvocation); + return document.WithSyntaxRoot(resultRoot); + } +} diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/DiagnosticProperties.cs b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/DiagnosticProperties.cs new file mode 100644 index 0000000..4041feb --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/DiagnosticProperties.cs @@ -0,0 +1,11 @@ +namespace StevanFreeborn.AsyncSyncFlagAnalyzer.Common; + +public static class DiagnosticProperties +{ + public const string DiagnosticId = "SYNC001"; + public const string DefaultSyncName = "sync"; + public const string EditorConfigKey = "dotnet_diagnostic.SYNC001.additional_sync_names"; + public const string EnclosingSyncName = "EnclosingSyncName"; + public const string TargetSyncName = "TargetSyncName"; + public const string TargetSyncOrdinal = "TargetSyncOrdinal"; +} diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/StevanFreeborn.AsyncSyncFlagAnalyzer.Common.csproj b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/StevanFreeborn.AsyncSyncFlagAnalyzer.Common.csproj new file mode 100644 index 0000000..012909d --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer.Common/StevanFreeborn.AsyncSyncFlagAnalyzer.Common.csproj @@ -0,0 +1,8 @@ + + + + netstandard2.0 + false + + + diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Shipped.md b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Shipped.md new file mode 100644 index 0000000..3d7901d --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Shipped.md @@ -0,0 +1,7 @@ +## Release 0.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|--------------|----------|---------------------- +SYNC001 | Architecture | Error | SyncParameterAnalyzer diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Unshipped.md b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/AnalyzerReleases.Unshipped.md new file mode 100644 index 0000000..e69de29 diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer/StevanFreeborn.AsyncSyncFlagAnalyzer.csproj b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/StevanFreeborn.AsyncSyncFlagAnalyzer.csproj new file mode 100644 index 0000000..094d02d --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/StevanFreeborn.AsyncSyncFlagAnalyzer.csproj @@ -0,0 +1,52 @@ + + + + netstandard2.0 + true + StevanFreeborn.AsyncSyncFlagAnalyzer + 0.0.0 + Stevan Freeborn + Roslyn analyzer to enforce passing the sync flag in optionally asynchronous execution paths. + analyzer,async,sync,flag + README.md + LICENSE.md + true + false + true + true + + + + true + + + + + + + + + + + + + + + + + + + + + + + + <_PackageFiles Include="$(MSBuildProjectDirectory)\..\$(MSBuildProjectName).CodeFixes\bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName).CodeFixes.dll"> + analyzers/dotnet/cs + false + None + + + + + diff --git a/src/StevanFreeborn.AsyncSyncFlagAnalyzer/SyncParameterAnalyzer.cs b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/SyncParameterAnalyzer.cs new file mode 100644 index 0000000..f95221d --- /dev/null +++ b/src/StevanFreeborn.AsyncSyncFlagAnalyzer/SyncParameterAnalyzer.cs @@ -0,0 +1,130 @@ +using System.Collections.Immutable; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; + +using StevanFreeborn.AsyncSyncFlagAnalyzer.Common; + +namespace StevanFreeborn.AsyncSyncFlagAnalyzer; + +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public class SyncParameterAnalyzer : DiagnosticAnalyzer +{ + private const string Title = "Missing sync parameter in optionally async call"; + private const string MessageFormat = "The method '{0}' must pass the '{1}' parameter to '{2}'"; + + private static readonly DiagnosticDescriptor Rule = new( + DiagnosticProperties.DiagnosticId, + Title, + MessageFormat, + "Architecture", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); + + public override ImmutableArray SupportedDiagnostics => [Rule]; + + public override void Initialize(AnalysisContext context) + { + if (context is null) + { + return; + } + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterSyntaxNodeAction(AnalyzeAwaitExpression, SyntaxKind.AwaitExpression); + } + + private void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context) + { + var awaitExpr = (AwaitExpressionSyntax)context.Node; + + var enclosingMethod = awaitExpr.FirstAncestorOrSelf(); + + if (enclosingMethod is null) + { + return; + } + + var validSyncNames = GetValidSyncNames(context); + + var enclosingSyncParam = enclosingMethod.ParameterList.Parameters + .FirstOrDefault(p => validSyncNames.Contains(p.Identifier.Text)); + + if (enclosingSyncParam is null) + { + return; + } + + var expectedSyncName = enclosingSyncParam.Identifier.Text; + + if (awaitExpr.Expression is not InvocationExpressionSyntax invocation) + { + return; + } + + + if (context.SemanticModel.GetSymbolInfo(invocation).Symbol is not IMethodSymbol methodSymbol) + { + return; + } + + var targetSyncParam = methodSymbol.Parameters.FirstOrDefault(p => validSyncNames.Contains(p.Name)); + + if (targetSyncParam is null) + { + return; + } + + var passedSync = false; + + foreach (var argument in invocation.ArgumentList.Arguments) + { + if (argument.Expression is IdentifierNameSyntax id && id.Identifier.Text == expectedSyncName) + { + passedSync = true; + break; + } + } + + if (!passedSync) + { + var properties = ImmutableDictionary.Empty + .Add(DiagnosticProperties.EnclosingSyncName, enclosingSyncParam.Identifier.Text) + .Add(DiagnosticProperties.TargetSyncName, targetSyncParam.Name) + .Add(DiagnosticProperties.TargetSyncOrdinal, targetSyncParam.Ordinal.ToString(System.Globalization.CultureInfo.InvariantCulture)); + + var diagnostic = Diagnostic.Create( + Rule, + invocation.GetLocation(), + properties, + enclosingMethod.Identifier.Text, + expectedSyncName, + methodSymbol.Name + ); + + context.ReportDiagnostic(diagnostic); + } + } + + private static HashSet GetValidSyncNames(SyntaxNodeAnalysisContext context) + { + var names = new HashSet(StringComparer.OrdinalIgnoreCase) { DiagnosticProperties.DefaultSyncName }; + var options = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree); + + if (options.TryGetValue(DiagnosticProperties.EditorConfigKey, out var customNames) && !string.IsNullOrWhiteSpace(customNames)) + { + var splitNames = customNames.Split([','], StringSplitOptions.RemoveEmptyEntries); + + foreach (var name in splitNames) + { + _ = names.Add(name.Trim()); + } + } + + return names; + } +} \ No newline at end of file diff --git a/tests/.editorconfig b/tests/.editorconfig new file mode 100644 index 0000000..924b845 --- /dev/null +++ b/tests/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.CA1707.severity = none diff --git a/tests/Directory.Packages.props b/tests/Directory.Packages.props new file mode 100644 index 0000000..07ef95f --- /dev/null +++ b/tests/Directory.Packages.props @@ -0,0 +1,14 @@ + + + true + + + + + + + + + + + \ No newline at end of file diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests.csproj b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests.csproj new file mode 100644 index 0000000..0203932 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests.csproj @@ -0,0 +1,39 @@ + + + + net11.0 + enable + enable + false + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + PreserveNewest + + + + + + + + + diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/SyncParameterAnalyzerTests.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/SyncParameterAnalyzerTests.cs new file mode 100644 index 0000000..27d2d4a --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/SyncParameterAnalyzerTests.cs @@ -0,0 +1,159 @@ +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.Testing; + +using StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes; + +using VerifyCS = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixVerifier< + StevanFreeborn.AsyncSyncFlagAnalyzer.SyncParameterAnalyzer, + StevanFreeborn.AsyncSyncFlagAnalyzer.CodeFixes.SyncParameterCodeFixProvider, + Microsoft.CodeAnalysis.Testing.DefaultVerifier>; + +namespace StevanFreeborn.AsyncSyncFlagAnalyzer.Tests; + +public class SyncParameterAnalyzerTests +{ + [Fact] + public async Task WhenSyncIsPassedCorrectly_ItShouldNotReportDiagnostic() + { + var testData = await LoadTestDataAsync("WhenSyncIsPassedCorrectly"); + await VerifyCS.VerifyAnalyzerAsync(testData); + } + + [Fact] + public async Task WhenSyncIsPassedPositionally_ItShouldNotReportDiagnostic() + { + var testData = await LoadTestDataAsync("WhenSyncIsPassedPositionally"); + await VerifyCS.VerifyAnalyzerAsync(testData); + } + + [Fact] + public async Task WhenSyncIsPassedAsNamed_ItShouldNotReportDiagnostic() + { + var testData = await LoadTestDataAsync("WhenSyncIsPassedAsNamed"); + await VerifyCS.VerifyAnalyzerAsync(testData); + } + + [Fact] + public async Task WhenSyncIsOmitted_ItShouldReportDiagnosticAndApplyCodeFix() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetCoreAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsOmitted"); + var fixedData = await LoadTestDataAsync("WhenSyncIsOmitted_Fixed"); + + await VerifyCS.VerifyCodeFixAsync(testData, expectedDiagnostic, fixedData); + } + + [Fact] + public async Task WhenSyncIsHardcodedFalse_ItShouldReportDiagnostic() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetCoreAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsHardcodedFalse"); + + await VerifyCS.VerifyAnalyzerAsync(testData, expectedDiagnostic); + } + + [Fact] + public async Task WhenSyncIsHardcodedFalse_ItShouldApplyCodeFix() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetCoreAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsHardcodedFalse"); + var fixedData = await LoadTestDataAsync("WhenSyncIsHardcodedFalse_Fixed"); + + await VerifyCS.VerifyCodeFixAsync(testData, expectedDiagnostic, fixedData); + } + + [Fact] + public async Task WhenSyncIsPassedAsNamedHardcoded_ItShouldReplaceNamedArgument() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetCoreAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsPassedAsNamedHardcoded"); + var fixedData = await LoadTestDataAsync("WhenSyncIsPassedAsNamedHardcoded_Fixed"); + + await VerifyCS.VerifyCodeFixAsync(testData, expectedDiagnostic, fixedData); + } + + [Fact] + public async Task WhenOuterMethodHasNoSyncParam_ItShouldNotReportDiagnostic() + { + var testData = await LoadTestDataAsync("WhenOuterMethodHasNoSyncParam"); + await VerifyCS.VerifyAnalyzerAsync(testData); + } + + [Fact] + public async Task WhenTargetHasNoSyncParam_ItShouldNotReportDiagnostic() + { + var testData = await LoadTestDataAsync("WhenTargetHasNoSyncParam"); + await VerifyCS.VerifyAnalyzerAsync(testData); + } + + [Fact] + public async Task WhenSyncIsOmitted_CustomName_ItShouldReportDiagnosticAndApplyCodeFix() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "runSynchronously", "GetMoreDataAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsOmitted_CustomName"); + var fixedData = await LoadTestDataAsync("WhenSyncIsOmitted_CustomName_Fixed"); + + var test = new CSharpCodeFixTest + { + TestCode = testData, + FixedCode = fixedData + }; + test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", """ +root = true + +[*.cs] +dotnet_diagnostic.SYNC001.additional_sync_names = runSynchronously +""")); + test.ExpectedDiagnostics.Add(expectedDiagnostic); + + await test.RunAsync(); + } + + [Fact] + public async Task WhenSyncIsOmitted_MultipleAwaits_OnlyOneShouldReportDiagnostic() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetMoreDataAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsOmitted_MultipleAwaits"); + var fixedData = await LoadTestDataAsync("WhenSyncIsOmitted_MultipleAwaits_Fixed"); + + await VerifyCS.VerifyCodeFixAsync(testData, expectedDiagnostic, fixedData); + } + + [Fact] + public async Task WhenSyncIsNotLastTargetParameter_ItShouldReportDiagnosticAndApplyCodeFix() + { + var expectedDiagnostic = VerifyCS.Diagnostic("SYNC001") + .WithLocation(0) + .WithArguments("GetFrobCoreAsync", "sync", "GetDataAsync"); + + var testData = await LoadTestDataAsync("WhenSyncIsNotLastTargetParameter"); + var fixedData = await LoadTestDataAsync("WhenSyncIsNotLastTargetParameter_Fixed"); + + await VerifyCS.VerifyCodeFixAsync(testData, expectedDiagnostic, fixedData); + } + + private static async Task LoadTestDataAsync(string name) + { + var path = Path.Combine(AppContext.BaseDirectory, "TestData", $"{name}.cs"); + var text = await File.ReadAllTextAsync(path); + return text; + } +} \ No newline at end of file diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenOuterMethodHasNoSyncParam.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenOuterMethodHasNoSyncParam.cs new file mode 100644 index 0000000..5e428dd --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenOuterMethodHasNoSyncParam.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync() + { + return await _dataService.GetCoreAsync(17); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse.cs new file mode 100644 index 0000000..ea943e3 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await {|#0:_dataService.GetCoreAsync(17, false)|}; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse_Fixed.cs new file mode 100644 index 0000000..a631faa --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsHardcodedFalse_Fixed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(17, sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter.cs new file mode 100644 index 0000000..a5c5adb --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetDataAsync(int id, bool sync = false, bool useCache = true); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await {|#0:_dataService.GetDataAsync(17)|}; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter_Fixed.cs new file mode 100644 index 0000000..04074ea --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsNotLastTargetParameter_Fixed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetDataAsync(int id, bool sync = false, bool useCache = true); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetDataAsync(17, sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted.cs new file mode 100644 index 0000000..4a3e5aa --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await {|#0:_dataService.GetCoreAsync(17)|}; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName.cs new file mode 100644 index 0000000..fec1711 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetMoreDataAsync(bool runSynchronously = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool runSynchronously) + { + return await {|#0:_dataService.GetMoreDataAsync()|}; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName_Fixed.cs new file mode 100644 index 0000000..2e27936 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_CustomName_Fixed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetMoreDataAsync(bool runSynchronously = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool runSynchronously) + { + return await _dataService.GetMoreDataAsync(runSynchronously); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_Fixed.cs new file mode 100644 index 0000000..a631faa --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_Fixed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(17, sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits.cs new file mode 100644 index 0000000..0ea34e6 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits.cs @@ -0,0 +1,20 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetDataAsync(bool sync = false); + Task GetMoreDataAsync(bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + var a = await _dataService.GetDataAsync(sync); + var b = await {|#0:_dataService.GetMoreDataAsync()|}; + return a + b; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits_Fixed.cs new file mode 100644 index 0000000..43f6c00 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsOmitted_MultipleAwaits_Fixed.cs @@ -0,0 +1,20 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetDataAsync(bool sync = false); + Task GetMoreDataAsync(bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + var a = await _dataService.GetDataAsync(sync); + var b = await _dataService.GetMoreDataAsync(sync); + return a + b; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamed.cs new file mode 100644 index 0000000..5cf048e --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(id: 17, sync: sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded.cs new file mode 100644 index 0000000..1a41a57 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await {|#0:_dataService.GetCoreAsync(17, sync: false)|}; + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded_Fixed.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded_Fixed.cs new file mode 100644 index 0000000..f1c2655 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedAsNamedHardcoded_Fixed.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(17, sync: sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedCorrectly.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedCorrectly.cs new file mode 100644 index 0000000..a631faa --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedCorrectly.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(17, sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedPositionally.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedPositionally.cs new file mode 100644 index 0000000..a631faa --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenSyncIsPassedPositionally.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; + +public interface IDataService +{ + Task GetCoreAsync(int id, bool sync = false); +} + +public class BusinessLogic +{ + private readonly IDataService _dataService; + public BusinessLogic(IDataService dataService) { _dataService = dataService; } + + private async Task GetFrobCoreAsync(bool sync) + { + return await _dataService.GetCoreAsync(17, sync); + } +} diff --git a/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenTargetHasNoSyncParam.cs b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenTargetHasNoSyncParam.cs new file mode 100644 index 0000000..74e52e3 --- /dev/null +++ b/tests/StevanFreeborn.AsyncSyncFlagAnalyzer.Tests/TestData/WhenTargetHasNoSyncParam.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; + +public class BusinessLogic +{ + private async Task GetFrobCoreAsync(bool sync) + { + await Task.Delay(100); + return "done"; + } +}