Skip to content

TaskAnalyzer: MSBuildTask0003 code fix produces non-compiling code for nested calls and static methods #14780

Closed

Description

@ViktorHofer

Summary

MultiThreadableTaskCodeFixProvider's MSBuildTask0003 fix ("Wrap with TaskEnvironment.GetAbsolutePath()") produces code that does not compile in two common shapes:

  1. When the flagged File.*/Directory.*/XDocument.Load call is itself nested as an argument of another call, the fix wraps the outer call's argument (i.e. the flagged call's return value) instead of the flagged call's own path argument → CS1503.
  2. When the flagged call sits in a static method, the fix emits TaskEnvironment.GetAbsolutePath(...) against the instance property → CS0120.

Both are reproducible with Microsoft.Build.TaskAuthoring.Analyzer 18.11.0-1.26420.118 and dotnet format analyzers.

Repro

Repro.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Build.Framework" Version="18.8.2" ExcludeAssets="runtime" />
    <PackageReference Include="Microsoft.Build.Utilities.Core" Version="18.8.2" ExcludeAssets="runtime" />
    <PackageReference Include="Microsoft.Build.TaskAuthoring.Analyzer" Version="18.11.0-1.26420.118"
                      PrivateAssets="all" IncludeAssets="analyzers" />
  </ItemGroup>
</Project>

Repro.cs:

using System.IO;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Repro
{
    [MSBuildMultiThreadableTask]
    public sealed class ReproTask : Task, IMultiThreadableTask
    {
        public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;

        public string InputPath { get; set; }

        public string OutputPath { get; set; }

        public override bool Execute()
        {
            // Case A: File call nested as an argument of an outer object creation.
            using (var writer = new StreamWriter(File.Create(OutputPath)))
            {
                writer.Write("x");
            }

            // Case B: File call nested as an argument of an outer method call.
            using (var reader = new StreamReader(File.OpenRead(InputPath)))
            {
                reader.ReadToEnd();
            }

            // Case C: XDocument.Load nested inside another call.
            Consume(XDocument.Load(InputPath));

            // Case D: call inside a static helper (no instance TaskEnvironment available).
            ReadStatic(InputPath);

            return true;
        }

        private static void Consume(XDocument doc)
        {
        }

        private static string ReadStatic(string path) => File.ReadAllText(path);
    }
}

dotnet build reports exactly the four expected diagnostics:

Repro.cs(20,50): warning MSBuildTask0003: 'File.Create(string)' may resolve a relative path against the shared working directory: wrap path argument with TaskEnvironment.GetAbsolutePath()
Repro.cs(26,50): warning MSBuildTask0003: 'File.OpenRead(string)' ...
Repro.cs(32,21): warning MSBuildTask0003: 'XDocument.Load(string)' ...
Repro.cs(44,58): warning MSBuildTask0003: 'File.ReadAllText(string)' ...

Then:

dotnet format analyzers Repro.csproj --diagnostics MSBuildTask0003 --severity warn

Actual output

// Case A
using (var writer = new StreamWriter(TaskEnvironment.GetAbsolutePath(File.Create(OutputPath))))

// Case B
using (var reader = new StreamReader(TaskEnvironment.GetAbsolutePath(File.OpenRead(InputPath))))

// Case C
Consume(TaskEnvironment.GetAbsolutePath(XDocument.Load(InputPath)));

// Case D
private static string ReadStatic(string path) => File.ReadAllText(TaskEnvironment.GetAbsolutePath(path));

Rebuilding:

Repro.cs(20,82): error CS1503: Argument 1: cannot convert from 'System.IO.FileStream' to 'string'
Repro.cs(26,82): error CS1503: Argument 1: cannot convert from 'System.IO.FileStream' to 'string'
Repro.cs(32,53): error CS1503: Argument 1: cannot convert from 'System.Xml.Linq.XDocument' to 'string'
Repro.cs(44,75): error CS0120: An object reference is required for the non-static field, method, or property 'ReproTask.TaskEnvironment'

Expected output

// Case A
using (var writer = new StreamWriter(File.Create(TaskEnvironment.GetAbsolutePath(OutputPath))))

// Case B
using (var reader = new StreamReader(File.OpenRead(TaskEnvironment.GetAbsolutePath(InputPath))))

// Case C
Consume(XDocument.Load(TaskEnvironment.GetAbsolutePath(InputPath)));

// Case D — no fix offered (or the fix should refuse / require the method be made non-static)
private static string ReadStatic(string path) => File.ReadAllText(path);

Notes on cause

For cases A–C, RegisterFilePathFix resolves the call to fix via:

private static SyntaxNode FindContainingCall(SyntaxNode node)
{
    return node.AncestorsAndSelf().FirstOrDefault(n =>
        n is InvocationExpressionSyntax ||
        n is ObjectCreationExpressionSyntax ||
        n is ImplicitObjectCreationExpressionSyntax);
}

and then wraps "the first argument that is not already wrapped" on whatever that returns. When the diagnostic node resolves such that the enclosing new StreamWriter(...) / Consume(...) is picked rather than the flagged File.Create(...) / XDocument.Load(...) itself, the wrap lands on the wrong argument. The fix should anchor on the invocation the analyzer actually reported (the one whose symbol is the banned path-taking API) and wrap that call's path parameter, rather than re-deriving the call by walking ancestors.

For case D, the fix should additionally check whether the enclosing member is static before emitting a reference to the instance TaskEnvironment property, and withhold the fix (or offer it only alongside a change that threads a TaskEnvironment/AbsolutePath parameter through) when it is.

Impact

This matters mostly at scale. Migrating dotnet/arcade's MSBuild tasks (dotnet/arcade#17378) applied ~74 GetAbsolutePath wraps across 83 files with dotnet format analyzers ... --severity warn. Roughly 10 files came out with the case A/B/C misplacement and 3 with the case D static-context error, all of which had to be found and repaired by hand afterwards. Since MultiThreadableTaskCodeFixProvider registers WellKnownFixAllProviders.BatchFixer, bulk application is the intended workflow, and the failures are only surfaced by a subsequent compile.

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions