Skip to content

REQUEST: Pattern matching/better type inferencing with generics. #5023

Closed

Description

@TonyValenti

Hi Roslyn Team:
When I was reading one of the feature requests from earlier:
#2212 (comment)

It made me think of something I have really been wanting as of late:

Pattern matching/better type inferencing with generics.

Today I can write code like this:

        private static void Foo<T, X>(T Object) where T : IEnumerable<X>, IComparable<X> {
            //Do Something
        }

        private class MyClass : IComparable<String>, IEnumerable<String> {
            int IComparable<string>.CompareTo(string other) {
                throw new NotImplementedException();
            }

            IEnumerator IEnumerable.GetEnumerator() {
                throw new NotImplementedException();
            }

            IEnumerator<string> IEnumerable<string>.GetEnumerator() {
                throw new NotImplementedException();
            }
        }

        private static void CallMyFunction() {
            var C = new MyClass();

            Foo<MyClass, String>(C);
        }

There is nastiness is in how I have to call the function.

        private static void CallMyFunction() {
            var C = new MyClass();

            Foo<MyClass, String>(C);
        }

In this example, I feel as though Foo should automatically figure out the type parameters and I should be able to call the method as follows:

        private static void CallMyFunction() {
            var C = new MyClass();

            Foo(C);
        }

Activity

  1. gafter commented on Sep 6, 2015

    @gafter
    Member

    It sounds like you want the bounds of type variables to participate in type inference. I can see us taking such a well-specified and prototyped change.

  2. added
    help wanted
    on Sep 6, 2015
  3. TonyValenti commented on Sep 6, 2015

    @TonyValenti
    Author

    That sounds great! This will make my code so much cleaner. Thank you!

    On Sunday, September 6, 2015, Neal Gafter notifications@github.com wrote:

    It sounds like you want the bounds of type variables to participate in
    type inference. I can see us taking such a well-specified and prototyped
    change.

    —
    Reply to this email directly or view it on GitHub
    #5023 (comment).

    Tony Valenti

  4. gafter commented on Sep 6, 2015

    @gafter
    Member

    @TonyValenti I've labeled this "up for grabs" in case someone from the community has the time and interest to take it on.

  5. HellBrick commented on Nov 7, 2015

    @HellBrick

    I think I might be able to take a shot at this. I'm currently toying with a prototype of this that works by promoting generic constraints of inferred type parameters to fake arguments. The idea is to add a 4th step to the phase 2 of the inference that works this way:

    1. For every constraint type of every type parameter that has been successfully fixed a new fake argument is added. The fixed type is used as an argument type, its default value is passed as an argument expression and the formal argument type is set to the constraint type. This is done no more than once per type parameter.
    2. Phase 1 is invoked for the newly added arguments.
    3. Phase 2 body is considered to make some progress if any constraints were promoted, and is considered to make no progress otherwise.

    Here's an example to illustrate the idea:

        class Item : IComparable<string>
        {
        }
    
        class Container : IEnumerable<Item>
        {
        }
    
        class Whatever
        {
            void DoSomething<TContainer, TItem, TComparand>( TContainer container )
                where TContainer : IEnumerable<TItem>
                where TItem : IComparable<TComparand>
            {
            }
    
            void Invoke()
            {
                DoSomething( new Container() );
            }
        }

    The type inferrer that exists today is able to infer that TContainer is Container and then fails. Here's what happens if the idea I've described is implemented:

    • We have a type parameter TContainer that's fixed to Container. It has IEnumerable<TItem> constraint which is promoted to a fake argument like this:
        class Whatever
        {
            void DoSomething<TContainer, TItem, TComparand>( TContainer container, IEnumerable<TItem> x )
                where TContainer : IEnumerable<TItem>
                where TItem : IComparable<TComparand>
            {
            }
    
            void Invoke()
            {
                DoSomething( new Container(), default( Container ) );
            }
        }
    • Phase 1 is invoked for the argument x, providing us bounds for TItem type.
    • Phase 2 body is repeated like it typically does, fixing TItem to Item.
    • Old phase 2 logic can't progress it any further, but now that TItem is fixed, we can promote its constraint like this:
        class Whatever
        {
            void DoSomething<TContainer, TItem, TComparand>( TContainer container, IEnumerable<TItem> x, IComparable<TComparand> y )
                where TContainer : IEnumerable<TItem>
                where TItem : IComparable<TComparand>
            {
            }
    
            void Invoke()
            {
                DoSomething( new Container(), default( Container ), default( Item ) );
            }
        }
    • Phase 1 is invoked for the argument y
    • Phase 2 continues its loop and is now able to fix TComparand to string
    • The fake arguments obviously exist only in the type inferrer's imagination =)

    So what do you guys think? This seems to be working for the simple scenarios it's designed for, but there's a lot of scary stuff in the type inference that I haven't even begun to understand, so it would be useful to get input from someone who has been familiar with this part of the compiler for more than a day ;)

  6. bbarry commented on Nov 7, 2015

    @bbarry

    I presume your phase 2 would still fail if Item were this instead:

    class Item : IComparable<string>, IComparable<IEnumerable<char>>
    {
    }
    
  7. HellBrick commented on Nov 7, 2015

    @HellBrick

    Yep, it fails for the same reason the following fails today (because in the end it boils down to exactly the same problem):

        class Item : IComparable<string>, IComparable<IEnumerable<char>> {}
        void Compare<T>( IComparable<T> comparable ) {}
    
        void Call()
        {
            Compare( default(Item) );
        }
  8. HellBrick commented on Nov 8, 2015

    @HellBrick

    I've submitted a PR with the prototype to provide something less abstract to discuss.

  9. MrJul commented on Nov 16, 2015

    @MrJul
    Contributor

    I know the Roslyn team is probably busy with Update 1, but it would be nice to get some feedback on @HellBrick's great PR :)

  10. gafter commented on Nov 16, 2015

    @gafter
    Member

    @HellBrick We'll take a look at this, thanks!

  11. gafter commented on Nov 16, 2015

    @gafter
    Member

    Removing "Up For Grabs" as @HellBrick has grabbed it!

  12. removed
    help wanted
    on Nov 16, 2015
  13. self-assigned this
    on Nov 20, 2015
  14. 15 remaining items

  15. soyeyalon commented on Jun 16, 2016

    @soyeyalon

    @gafter It's always possible to have something like M<>("foo"); to disambiguate, it was suggested in multiple posts before, what do you think about it?

    Personally, I feel like this feature should be considered it takes away the verbosity of generics and hopefully you will come up with ways to do it! I'm really looking forward to this one.

    p.s. A tool to modify the code is a great idea the question is whether people will want to run such a tool.

  16. gafter commented on Jun 16, 2016

    @gafter
    Member

    @eyalsk How does that make this not a breaking change?

  17. TonyValenti commented on Jun 16, 2016

    @TonyValenti
    Author

    Because today you have to specify type parameters when you call a
    function. You can't simply do Foo<>(Param)

    On Thu, Jun 16, 2016 at 10:47 AM, Neal Gafter notifications@github.com
    wrote:

    @eyalsk https://github.com/eyalsk How does that make this not a
    breaking change?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #5023 (comment), or mute
    the thread
    https://github.com/notifications/unsubscribe/AM-qVl43IPPrkwASXIUQwbYVYevUvADsks5qMXAogaJpZM4F4Szu
    .

    Tony Valenti

  18. soyeyalon commented on Jun 16, 2016

    @soyeyalon

    @gafter Well, can you do M<>("foo") today? afaik it's an error but dunno maybe I'm unaware and it's actually a breaking change, can you please elaborate?

  19. HellBrick commented on Jun 16, 2016

    @HellBrick

    I think adding a new syntax for enabling new type inference features is not a good idea. First, it would be very confusing to have two subtly different type inference mechanisms for M("foo") and M<>("foo"). Second, it doesn't fix the long-term problem of handling the breaking changes: even if the new syntax ships, there can easily be future improvements that will introduce new breaking changes for this new syntax and we will once again have exactly the same problem we're discussing right now.

    So I believe introducing an analyzer-like mechanism of detecting and fixing the code affected by the breaking changes is the way to go here, like mentioned in #7850 (comment). I'm really curious about the details of how this is supposed to work though. @gafter, is there an issue/document that tracks/describes this? And if there isn't one, can you tell us what the current thinking on this matter is? I guess it has been discussed by LDM quite a few times during the years of developing the language, so you guys should have some knowledge of what the main challenges are and some ideas on solving them.

  20. soyeyalon commented on Jun 16, 2016

    @soyeyalon

    @HellBrick

    I think adding a new syntax for enabling new type inference features is not a good idea. First, it would be very confusing to have two subtly different type inference mechanisms for M("foo") and M<>("foo")

    I totally agree with you that having a tool to modify the code and accommodate the required changes is way better than introducing a new syntax, simply because if there's no need for a new syntax then no one needs to learn anything new, the old way was always to introduce new syntax to evolve a language if and only if it's necessary so my proposal came before I knew a tool is proposed.

    However, in cases that a tool wouldn't be feasible for whatever reason (and in all honesty I don't think that there should be a reason not to change it but still), would you rather not have it at all?

  21. HellBrick commented on Jun 17, 2016

    @HellBrick

    However, in cases that a tool wouldn't be feasible for whatever reason (and in all honesty I don't think that there should be a reason not to change it but still), would you rather not have it at all?

    If we're talking about the breaking changes in general, then I'd say it depends on the discoverability of the breaks. If the code just stops compiling after an upgrade, that's okay: you have a clear error and a pretty good idea how to fix it. But some breaking changes are next to impossible to detect manually, even if they are properly documented and understood. The inference changes caused by the current issue is a good example of that. Combing though all the overload calls that could have changed their behavior after recompiling is very difficult and error-prone even if you know the codebase well. So I think it wouldn't be nice to ship such a feature without an automatic way to find the breaks.

    I don't think the tool is too difficult to write, though. Even if designing a proper upgrade path that provides a nice user experience across all possible IDEs and console compilers could be tricky, writing a simple Roslyn analyzer + code fix per a breaking change seems quite possible.

  22. ThatRendle commented on Jun 21, 2016

    @ThatRendle

    This could really optimize LINQ extension methods (and similar).

    Example: given this slightly more involved version of IEnumerable

        public interface IExplicitEnumerable<out T, out TEnumerator>
            where TEnumerator : IEnumerator<T>
        {
            TEnumerator GetEnumerator();
        }

    one could write generic forms of LINQ extension methods that look something like this:

        public static class InferredLinq
        {
            public static void Run<T, TAble, TAtor>(this TAble source, Action<T> func)
                where TAtor: IEnumerator<T>
                where TAble : IExplicitEnumerable<T, TAtor>
            {
                var enumerator = source.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    func(enumerator.Current);
                }
                enumerator.Dispose();
            } 
        }

    The authors of types that implement IEnumerable<T> then have the option of implementing this extra interface with IExplicitEnumerable<T, CustomEnumerator<T>>.

    Advantages:

    • For all types, method invocation against the type itself instead of indirect via the interface (i.e. faster)
    • For value types, no boxing allocations

    It's possible at present if you supply the explicit type parameters:

        range.Run<int, Range, Range.RangeEnumerator>((n) => Console.WriteLine(n.ToString()));

    but that's hideous, especially since you have to remember what the CustomEnumerator<T> class was for any implementing type. Compiler inference as proposed here would take care of that.

  23. masaeedu commented on Jul 15, 2016

    @masaeedu

    +1 for letting the pressure for a backwards-compat analyzer continue to build, rather than relieving it by contorting language features to squeak past backwards-compat issues. @gafter would you folks be more open to proposals with backward compat issues if they came with Roslyn refactorings to address them? It shouldn't be too difficult to write one that addresses the problem you brought up, for example, although I haven't thought about all edge cases.

  24. Thaina commented on Dec 24, 2016

    @Thaina

    Wish for this too

  25. gafter commented on Mar 27, 2017

    @gafter
    Member

    We are now taking language feature discussion in other repositories:

    Features that are under active design or development, or which are "championed" by someone on the language design team, have already been moved either as issues or as checked-in design documents. For example, the proposal in this repo "Proposal: Partial interface implementation a.k.a. Traits" (issue 16139 and a few other issues that request the same thing) are now tracked by the language team at issue 52 in https://github.com/dotnet/csharplang/issues, and there is a draft spec at https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md and further discussion at issue 288 in https://github.com/dotnet/csharplang/issues. Prototyping of the compiler portion of language features is still tracked here; see, for example, https://github.com/dotnet/roslyn/tree/features/DefaultInterfaceImplementation and issue 17952.

    In order to facilitate that transition, we have started closing language design discussions from the roslyn repo with a note briefly explaining why. When we are aware of an existing discussion for the feature already in the new repo, we are adding a link to that. But we're not adding new issues to the new repos for existing discussions in this repo that the language design team does not currently envision taking on. Our intent is to eventually close the language design issues in the Roslyn repo and encourage discussion in one of the new repos instead.

    Our intent is not to shut down discussion on language design - you can still continue discussion on the closed issues if you want - but rather we would like to encourage people to move discussion to where we are more likely to be paying attention (the new repo), or to abandon discussions that are no longer of interest to you.

    If you happen to notice that one of the closed issues has a relevant issue in the new repo, and we have not added a link to the new issue, we would appreciate you providing a link from the old to the new discussion. That way people who are still interested in the discussion can start paying attention to the new issue.

    Also, we'd welcome any ideas you might have on how we could better manage the transition. Comments and discussion about closing and/or moving issues should be directed to #18002. Comments and discussion about this issue can take place here or on an issue in the relevant repo.


    As described in #5023 (comment), the LDM looked at this and found it to be a breaking change, and one that we would therefore be quite unlikely to ever take.

  26. declard commented on Nov 9, 2019

    @declard

    I'm wondering why a syntax like Method<Type1, _, _, _, Type5<_>, _>(args) was not proposed. It seems to be backward compatible - just tell the compiler "well, i have some generic parameters there, could you infer them for me from the context?"

  27. ahmednfwela commented on Dec 7, 2021

    @ahmednfwela

    why was this ruled out as a breaking change ?
    it appears the only case where this would be a breaking change is if there is ambiguity, so why not fallback to old behavior of needing to explicitly define all type arguments when there is ambiguity ?

    so for this case:

    void M(object) {}
    void M<T, U>(T t) where T : IEnumerable<U> {}
    
    M("foo")
    1. determine if there are overloads for M with ambiguous constraints
    2. if no: assign the type arguments based on input
    3. if yes: check for a flag (e.g. PreferMostStrictTypeArgumentOverload)
    4. if flag is set: use the M<T,U> overload
    5. if flag is not set (default): use the M(object) overload
  28. CyrusNajmabadi commented on Dec 7, 2021

    @CyrusNajmabadi
    Contributor

    @ahmednfwela language design happens over at dotnet/csharplang now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

4 - In ReviewArea-Language DesignFeature Request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions