Skip to content
This repository was archived by the owner on Jun 16, 2026. It is now read-only.
Merged
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
2 changes: 0 additions & 2 deletions Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,5 @@
<PackageReference Update="System.Text.Json" Version="4.7.2" />
<PackageReference Update="YamlDotNet" Version="11.2.1" />
<PackageReference Update="System.Memory" Version="4.5.4" />
<PackageReference Update="NuGet.Configuration" Version="6.8.0" />
<PackageReference Update="Microsoft.Build" Version="16.11.0" />
</ItemGroup>
</Project>
2 changes: 0 additions & 2 deletions src/AutoRest.CSharp/AutoRest.CSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@
<!-- Any stable version of System.Memory should work here. -->
<PackageReference Include="System.Memory" />
<PackageReference Include="System.Net.ClientModel" />
<PackageReference Include="NuGet.Configuration" />
<PackageReference Include="Microsoft.Build" />
</ItemGroup>

<!-- Enable SourceLink -->
Expand Down
37 changes: 2 additions & 35 deletions src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@
using AutoRest.CSharp.Input.Source;
using AutoRest.CSharp.Mgmt.Report;
using AutoRest.CSharp.Utilities;
using Microsoft.Build.Construction;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NuGet.Configuration;

namespace AutoRest.CSharp.AutoRest.Plugins
{
Expand All @@ -25,9 +22,10 @@ internal class CSharpGen : IPlugin
public async Task<GeneratedCodeWorkspace> ExecuteAsync(CodeModel codeModel)
{
ValidateConfiguration();

Directory.CreateDirectory(Configuration.OutputFolder);
var project = await GeneratedCodeWorkspace.Create(Configuration.AbsoluteProjectFolder, Configuration.OutputFolder, Configuration.SharedSourceFolders);
var sourceInputModel = new SourceInputModel(await project.GetCompilationAsync(), previousContract: await LoadBaselineContract());
var sourceInputModel = new SourceInputModel(await project.GetCompilationAsync());

if (Configuration.Generation1ConvenienceClient)
{
Expand Down Expand Up @@ -56,37 +54,6 @@ public async Task<GeneratedCodeWorkspace> ExecuteAsync(CodeModel codeModel)
return project;
}

private async Task<CSharpCompilation?> LoadBaselineContract()
{
string fullPath;
string projectFilePath = Path.GetFullPath(Path.Combine(Configuration.AbsoluteProjectFolder, $"{Configuration.Namespace}.csproj"));
if (!File.Exists(projectFilePath))
return null;

var baselineVersion = ProjectRootElement.Open(projectFilePath).Properties.SingleOrDefault(p => p.Name == "ApiCompatVersion")?.Value;

if (baselineVersion is not null)
{
var nugetGlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(new NullSettings());
var nugetFolder = Path.Combine(nugetGlobalPackageFolder, Configuration.Namespace.ToLowerInvariant(), baselineVersion, "lib", "netstandard2.0");
fullPath = Path.Combine(nugetFolder, $"{Configuration.Namespace}.dll");
if (File.Exists(fullPath))
{
return await GeneratedCodeWorkspace.CreatePreviousContractFromDll(Path.Combine(nugetFolder, $"{Configuration.Namespace}.xml"), fullPath).GetCompilationAsync();
}
}

// fallback for testing purpose
var baselinePath = Path.GetFullPath(Path.Combine(Configuration.AbsoluteProjectFolder, "..", "..", "BaselineContract", Configuration.Namespace));
fullPath = Path.Combine(baselinePath, $"{Configuration.Namespace}.dll");
if (File.Exists(fullPath))
{
return await GeneratedCodeWorkspace.CreatePreviousContractFromDll(Path.Combine(baselinePath, $"{Configuration.Namespace}.xml"), fullPath).GetCompilationAsync();
}

return null;
}

private void GenerateMgmtReport(GeneratedCodeWorkspace project)
{
MgmtReport.Instance.TransformSection.ForEachTransform((t, usages) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,18 +253,6 @@ public static GeneratedCodeWorkspace CreateExistingCodeProject(string outputDire
return new GeneratedCodeWorkspace(project);
}

public static GeneratedCodeWorkspace CreatePreviousContractFromDll(string xmlDocumentationpath, string dllPath)
{
var workspace = new AdhocWorkspace();
Project project = workspace.AddProject("PreviousContract", LanguageNames.CSharp);
project = project
.AddMetadataReferences(AssemblyMetadataReferences)
.WithCompilationOptions(new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Disable));
project = project.AddMetadataReference(MetadataReference.CreateFromFile(dllPath, documentation: XmlDocumentationProvider.CreateFromFile(xmlDocumentationpath)));
return new GeneratedCodeWorkspace(project);
}

private static Project CreateGeneratedCodeProject()
{
var workspace = new AdhocWorkspace();
Expand Down
37 changes: 0 additions & 37 deletions src/AutoRest.CSharp/Common/Generation/Types/CSharpType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,42 +257,5 @@ public bool TryCast<T>([MaybeNullWhen(false)] out T provider) where T : TypeProv
provider = this.Implementation as T;
return provider != null;
}

/// <summary>
/// Check whether two CSharpType instances equal or not
/// This is not the same as left.Equals(right) because this function only checks the names
/// </summary>
/// <param name="left"></param>
/// <param name="other"></param>
/// <returns></returns>
public bool EqualsByName(CSharpType? other)
{
if (ReferenceEquals(this, other))
{
return true;
}

if (other is null)
{
return false;
}

if (Namespace != other.Namespace)
return false;

if (Name != other.Name)
return false;

if (Arguments.Length != other.Arguments.Length)
return false;

for (int i = 0; i < Arguments.Length; i++)
{
if (!Arguments[i].EqualsByName(other.Arguments[i]))
return false;
}

return true;
}
}
}
11 changes: 0 additions & 11 deletions src/AutoRest.CSharp/Common/Generation/Writers/CodeWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,17 +220,6 @@ public void UseNamespace(string @namespace)
_usingNamespaces.Add(@namespace);
}

