From f607df631251518b3281015188673d3553222105 Mon Sep 17 00:00:00 2001 From: Mohammadreza Taikandi Date: Sat, 19 Dec 2020 07:55:47 +0000 Subject: [PATCH] Generate partial class and assign destination properties based on an attribute. --- .gitignore | 442 +++++++++++++++++++++++ MapTo.sln | 22 ++ MapTo.sln.DotSettings | 3 + MapTo/CompilerServices/IsExternalInit.cs | 18 + MapTo/Extensions/RoslynExtensions.cs | 82 +++++ MapTo/Extensions/StringExtensions.cs | 10 + MapTo/MapToGenerator.cs | 84 +++++ MapTo/MapToSyntaxReceiver.cs | 38 ++ MapTo/Mapto.csproj | 17 + MapTo/Models/MapModel.cs | 33 ++ MapTo/SourceProvider.cs | 134 +++++++ MapToTests/CSharpGenerator.cs | 51 +++ MapToTests/MaptoTests.csproj | 35 ++ MapToTests/Tests.cs | 200 ++++++++++ 14 files changed, 1169 insertions(+) create mode 100644 .gitignore create mode 100644 MapTo.sln create mode 100644 MapTo.sln.DotSettings create mode 100644 MapTo/CompilerServices/IsExternalInit.cs create mode 100644 MapTo/Extensions/RoslynExtensions.cs create mode 100644 MapTo/Extensions/StringExtensions.cs create mode 100644 MapTo/MapToGenerator.cs create mode 100644 MapTo/MapToSyntaxReceiver.cs create mode 100644 MapTo/Mapto.csproj create mode 100644 MapTo/Models/MapModel.cs create mode 100644 MapTo/SourceProvider.cs create mode 100644 MapToTests/CSharpGenerator.cs create mode 100644 MapToTests/MaptoTests.csproj create mode 100644 MapToTests/Tests.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..920d1cd --- /dev/null +++ b/.gitignore @@ -0,0 +1,442 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/MapTo.sln b/MapTo.sln new file mode 100644 index 0000000..1c5d946 --- /dev/null +++ b/MapTo.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MapTo", "MapTo\MapTo.csproj", "{4DB371AC-48D0-4F01-8EF3-7707D06EF0A7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MapToTests", "MapToTests\MapToTests.csproj", "{797DA57B-AC7E-468B-8799-44C5A574C0E3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4DB371AC-48D0-4F01-8EF3-7707D06EF0A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4DB371AC-48D0-4F01-8EF3-7707D06EF0A7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4DB371AC-48D0-4F01-8EF3-7707D06EF0A7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4DB371AC-48D0-4F01-8EF3-7707D06EF0A7}.Release|Any CPU.Build.0 = Release|Any CPU + {797DA57B-AC7E-468B-8799-44C5A574C0E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {797DA57B-AC7E-468B-8799-44C5A574C0E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {797DA57B-AC7E-468B-8799-44C5A574C0E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {797DA57B-AC7E-468B-8799-44C5A574C0E3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/MapTo.sln.DotSettings b/MapTo.sln.DotSettings new file mode 100644 index 0000000..ff51a4e --- /dev/null +++ b/MapTo.sln.DotSettings @@ -0,0 +1,3 @@ + + True + True \ No newline at end of file diff --git a/MapTo/CompilerServices/IsExternalInit.cs b/MapTo/CompilerServices/IsExternalInit.cs new file mode 100644 index 0000000..12de4db --- /dev/null +++ b/MapTo/CompilerServices/IsExternalInit.cs @@ -0,0 +1,18 @@ +// ReSharper disable UnusedType.Global +// ReSharper disable CheckNamespace +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; + +namespace System.Runtime.CompilerServices +{ + /// + /// Reserved to be used by the compiler for tracking metadata. + /// This class should not be used by developers in source code. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + internal static class IsExternalInit + { + } +} \ No newline at end of file diff --git a/MapTo/Extensions/RoslynExtensions.cs b/MapTo/Extensions/RoslynExtensions.cs new file mode 100644 index 0000000..6328b16 --- /dev/null +++ b/MapTo/Extensions/RoslynExtensions.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace MapTo.Extensions +{ + internal static class RoslynExtensions + { + public static IEnumerable GetBaseTypesAndThis(this ITypeSymbol type) + { + var current = type; + while (current != null) + { + yield return current; + + current = current.BaseType; + } + } + + public static IEnumerable GetAllMembers(this ITypeSymbol type) + { + return type.GetBaseTypesAndThis().SelectMany(n => n.GetMembers()); + } + + public static IEnumerable GetAllMembersOfType(this ITypeSymbol type) where T : ISymbol + { + return type.GetAllMembers().OfType(); + } + + public static CompilationUnitSyntax? GetCompilationUnit(this SyntaxNode syntaxNode) + { + return syntaxNode.Ancestors().OfType().FirstOrDefault(); + } + + public static string GetClassName(this ClassDeclarationSyntax classSyntax) + { + return classSyntax.Identifier.Text; + } + + public static string GetClassModifier(this ClassDeclarationSyntax classSyntax) + { + return classSyntax.Modifiers.ToFullString().Trim(); + } + + public static bool HaveAttribute(this ClassDeclarationSyntax classSyntax, string attributeName) + { + return classSyntax.AttributeLists.Count > 0 && + classSyntax.AttributeLists.SelectMany(al => al.Attributes + .Where(a => + (a.Name as IdentifierNameSyntax)?.Identifier.Text == attributeName || + ((a.Name as QualifiedNameSyntax)?.Right as IdentifierNameSyntax)?.Identifier.ValueText == attributeName)) + .Any(); + } + + public static AttributeSyntax? GetAttribute(this ClassDeclarationSyntax classSyntax, string attributeName) + { + return classSyntax.AttributeLists + .SelectMany(al => al.Attributes) + .SingleOrDefault(a => + (a.Name as IdentifierNameSyntax)?.Identifier.ValueText == attributeName || + ((a.Name as QualifiedNameSyntax)?.Right as IdentifierNameSyntax)?.Identifier.ValueText == attributeName); + } + + public static string? GetNamespace(this CompilationUnitSyntax root) + { + return root.ChildNodes() + .OfType() + .FirstOrDefault() + ?.Name + .ToString(); + } + + public static List GetUsings(this CompilationUnitSyntax root) + { + return root.ChildNodes() + .OfType() + .Select(n => n.Name.ToString()) + .ToList(); + } + } +} \ No newline at end of file diff --git a/MapTo/Extensions/StringExtensions.cs b/MapTo/Extensions/StringExtensions.cs new file mode 100644 index 0000000..dff6852 --- /dev/null +++ b/MapTo/Extensions/StringExtensions.cs @@ -0,0 +1,10 @@ +namespace MapTo.Extensions +{ + internal static class StringExtensions + { + public static string ToCamelCase(this string value) + { + return string.IsNullOrWhiteSpace(value) ? value : $"{char.ToLower(value[0])}{value.Substring(1)}"; + } + } +} \ No newline at end of file diff --git a/MapTo/MapToGenerator.cs b/MapTo/MapToGenerator.cs new file mode 100644 index 0000000..36b8d14 --- /dev/null +++ b/MapTo/MapToGenerator.cs @@ -0,0 +1,84 @@ +using System.Collections.Generic; +using System.Linq; +using MapTo.Extensions; +using MapTo.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace MapTo +{ + public class MapToGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + context.RegisterForSyntaxNotifications(() => new MapToSyntaxReceiver()); + } + + /// + public void Execute(GeneratorExecutionContext context) + { + context.AddMapToAttribute(); + + if (!(context.SyntaxReceiver is MapToSyntaxReceiver receiver) || !receiver.CandidateClasses.Any()) + { + return; + } + + foreach (var (classDeclarationSyntax, attributeSyntax) in receiver.CandidateClasses) + { + var model = GetModel(context.Compilation, classDeclarationSyntax); + if (model is null) + { + // TODO: Emit diagnostic info. + continue; + } + + var (source, hintName) = SourceProvider.GenerateSource(model); + + context.AddSource(hintName, source); + } + } + + private static MapModel? GetModel(Compilation compilation, ClassDeclarationSyntax classSyntax) + { + var root = classSyntax.GetCompilationUnit(); + if (root is null) + { + return null; + } + + var classSemanticModel = compilation.GetSemanticModel(classSyntax.SyntaxTree); + + if (!(classSemanticModel.GetDeclaredSymbol(classSyntax) is INamedTypeSymbol classSymbol)) + { + return null; + } + + var destinationTypeSymbol = GetDestinationTypeSymbol(classSyntax, classSemanticModel); + if (destinationTypeSymbol is null) + { + return null; + } + + return new MapModel( + ns: root.GetNamespace(), + classModifiers: classSyntax.GetClassModifier(), + className: classSyntax.GetClassName(), + properties: classSymbol.GetAllMembersOfType(), + destinationClassName: destinationTypeSymbol.Name, + destinationTypeProperties: destinationTypeSymbol.GetAllMembersOfType()); + } + + private static ITypeSymbol? GetDestinationTypeSymbol(ClassDeclarationSyntax classSyntax, SemanticModel model) + { + var destinationTypeExpressionSyntax = classSyntax + .GetAttribute(SourceProvider.MapFromAttributeName) + ?.DescendantNodes() + .OfType() + .SingleOrDefault(); + + return destinationTypeExpressionSyntax is not null ? model.GetTypeInfo(destinationTypeExpressionSyntax.Type).Type : null; + } + } +} \ No newline at end of file diff --git a/MapTo/MapToSyntaxReceiver.cs b/MapTo/MapToSyntaxReceiver.cs new file mode 100644 index 0000000..f4272bc --- /dev/null +++ b/MapTo/MapToSyntaxReceiver.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace MapTo +{ + internal class MapToSyntaxReceiver : ISyntaxReceiver + { + public List<(ClassDeclarationSyntax classDeclarationSyntax, AttributeSyntax attributeSyntax)> CandidateClasses { get; } = new(); + + /// + public void OnVisitSyntaxNode(SyntaxNode syntaxNode) + { + if (syntaxNode is not ClassDeclarationSyntax { AttributeLists: { Count: >= 1 } attributes } classDeclaration) + { + return; + } + + var attributeSyntax = attributes + .SelectMany(a => a.Attributes) + .SingleOrDefault(a => a.Name is + IdentifierNameSyntax { Identifier: { ValueText: SourceProvider.MapFromAttributeName } } // For: [MapFrom] + or + QualifiedNameSyntax // For: [MapTo.MapFrom] + { + Left: IdentifierNameSyntax { Identifier: { ValueText: SourceProvider.NamespaceName } }, + Right: IdentifierNameSyntax { Identifier: { ValueText: SourceProvider.MapFromAttributeName } } + } + ); + + if (attributeSyntax is not null) + { + CandidateClasses.Add((classDeclaration, attributeSyntax)); + } + } + } +} \ No newline at end of file diff --git a/MapTo/Mapto.csproj b/MapTo/Mapto.csproj new file mode 100644 index 0000000..ff7bb1f --- /dev/null +++ b/MapTo/Mapto.csproj @@ -0,0 +1,17 @@ + + + + netstandard2.0 + 9 + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/MapTo/Models/MapModel.cs b/MapTo/Models/MapModel.cs new file mode 100644 index 0000000..da5bc26 --- /dev/null +++ b/MapTo/Models/MapModel.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace MapTo.Models +{ + public class MapModel + { + public MapModel(string? ns, string classModifiers, string className, IEnumerable properties, string destinationClassName, IEnumerable destinationTypeProperties) + { + Namespace = ns; + ClassModifiers = classModifiers; + ClassName = className; + Properties = properties; + DestinationClassName = destinationClassName; + DestinationTypeProperties = destinationTypeProperties; + } + + public string? Namespace { get; } + + public string ClassModifiers { get; } + + public string ClassName { get; } + + public IEnumerable Properties { get; } + + public string DestinationClassName { get; } + + public IEnumerable DestinationTypeProperties { get; } + + public bool IsEmpty => !Properties.Any() || !DestinationTypeProperties.Any(); + } +} \ No newline at end of file diff --git a/MapTo/SourceProvider.cs b/MapTo/SourceProvider.cs new file mode 100644 index 0000000..1cd4c51 --- /dev/null +++ b/MapTo/SourceProvider.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MapTo.Extensions; +using MapTo.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace MapTo +{ + internal static class SourceProvider + { + internal const string NamespaceName = "MapTo"; + internal const string MapFromAttributeName = "MapFrom"; + private const int Indent1 = 4; //" "; + private const int Indent2 = Indent1 * 2; // " "; + private const int Indent3 = Indent1 * 3; // " "; + + internal static void AddMapToAttribute(this GeneratorExecutionContext context) + { + const string source = @" +using System; + +namespace MapTo +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + public sealed class MapFromAttribute : Attribute + { + public MapFromAttribute(Type sourceType) + { + SourceType = sourceType; + } + + public Type SourceType { get; } + } +} +"; + + context.AddSource("MapFromAttribute", SourceText.From(source, Encoding.UTF8)); + } + + internal static (string source, string hintName) GenerateSource(MapModel model) + { + var builder = new StringBuilder(); + + // Namespace declaration + builder + .AppendFileHeader() + .AppendFormat("namespace {0}", model.Namespace) + .AppendOpeningBracket(); + + // Class declaration + builder + .PadLeft(Indent1) + .AppendFormat("{0} class {1}", model.ClassModifiers, model.ClassName) + .AppendOpeningBracket(Indent1); + + // Constructor declaration + builder.GenerateConstructor(model, out var mappedProperties); + + // End class declaration + builder.AppendClosingBracket(Indent1); + + // End namespace declaration + builder.AppendClosingBracket(); + + return (builder.ToString(), $"{model.ClassName}.cs"); + } + + private static StringBuilder GenerateConstructor(this StringBuilder builder, MapModel model, out List mappedProperties) + { + var destinationClassParameterName = model.DestinationClassName.ToCamelCase(); + + builder + .PadLeft(Indent2) + .AppendFormat("public {0}({1} {2})", model.ClassName, model.DestinationClassName, destinationClassParameterName) + .AppendOpeningBracket(Indent2); + + mappedProperties = new List(); + foreach (var propertySymbol in model.DestinationTypeProperties) + { + if (model.Properties.Any(p => p.Name == propertySymbol.Name)) + { + mappedProperties.Add(propertySymbol); + builder + .PadLeft(Indent3) + .AppendFormat("{0} = {1}.{2};{3}", propertySymbol.Name, destinationClassParameterName, propertySymbol.Name, Environment.NewLine); + } + } + + // End constructor declaration + return builder.AppendClosingBracket(Indent2, padNewLine: false); + } + + private static StringBuilder AppendOpeningBracket(this StringBuilder builder, int indent = 0) + { + return builder.AppendLine().PadLeft(indent).AppendFormat("{{{0}", Environment.NewLine); + } + + private static StringBuilder AppendClosingBracket(this StringBuilder builder, int indent = 0, bool padNewLine = true) + { + if (padNewLine) + { + builder.AppendLine(); + } + + return builder.PadLeft(indent).Append("}"); + } + + private static StringBuilder PadLeft(this StringBuilder builder, int width) + { + for (var i = 0; i < width; i++) + { + builder.Append(" "); + } + + return builder; + } + + private static StringBuilder AppendFileHeader(this StringBuilder builder) + { + return builder + .AppendLine("// ") + .AppendLine(); + } + + private static string GetValueText(this NameSyntax? nameSyntax) + { + return (nameSyntax as IdentifierNameSyntax)?.Identifier.ValueText ?? string.Empty; + } + } +} \ No newline at end of file diff --git a/MapToTests/CSharpGenerator.cs b/MapToTests/CSharpGenerator.cs new file mode 100644 index 0000000..8ca9356 --- /dev/null +++ b/MapToTests/CSharpGenerator.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using MapTo; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; +using Xunit.Abstractions; + +namespace MapToTests +{ + internal static class CSharpGenerator + { + internal static string GetGeneratedOutput(this ITestOutputHelper outputHelper, string source) + { + var (compilation, diagnostics) = GetOutputCompilation(source); + diagnostics.ShouldBeSuccessful(); + + var generatedOutput = compilation.SyntaxTrees.Last().ToString(); + outputHelper.WriteLine(generatedOutput); + + return generatedOutput; + } + + internal static void ShouldBeSuccessful(this ImmutableArray diagnostics) + { + Assert.False(diagnostics.Any(d => d.Severity >= DiagnosticSeverity.Warning), $"Failed: {diagnostics.FirstOrDefault()?.GetMessage()}"); + } + + internal static (Compilation compilation, ImmutableArray diagnostics) GetOutputCompilation(string source) + { + var syntaxTree = CSharpSyntaxTree.ParseText(source); + var references = AppDomain.CurrentDomain.GetAssemblies() + .Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location)) + .Select(a => MetadataReference.CreateFromFile(a.Location)) + .ToList(); + + var compilation = CSharpCompilation.Create("foo", new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + + // NB: Uncomment this line if you want to fail tests when the injected program isn't valid _before_ running generators + // var compileDiagnostics = compilation.GetDiagnostics(); + // Assert.False(compileDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error), "Failed: " + compileDiagnostics.FirstOrDefault()?.GetMessage()); + + ISourceGenerator generator = new MapToGenerator(); + var driver = CSharpGeneratorDriver.Create(generator); + driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generateDiagnostics); + + return (outputCompilation, generateDiagnostics); + } + } +} \ No newline at end of file diff --git a/MapToTests/MaptoTests.csproj b/MapToTests/MaptoTests.csproj new file mode 100644 index 0000000..3507ec8 --- /dev/null +++ b/MapToTests/MaptoTests.csproj @@ -0,0 +1,35 @@ + + + + net5.0 + + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/MapToTests/Tests.cs b/MapToTests/Tests.cs new file mode 100644 index 0000000..f26d81a --- /dev/null +++ b/MapToTests/Tests.cs @@ -0,0 +1,200 @@ +using System.Linq; +using Shouldly; +using Xunit; +using Xunit.Abstractions; + +namespace MapToTests +{ + public class Tests + { + private readonly ITestOutputHelper _output; + private const string ExpectedAttribute = @" +using System; + +namespace MapTo +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + public sealed class MapFromAttribute : Attribute + { + public MapFromAttribute(Type sourceType) + { + SourceType = sourceType; + } + + public Type SourceType { get; } + } +} +"; + + public Tests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public void VerifyMapToAttribute() + { + // Arrange + const string source = ""; + + // Act + var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source); + + // Assert + diagnostics.ShouldBeSuccessful(); + compilation.SyntaxTrees.ShouldContain(c => c.ToString() == ExpectedAttribute); + } + + [Fact] + public void When_NoMapToAttributeFound_Should_GenerateOnlyTheAttribute() + { + // Arrange + const string source = ""; + + // Act + var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source); + + // Assert + diagnostics.ShouldBeSuccessful(); + compilation.SyntaxTrees.ShouldContain(s => s.ToString() == ExpectedAttribute); + compilation.SyntaxTrees.Select(s => s.ToString()).Where(s => s != string.Empty && s != ExpectedAttribute).ShouldBeEmpty(); + } + + [Fact] + public void When_MapToAttributeFound_Should_GenerateTheClass() + { + // Arrange + const string source = @" +namespace Test +{ + [MapFrom(typeof(Baz)] + public partial class Foo + { + + } + + public class Baz + { + public int Prop1 { get; set; } + public int Prop2 { get; } + public int Prop3 { get; set; } + } +} +"; + + const string expectedResult = @" +// + +namespace Test +{ + public partial class Foo + { + public Foo(Baz baz) + { + } + } +} +"; + + // Act + var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source); + + // Assert + diagnostics.ShouldBeSuccessful(); + compilation.SyntaxTrees.Count().ShouldBe(3); + compilation.SyntaxTrees.Last().ToString().ShouldBe(expectedResult.Trim()); + } + + [Fact] + public void When_MapToAttributeWithNamespaceFound_Should_GenerateTheClass() + { + // Arrange + const string source = @" +namespace Test +{ + [MapTo.MapFrom(typeof(Baz)] + public partial class Foo + { + + } + + public class Baz + { + + } +} +"; + + const string expectedResult = @" +// + +namespace Test +{ + public partial class Foo + { + public Foo(Baz baz) + { + } + } +} +"; + + // Act + var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source); + + // Assert + diagnostics.ShouldBeSuccessful(); + compilation.SyntaxTrees.Count().ShouldBe(3); + compilation.SyntaxTrees.Last().ToString().ShouldBe(expectedResult.Trim()); + } + + [Fact] + public void When_SourceTypeHasMatchingProperties_Should_CreateConstructorAndAssignSrcToDest() + { + // Arrange + var source = GetSourceText(); + + const string expectedResult = @" + public partial class Foo + { + public Foo(Baz baz) + { + Prop1 = baz.Prop1; + Prop2 = baz.Prop2; + Prop3 = baz.Prop3; + } +"; + + // Act + var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source); + + // Assert + diagnostics.ShouldBeSuccessful(); + compilation.SyntaxTrees.Count().ShouldBe(3); + compilation.SyntaxTrees.Last().ToString().ShouldContain(expectedResult.Trim()); + } + + private static string GetSourceText(bool includeAttributeNamespace = false) + { + return @$" +namespace Test +{{ + {(includeAttributeNamespace ? "[MapTo.MapFrom(typeof(Baz))]" : "[MapFrom(typeof(Baz))]")} + public partial class Foo + {{ + public int Prop1 {{ get; set; }} + public int Prop2 {{ get; }} + public int Prop3 {{ get; }} + }} + + public class Baz + {{ + public int Prop1 {{ get; set; }} + public int Prop2 {{ get; }} + public int Prop3 {{ get; set; }} + }} +}} +"; + } + } +}