Skip to content

Commit 9090864

Browse files
committed
Create extension method when infer method is not possible
1 parent 68396ca commit 9090864

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

presentation-compiler/src/main/dotty/tools/pc/InferredMethodProvider.scala

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,25 @@ final class InferredMethodProvider(
227227
s"\n$indent$signature",
228228
)
229229
) ::: imports
230-
case None => Nil
230+
case None =>
231+
extensionMethodEdits(signature, container)
232+
233+
def extensionMethodEdits(signature: String, container: Tree): List[TextEdit] =
234+
val containerTypeStr = printType(container.tpe.widenDealias)
235+
236+
val pos = insertPosition()
237+
val indent = indentation(params.text(), pos.start - 1)
238+
val extensionSignature = s"extension (x: $containerTypeStr)\n $indent$signature"
239+
240+
val lspPos = pos.toLsp
241+
lspPos.setEnd(lspPos.getStart())
242+
243+
List(
244+
TextEdit(
245+
lspPos,
246+
s"$extensionSignature\n$indent",
247+
)
248+
) ::: imports
231249

232250
path match
233251
/**

presentation-compiler/test/dotty/tools/pc/tests/edit/InsertInferredMethodSuite.scala

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,48 @@ class InsertInferredMethodSuite extends BaseCodeActionSuite:
495495
|""".stripMargin,
496496
)
497497

498+
@Test def `extension-method` =
499+
checkEdit(
500+
"""|object Main:
501+
| val x = 1
502+
| x.<<incr>>
503+
|""".stripMargin,
504+
"""|object Main:
505+
| val x = 1
506+
| extension (x: Int)
507+
| def incr = ???
508+
| x.incr
509+
|""".stripMargin,
510+
)
511+
512+
@Test def `extension-method-1` =
513+
checkEdit(
514+
"""|object Main:
515+
| val x = 1
516+
| x.<<add>>(2)
517+
|""".stripMargin,
518+
"""|object Main:
519+
| val x = 1
520+
| extension (x: Int)
521+
| def add(arg0: Int) = ???
522+
| x.add(2)
523+
|""".stripMargin,
524+
)
525+
526+
@Test def `extension-method-2` =
527+
checkEdit(
528+
"""|object Main:
529+
| val s = "hello"
530+
| s.<<shout>>
531+
|""".stripMargin,
532+
"""|object Main:
533+
| val s = "hello"
534+
| extension (x: String)
535+
| def shout = ???
536+
| s.shout
537+
|""".stripMargin,
538+
)
539+
498540
def checkEdit(
499541
original: String,
500542
expected: String

0 commit comments

Comments
 (0)