Skip to content

Opaque type extension method puzzler #7821

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
nicolasstucki opened this issue Dec 20, 2019 · 6 comments
Closed

Opaque type extension method puzzler #7821

nicolasstucki opened this issue Dec 20, 2019 · 6 comments
Assignees

Comments

@nicolasstucki
Copy link
Contributor

minimized code

X and MyX are both opaque typed defining extension methods in the same way.

object XObject {
  opaque type X = Int

  def anX: X = 5

  given ops: Object {
    def (x: X) + (y: X): X = x + y
  }
}

object MyXObject {
  opaque type MyX = XObject.X

  def anX: MyX = XObject.anX

  given ops: Object {
    def (x: MyX) + (y: MyX): MyX = x + y
  }
}

object Main extends App {
  println(XObject.anX + XObject.anX) // prints 10
  println(MyXObject.anX + MyXObject.anX) // infinite loop
}

The issue is that when we look + in def (x: MyX) + (y: MyX): MyX = x + y we know that x: XObject.X and therfore both XObject.ops.+ and MyXObject.ops.+ are valid extensions for + but MyXObject.ops.+ is chosen becuase it is closer in scope. The hope here wast to use the primitive XObject.ops.+ on x.

Defining the extensions outside MyXObject fixes the issue but then the extension are not automatically available for the opaque type MyXObject.X.

@nicolasstucki
Copy link
Contributor Author

This came from an issue encountered in #7795 which was minimized to

object Foo {
  opaque type MyArray = Array[Int]

  def anArray: MyArray = Array(1, 2, 3)

  given ops: Object {
    def (arr: MyArray) drop(n: Int): MyArray = arr.drop(n)
  }
}

object Main extends App {
  println(Foo.anArray.drop(1))
}

@nicolasstucki
Copy link
Contributor Author

This can be worked around with

def (x: MyX) + (y: MyX): MyX = XObject.ops.+(x)(y)

@odersky
Copy link
Contributor

odersky commented Dec 22, 2019

@nicolasstucki What do you suggest should happen here? I agree it might be surprising, but as far as I can see, that's how it is supposed to work, no?

@nicolasstucki
Copy link
Contributor Author

Maybe this should have a warning.

@odersky
Copy link
Contributor

odersky commented Dec 25, 2019

What would be the condition in which a warning should be issued?

@nicolasstucki
Copy link
Contributor Author

In general, if the RHS of the method only calls itself we can warn that this is an infinite recursive call.

anatoliykmetyuk added a commit that referenced this issue Jan 9, 2020
Fix #7821: Warn on simple infinite tailrec loops
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants