Skip to content

Commit cb9aa46

Browse files
committed
Implement Fields as a Selectable type member
Subclasses of Selectable can instantiate Fields to a named tuple type that provides possible selection names and their types on instances of the type. See: https://contributors.scala-lang.org/t/expanding-changing-selectable-based-on-upcoming-named-tuples-feature/6395/5
1 parent b3fb14d commit cb9aa46

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

compiler/src/dotty/tools/dotc/core/StdNames.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@ object StdNames {
362362
val EnumValue: N = "EnumValue"
363363
val ExistentialTypeTree: N = "ExistentialTypeTree"
364364
val Flag : N = "Flag"
365+
val Fields: N = "Fields"
365366
val From: N = "From"
366367
val Ident: N = "Ident"
367368
val Import: N = "Import"

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -782,6 +782,19 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
782782
else
783783
typedDynamicSelect(tree2, Nil, pt)
784784
else
785+
if qual.tpe.derivesFrom(defn.SelectableClass)
786+
&& selName.isTermName && !isDynamicExpansion(tree)
787+
&& !pt.isInstanceOf[FunOrPolyProto] && pt != LhsProto
788+
then
789+
val fieldsType = qual.tpe.select(tpnme.Fields).dealias.simplified
790+
val fields = fieldsType.namedTupleElementTypes
791+
typr.println(i"try dyn select $qual, $selName, $fields")
792+
fields.find(_._1 == selName) match
793+
case Some((fieldName, fieldType)) =>
794+
val tree2 = cpy.Select(tree0)(untpd.TypedSplice(qual), selName)
795+
val sel = typedDynamicSelect(tree2, Nil, pt)
796+
return sel.cast(fieldType)
797+
case _ =>
785798
assignType(tree,
786799
rawType match
787800
case rawType: NamedType =>

library/src/scala/Selectable.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ package scala
2222
* In this case the call will synthesize `Class` arguments for the erasure of
2323
* all formal parameter types of the method in the structural type.
2424
*/
25-
trait Selectable extends Any
25+
trait Selectable extends Any:
26+
type Fields // TODO: add <: NamedTyple.AnyNamedTuple when NamedTuple is no longer experimental
2627

2728
object Selectable:
2829
/* Scala 2 compat + allowing for cross-compilation:

0 commit comments

Comments
 (0)