Giter Club home page Giter Club logo

uno.codegen's Introduction

Uno CodeGen

Uno.CodeGen is a set of tools to generate C# code in msbuild based projects.

Generate Equality Members for your C# classes

Equality Members generation snippet

Features:

  • Amazingly fast: absolutely zero reflection at runtime
  • Generates both .Equals() and .GetHashCode() overrrides
  • Generates equality (== and !=) operators
  • Implements IEquatable<T>
  • Works with derived classes
  • Custom comparers supported
  • Works with collection members (both same order and unsorted equality)
  • Works with dictionary members (both same order and unsorted equality)
  • Optional case insentive comparisons for strings
  • Optional support for KeyEquality (see doc for more details)
  • Debuggable: You can put a breakpoint directly in the generated code
  • Highly configureable: Generated code provides a lot of useful tips (stripped in previous snippet)
  • Documentation here for Equality Members Generator

Create truly Immutable Entities in C#

Equality Members generation snippet

Features:

  • Automatic Null object pattern generation
  • Automatic generation of <YourClass>.Builder nested class
  • Fluent .With<field/property name>() generation of every members of your class
  • Amazingly fast: absolutely zero reflection at runtime
  • Works with generics & derived classes (even if they are from external assembly)
  • Optional support (on by default) for [GeneratedEquality]
  • Transparent support for Newtonsoft's JSON.NET (activated when detected, can be turned off)
  • Transparent support for System.Text.Json (activated when detected, can be turned off)
  • Debuggable: You can put a breakpoint directly in the generated code
  • Validation to avoid mutable code in your class
  • Highly configureable: Generated code provides a lot of useful tips (stripped in previous snippet)
  • Documentation here for Immutable Entities Generator

Available Generators

Generator Triggering Attributes Usage
ClassLifecycleGenerator [ConstructorMethod] [DisposeMethod] [FinalizerMethod] Generate code to extend the lifecyle of a class. Documentation
CompilationReferencesListingGenerator none Generate a file without useful code, containing only comments detailing references used to compile the project. Documentation
EqualityGenerator [GenerateEquality] Generate code for efficient .Equals() members generation. Documentation
ImmutableGenerator [GenerateImmutable] Generate code to build truly immutable entities. Documentation
InjectableGenerator [Inject] Generate code to resolve and inject dependencies. Documentation

Nuget

NuGet

FAQ

Read our FAQ here

Have questions? Feature requests? Issues?

Make sure to visit our FAQ, StackOverflow, create an issue or visit our gitter.

Contributing

Read our contributing guide to learn about our development process and how to propose bug fixes and improvements.

uno.codegen's People

Contributors

agneszitte avatar arnaudrivard avatar artemious7 avatar beppemarazzi avatar carldebilly avatar dahlia avatar dr1rrb avatar jeremiethibeault avatar jeromelaban avatar ledouxpl avatar matfillion avatar miguelrochefort avatar nventive-devops avatar xiaotiannetlift avatar xiaoy312 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uno.codegen's Issues

IKeyEquatable refactorings

The IKeyEquatable interface (and its generic version) should be moved to Uno.Equality project.

Also the generic version should derive from the non-generic one.

B.Builder() from class B returns a class A object when B inherit from A

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

B.Builder() from class B returns a class A object when B inherit from A

Expected behavior

B.Builder() from class B returns a class B object when B inherit from A

Minimal reproduction of the problem with instructions

Class A

[GeneratedImmutable]
public partial class ClassA
{
	[... some properties ...]
}

Class B

[GeneratedImmutable]
public partial class ClassB : ClassA
{
	[... some properties ...]
}

And call this wherever you want

var test = new ClassB.Builder()
	.WithPropertyFromClassA(...)
	.WithPropertyFromClassB(....)
	.ToImmutable();

Doesn't work because ClassB.Builder() is returning a ClassA object

Environment

Nuget Package: 5.7.0

Package Version(s): Uno.UI 3.0.11 / Uno.CodeGen 1.32.0

Affected platform(s):
- [ X ] iOS
- [ X ] Android
- [ X ] WebAssembly
- [ X ] Windows
- [ ] Build tasks

Visual Studio
- [ X ] 2019 (version: 16.7.2 )
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

Generate helpers for immutable collections/dictionaries

Feature request

Should generate helpers to manage collections and dictionaries on immutable entities.

Example

Declaration

  [GeneratedImmutable]
  public class MyClass
  {
    public ImmutableArray<string> Favorites { get; }
    public ImmutableDictionary<string, string> Settings { get; }
  }

Usage

  public void Do()
  {
    var a = new MyClass();
    var b = a.WithAddFavorite("ID01");
    var c = b.WithSetting("owner", "uno platform");
  }

Features

  • Should support implementations of IImmutableList<T>, IImmutableSet<T>, IImmutableQueue<T>, IImmutableStack<T>, IImmutableDictionary<TKey, TValue>.
  • Should handle null

IList's `Default` doesn't use the default

I'm submitting a...

Bug report (I searched for similar issues and did not find one)

Current behavior

        [EqualityComparerOptions(CollectionMode = CollectionComparerMode.Default)]
        public IList<string> InOrderRules { get; }

vs.

        [EqualityComparerOptions]
        public IList<string> InOrderRules { get; }

do not generate the same code (e.g. 'Default' is not the default)

Expected behavior

They use SortedCollectionEqualityComparer for both

Minimal reproduction of the problem with instructions

I can make a project if you wish, but I'm imagining for this issue it's not necessary ;) Problem is that Default = 0 and Unsorted = 0 on the enum.

Environment

Nuget Package: Uno.CodeGen

Package Version(s): 1.32.0

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [x] Windows
- [ ] Build tasks

Visual Studio
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )
- [x] 2019

Relevant plugins
- [ ] Resharper (version: )

Compiler error CS0453 with nullable ref types + GeneratedImmutable

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

When using nullable reference types and [GeneratedImmutable] the generated methods have wrong parameters.

For a public string? TestProperty { get; } we get

public Builder WithTestProperty(global::System.Nullable<string> value)
{
    TestProperty = value;
    return this;
}

for example.

The value parameter here gives a compile error CS0453.

Expected behavior

We should be able to use GeneratedImmutable on (partial) classes that use nullable reference types without any errors.

Minimal reproduction of the problem with instructions

using Uno;

#nullable enable

[GeneratedImmutable]
public sealed partial class Test
{
    [EqualityKey]
    public string? TestProperty { get; }
}

#nullable restore 

Environment

Nuget Package: Uno.CodeGen

Package Version(s): 1.33.0-dev.143

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [x] Windows
- [ ] Build tasks

(This is what I'm testing on, but I assume all platforms that support C# 8's nullable reference types are affected.)

Visual Studio
- [x] 2019 (version: 16.3.9)
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

[EqualityHash] on objects try to convert them to string in instead of getting hash

error CS1503: Argument 1: cannot convert from 'MyProject.AuthenticationData' to 'string'

[Bindable]
[GeneratedImmutable]
public partial class ApplicationSettings
{
[EqualityHash]
public AuthenticationData AuthenticationData { get; }
...}

[Bindable]
[GeneratedImmutable]
public partial class AuthenticationData
{
public AuthenticationData(string accessToken)
{
AccessToken = accessToken;
}

[SerializationProperty("access_token")]
[EqualityKey]
public string AccessToken { get; }
}

}

Add support for `IStructuralEquatable`

When a member implements IStructuralEquatable, it should be used for equality & hashcode.

  • Support when the member type implements it (compile-time)
  • Support when the instance type implements it (runtime)

It should be possible to compare the builder with its entity

Feature request

Current behavior

Take this code:

var a = A.Default;
var b = a.WithName("myName");
var c = a.WithName("myName");
if(b == c || a == b || a == c)
{
  doSomething(); // Never called!
}

It's never called because b if of type A.Builder, not A.
It's hard to diagnose this problem by reading at the code.

Expected behavior

That comparaison with the builder should works directly.

Can't update the value of a property on Immutable object when the property has [EqualityIgnore] attribute

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

When you have an immutable type with a property that has the [EqualityIgnore] attribute and you update that property with the .WithXXX syntax then the new value is ignored. I see the issue is in the builder that when comparing the cached value with the new value, .Equals returns true so it'll return the cached value.

Expected behavior

When you update a property that has the [EqualityIgnore] attribute, that value should still be updatable

Minimal reproduction of the problem with instructions

Here's a simple repo reproducing this issue
https://github.com/abrull/TestUnoImmutables

Derived version of a Key Equatable class should also be Key Equatable

Bug report

Derived class for a IKeyEquatable class should be IKeyEquatable also using the same key (if none defined on derived class)

[GeneratedImmutable]
public partial class A
{
  [EqualityKey]
  public string Id { get; }

  public string Name { get; }
}

[GeneratedImmutable]
public partial class B : A
{
  public string Description { get; }
}

// A will be IKeyEquatable<A>
// B should also be IKeyEquatable<B> --AND-- IKeyEquatable<A>

Expected behavior

In previous example, B should be both IKeyEquatable<A> and IKeyEquatable<B>.

EqualityHash should work with enums

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

Writing this:

[EqualityHash]
public DayOfWeek DayOfWeek { get; }

yields this warning:

Type DayOfWeek of member DayOfWeek doesn't implements .GetHashCode(): it won't be used for hash computation. If you can't change the type System.DayOfWeek, you should use a custom hash method or a custom comparer. Alternatively, use something else for hash computation.

Expected behavior

No warning.
The numerical value from the enum should be used for the hashcode computation.

Environment

Nuget Package: Uno.Equality

Package Version(s): 1.27.0

Affected platform(s):
- [x] iOS
- [x] Android
- [x] WebAssembly
- [x] Windows
- [ ] Build tasks

Visual Studio
- [x] 2017 (version: )
- [x] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

Ability to bypass the check that all properties are immutable

When we use 3rd party classes we will face issues referencing them. If we know they are immutable, we should have a way to tell the generator to consider them as immutables.

Proposed solution:

[assembly: KnownAsImmutable(typeof(ClassWeKnowToBeImmutable))]

EqualityGenerator: Generated code is uncompilable for readonly structs

Hello,
very interesting library, thank you :)

I'm submitting a...

Bug report / Feature request

Current behavior

To reproduce, just apply GeneratedEquality to any readonly struct. The generated mutable int? _computedHashCode field is not allowed for readonly structs.

Expected behavior

Possible solutions:

  • Just recompute the hash on every GetHashCode call.
  • Initialize _computedHashCode in the constructor. I don't think this is possible by adding additional members to the struct; would need cooperation from the user's constructor code.
  • (Bad, but for completeness:) Mark _computedHashCode readonly and write to it in an unsafe way.

Complication: There doesn't seem to be a public Roslyn API to detect readonly structs yet: dotnet/roslyn#23792

I have a branch here (I was hesitant to just barge in with a pull request) that resolves the issue by adding an AddHashCodeField property to GeneratedEqualityAttribute. If it is false, _computedHashCode is not generated and the hash is recomputed on every call to GetHashCode.

IMHO, this is a useful feature even without the readonly struct problem because caching the hash code is potentially detrimental to performance if the calculation is just a few arithmetic instructions (since fewer of the objects to be hashed will fit into processor caches).

Minimal reproduction of the problem with instructions

See above

Environment

Nuget Package: Uno.CodeGen

Package Version(s): 1.29.0; master branch

Affected platform(s), Visual Studio: Presumably all platforms and Visual Studio versions that support readonly structs.

Unable to build using dotnet core

Bug report

Unable to build a project using Uno.CodeGen on the dotnet core platform from
command line.

Repro steps

  1. Create a new dotnet core project.
  2. Add reference to Uno.CodeGen
  3. Build from command line:
    C:\myproject>dotnet build myproject.csproj

Current behavior

We're getting an error like that:

C:\Users\[...]\.nuget\packages\uno.sourcegenerationtasks\1.31.0\build\netstandard1.0\Uno.SourceGenerationTasks.targets(122,2): error : Generation failed, error code -2147450740 [C:\src\[projectfolder]\[projectfile].csproj]

Expected behavior

Should compile without errors.

Extra information

Building using MSBuild won't produce this error:

C:\myproject>msbuild myproject.csproj
[...]
Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:07.12

Environment

Dotnet Code 2.2
Nuget Package: 1.31.0

Update Uno.SourceGeneration and Uno SourceGenerationTasks

I'm submitting a...

Bug report (I searched for similar issues and did not find one)

Current behavior

Uno.SourceGeneration and Uno.SourceGenerationTasks are at version 1.30.0-dev.245 which caused package downgrade in current projects

Expected behavior

Uno.SourceGeneration and Uno SourceGenerationTasks needs to be at version 3.1.0

Environment

Nuget Package: 

Package Version(s): 

Affected platform(s): All platforms
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [ ] Windows
- [ ] Build tasks

Build failed on macOS: Exec format error

Build failed on macOS

When I build a project, the following error message is shown.

/Users/Username/.nuget/packages/uno.sourcegenerationtasks/1.31.0/build/netstandard1.0/Uno.SourceGenerationTasks.targets(122,2): error : Exec format error [/Users/Username/Code/ScriptSharp/ScriptCSharp/ScriptCSharp.csproj]

OS: macOS Catalina 10.15.7
.NET Core version: 3.1.402

Annotate generated methods/operators with [ExcludeFromCodeCoverage]

I'm submitting a…

  • Feature request

Current behavior

Methods generated by Uno.CodeGen usually do not have unit tests, but it makes code coverage reports find them not covered.

Expected behavior

It would be good if generated code are excluded by code coverage reports. FYI several coverage tools are aware of ExcludeFromCodeCoverageAttribute.

Minimal reproduction of the problem with instructions

It can be reproduced by running coverage tools like dotCover or OpenCover.

Consider adding a GeneratedCode attribute (or reuse CompilerGenerated?)

I'm submitting a...

  • Feature request

Current behavior

Consider adding CompilerGeneratedAttribute (or another custom method) to generated methods.

Expected behavior

I have some developer-guiding unit tests that validate developer-written code follows some guidelines. The code generated by Uno is great, but I need to ignore it from the tests. I am going to work around this and add explicit understanding of GeneratedEquality to try to ignore those methods, but it would've been nice to have the methods noted first-hand as machine-generated methods (consider maybe for StyleCop rules?)

Minimal reproduction of the problem with instructions

N/A for non-bug

Environment

Nuget Package: Uno.CodeGen

Package Version(s): 1.32.0

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [x] Windows
- [ ] Build tasks

Visual Studio
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )
- [x] 2019

Relevant plugins
- [ ] Resharper (version: )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.