public void WriteRawXmlDocumentation(FormattableString? content)
{
if (content is null)
return;

var lines = content.ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
var xmlLines = string.Join('\n', lines.Select(l => "/// " + l));
AppendRaw(xmlLines);
Line();
}

public CodeWriter AppendXmlDocumentation(FormattableString startTag, FormattableString endTag, FormattableString content)
{
const string xmlDoc = "/// ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using AutoRest.CSharp.Common.Output.Builders;
Expand Down Expand Up @@ -751,34 +750,5 @@ static void WritePropertyAccessorModifiers(CodeWriter writer, MethodSignatureMod
.AppendRawIf("private ", modifiers.HasFlag(MethodSignatureModifiers.Private));
}
}

public static void WriteOverloadMethod(this CodeWriter writer, OverloadMethodSignature overloadMethod)
{
writer.WriteRawXmlDocumentation(overloadMethod.Description);
if (overloadMethod.IsHiddenFromUser)
{
writer.Line($"[{typeof(EditorBrowsableAttribute)}({typeof(EditorBrowsableState)}.{nameof(EditorBrowsableState.Never)})]");
}
using (writer.WriteMethodDeclaration(overloadMethod.PreviousMethodSignature))
{
writer.Line();
var awaitOperation = overloadMethod.PreviousMethodSignature.Modifiers.HasFlag(MethodSignatureModifiers.Async) ? "await " : "";
writer.Append($"return {awaitOperation}{overloadMethod.MethodSignature.Name}(");
var set = overloadMethod.MissingParameters.ToHashSet(Parameter.TypeAndNameEqualityComparer);
foreach (var parameter in overloadMethod.MethodSignature.Parameters)
{
if (set.Contains(parameter))
{
writer.Append($"{parameter.DefaultValue?.Value ?? "default"}, ");
}
else
{
writer.Append($"{parameter.Name}, ");
}
}
writer.RemoveTrailingComma();
writer.Line($");");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using AutoRest.CSharp.Common.Output.Models.Types;
using AutoRest.CSharp.Generation.Types;
using AutoRest.CSharp.Input;
using AutoRest.CSharp.Output.Models;
using AutoRest.CSharp.Output.Models.Types;

namespace AutoRest.CSharp.Generation.Writers
Expand All @@ -34,17 +27,11 @@ public void Write()
_writer.WriteXmlDocumentationSummary(This.Description);
using (_writer.Scope($"{This.Declaration.Accessibility} static partial class {This.Type:D}"))
{
foreach (var method in This.OutputMethods)
foreach (var method in This.Methods)
{
_writer.WriteMethodDocumentation(method.Signature);
_writer.WriteMethod(method);
}

foreach (OverloadMethodSignature overloadMethod in This.SignatureType!.OverloadMethods)
{
_writer.WriteOverloadMethod(overloadMethod);
_writer.Line();
}
}
}
}
Expand Down
19 changes: 8 additions & 11 deletions src/AutoRest.CSharp/Common/Input/Source/SourceInputModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,19 @@ namespace AutoRest.CSharp.Input.Source
{
public class SourceInputModel
{
private readonly Compilation _compilation;
private readonly CompilationInput? _existingCompilation;
private readonly CodeGenAttributes _codeGenAttributes;
private readonly Dictionary<string, INamedTypeSymbol> _nameMap = new Dictionary<string, INamedTypeSymbol>(StringComparer.OrdinalIgnoreCase);

public Compilation Customization { get; }
public Compilation? PreviousContract { get; }

public SourceInputModel(Compilation customization, CompilationInput? existingCompilation = null, Compilation? previousContract = null)
public SourceInputModel(Compilation compilation, CompilationInput? existingCompilation = null)
{
Customization = customization;
PreviousContract = previousContract;
_compilation = compilation;
_existingCompilation = existingCompilation;

_codeGenAttributes = new CodeGenAttributes(customization);
_codeGenAttributes = new CodeGenAttributes(compilation);

IAssemblySymbol assembly = Customization.Assembly;
IAssemblySymbol assembly = _compilation.Assembly;

foreach (IModuleSymbol module in assembly.Modules)
{
Expand All @@ -44,8 +41,8 @@ public SourceInputModel(Compilation customization, CompilationInput? existingCom

public IReadOnlyList<string>? GetServiceVersionOverrides()
{
var osvAttributeType = Customization.GetTypeByMetadataName(typeof(CodeGenOverrideServiceVersionsAttribute).FullName!)!;
var osvAttribute = Customization.Assembly.GetAttributes()
var osvAttributeType = _compilation.GetTypeByMetadataName(typeof(CodeGenOverrideServiceVersionsAttribute).FullName!)!;
var osvAttribute = _compilation.Assembly.GetAttributes()
.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, osvAttributeType));

return osvAttribute?.ConstructorArguments[0].Values.Select(v => v.Value).OfType<string>().ToList();
Expand All @@ -70,7 +67,7 @@ public SourceInputModel(Compilation customization, CompilationInput? existingCom
if (!_nameMap.TryGetValue(name, out var type) &&
!_nameMap.TryGetValue(fullyQualifiedMetadataName, out type))
{
type = includeArmCore ? Customization.GetTypeByMetadataName(fullyQualifiedMetadataName) : Customization.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
type = includeArmCore ? _compilation.GetTypeByMetadataName(fullyQualifiedMetadataName) : _compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName);
}

return type;
Expand Down
41 changes: 1 addition & 40 deletions src/AutoRest.CSharp/Common/Output/Models/MethodSignature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,22 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoRest.CSharp.Generation.Types;
using AutoRest.CSharp.Generation.Writers;
using AutoRest.CSharp.Mgmt.Decorator;
using AutoRest.CSharp.Output.Models.Shared;
using Azure;
using Microsoft.CodeAnalysis;
using static AutoRest.CSharp.Output.Models.MethodSignatureModifiers;

namespace AutoRest.CSharp.Output.Models
{
internal record MethodSignature(string Name, FormattableString? Summary, FormattableString? Description, MethodSignatureModifiers Modifiers, CSharpType? ReturnType, FormattableString? ReturnDescription, IReadOnlyList<Parameter> Parameters, IReadOnlyList<CSharpAttribute>? Attributes = null, IReadOnlyList<CSharpType>? GenericArguments = null, IReadOnlyDictionary<CSharpType, FormattableString>? GenericParameterConstraints = null, CSharpType? ExplicitInterface = null, string? NonDocumentComment = null)
: MethodSignatureBase(Name, Summary, Description, NonDocumentComment, Modifiers, Parameters, Attributes ?? Array.Empty<CSharpAttribute>())
{
public static IEqualityComparer<MethodSignature> ParameterAndReturnTypeEqualityComparer = new MethodSignatureParameterAndReturnTypeEqualityComparer();

public MethodSignature WithAsync(bool isAsync) => isAsync ? MakeAsync() : MakeSync();

public MethodSignature DisableOptionalParameters()
{
if (Parameters.All(p => p.DefaultValue is null))
{
return this;
}
return this with { Parameters = Parameters.Select(p => p.ToRequired()).ToList() };
}

private MethodSignature MakeAsync()
{
if (Modifiers.HasFlag(Async) || ReturnType != null && TypeFactory.IsAsyncPageable(ReturnType))
Expand Down Expand Up @@ -111,31 +98,5 @@ private MethodSignature MakeSync()
}

public FormattableString GetCRef() => $"{Name}({Parameters.GetTypesFormattable()})";

private class MethodSignatureParameterAndReturnTypeEqualityComparer : IEqualityComparer<MethodSignature>
{
public bool Equals(MethodSignature? x, MethodSignature? y)
{
if (ReferenceEquals(x, y))
{
return true;
}

if (x is null || y is null)
{
return false;
}

var result = x.Name == x.Name
&& x.ReturnType == y.ReturnType
&& x.Parameters.SequenceEqual(y.Parameters, Parameter.TypeAndNameEqualityComparer);
return result;
}

public int GetHashCode([DisallowNull] MethodSignature obj)
{
return HashCode.Combine(obj.Name, obj.ReturnType);
}
}
}
}

This file was deleted.

Loading