diff --git a/packages/http-client-csharp/eng/scripts/Test-CadlRanch.ps1 b/packages/http-client-csharp/eng/scripts/Test-CadlRanch.ps1 index 7b11254d0a..4f2a3eaa64 100644 --- a/packages/http-client-csharp/eng/scripts/Test-CadlRanch.ps1 +++ b/packages/http-client-csharp/eng/scripts/Test-CadlRanch.ps1 @@ -32,10 +32,22 @@ foreach ($directory in $directories) { if (-not (Compare-Paths $subPath $filter)) { continue } - + + $testPath = "$cadlRanchRoot.Tests" $testFilter = "TestProjects.CadlRanch.Tests" foreach ($folder in $folders) { - $testFilter += ".$(Get-Namespace $folder)" + $segment = "$(Get-Namespace $folder)" + + # the test directory names match the test namespace names, but the source directory names will not have the leading underscore + # so check to see if the filter should contain a leading underscore by comparing with the test directory + if (-not (Test-Path (Join-Path $testPath $segment))) { + $testFilter += "._$segment" + $testPath = Join-Path $testPath "_$segment" + } + else{ + $testFilter += ".$segment" + $testPath = Join-Path $testPath $segment + } } Write-Host "Regenerating $subPath" -ForegroundColor Cyan diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/CSharpGen.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/CSharpGen.cs index d43e575aa6..df2460f0fa 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/CSharpGen.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/CSharpGen.cs @@ -62,6 +62,8 @@ public async Task ExecuteAsync() DeleteDirectory(generatedTestOutputPath, _filesToKeep); } + await workspace.PostProcessAsync(); + // Write the generated files to the output directory await foreach (var file in workspace.GetGeneratedFilesAsync()) { diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Configuration.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Configuration.cs index c5cad927a6..9ae7f9620f 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Configuration.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Configuration.cs @@ -20,6 +20,13 @@ public class Configuration "Enum", ]; + internal enum UnreferencedTypesHandlingOption + { + RemoveOrInternalize = 0, + Internalize = 1, + KeepAll = 2 + } + private const string GeneratedFolderName = "Generated"; private const string ConfigurationFileName = "Configuration.json"; @@ -43,7 +50,8 @@ private Configuration( string libraryName, bool useModelNamespace, string libraryNamespace, - bool disableXmlDocs) + bool disableXmlDocs, + UnreferencedTypesHandlingOption unreferencedTypesHandling) { OutputDirectory = outputPath; AdditionalConfigOptions = additionalConfigOptions; @@ -56,6 +64,7 @@ private Configuration( RootNamespace = GetCleanNameSpace(libraryNamespace); ModelNamespace = useModelNamespace ? $"{RootNamespace}.Models" : RootNamespace; DisableXmlDocs = disableXmlDocs; + UnreferencedTypesHandling = unreferencedTypesHandling; } private string GetCleanNameSpace(string libraryNamespace) @@ -127,6 +136,7 @@ private static class Options public const string Namespace = "namespace"; public const string UseModelNamespace = "use-model-namespace"; public const string DisableXmlDocs = "disable-xml-docs"; + public const string UnreferencedTypesHandling = "unreferenced-types-handling"; } /// @@ -142,6 +152,8 @@ private static class Options internal string OutputDirectory { get; } + internal static UnreferencedTypesHandlingOption UnreferencedTypesHandling { get; private set; } = UnreferencedTypesHandlingOption.RemoveOrInternalize; + private string? _projectDirectory; internal string ProjectDirectory => _projectDirectory ??= Path.Combine(OutputDirectory, "src"); @@ -211,7 +223,8 @@ internal static Configuration Load(string outputPath, string? json = null) ReadRequiredStringOption(root, Options.LibraryName), ReadOption(root, Options.UseModelNamespace), ReadRequiredStringOption(root, Options.Namespace), - ReadOption(root, Options.DisableXmlDocs)); + ReadOption(root, Options.DisableXmlDocs), + ReadEnumOption(root, Options.UnreferencedTypesHandling)); } /// @@ -240,6 +253,7 @@ internal static Configuration Load(string outputPath, string? json = null) Options.UseModelNamespace, Options.Namespace, Options.DisableXmlDocs, + Options.UnreferencedTypesHandling, }; private static bool ReadOption(JsonElement root, string option) @@ -276,6 +290,22 @@ private static bool GetDefaultBoolOptionValue(string option) return _defaultBoolOptionValues.TryGetValue(option, out bool defaultValue) && defaultValue; } + private static T ReadEnumOption(JsonElement root, string option) where T : struct, Enum + { + if (root.TryGetProperty(option, out JsonElement value) && Enum.TryParse(value.ToString(), true, out var enumValue)) + { + return enumValue; + } + + return (T)GetDefaultEnumOptionValue(option)!; + } + + public static Enum? GetDefaultEnumOptionValue(string option) => option switch + { + Options.UnreferencedTypesHandling => UnreferencedTypesHandlingOption.RemoveOrInternalize, + _ => null + }; + /// /// Parses the additional configuration options from the given JSON element root and stores them in a dictionary. /// diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/OutputLibrary.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/OutputLibrary.cs index b6d9f54344..e4505cee4b 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/OutputLibrary.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/OutputLibrary.cs @@ -74,7 +74,7 @@ .. BuildModelFactory() private static TypeProvider[] BuildModelFactory() { - var modelFactory = new ModelFactoryProvider(CodeModelPlugin.Instance.InputLibrary.InputNamespace.Models); + var modelFactory = ModelFactoryProvider.FromInputLibrary(); return modelFactory.Methods.Count > 0 ? [modelFactory] : []; } } diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/GeneratedCodeWorkspace.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/GeneratedCodeWorkspace.cs index 08b34a424d..ca894226db 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/GeneratedCodeWorkspace.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/GeneratedCodeWorkspace.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; @@ -14,6 +13,7 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.Generator.CSharp.Primitives; +using Microsoft.Generator.CSharp.Providers; namespace Microsoft.Generator.CSharp { @@ -21,6 +21,7 @@ internal class GeneratedCodeWorkspace { private const string GeneratedFolder = "Generated"; private const string GeneratedCodeProjectName = "GeneratedCode"; + private const string GeneratedTestFolder = "GeneratedTests"; private static readonly Lazy> _assemblyMetadataReferences = new(() => new List() { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }); @@ -30,6 +31,7 @@ internal class GeneratedCodeWorkspace private static readonly string _newLine = "\n"; private Project _project; + private Compilation? _compilation; private Dictionary PlainFiles { get; } private GeneratedCodeWorkspace(Project generatedCodeProject) @@ -101,11 +103,22 @@ public async Task AddGeneratedFile(CodeFile codefile) private async Task ProcessDocument(Document document) { + var syntaxTree = await document.GetSyntaxTreeAsync(); + var compilation = await GetProjectCompilationAsync(); + if (syntaxTree != null) + { + var semanticModel = compilation.GetSemanticModel(syntaxTree); + var modelRemoveRewriter = new MemberRemoverRewriter(_project, semanticModel); + document = document.WithSyntaxRoot(modelRemoveRewriter.Visit(await syntaxTree.GetRootAsync())); + } + document = await Simplifier.ReduceAsync(document); return document; } public static bool IsGeneratedDocument(Document document) => document.Folders.Contains(GeneratedFolder); + public static bool IsCustomDocument(Document document) => !IsGeneratedDocument(document); + public static bool IsGeneratedTestDocument(Document document) => document.Folders.Contains(GeneratedTestFolder); /// /// Create a new AdHoc workspace using the Roslyn SDK and add a project with all the necessary compilation options. @@ -183,7 +196,7 @@ internal static GeneratedCodeWorkspace CreateExistingCodeProject(string projectD } /// - /// Add the files in the directory to a project per a given predicate with the folders specified + /// Add the files in the directory to a project per a given predicate with the folders specified. /// /// /// @@ -202,5 +215,33 @@ internal static Project AddDirectory(Project project, string directory, Func + /// This method invokes the postProcessor to do some post processing work + /// Depending on the configuration, it will either remove + internalize, just internalize or do nothing + /// + public async Task PostProcessAsync() + { + var modelFactory = ModelFactoryProvider.FromInputLibrary(); + var postProcessor = new PostProcessor(CodeModelPlugin.Instance.TypeFactory.UnionTypes, modelFactoryFullName: $"{modelFactory.Namespace}.{modelFactory.Name}"); + switch (Configuration.UnreferencedTypesHandling) + { + case Configuration.UnreferencedTypesHandlingOption.KeepAll: + break; + case Configuration.UnreferencedTypesHandlingOption.Internalize: + _project = await postProcessor.InternalizeAsync(_project); + break; + case Configuration.UnreferencedTypesHandlingOption.RemoveOrInternalize: + _project = await postProcessor.InternalizeAsync(_project); + _project = await postProcessor.RemoveAsync(_project); + break; + } + } + + private async Task GetProjectCompilationAsync() + { + _compilation ??= await _project.GetCompilationAsync(); + return _compilation!; + } } } diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/MemberRemoverRewriter.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/MemberRemoverRewriter.cs new file mode 100644 index 0000000000..a00496ae75 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/MemberRemoverRewriter.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Microsoft.Generator.CSharp +{ + internal class MemberRemoverRewriter : CSharpSyntaxRewriter + { + private readonly Project _project; + private readonly SemanticModel _semanticModel; + + public MemberRemoverRewriter(Project project, SemanticModel semanticModel) + { + _project = project; + _semanticModel = semanticModel; + } + + public override SyntaxNode? VisitCompilationUnit(CompilationUnitSyntax node) + { + var visitedNode = base.VisitCompilationUnit(node); + return visitedNode is CompilationUnitSyntax cu && !cu.Members.Any() ? SyntaxFactory.CompilationUnit() : visitedNode; + } + + public override SyntaxNode? VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + var visitedNode = base.VisitNamespaceDeclaration(node); + return visitedNode is NamespaceDeclarationSyntax ns && !ns.Members.Any() ? null : visitedNode; + } + + public override SyntaxNode? VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + var symbol = _semanticModel.GetDeclaredSymbol(node); + return ShouldRemoveMember(symbol) ? null : base.VisitConstructorDeclaration(node); + } + + public override SyntaxNode? VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + var symbol = _semanticModel.GetDeclaredSymbol(node); + return ShouldRemoveMember(symbol) ? null : base.VisitPropertyDeclaration(node); + } + + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + var symbol = _semanticModel.GetDeclaredSymbol(node); + return ShouldRemoveMember(symbol) ? null : base.VisitMethodDeclaration(node); + } + + public override SyntaxNode? VisitOperatorDeclaration(OperatorDeclarationSyntax node) + { + var symbol = _semanticModel.GetDeclaredSymbol(node); + return ShouldRemoveMember(symbol) ? null : base.VisitOperatorDeclaration(node); + } + + public override SyntaxNode? VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + var symbol = _semanticModel.GetDeclaredSymbol(node); + return ShouldRemoveMember(symbol) ? null : base.VisitConversionOperatorDeclaration(node); + } + + public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) + { + var symbol = node.Declaration.Variables.Count == 1 + ? _semanticModel.GetDeclaredSymbol(node.Declaration.Variables[0]) + : null; + + return ShouldRemoveMember(symbol) ? null : base.VisitFieldDeclaration(node); + } + + private bool ShouldRemoveMember(ISymbol? symbol) + { + if (symbol != null) + { + INamedTypeSymbol? containingType = symbol.ContainingType; + IMethodSymbol? methodSymbol = symbol as IMethodSymbol; + + while (containingType != null) + { + var members = containingType.GetMembers(symbol.Name); + foreach (var member in members) + { + if (!SymbolEqualityComparer.Default.Equals(member, symbol) && + IsDeclaredInNonGeneratedCode(member)) + { + if (methodSymbol != null && + member is IMethodSymbol memberMethodSymbol && + !methodSymbol.Parameters.SequenceEqual( + memberMethodSymbol.Parameters, (s1, s2) => SymbolEqualityComparer.Default.Equals(s1, s2.Type))) + { + continue; + } + + return true; + } + } + + // Skip traversing parents for constructors and explicit interface implementations + if (methodSymbol != null && + (methodSymbol.MethodKind == MethodKind.Constructor || + !methodSymbol.ExplicitInterfaceImplementations.IsEmpty)) + { + break; + } + containingType = containingType.BaseType; + } + } + + return false; + } + + private bool IsDeclaredInNonGeneratedCode(ISymbol member) + { + var references = member.DeclaringSyntaxReferences; + + if (references.Length == 0) + { + return false; + } + + foreach (var reference in references) + { + Document? document = _project.GetDocument(reference.SyntaxTree); + + if (document != null && GeneratedCodeWorkspace.IsGeneratedDocument(document)) + { + return false; + } + } + + return true; + } + + private readonly struct Supression + { + private readonly string? _name; + private readonly ISymbol?[] _types; + + public Supression(string? name, ISymbol?[] types) + { + _name = name; + _types = types; + } + + public bool Matches(ISymbol symbol) + { + if (symbol is IMethodSymbol methodSymbol) + { + string name = methodSymbol.Name; + // Use friendly name for ctors + if (methodSymbol.MethodKind == MethodKind.Constructor) + { + name = methodSymbol.ContainingType.Name; + } + + return _name == name && + _types.SequenceEqual(methodSymbol.Parameters.Select(p => p.Type), SymbolEqualityComparer.Default); + } + else + { + return symbol.Name == _name; + } + } + } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/PostProcessor.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/PostProcessor.cs new file mode 100644 index 0000000000..96167f06c8 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/PostProcessor.cs @@ -0,0 +1,456 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Simplification; + +namespace Microsoft.Generator.CSharp +{ + internal class PostProcessor + { + private readonly string? _modelFactoryFullName; + private readonly string? _aspExtensionClassName; + private readonly HashSet _typesToKeep; + private INamedTypeSymbol? _modelFactorySymbol; + + public PostProcessor( + HashSet typesToKeep, + string? modelFactoryFullName = null, + string? aspExtensionClassName = null) + { + _typesToKeep = typesToKeep; + _modelFactoryFullName = modelFactoryFullName; + _aspExtensionClassName = aspExtensionClassName; + } + + private record TypeSymbols( + HashSet DeclaredSymbols, + INamedTypeSymbol? ModelFactorySymbol, + IReadOnlyDictionary> DeclaredNodesCache, + IReadOnlyDictionary> DocumentsCache); + + /// + /// This method reads the project, returns the types defined in it and build symbol caches to acceralate the calculation + /// By default, the types defined in shared documents are not included. Please override to tweak this behavior + /// + /// The of the + /// The project to extract type symbols from + /// If is true, only public types will be included. If is false, all types will be included + /// A instance of which includes the information of the declared symbols of the given accessibility, along with some useful cache that is useful in this class. + private async Task GetTypeSymbolsAsync(Compilation compilation, + Project project, + bool publicOnly = true) + { + var result = new HashSet(SymbolEqualityComparer.Default); + var declarationCache = + new Dictionary>(SymbolEqualityComparer.Default); + var documentCache = new Dictionary>(); + + if (_modelFactoryFullName != null) + _modelFactorySymbol = compilation.GetTypeByMetadataName(_modelFactoryFullName); + INamedTypeSymbol? aspDotNetExtensionSymbol = null; + if (_aspExtensionClassName != null) + aspDotNetExtensionSymbol = compilation.GetTypeByMetadataName(_aspExtensionClassName); + + foreach (var document in project.Documents) + { + if (ShouldIncludeDocument(document)) + { + var root = await document.GetSyntaxRootAsync(); + if (root == null) + continue; + + var semanticModel = compilation.GetSemanticModel(root.SyntaxTree); + + foreach (var typeDeclaration in root.DescendantNodes().OfType()) + { + var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration); + if (symbol == null) + continue; + if (publicOnly && symbol.DeclaredAccessibility != Accessibility.Public && + !document.Name.StartsWith("Internal/", StringComparison.Ordinal)) + continue; + + // we do not add the model factory and aspDotNetExtension symbol to the declared symbol list so that it will never be included in any process of internalization or removal + if (!SymbolEqualityComparer.Default.Equals(symbol, _modelFactorySymbol) + && !SymbolEqualityComparer.Default.Equals(symbol, aspDotNetExtensionSymbol)) + result.Add(symbol); + + AddInList(declarationCache, symbol, typeDeclaration); + AddInList(documentCache, document, symbol, + () => new HashSet(SymbolEqualityComparer.Default)); + } + } + } + + return new TypeSymbols(result, + _modelFactorySymbol, + declarationCache.ToDictionary(kv => kv.Key, kv => kv.Value.ToHashSet(), + (IEqualityComparer)SymbolEqualityComparer.Default), + documentCache.ToDictionary(kv => kv.Key, + kv => kv.Value.ToHashSet(SymbolEqualityComparer.Default))); + } + + protected virtual bool ShouldIncludeDocument(Document document) => + !GeneratedCodeWorkspace.IsGeneratedTestDocument(document); + + /// + /// This method marks the "not publicly" referenced types as internal if they are previously defined as public. It will do this job in the following steps: + /// 1. This method will read all the public types defined in the given , and build a cache for those symbols + /// 2. Build a public reference map for those symbols + /// 3. Finds all the root symbols, please override the to control which document you would like to include + /// 4. Visit all the symbols starting from the root symbols following the reference map to get all unvisited symbols + /// 5. Change the accessibility of the unvisited symbols in step 4 to internal + /// + /// The project to process + /// The processed . is immutable, therefore this should usually be a new instance + public async Task InternalizeAsync(Project project) + { + var compilation = await project.GetCompilationAsync(); + if (compilation == null) + return project; + + // first get all the declared symbols + var definitions = await GetTypeSymbolsAsync(compilation, project, true); + // build the reference map + var referenceMap = + await new ReferenceMapBuilder(compilation, project).BuildPublicReferenceMapAsync( + definitions.DeclaredSymbols, definitions.DeclaredNodesCache); + // get the root symbols + var rootSymbols = await GetRootSymbolsAsync(project, definitions); + // traverse all the root and recursively add all the things we met + var publicSymbols = VisitSymbolsFromRootAsync(rootSymbols, referenceMap); + + var symbolsToInternalize = definitions.DeclaredSymbols.Except(publicSymbols); + + var nodesToInternalize = new Dictionary(); + foreach (var symbol in symbolsToInternalize) + { + foreach (var node in definitions.DeclaredNodesCache[symbol]) + { + nodesToInternalize[node] = project.GetDocumentId(node.SyntaxTree)!; + } + } + + foreach (var (model, documentId) in nodesToInternalize) + { + project = MarkInternal(project, model, documentId); + } + + var modelNamesToRemove = + nodesToInternalize.Keys.Select(item => item.Identifier.Text); + project = await RemoveMethodsFromModelFactoryAsync(project, definitions, modelNamesToRemove.ToHashSet()); + + return project; + } + + private async Task RemoveMethodsFromModelFactoryAsync(Project project, + TypeSymbols definitions, + HashSet namesToRemove) + { + var modelFactorySymbol = definitions.ModelFactorySymbol; + if (modelFactorySymbol == null) + return project; + + var nodesToRemove = new List(); + + foreach (var method in modelFactorySymbol.GetMembers().OfType()) + { + if (namesToRemove.Contains(method.Name)) + { + foreach (var reference in method.DeclaringSyntaxReferences) + { + var node = await reference.GetSyntaxAsync(); + nodesToRemove.Add(node); + } + } + } + + // find the GENERATED document of model factory (we may have the customized document of this for overloads) + Document? modelFactoryGeneratedDocument = null; + // the nodes corresponding to the model factory symbol has never been changed therefore the nodes inside the cache are still usable + foreach (var declarationNode in definitions.DeclaredNodesCache[modelFactorySymbol]) + { + var document = project.GetDocument(declarationNode.SyntaxTree); + if (document != null && GeneratedCodeWorkspace.IsGeneratedDocument(document)) + { + modelFactoryGeneratedDocument = document; + break; + } + } + + // maybe this is possible, for instance, we could be adding the customization all entries previously inside the generated model factory so that the generated model factory is empty and removed. + if (modelFactoryGeneratedDocument == null) + return project; + + var root = await modelFactoryGeneratedDocument.GetSyntaxRootAsync(); + Debug.Assert(root is not null); + root = root.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia)!; + modelFactoryGeneratedDocument = modelFactoryGeneratedDocument.WithSyntaxRoot(root); + + // see if this class still has any method, if it contains nothing, we should remove this document + var methods = root.DescendantNodes().OfType(); + if (!methods.Any()) + { + return project.RemoveDocument(modelFactoryGeneratedDocument.Id); + } + + return modelFactoryGeneratedDocument.Project; + } + + /// + /// This method removes the no-referenced types from the . It will do this job in the following steps: + /// 1. This method will read all the defined types in the given , and build a cache for those symbols + /// 2. Build a reference map for those symbols (including non-public usage) + /// 3. Finds all the root symbols, please override the to control which document you would like to include + /// 4. Visit all the symbols starting from the root symbols following the reference map to get all unvisited symbols + /// 5. Remove the definition of the unvisited symbols in step 4 + /// + /// The project to process + /// The processed . is immutable, therefore this should usually be a new instance + public async Task RemoveAsync(Project project) + { + var compilation = await project.GetCompilationAsync(); + if (compilation == null) + return project; + + // find all the declarations, including non-public declared + var definitions = await GetTypeSymbolsAsync(compilation, project, false); + // build reference map + var referenceMap = + await new ReferenceMapBuilder(compilation, project).BuildAllReferenceMapAsync( + definitions.DeclaredSymbols, definitions.DocumentsCache); + // get root symbols + var rootSymbols = await GetRootSymbolsAsync(project, definitions); + // include model factory as a root symbol when doing the remove pass so that we are sure to include any internal + // helpers that are required by the model factory. + if (_modelFactorySymbol != null) + rootSymbols.Add(_modelFactorySymbol); + // traverse the map to determine the declarations that we are about to remove, starting from root nodes + var referencedSymbols = VisitSymbolsFromRootAsync(rootSymbols, referenceMap); + + referencedSymbols = AddSampleSymbols(referencedSymbols, definitions.DeclaredSymbols); + var referencedSet = new HashSet(referencedSymbols, SymbolEqualityComparer.Default); + + var symbolsToRemove = definitions.DeclaredSymbols.Except(referencedSet); + + var nodesToRemove = new List(); + foreach (var symbol in symbolsToRemove) + { + if (referencedSet.Contains(GetBase(symbol))) + { + continue; + } + nodesToRemove.AddRange(definitions.DeclaredNodesCache[symbol]); + } + + // remove them one by one + project = await RemoveModelsAsync(project, nodesToRemove); + + return project; + } + + private INamedTypeSymbol GetBase(INamedTypeSymbol symbol) + { + var baseType = symbol.BaseType; + if (baseType == null || baseType.SpecialType == SpecialType.System_Object) + return symbol; + return GetBase(baseType); + } + + private IEnumerable AddSampleSymbols( + IEnumerable referencedSymbols, + HashSet declaredSymbols) + { + List symbolsToAdd = new List(); + foreach (var symbol in declaredSymbols) + { + if (symbol.ContainingNamespace.Name == "Samples" && symbol.Name.StartsWith("Samples_") && + !referencedSymbols.Any(s => s.Name == symbol.Name)) + { + symbolsToAdd.Add(symbol); + } + } + + return referencedSymbols.Concat(symbolsToAdd); + } + + /// + /// Do a BFS starting from the by following the + /// + /// + /// + /// + private static IEnumerable VisitSymbolsFromRootAsync( + IEnumerable rootSymbols, + ReferenceMap referenceMap) + { + var queue = new Queue(rootSymbols.Concat(referenceMap.GlobalReferencedSymbols)); + var visited = new HashSet(SymbolEqualityComparer.Default); + while (queue.Count > 0) + { + var definition = queue.Dequeue(); + if (visited.Contains(definition)) + continue; + visited.Add(definition); + // add this definition to the result + yield return definition; + // add every type referenced by this node to the queue + foreach (var child in GetReferencedTypes(definition, referenceMap)) + { + queue.Enqueue(child); + } + } + } + + private static IEnumerable GetReferencedTypes(T definition, + IReadOnlyDictionary> referenceMap) where T : notnull + { + if (referenceMap.TryGetValue(definition, out var references)) + return references; + + return Enumerable.Empty(); + } + + private Project MarkInternal(Project project, BaseTypeDeclarationSyntax declarationNode, DocumentId documentId) + { + var newNode = ChangeModifier(declarationNode, SyntaxKind.PublicKeyword, SyntaxKind.InternalKeyword); + var tree = declarationNode.SyntaxTree; + var document = project.GetDocument(documentId)!; + var newRoot = tree.GetRoot().ReplaceNode(declarationNode, newNode) + .WithAdditionalAnnotations(Simplifier.Annotation); + document = document.WithSyntaxRoot(newRoot); + return document.Project; + } + + private async Task RemoveModelsAsync(Project project, + IEnumerable unusedModels) + { + // accumulate the definitions from the same document together + var documents = new Dictionary>(); + foreach (var model in unusedModels) + { + var document = project.GetDocument(model.SyntaxTree); + Debug.Assert(document != null); + if (!documents.ContainsKey(document)) + documents.Add(document, new HashSet()); + + documents[document].Add(model); + } + + foreach (var models in documents.Values) + { + project = await RemoveModelsFromDocumentAsync(project, models); + } + + return project; + } + + private static BaseTypeDeclarationSyntax ChangeModifier(BaseTypeDeclarationSyntax memberDeclaration, + SyntaxKind from, + SyntaxKind to) + { + var originalTokenInList = memberDeclaration.Modifiers.FirstOrDefault(token => token.IsKind(from)); + + // skip this if there is nothing to replace + if (originalTokenInList == default) + return memberDeclaration; + + var newToken = + SyntaxFactory.Token(originalTokenInList.LeadingTrivia, to, originalTokenInList.TrailingTrivia); + var newModifiers = memberDeclaration.Modifiers.Replace(originalTokenInList, newToken); + return memberDeclaration.WithModifiers(newModifiers); + } + + private async Task RemoveModelsFromDocumentAsync(Project project, + IEnumerable models) + { + var tree = models.First().SyntaxTree; + var document = project.GetDocument(tree); + if (document == null) + return project; + var root = await tree.GetRootAsync(); + root = root.RemoveNodes(models, SyntaxRemoveOptions.KeepNoTrivia); + document = document.WithSyntaxRoot(root!); + return document.Project; + } + + private async Task> GetRootSymbolsAsync(Project project, TypeSymbols modelSymbols) + { + var result = new HashSet(SymbolEqualityComparer.Default); + foreach (var symbol in modelSymbols.DeclaredSymbols) + { + foreach (var declarationNode in modelSymbols.DeclaredNodesCache[symbol]) + { + var document = project.GetDocument(declarationNode.SyntaxTree); + if (document == null) + continue; + if (await IsRootDocument(document)) + { + result.Add(symbol); + break; + // if any of the declaring document of this symbol is considered as a root document, we add the symbol to the root list, skipping the processing of any other documents of this symbol + } + } + } + + return result; + } + + private async Task IsRootDocument(Document document) + { + var root = await document.GetSyntaxRootAsync(); + // a document is a root document, when + // 1. it is a custom document (not generated or shared) + // 2. it is a client + // 3. user exceptions + return GeneratedCodeWorkspace.IsCustomDocument(document) || IsClientDocument(document) || + ShouldKeepType(root, _typesToKeep); + } + + private static bool ShouldKeepType(SyntaxNode? root, HashSet typesToKeep) + { + if (root is null) + return false; + + // use `BaseTypeDeclarationSyntax` to also include enums because `EnumDeclarationSyntax` extends `BaseTypeDeclarationSyntax` + // `ClassDeclarationSyntax` and `StructDeclarationSyntax` both inherit `TypeDeclarationSyntax` + var typeNodes = root.DescendantNodes().OfType(); + // there is possibility that we have multiple types defined in the same document (for instance, custom code) + return typeNodes.Any(t => typesToKeep.Contains(t.Identifier.Text)); + } + + private static bool IsClientDocument(Document document) + { + return document.Name.EndsWith("Client.cs", StringComparison.Ordinal); + } + + private static void AddInList(Dictionary dictionary, + TKey key, + TValue value, + Func? collectionConstructor = null) where TKey : notnull where TList : ICollection, new() + { + if (dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + TList newList; + if (collectionConstructor == null) + newList = new TList(); + else + newList = collectionConstructor(); + newList.Add(value); + dictionary.Add(key, newList); + } + } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMap.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMap.cs new file mode 100644 index 0000000000..b1286cfe97 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMap.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Generator.CSharp +{ + internal class ReferenceMap : IReadOnlyDictionary> + { + private Dictionary> _referenceMap; + + private List _globalReference; + + public ReferenceMap() + { + _referenceMap = new(SymbolEqualityComparer.Default); + _globalReference = new(); + } + + /// + /// Adds the value into the list corresponding to key + /// + /// + /// + /// true if the value is added into the list, false if the value already exists in the list + internal bool AddInList(INamedTypeSymbol key, INamedTypeSymbol value) + { + if (_referenceMap.TryGetValue(key, out var list)) + { + // the list is guaranteed to be a HashSet + var set = (HashSet)list; + return set.Add(value); + } + else + { + var newList = new HashSet(SymbolEqualityComparer.Default) { value }; + _referenceMap.Add(key, newList); + return true; + } + } + + internal void AddGlobal(INamedTypeSymbol typeSymbol) + { + _globalReference.Add(typeSymbol); + } + + public IEnumerable GlobalReferencedSymbols => _globalReference; + + public IEnumerable this[INamedTypeSymbol key] => _referenceMap[key]; + + public IEnumerable Keys => _referenceMap.Keys; + + public IEnumerable> Values => _referenceMap.Values; + + public int Count => _referenceMap.Count; + + public bool ContainsKey(INamedTypeSymbol key) => _referenceMap.ContainsKey(key); + + public IEnumerator>> GetEnumerator() => + _referenceMap.GetEnumerator(); + + public bool TryGetValue(INamedTypeSymbol key, [MaybeNullWhen(false)] out IEnumerable value) => + _referenceMap.TryGetValue(key, out value); + + IEnumerator IEnumerable.GetEnumerator() => _referenceMap.GetEnumerator(); + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMapBuilder.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMapBuilder.cs new file mode 100644 index 0000000000..a97bb0e427 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/PostProcessing/ReferenceMapBuilder.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Xml.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.FindSymbols; + +namespace Microsoft.Generator.CSharp +{ + internal class ReferenceMapBuilder + { + private readonly Compilation _compilation; + private readonly Project _project; + + public ReferenceMapBuilder(Compilation compilation, Project project) + { + _compilation = compilation; + _project = project; + } + + public async Task BuildPublicReferenceMapAsync(IEnumerable definitions, IReadOnlyDictionary> nodeCache) + { + var referenceMap = new ReferenceMap(); + foreach (var definition in definitions) + { + await ProcessPublicSymbolAsync(definition, referenceMap, nodeCache); + } + + return referenceMap; + } + + public async Task BuildAllReferenceMapAsync(IEnumerable definitions, IReadOnlyDictionary> documentCache) + { + var referenceMap = new ReferenceMap(); + foreach (var definition in definitions) + { + await ProcessSymbolAsync(definition, referenceMap, documentCache); + } + + return referenceMap; + } + + private async Task ProcessPublicSymbolAsync(INamedTypeSymbol symbol, ReferenceMap referenceMap, IReadOnlyDictionary> cache) + { + // only add to reference when myself is public + if (symbol.DeclaredAccessibility != Accessibility.Public) + return; + + // process myself, adding base and generic arguments + AddTypeSymbol(symbol, symbol, referenceMap); + + // add my sibling classes + foreach (var declaration in cache[symbol]) + { + // first find all the derived types from this type + foreach (var derivedTypeSymbol in await SymbolFinder.FindDerivedClassesAsync(symbol, _project.Solution)) + { + AddTypeSymbol(symbol, derivedTypeSymbol, referenceMap); + } + } + + // go over all the members + foreach (var member in symbol.GetMembers()) + { + // only go through the public members + if (member.DeclaredAccessibility != Accessibility.Public) + continue; + + switch (member) + { + case IMethodSymbol methodSymbol: + ProcessMethodSymbol(symbol, methodSymbol, referenceMap); + break; + case IPropertySymbol propertySymbol: + ProcessPropertySymbol(symbol, propertySymbol, referenceMap); + break; + case IFieldSymbol fieldSymbol: + ProcessFieldSymbol(symbol, fieldSymbol, referenceMap); + break; + case IEventSymbol eventSymbol: + ProcessEventSymbol(symbol, eventSymbol, referenceMap); + break; + case INamedTypeSymbol innerTypeSymbol: + break; // do nothing for the inner types + default: + throw new InvalidOperationException($"This case has not been covered {member.GetType()}"); + } + } + } + + private async Task ProcessSymbolAsync(INamedTypeSymbol symbol, ReferenceMap referenceMap, IReadOnlyDictionary> documentCache) + { + foreach (var reference in await SymbolFinder.FindReferencesAsync(symbol, _project.Solution)) + { + await AddReferenceToReferenceMapAsync(symbol, reference, referenceMap, documentCache); + } + + // static class can have direct references, like ClassName.Method, but the extension methods might not have direct reference to the class itself + // therefore here we find the references of all its members and add them to the reference map + await ProcessExtensionSymbol(symbol, referenceMap, documentCache); + } + + private async Task ProcessExtensionSymbol(INamedTypeSymbol extensionClassSymbol, ReferenceMap referenceMap, IReadOnlyDictionary> documentCache) + { + if (!extensionClassSymbol.IsStatic) + return; + + foreach (var member in extensionClassSymbol.GetMembers()) + { + if (member is not IMethodSymbol methodSymbol) + continue; + + if (!methodSymbol.IsExtensionMethod) + continue; + + foreach (var reference in await SymbolFinder.FindReferencesAsync(member, _project.Solution)) + { + await AddReferenceToReferenceMapAsync(extensionClassSymbol, reference, referenceMap, documentCache); + } + + // this is to hook the extension class like this: + // internal static class FooExtensions + // { + // public static string ToSerialString(this Foo foo) => foo.ToString(); + // public static Foo ToFoo(this string foo) => // omit body + // } + + // if this is an extension method, we add it to the reference map of the type it is extending to pretend that this class is a part of that type + // handle the first method above + if (methodSymbol.Parameters.FirstOrDefault()?.Type is INamedTypeSymbol typeSymbol) + referenceMap.AddInList(typeSymbol, extensionClassSymbol); + + // we also add the return type into the reference map of the extension class to cover both cases + // handle the second method above + if (methodSymbol.ReturnType is INamedTypeSymbol returnTypeSymbol) + referenceMap.AddInList(returnTypeSymbol, extensionClassSymbol); + } + } + + private async Task AddReferenceToReferenceMapAsync(INamedTypeSymbol symbol, ReferencedSymbol reference, ReferenceMap referenceMap, IReadOnlyDictionary> documentCache) + { + foreach (var location in reference.Locations) + { + var document = location.Document; + + // skip this reference if it comes from a document that does not define any symbol + if (!documentCache.TryGetValue(document, out var candidateReferenceSymbols)) + continue; + + if (candidateReferenceSymbols.Count == 1) + { + referenceMap.AddInList(candidateReferenceSymbols.Single(), symbol); + } + else + { + // fallback to calculate the symbol when the document contains multiple type symbols + // this should never happen in the generated code + // customized code might have this issue + var root = await document.GetSyntaxRootAsync(); + if (root == null) + continue; + // get the node of this reference + var node = root.FindNode(location.Location.SourceSpan); + var owner = GetOwnerTypeOfReference(node); + if (owner == null) + { + referenceMap.AddGlobal(symbol); + } + else + { + var semanticModel = _compilation.GetSemanticModel(owner.SyntaxTree); + var ownerSymbol = semanticModel.GetDeclaredSymbol(owner); + + if (ownerSymbol == null) + continue; + // add it to the map + referenceMap.AddInList(ownerSymbol, symbol); + } + } + } + } + + /// + /// This method recursively adds all related types in to the reference map as the value of key + /// + /// + /// + /// + private void AddTypeSymbol(ITypeSymbol keySymbol, ITypeSymbol? valueSymbol, ReferenceMap referenceMap) + { + if (keySymbol is not INamedTypeSymbol keyTypeSymbol) + return; + if (valueSymbol is not INamedTypeSymbol valueTypeSymbol) + return; + // add the class and all its partial classes to the map + // this will make all the partial classes are referencing each other in the reference map + // when we make the travesal over the reference map, we will not only remove one of the partial class, instead we will either keep all the partial classes (if at least one of them has references), or remove all of them (if none of them has references) + if (!referenceMap.AddInList(keyTypeSymbol, valueTypeSymbol)) + { + return; // we short cut if the valueTypeSymbol has already existed in the list to avoid infinite loops + } + // add the base type + AddTypeSymbol(keyTypeSymbol, valueTypeSymbol.BaseType, referenceMap); + // add the interfaces if there is any + foreach (var interfaceSymbol in valueTypeSymbol.Interfaces) + { + AddTypeSymbol(keyTypeSymbol, interfaceSymbol, referenceMap); + } + // add the generic type arguments + foreach (var typeArgument in valueTypeSymbol.TypeArguments) + { + AddTypeSymbol(keyTypeSymbol, typeArgument, referenceMap); + } + } + + private void ProcessMethodSymbol(INamedTypeSymbol keySymbol, IMethodSymbol methodSymbol, ReferenceMap referenceMap) + { + // add the return type + AddTypeSymbol(keySymbol, methodSymbol.ReturnType, referenceMap); + // add the parameters + foreach (var parameter in methodSymbol.Parameters) + { + AddTypeSymbol(keySymbol, parameter.Type, referenceMap); + } + } + + private void ProcessPropertySymbol(INamedTypeSymbol keySymbol, IPropertySymbol propertySymbol, ReferenceMap referenceMap) + { + AddTypeSymbol(keySymbol, propertySymbol.Type, referenceMap); + + // find the node that defines myself + var xml = propertySymbol.GetDocumentationCommentXml(); + if (string.IsNullOrEmpty(xml)) + { + return; + } + + var xDocument = XDocument.Parse(xml); + var cRefs = xDocument.Descendants().Attributes("cref").Select(a => a.Value).Where(a => a[0] == 'T' && a[1] == ':').Select(a => a.Substring(2)); + + foreach (var cref in cRefs) + { + var symbol = _compilation.GetTypeByMetadataName(cref); + AddTypeSymbol(keySymbol, symbol, referenceMap); + } + } + + private void ProcessFieldSymbol(INamedTypeSymbol keySymbol, IFieldSymbol fieldSymbol, ReferenceMap referenceMap) => AddTypeSymbol(keySymbol, fieldSymbol.Type, referenceMap); + + private void ProcessEventSymbol(INamedTypeSymbol keySymbol, IEventSymbol eventSymbol, ReferenceMap referenceMap) => AddTypeSymbol(keySymbol, eventSymbol.Type, referenceMap); + + /// + /// Returns the node that defines inside the document, which should be , or + /// The here should come from the result of , therefore a result is guaranteed + /// + /// + /// + private static BaseTypeDeclarationSyntax? GetOwnerTypeOfReference(SyntaxNode node) + { + SyntaxNode? current = node; + while (current != null) + { + if (current is BaseTypeDeclarationSyntax declarationNode) + return declarationNode; + + current = current.Parent; + } + + // this means owner of the reference is outside a type definition. For instance, we could have an assembly attribute that is referencing a class using `nameof` + return null; + } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelFactoryProvider.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelFactoryProvider.cs index e4d7c38c49..4a4d20aa1c 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelFactoryProvider.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelFactoryProvider.cs @@ -21,7 +21,9 @@ internal class ModelFactoryProvider : TypeProvider private readonly IEnumerable _models; - public ModelFactoryProvider(IEnumerable models) + public static ModelFactoryProvider FromInputLibrary() => new ModelFactoryProvider(CodeModelPlugin.Instance.InputLibrary.InputNamespace.Models); + + private ModelFactoryProvider(IEnumerable models) { _models = models; } @@ -109,15 +111,21 @@ private static IReadOnlyList GetCtorArgs( ConstructorSignature modelCtorFullSignature) { var expressions = new List(signature.Parameters.Count); - foreach (var param in signature.Parameters) + for (int i = 0; i < signature.Parameters.Count; i++) { - if (param.Type.IsList) + var factoryParam = signature.Parameters[i]; + var ctorParam = modelCtorFullSignature.Parameters[i]; + if (factoryParam.Type.IsList) { - expressions.Add(param.NullConditional().ToList()); + expressions.Add(factoryParam.NullConditional().ToList()); + } + else if (IsEnumDiscriminator(ctorParam)) + { + expressions.Add(ctorParam.Type.ToEnum(factoryParam)); } else { - expressions.Add(param); + expressions.Add(factoryParam); } } @@ -162,7 +170,8 @@ private static ParameterProvider GetModelFactoryParam(ParameterProvider paramete return new ParameterProvider( parameter.Name, parameter.Description, - parameter.Type.InputType, + // in order to avoid exposing discriminator enums as public, we will use the underlying types in the model factory methods + IsEnumDiscriminator(parameter) ? parameter.Type.UnderlyingEnumType : parameter.Type.InputType, Default, parameter.IsRef, parameter.IsOut, @@ -174,5 +183,8 @@ private static ParameterProvider GetModelFactoryParam(ParameterProvider paramete Validation = ParameterValidationType.None, }; } + + private static bool IsEnumDiscriminator(ParameterProvider parameter) => + parameter.Property?.IsDiscriminator == true && parameter.Type.IsEnum; } } diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelProvider.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelProvider.cs index fcfa580610..8e9af24a5f 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelProvider.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/ModelProvider.cs @@ -153,7 +153,7 @@ protected override ConstructorProvider[] BuildConstructors() // Build the initialization constructor var accessibility = DeclarationModifiers.HasFlag(TypeSignatureModifiers.Abstract) - ? MethodSignatureModifiers.Protected + ? MethodSignatureModifiers.Private | MethodSignatureModifiers.Protected : _inputModel.Usage.HasFlag(InputModelTypeUsage.Input) ? MethodSignatureModifiers.Public : MethodSignatureModifiers.Internal; diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/TypeProvider.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/TypeProvider.cs index e73b1f0acd..ad069a8226 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/TypeProvider.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Providers/TypeProvider.cs @@ -37,6 +37,9 @@ protected TypeProvider() private string? _name; + public string Namespace => _namespace ??= GetNamespace(); + private string? _namespace; + protected virtual FormattableString Description { get; } = FormattableStringHelpers.Empty; private XmlDocProvider? _xmlDocs; diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp.ClientModel/src/Snippets/CSharpTypeSnippets.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Snippets/CSharpTypeSnippets.cs similarity index 95% rename from packages/http-client-csharp/generator/Microsoft.Generator.CSharp.ClientModel/src/Snippets/CSharpTypeSnippets.cs rename to packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Snippets/CSharpTypeSnippets.cs index a475f10204..89cc4e6a8b 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp.ClientModel/src/Snippets/CSharpTypeSnippets.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Snippets/CSharpTypeSnippets.cs @@ -7,9 +7,9 @@ using Microsoft.Generator.CSharp.Providers; using static Microsoft.Generator.CSharp.Snippets.Snippet; -namespace Microsoft.Generator.CSharp.ClientModel.Snippets +namespace Microsoft.Generator.CSharp.Snippets { - internal static class CSharpTypeSnippets + public static class CSharpTypeSnippets { public static ValueExpression ToEnum(this CSharpType type, ValueExpression valueExpression) { diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/TypeFactory.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/TypeFactory.cs index 3ea0f46464..4d081265ed 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/TypeFactory.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/TypeFactory.cs @@ -37,6 +37,9 @@ public class TypeFactory private IReadOnlyList Visitors => CodeModelPlugin.Instance.Visitors; private Dictionary> SerializationsCache => _serializationsCache ??= []; + private HashSet? _unionTypes; + internal HashSet UnionTypes => _unionTypes ??= []; + protected internal TypeFactory() { } @@ -75,6 +78,7 @@ protected internal TypeFactory() if (unionInput != null) { unionInputs.Add(unionInput); + UnionTypes.Add(unionInput.Name); } } type = CSharpType.FromUnion(unionInputs); @@ -119,7 +123,7 @@ internal CSharpType CreatePrimitiveCSharpType(InputType inputType) /// /// The to convert. /// An instance of . - private protected virtual CSharpType CreatePrimitiveCSharpTypeCore(InputType inputType) => inputType switch + private CSharpType CreatePrimitiveCSharpTypeCore(InputType inputType) => inputType switch { InputPrimitiveType primitiveType => primitiveType.Kind switch { diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Writers/CodeWriter.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Writers/CodeWriter.cs index b7be122ca8..bbac556d52 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Writers/CodeWriter.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/src/Writers/CodeWriter.cs @@ -723,9 +723,9 @@ public IDisposable WriteMethodDeclarationNoScope(MethodSignatureBase methodBase, } AppendRawIf("public ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Public)) - .AppendRawIf("internal ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Internal)) - .AppendRawIf("protected ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Protected)) .AppendRawIf("private ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Private)) + .AppendRawIf("protected ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Protected)) + .AppendRawIf("internal ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Internal)) .AppendRawIf("static ", methodBase.Modifiers.HasFlag(MethodSignatureModifiers.Static)); if (methodBase is MethodSignature method) diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/ConfigurationTests.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/ConfigurationTests.cs index 978e77b5f1..94b070c18b 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/ConfigurationTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/ConfigurationTests.cs @@ -155,6 +155,31 @@ public void DisableDocsForProperty() Assert.AreEqual("public int IntProperty { get; set; }\n", writer.ToString(false)); } + [Test] + [TestCase("removeOrInternalize")] + [TestCase("keepAll")] + [TestCase("internalize")] + public void UnreferencedTypeHandling(string input) + { + var mockJson = @"{ + ""output-folder"": ""outputFolder"", + ""library-name"": ""libraryName"", + ""namespace"": ""namespace"", + ""unreferenced-types-handling"": ""keepAll"" + }"; + + MockHelpers.LoadMockPlugin(configuration: mockJson); + var expected = input switch + { + "removeOrInternalize" => Configuration.UnreferencedTypesHandlingOption.RemoveOrInternalize, + "keepAll" => Configuration.UnreferencedTypesHandlingOption.KeepAll, + "internalize" => Configuration.UnreferencedTypesHandlingOption.Internalize, + _ => throw new ArgumentException("Invalid input", nameof(input)) + }; + + StringAssert.AreEqualIgnoringCase(expected.ToString(), input); + } + [Test] public void DisableDocsForMethod() { diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelFactories/ModelFactoryProviderTests.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelFactories/ModelFactoryProviderTests.cs index 8e1c05519b..77188a8a1f 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelFactories/ModelFactoryProviderTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelFactories/ModelFactoryProviderTests.cs @@ -18,20 +18,20 @@ public class ModelFactoryProviderTests public ModelFactoryProviderTests() { - MockHelpers.LoadMockPlugin(); + MockHelpers.LoadMockPlugin(inputModelTypes: ModelList); } [Test] public void SkipInternalModels() { - var modelFactory = new ModelFactoryProvider(ModelList); + var modelFactory = ModelFactoryProvider.FromInputLibrary(); Assert.AreEqual(ModelList.Length - ModelList.Where(m => m.Access == "internal").Count(), modelFactory.Methods.Count); } [Test] public void ListParamShape() { - var modelFactory = new ModelFactoryProvider(ModelList); + var modelFactory = ModelFactoryProvider.FromInputLibrary(); var models = ModelList.Select(CodeModelPlugin.Instance.TypeFactory.CreateModel); foreach (var model in models) { @@ -54,7 +54,7 @@ public void ListParamShape() [Test] public void DictionaryParamShape() { - var modelFactory = new ModelFactoryProvider(ModelList); + var modelFactory = ModelFactoryProvider.FromInputLibrary(); var models = ModelList.Select(CodeModelPlugin.Instance.TypeFactory.CreateModel); foreach (var model in models) { @@ -74,10 +74,33 @@ public void DictionaryParamShape() } } + [Test] + public void DiscriminatorEnumParamShape() + { + var modelFactory = ModelFactoryProvider.FromInputLibrary(); + var models = ModelList.Select(CodeModelPlugin.Instance.TypeFactory.CreateModel); + foreach (var model in models) + { + if (!model!.DeclarationModifiers.HasFlag(TypeSignatureModifiers.Public)) + continue; //skip internal models + + Assert.IsNotNull(model, "Null ModelProvider found"); + var method = modelFactory.Methods.FirstOrDefault(m => m.Signature.Name == model!.Name); + Assert.IsNotNull(method); + foreach (var property in model!.Properties.Where(p => p.Type.IsEnum)) + { + var parameter = method!.Signature.Parameters.FirstOrDefault(p => p.Name == property.Name.ToVariableName()); + Assert.IsNotNull(parameter); + Assert.IsTrue(parameter!.Type.IsFrameworkType); + Assert.AreEqual(typeof(int), parameter!.Type.FrameworkType); + } + } + } + [Test] public void ModelFactoryName() { - var modelFactory = new ModelFactoryProvider(ModelList); + var modelFactory = ModelFactoryProvider.FromInputLibrary(); Assert.AreEqual("SampleNamespaceModelFactory", modelFactory.Name); } @@ -87,13 +110,23 @@ private static InputModelType[] GetTestModels() [ InputFactory.Property("StringProp", InputPrimitiveType.String), InputFactory.Property("ListProp", InputFactory.Array(InputPrimitiveType.String)), - InputFactory.Property("DictProp", InputFactory.Dictionary(InputPrimitiveType.String, InputPrimitiveType.String)) + InputFactory.Property("DictProp", InputFactory.Dictionary(InputPrimitiveType.String, InputPrimitiveType.String)), ]; + InputModelProperty[] inheritanceProperties = properties.Concat(new[] + { + InputFactory.Property("EnumProp", + InputFactory.Enum("inputEnum", InputPrimitiveType.Int32, isExtensible: true, + values: [InputFactory.EnumMember.String("foo", "bar")]), isDiscriminator: true) + }).ToArray(); + + var derivedModel = InputFactory.Model("DerivedModel", properties: inheritanceProperties, discriminatedKind: "unknown"); return [ InputFactory.Model("InternalModel", "internal", properties: properties), InputFactory.Model("PublicModel1", properties: properties), - InputFactory.Model("PublicModel2", properties: properties) + InputFactory.Model("PublicModel2", properties: properties), + derivedModel, + InputFactory.Model("BaseModel", properties: properties, derivedModels: [derivedModel]), ]; } } diff --git a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelProviders/DiscriminatorTests.cs b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelProviders/DiscriminatorTests.cs index 07d204a9e2..ce50601555 100644 --- a/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelProviders/DiscriminatorTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.Generator.CSharp/test/Providers/ModelProviders/DiscriminatorTests.cs @@ -51,7 +51,7 @@ public void DiscriminatorPropertyShouldBeInternal() } [Test] - public void BaseConstructorShouldBeProtected() + public void BaseConstructorShouldBePrivateProtected() { MockHelpers.LoadMockPlugin(); var baseModel = CodeModelPlugin.Instance.TypeFactory.CreateModel(_baseModel); @@ -62,7 +62,8 @@ public void BaseConstructorShouldBeProtected() var initCtor = ctor1.Signature.Parameters.Count < ctor2.Signature.Parameters.Count ? ctor1 : ctor2; var serializationCtor = ctor1.Signature.Parameters.Count < ctor2.Signature.Parameters.Count ? ctor2 : ctor1; Assert.IsNotNull(initCtor); - Assert.IsTrue(initCtor!.Signature.Modifiers.HasFlag(MethodSignatureModifiers.Protected)); + Assert.IsTrue(initCtor.Signature.Modifiers.HasFlag(MethodSignatureModifiers.Protected)); + Assert.IsTrue(initCtor.Signature.Modifiers.HasFlag(MethodSignatureModifiers.Private)); Assert.IsNotNull(serializationCtor); Assert.IsTrue(serializationCtor!.Signature.Modifiers.HasFlag(MethodSignatureModifiers.Internal)); } diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch.Tests/Http/_Type/Union/UnionTests.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch.Tests/Http/_Type/Union/UnionTests.cs index 69db503e03..959de71bce 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch.Tests/Http/_Type/Union/UnionTests.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch.Tests/Http/_Type/Union/UnionTests.cs @@ -4,6 +4,8 @@ using System; using System.ClientModel.Primitives; using System.Collections.Generic; +using System.Diagnostics; +using System.Reflection; using System.Threading.Tasks; using _Type.Union; using _Type.Union.Models; @@ -93,16 +95,25 @@ public Task GetModelsOnly() => Test(async (host) => { var response = await new UnionClient(host, null).GetModelsOnlyClient().GetAsync(); Assert.AreEqual(200, response.GetRawResponse().Status); - AssertEqual(new Cat("test"), ModelReaderWriter.Read(response.Value.Prop)!); }); [CadlRanchTest] public Task SendModelsOnly() => Test(async (host) => { - var response = await new UnionClient(host, null).GetModelsOnlyClient().SendAsync(ModelReaderWriter.Write(new Cat("test"))); + var response = await new UnionClient(host, null).GetModelsOnlyClient().SendAsync(WriteCat()); Assert.AreEqual(204, response.GetRawResponse().Status); }); + private static BinaryData WriteCat() + { + // We need to use reflection because the Cat model gets deleted in Stubbed mode which is what we check in. + // The type will exist when actually running the test using the ClientModelPlugin. + var catType = typeof(UnionClient).Assembly.GetType("_Type.Union.Models.Cat"); + Debug.Assert(catType != null); + var cat = Activator.CreateInstance(catType, "test"); + return ModelReaderWriter.Write(cat!); + } + [CadlRanchTest] public Task GetEnumsOnly() => Test(async (host) => @@ -173,13 +184,13 @@ public Task GetMixedTypes() => Test(async (host) => public Task SendMixedTypesOnlyOnly() => Test(async (host) => { var response = await new UnionClient(host, null).GetMixedTypesClient().SendAsync(new MixedTypesCases( - ModelReaderWriter.Write(new Cat("test")), + WriteCat(), BinaryData.FromObjectAsJson("a"), BinaryData.FromObjectAsJson(2), BinaryData.FromObjectAsJson(true), new[] { - ModelReaderWriter.Write(new Cat("test")), + WriteCat(), BinaryData.FromObjectAsJson("a"), BinaryData.FromObjectAsJson(2), BinaryData.FromObjectAsJson(true) @@ -191,10 +202,5 @@ private static void AssertEqual(BinaryData source, BinaryData target) { BinaryDataAssert.AreEqual(source, target); } - - private void AssertEqual(Cat cat1, Cat cat2) - { - Assert.IsTrue(cat1 == cat2 || cat1.Name == cat2.Name); - } } } diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/AuthenticationApiKeyModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/AuthenticationApiKeyModelFactory.cs deleted file mode 100644 index 7e6a0541c7..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/AuthenticationApiKeyModelFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Authentication.ApiKey.Models -{ - public static partial class AuthenticationApiKeyModelFactory - { - public static InvalidAuth InvalidAuth(string error = default) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.Serialization.cs deleted file mode 100644 index 948df57193..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Authentication.ApiKey.Models -{ - public partial class InvalidAuth : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - InvalidAuth IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - InvalidAuth IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(InvalidAuth invalidAuth) => throw null; - - public static explicit operator InvalidAuth(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.cs deleted file mode 100644 index ed6f8e6825..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/api-key/src/Generated/Models/InvalidAuth.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace Authentication.ApiKey.Models -{ - public partial class InvalidAuth - { - public string Error - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/AuthenticationHttpCustomModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/AuthenticationHttpCustomModelFactory.cs deleted file mode 100644 index c5c918b16d..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/AuthenticationHttpCustomModelFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Authentication.Http.Custom.Models -{ - public static partial class AuthenticationHttpCustomModelFactory - { - public static InvalidAuth InvalidAuth(string error = default) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.Serialization.cs deleted file mode 100644 index a381acb0ec..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Authentication.Http.Custom.Models -{ - public partial class InvalidAuth : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - InvalidAuth IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - InvalidAuth IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(InvalidAuth invalidAuth) => throw null; - - public static explicit operator InvalidAuth(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.cs deleted file mode 100644 index 28738191bd..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/http/custom/src/Generated/Models/InvalidAuth.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace Authentication.Http.Custom.Models -{ - public partial class InvalidAuth - { - public string Error - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/AuthenticationOAuth2ModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/AuthenticationOAuth2ModelFactory.cs deleted file mode 100644 index 34f6bbe9e5..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/AuthenticationOAuth2ModelFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Authentication.OAuth2.Models -{ - public static partial class AuthenticationOAuth2ModelFactory - { - public static InvalidAuth InvalidAuth(string error = default) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.Serialization.cs deleted file mode 100644 index 5fd95f3d70..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Authentication.OAuth2.Models -{ - public partial class InvalidAuth : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - InvalidAuth IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - InvalidAuth IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual InvalidAuth PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(InvalidAuth invalidAuth) => throw null; - - public static explicit operator InvalidAuth(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.cs deleted file mode 100644 index af44cc895e..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/authentication/oauth2/src/Generated/Models/InvalidAuth.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace Authentication.OAuth2.Models -{ - public partial class InvalidAuth - { - public string Error - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.Serialization.cs deleted file mode 100644 index 4bbc9294e0..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Parameters.Basic.Models -{ - public partial class SimpleRequest : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SimpleRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SimpleRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SimpleRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SimpleRequest PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SimpleRequest simpleRequest) => throw null; - - public static explicit operator SimpleRequest(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.cs deleted file mode 100644 index c2860b2c61..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/Models/SimpleRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace Parameters.Basic.Models -{ - public partial class SimpleRequest - { - public string Name - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/ParametersBasicModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/ParametersBasicModelFactory.cs index 86f4418b2b..3aa6dd75fe 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/ParametersBasicModelFactory.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/parameters/basic/src/Generated/ParametersBasicModelFactory.cs @@ -6,7 +6,6 @@ namespace Parameters.Basic.Models { public static partial class ParametersBasicModelFactory { - public static SimpleRequest SimpleRequest(string name = default) => throw null; public static User User(string name = default) => throw null; } diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Dog.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Dog.cs index 50bc948e7c..8e7dcb127d 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Dog.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Dog.cs @@ -9,7 +9,7 @@ namespace _Type.Model.Inheritance.EnumDiscriminator.Models { public abstract partial class Dog { - protected Dog(DogKind kind, int weight) => throw null; + private protected Dog(DogKind kind, int weight) => throw null; internal Dog(DogKind kind, int weight, IDictionary serializedAdditionalRawData) => throw null; diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/DogKind.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/DogKind.cs index 36f9eef2c7..72750d7f3f 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/DogKind.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/DogKind.cs @@ -7,7 +7,7 @@ namespace _Type.Model.Inheritance.EnumDiscriminator.Models { - public readonly partial struct DogKind : IEquatable + internal readonly partial struct DogKind : IEquatable { public DogKind(string value) => throw null; diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Snake.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Snake.cs index 6932240deb..9cccf72560 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Snake.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/Snake.cs @@ -9,7 +9,7 @@ namespace _Type.Model.Inheritance.EnumDiscriminator.Models { public abstract partial class Snake { - protected Snake(SnakeKind kind, int length) => throw null; + private protected Snake(SnakeKind kind, int length) => throw null; internal Snake(SnakeKind kind, int length, IDictionary serializedAdditionalRawData) => throw null; diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/SnakeKind.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/SnakeKind.cs index a5d11b2230..bf3c27715a 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/SnakeKind.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/Models/SnakeKind.cs @@ -4,7 +4,7 @@ namespace _Type.Model.Inheritance.EnumDiscriminator.Models { - public enum SnakeKind + internal enum SnakeKind { /// Species cobra. Cobra diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/TypeModelInheritanceEnumDiscriminatorModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/TypeModelInheritanceEnumDiscriminatorModelFactory.cs index 83282e5a42..61e50b74d3 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/TypeModelInheritanceEnumDiscriminatorModelFactory.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/enum-discriminator/src/Generated/TypeModelInheritanceEnumDiscriminatorModelFactory.cs @@ -6,11 +6,11 @@ namespace _Type.Model.Inheritance.EnumDiscriminator.Models { public static partial class TypeModelInheritanceEnumDiscriminatorModelFactory { - public static Dog Dog(DogKind kind = default, int weight = default) => throw null; + public static Dog Dog(string kind = default, int weight = default) => throw null; public static Golden Golden(int weight = default) => throw null; - public static Snake Snake(SnakeKind kind = default, int length = default) => throw null; + public static Snake Snake(string kind = default, int length = default) => throw null; public static Cobra Cobra(int length = default) => throw null; } diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Bird.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Bird.cs index e3ee37ea34..04e91a4ff1 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Bird.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Bird.cs @@ -9,7 +9,7 @@ namespace _Type.Model.Inheritance.SingleDiscriminator.Models { public abstract partial class Bird { - protected Bird(string kind, int wingspan) => throw null; + private protected Bird(string kind, int wingspan) => throw null; internal Bird(string kind, int wingspan, IDictionary serializedAdditionalRawData) => throw null; diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Dinosaur.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Dinosaur.cs index f8a906bcec..da358b1e5f 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Dinosaur.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/model/inheritance/single-discriminator/src/Generated/Models/Dinosaur.cs @@ -9,7 +9,7 @@ namespace _Type.Model.Inheritance.SingleDiscriminator.Models { public abstract partial class Dinosaur { - protected Dinosaur(string kind, int size) => throw null; + private protected Dinosaur(string kind, int size) => throw null; internal Dinosaur(string kind, int size, IDictionary serializedAdditionalRawData) => throw null; diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.Serialization.cs deleted file mode 100644 index 3a7abed0b9..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest sendRequest) => throw null; - - public static explicit operator SendRequest(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.cs deleted file mode 100644 index 6a4dfbfb63..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest - { - public MixedTypesCases Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.Serialization.cs deleted file mode 100644 index 24b07b8994..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest1 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest1 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest1 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest1 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest1 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest1 sendRequest1) => throw null; - - public static explicit operator SendRequest1(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.cs deleted file mode 100644 index c203e028f9..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest1.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest1 - { - public MixedLiteralsCases Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.Serialization.cs deleted file mode 100644 index e33cee8900..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest2 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest2 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest2 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest2 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest2 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest2 sendRequest2) => throw null; - - public static explicit operator SendRequest2(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.cs deleted file mode 100644 index 59b914145c..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest2.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest2 - { - public StringAndArrayCases Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.Serialization.cs deleted file mode 100644 index e1123655d0..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest3 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest3 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest3 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest3 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest3 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest3 sendRequest3) => throw null; - - public static explicit operator SendRequest3(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.cs deleted file mode 100644 index 4227187c18..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest3.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest3 - { - public EnumsOnlyCases Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.Serialization.cs deleted file mode 100644 index 9c631f5e1f..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest4 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest4 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest4 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest4 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest4 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest4 sendRequest4) => throw null; - - public static explicit operator SendRequest4(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.cs deleted file mode 100644 index d5228298cd..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest4.cs +++ /dev/null @@ -1,18 +0,0 @@ -// - -#nullable disable - -using System; - -namespace _Type.Union.Models -{ - public partial class SendRequest4 - { - public BinaryData Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.Serialization.cs deleted file mode 100644 index f834c715f9..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest5 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest5 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest5 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest5 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest5 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest5 sendRequest5) => throw null; - - public static explicit operator SendRequest5(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.cs deleted file mode 100644 index 23878be895..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest5.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest5 - { - public GetResponseProp1 Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.Serialization.cs deleted file mode 100644 index acf28bf2c9..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest6 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest6 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest6 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest6 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest6 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest6 sendRequest6) => throw null; - - public static explicit operator SendRequest6(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.cs deleted file mode 100644 index 6e7f01e402..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest6.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest6 - { - public GetResponseProp2 Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.Serialization.cs deleted file mode 100644 index 9033402cfe..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest7 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest7 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest7 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest7 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest7 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest7 sendRequest7) => throw null; - - public static explicit operator SendRequest7(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.cs deleted file mode 100644 index 069216ef1e..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest7.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest7 - { - public StringExtensibleNamedUnion Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.Serialization.cs deleted file mode 100644 index d6b10a1942..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest8 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest8 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest8 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest8 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest8 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest8 sendRequest8) => throw null; - - public static explicit operator SendRequest8(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.cs deleted file mode 100644 index a615ab9b58..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest8.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest8 - { - public GetResponseProp3 Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.Serialization.cs deleted file mode 100644 index d42898d9db..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.Serialization.cs +++ /dev/null @@ -1,36 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace _Type.Union.Models -{ - public partial class SendRequest9 : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) => throw null; - - SendRequest9 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest9 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => throw null; - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => throw null; - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) => throw null; - - SendRequest9 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => throw null; - - protected virtual SendRequest9 PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) => throw null; - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => throw null; - - public static implicit operator BinaryContent(SendRequest9 sendRequest9) => throw null; - - public static explicit operator SendRequest9(ClientResult result) => throw null; - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.cs deleted file mode 100644 index 3bd5205779..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/Models/SendRequest9.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -namespace _Type.Union.Models -{ - public partial class SendRequest9 - { - public GetResponseProp4 Prop - { - get => throw null; - set => throw null; - } - - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/TypeUnionModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/TypeUnionModelFactory.cs index 5a74c3cda4..680a58a441 100644 --- a/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/TypeUnionModelFactory.cs +++ b/packages/http-client-csharp/generator/TestProjects/CadlRanch/http/type/union/src/Generated/TypeUnionModelFactory.cs @@ -15,50 +15,30 @@ public static partial class TypeUnionModelFactory public static Cat Cat(string name = default) => throw null; - public static SendRequest SendRequest(MixedTypesCases prop = default) => throw null; - public static GetResponse1 GetResponse1(MixedLiteralsCases prop = default) => throw null; public static MixedLiteralsCases MixedLiteralsCases(BinaryData stringLiteral = default, BinaryData intLiteral = default, BinaryData floatLiteral = default, BinaryData booleanLiteral = default) => throw null; - public static SendRequest1 SendRequest1(MixedLiteralsCases prop = default) => throw null; - public static GetResponse2 GetResponse2(StringAndArrayCases prop = default) => throw null; public static StringAndArrayCases StringAndArrayCases(BinaryData @string = default, BinaryData array = default) => throw null; - public static SendRequest2 SendRequest2(StringAndArrayCases prop = default) => throw null; - public static GetResponse3 GetResponse3(EnumsOnlyCases prop = default) => throw null; public static EnumsOnlyCases EnumsOnlyCases(EnumsOnlyCasesLr lr = default, EnumsOnlyCasesUd ud = default) => throw null; - public static SendRequest3 SendRequest3(EnumsOnlyCases prop = default) => throw null; - public static GetResponse4 GetResponse4(BinaryData prop = default) => throw null; public static Dog Dog(string bark = default) => throw null; - public static SendRequest4 SendRequest4(BinaryData prop = default) => throw null; - public static GetResponse5 GetResponse5(GetResponseProp1 prop = default) => throw null; - public static SendRequest5 SendRequest5(GetResponseProp1 prop = default) => throw null; - public static GetResponse6 GetResponse6(GetResponseProp2 prop = default) => throw null; - public static SendRequest6 SendRequest6(GetResponseProp2 prop = default) => throw null; - public static GetResponse7 GetResponse7(StringExtensibleNamedUnion prop = default) => throw null; - public static SendRequest7 SendRequest7(StringExtensibleNamedUnion prop = default) => throw null; - public static GetResponse8 GetResponse8(GetResponseProp3 prop = default) => throw null; - public static SendRequest8 SendRequest8(GetResponseProp3 prop = default) => throw null; - public static GetResponse9 GetResponse9(GetResponseProp4 prop = default) => throw null; - - public static SendRequest9 SendRequest9(GetResponseProp4 prop = default) => throw null; } } diff --git a/packages/http-client-csharp/generator/TestProjects/Local.Tests/UnreferencedTypeTests.cs b/packages/http-client-csharp/generator/TestProjects/Local.Tests/UnreferencedTypeTests.cs new file mode 100644 index 0000000000..bd2312cf88 --- /dev/null +++ b/packages/http-client-csharp/generator/TestProjects/Local.Tests/UnreferencedTypeTests.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Linq; +using System.Reflection; +using NUnit.Framework; +using UnbrandedTypeSpec; + +namespace TestProjects.Local.Tests +{ + public class UnreferencedTypeTests + { + [Test] + public void UnreferencedTypesAreRemoved() + { + var types = Assembly.GetAssembly(typeof(UnbrandedTypeSpecClient))!.GetTypes(); + Assert.IsFalse(types.Any(t => t.Name == "BinaryContentHelper")); + Assert.IsFalse(types.Any(t => t.Name == "PipelineRequestHeadersExtensions")); + Assert.IsFalse(types.Any(t => t.Name == "Utf8JsonBinaryContent")); + } + } +} diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/BinaryContentHelper.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/BinaryContentHelper.cs deleted file mode 100644 index 8ad092fa35..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/BinaryContentHelper.cs +++ /dev/null @@ -1,134 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.Text.Json; - -namespace UnbrandedTypeSpec -{ - internal static partial class BinaryContentHelper - { - public static BinaryContent FromEnumerable(IEnumerable enumerable) - where T : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - content.JsonWriter.WriteObjectValue(item, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromEnumerable(IEnumerable enumerable) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - if (item == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); -#else - using (JsonDocument document = JsonDocument.Parse(item)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromEnumerable(ReadOnlySpan span) - where T : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - int i = 0; - for (; i < span.Length; i++) - { - content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromDictionary(IDictionary dictionary) - where TValue : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - content.JsonWriter.WriteObjectValue(item.Value, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static BinaryContent FromDictionary(IDictionary dictionary) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - if (item.Value == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static BinaryContent FromObject(object value) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteObjectValue(value, ModelSerializationExtensions.WireOptions); - return content; - } - - public static BinaryContent FromObject(BinaryData value) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(value); -#else - using (JsonDocument document = JsonDocument.Parse(value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - return content; - } - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/PipelineRequestHeadersExtensions.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/PipelineRequestHeadersExtensions.cs deleted file mode 100644 index d7ae8691a4..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/PipelineRequestHeadersExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; - -namespace UnbrandedTypeSpec -{ - internal static partial class PipelineRequestHeadersExtensions - { - public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter) - { - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v)); - headers.Set(name, string.Join(delimiter, stringValues)); - } - - public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter, string format) - { - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - headers.Set(name, string.Join(delimiter, stringValues)); - } - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/Utf8JsonBinaryContent.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/Utf8JsonBinaryContent.cs deleted file mode 100644 index debd94c078..0000000000 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Internal/Utf8JsonBinaryContent.cs +++ /dev/null @@ -1,52 +0,0 @@ -// - -#nullable disable - -using System.ClientModel; -using System.IO; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; - -namespace UnbrandedTypeSpec -{ - internal partial class Utf8JsonBinaryContent : BinaryContent - { - private readonly MemoryStream _stream; - private readonly BinaryContent _content; - - public Utf8JsonBinaryContent() - { - _stream = new MemoryStream(); - _content = Create(_stream); - JsonWriter = new Utf8JsonWriter(_stream); - } - - public Utf8JsonWriter JsonWriter { get; } - - public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) - { - await JsonWriter.FlushAsync().ConfigureAwait(false); - await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); - } - - public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) - { - JsonWriter.Flush(); - _content.WriteTo(stream, cancellationToken); - } - - public override bool TryComputeLength(out long length) - { - length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; - return true; - } - - public override void Dispose() - { - JsonWriter.Dispose(); - _content.Dispose(); - _stream.Dispose(); - } - } -} diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.Serialization.cs index ae451492ff..2d280af055 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.Serialization.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.Serialization.cs @@ -12,7 +12,7 @@ namespace UnbrandedTypeSpec.Models { /// - public partial class AnonymousBodyRequest : IJsonModel + internal partial class AnonymousBodyRequest : IJsonModel { internal AnonymousBodyRequest() { diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.cs index f3990e0ab4..5ccfd27ca6 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/AnonymousBodyRequest.cs @@ -11,7 +11,7 @@ namespace UnbrandedTypeSpec.Models { /// The AnonymousBodyRequest. - public partial class AnonymousBodyRequest + internal partial class AnonymousBodyRequest { /// Keeps track of any properties unknown to the library. private IDictionary _serializedAdditionalRawData; diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.Serialization.cs index bee8747b3c..6a676d651a 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.Serialization.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.Serialization.cs @@ -12,7 +12,7 @@ namespace UnbrandedTypeSpec.Models { /// - public partial class FriendlyModelRequest : IJsonModel + internal partial class FriendlyModelRequest : IJsonModel { internal FriendlyModelRequest() { diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.cs index f48ffdeca8..29bd178ded 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/FriendlyModelRequest.cs @@ -8,7 +8,7 @@ namespace UnbrandedTypeSpec.Models { /// The FriendlyModelRequest. - public partial class FriendlyModelRequest + internal partial class FriendlyModelRequest { /// Keeps track of any properties unknown to the library. private IDictionary _serializedAdditionalRawData; diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.Serialization.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.Serialization.cs index 84ca8f84e3..05c39e5ad5 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.Serialization.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.Serialization.cs @@ -12,7 +12,7 @@ namespace UnbrandedTypeSpec.Models { /// - public partial class ProjectedNameModelRequest : IJsonModel + internal partial class ProjectedNameModelRequest : IJsonModel { internal ProjectedNameModelRequest() { diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.cs index 6c0c9696d5..37d668eaff 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/Models/ProjectedNameModelRequest.cs @@ -8,7 +8,7 @@ namespace UnbrandedTypeSpec.Models { /// The ProjectedNameModelRequest. - public partial class ProjectedNameModelRequest + internal partial class ProjectedNameModelRequest { /// Keeps track of any properties unknown to the library. private IDictionary _serializedAdditionalRawData; diff --git a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/UnbrandedTypeSpecModelFactory.cs b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/UnbrandedTypeSpecModelFactory.cs index d33080dffd..f84f4639a2 100644 --- a/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/UnbrandedTypeSpecModelFactory.cs +++ b/packages/http-client-csharp/generator/TestProjects/Local/Unbranded-TypeSpec/src/Generated/UnbrandedTypeSpecModelFactory.cs @@ -127,52 +127,6 @@ public static ModelWithRequiredNullableProperties ModelWithRequiredNullablePrope return new ModelWithRequiredNullableProperties(requiredNullablePrimitive, requiredExtensibleEnum, requiredFixedEnum, null); } - /// The AnonymousBodyRequest. - /// name of the Thing. - /// required Union. - /// required literal string. - /// required literal int. - /// required literal float. - /// required literal bool. - /// optional literal string. - /// optional literal int. - /// optional literal float. - /// optional literal bool. - /// description with xml <|endoftext|>. - /// optional nullable collection. - /// required nullable collection. - /// A new instance for mocking. - public static AnonymousBodyRequest AnonymousBodyRequest(string name = default, BinaryData requiredUnion = default, AnonymousBodyRequestRequiredLiteralString requiredLiteralString = default, AnonymousBodyRequestRequiredLiteralInt requiredLiteralInt = default, AnonymousBodyRequestRequiredLiteralFloat requiredLiteralFloat = default, bool requiredLiteralBool = default, AnonymousBodyRequestOptionalLiteralString? optionalLiteralString = default, AnonymousBodyRequestOptionalLiteralInt? optionalLiteralInt = default, AnonymousBodyRequestOptionalLiteralFloat? optionalLiteralFloat = default, bool? optionalLiteralBool = default, string requiredBadDescription = default, IEnumerable optionalNullableList = default, IEnumerable requiredNullableList = default) - { - optionalNullableList ??= new ChangeTrackingList(); - requiredNullableList ??= new ChangeTrackingList(); - - return new AnonymousBodyRequest( - name, - requiredUnion, - requiredLiteralString, - requiredLiteralInt, - requiredLiteralFloat, - requiredLiteralBool, - optionalLiteralString, - optionalLiteralInt, - optionalLiteralFloat, - optionalLiteralBool, - requiredBadDescription, - optionalNullableList?.ToList(), - requiredNullableList?.ToList(), - null); - } - - /// The FriendlyModelRequest. - /// name of the NotFriend. - /// A new instance for mocking. - public static FriendlyModelRequest FriendlyModelRequest(string name = default) - { - - return new FriendlyModelRequest(name, null); - } - /// this is not a friendly model but with a friendly name. /// name of the NotFriend. /// A new instance for mocking. @@ -182,15 +136,6 @@ public static Friend Friend(string name = default) return new Friend(name, null); } - /// The ProjectedNameModelRequest. - /// name of the ModelWithProjectedName. - /// A new instance for mocking. - public static ProjectedNameModelRequest ProjectedNameModelRequest(string name = default) - { - - return new ProjectedNameModelRequest(name, null); - } - /// this is a model with a projected name. /// name of the ModelWithProjectedName. /// A new instance for mocking.