Skip to content

25x nonparallelized speedup by avoiding MSBuildWorkspace in example tester #1338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: draft-v8
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tools/ExampleTester.Tests/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[assembly: Parallelizable(ParallelScope.Children)]
25 changes: 25 additions & 0 deletions tools/ExampleTester.Tests/ExampleTester.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
<PackageReference Include="NUnit" Version="4.3.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.8.1" PrivateAssets="all" />
<PackageReference Include="NUnit3TestAdapter" Version="5.0.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ExampleTester\ExampleTester.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>

</Project>
267 changes: 267 additions & 0 deletions tools/ExampleTester.Tests/FastCsprojCompilationParserTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
using System.Collections.Immutable;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.MSBuild;
using Shouldly;

namespace ExampleTester.Tests;

#pragma warning disable CS8509 // The switch expression does not handle all possible values of its input type (it is not exhaustive).

public static class FastCsprojCompilationParserTests
{
private const string CsprojFileName = "Test.csproj";

private static CsprojParseResult ParseCsproj(string csprojContents)
{
var result = FastCsprojCompilationParser.ParseCsproj(XDocument.Parse(csprojContents), CsprojFileName);
CompareMSBuildWorkspaceCompilation(csprojContents, result);
return result;
}

private static void CompareMSBuildWorkspaceCompilation(string csprojContents, CsprojParseResult result)
{
var msbuildCompilation = GetMSBuildWorkspaceCompilation(csprojContents);

result.AssemblyName.ShouldBe(msbuildCompilation.AssemblyName);

var sanitizedCompilationOptions = msbuildCompilation.Options
.WithAssemblyIdentityComparer(result.CompilationOptions.AssemblyIdentityComparer)
.WithMetadataReferenceResolver(null)
.WithSourceReferenceResolver(null)
.WithStrongNameProvider(null)
.WithSyntaxTreeOptionsProvider(null)
.WithXmlReferenceResolver(null);

result.CompilationOptions.Equals(sanitizedCompilationOptions).ShouldBeTrue();

var sanitizedParseOptions = msbuildCompilation.SyntaxTrees.First().Options;

result.ParseOptions.Equals(sanitizedParseOptions).ShouldBeTrue();

var sanitizedSyntaxTrees = msbuildCompilation.SyntaxTrees
.Where(tree => !new[] { ".AssemblyAttributes.cs", ".AssemblyInfo.cs" }.Any(ending =>
Path.GetFileName(tree.FilePath).EndsWith(ending, StringComparison.OrdinalIgnoreCase)))
.ToImmutableArray();

result.GeneratedSources.SequenceEqual(sanitizedSyntaxTrees, (a, b) =>
Path.GetFileName(a.FilePath).Equals(Path.GetFileName(b.FilePath), StringComparison.OrdinalIgnoreCase)
&& a.Options.Equals(b.Options)
&& a.GetText().ToString() == b.GetText().ToString())
.ShouldBeTrue();
}

private static Compilation GetMSBuildWorkspaceCompilation(string csprojContents)
{
using var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { ["Configuration"] = "Release" });

var tempFolder = Path.Join(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempFolder);
try
{
var csprojPath = Path.Join(tempFolder, CsprojFileName);
File.WriteAllText(csprojPath, csprojContents);
var project = workspace.OpenProjectAsync(csprojPath).GetAwaiter().GetResult();
return project.GetCompilationAsync().GetAwaiter().GetResult().ShouldNotBeNull();
}
finally
{
Directory.Delete(tempFolder, recursive: true);
}
}

[Test]
public static void Defaults()
{
var result = ParseCsproj("""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

</Project>
""");

result.CompilationOptions.OutputKind.ShouldBe(OutputKind.DynamicallyLinkedLibrary);
result.CompilationOptions.NullableContextOptions.ShouldBe(NullableContextOptions.Disable);
result.AssemblyName.ShouldBe(Path.GetFileNameWithoutExtension(CsprojFileName));
result.CompilationOptions.AllowUnsafe.ShouldBeFalse();
result.ParseOptions.LanguageVersion.ShouldBe(LanguageVersion.CSharp10); // Due to net6.0
result.CompilationOptions.WarningLevel.ShouldBe(6); // Due to net6.0
result.GeneratedSources.ShouldBeEmpty();
}

[Test]
public static void ParsesTargetFramework()
{
ParseCsproj("""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

</Project>
""").TargetFramework.ShouldBe("net6.0");
}

[Test]
public static void ParsesOutputType([Values("Library", "Exe", "WinExe")] string outputType)
{
ParseCsproj($"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<OutputType>{outputType}</OutputType>
</PropertyGroup>

</Project>
""").CompilationOptions.OutputKind.ShouldBe(outputType switch
{
"Library" => OutputKind.DynamicallyLinkedLibrary,
"Exe" => OutputKind.ConsoleApplication,
"WinExe" => OutputKind.WindowsApplication,
});
}

[Test]
public static void ParsesNullable([Values("enable", "disable", "annotations", "warnings")] string nullable)
{
ParseCsproj($"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>{nullable}</Nullable>
</PropertyGroup>

</Project>
""").CompilationOptions.NullableContextOptions.ShouldBe(nullable switch
{
"enable" => NullableContextOptions.Enable,
"disable" => NullableContextOptions.Disable,
"annotations" => NullableContextOptions.Annotations,
"warnings" => NullableContextOptions.Warnings,
});
}

[Test]
public static void ParsesAssemblyName()
{
ParseCsproj($"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AssemblyName>Xyz</AssemblyName>
</PropertyGroup>

</Project>
""").AssemblyName.ShouldBe("Xyz");
}

[Test]
public static void ParsesAllowUnsafeBlocks([Values("true", "false")] string allowUnsafeBlocks)
{
ParseCsproj($"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AllowUnsafeBlocks>{allowUnsafeBlocks}</AllowUnsafeBlocks>
</PropertyGroup>

</Project>
""").CompilationOptions.AllowUnsafe.ShouldBe(allowUnsafeBlocks switch
{
"true" => true,
"false" => false,
});
}

[Test]
public static void ParsesImplicitUsings([Values("true", "enable", "false", "disable")] string implicitUsings)
{
var hasImplicitUsings = implicitUsings switch
{
"true" or "enable" => true,
"false" or "disable" => false,
};

var result = ParseCsproj($"""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>{implicitUsings}</ImplicitUsings>
</PropertyGroup>

</Project>
""");

if (hasImplicitUsings)
{
var source = result.GeneratedSources.ShouldHaveSingleItem();
source.Options.ShouldBe(result.ParseOptions);
source.FilePath.ShouldBe("Test.GlobalUsings.g.cs");
source.GetText().ToString().ShouldBe("""
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

""");
}
else
{
result.GeneratedSources.ShouldBeEmpty();
}
}

[Test]
public static void ThrowsNotImplementedExceptionForUnrecognizedProperty()
{
Should.Throw<NotImplementedException>(() => ParseCsproj("""
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Xyz></Xyz>
</PropertyGroup>

</Project>
"""));
}

[Test]
public static void ThrowsNotImplementedExceptionForUnrecognizedItem()
{
Should.Throw<NotImplementedException>(() => ParseCsproj("""
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<Xyz Include="" />
</ItemGroup>

</Project>
"""));
}

[Test]
public static void ThrowsNotImplementedExceptionForUnrecognizedTopLevelElement()
{
Should.Throw<NotImplementedException>(() => ParseCsproj("""
<Project Sdk="Microsoft.NET.Sdk">

<Xyz></Xyz>

</Project>
"""));
}
}
12 changes: 12 additions & 0 deletions tools/ExampleTester/CsprojParseResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace ExampleTester;

public sealed record CsprojParseResult(
string? AssemblyName,
string TargetFramework,
CSharpParseOptions ParseOptions,
CSharpCompilationOptions CompilationOptions,
ImmutableArray<SyntaxTree> GeneratedSources);
1 change: 1 addition & 0 deletions tools/ExampleTester/ExampleTester.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Basic.Reference.Assemblies.Net60" Version="1.8.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.14.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.14.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
Expand Down
Loading