@@ -705,6 +705,36 @@ trait Implicits { self: Typer =>
705705 EmptyTree
706706 }
707707
708+ lazy val synthesizedTypeTest : SpecialHandler =
709+ (formal, span) => implicit ctx => formal.argInfos match {
710+ case arg1 :: arg2 :: Nil if ! defn.isBottomClass(arg2.typeSymbol) =>
711+ val tp1 = fullyDefinedType(arg1, " TypeTest argument" , span)
712+ val tp2 = fullyDefinedType(arg2, " TypeTest argument" , span)
713+ val sym2 = tp2.typeSymbol
714+ if tp1 <:< tp2 then
715+ ref(defn.TypeTestModule_identity ).appliedToType(tp2).withSpan(span)
716+ else if sym2 == defn.AnyValClass || sym2 == defn.AnyRefAlias || sym2 == defn.ObjectClass then
717+ EmptyTree
718+ else
719+ // Generate SAM: (s: <tp1>) => if s.isInstanceOf[s.type & <tp2>] then Some(s.asInstanceOf[s.type & <tp2>]) else None
720+ def body (args : List [Tree ]): Tree = {
721+ val arg :: Nil = args
722+ val t = arg.tpe & tp2
723+ If (
724+ arg.select(defn.Any_isInstanceOf ).appliedToType(t),
725+ ref(defn.SomeClass .companionModule.termRef).select(nme.apply)
726+ .appliedToType(t)
727+ .appliedTo(arg.select(nme.asInstanceOf_).appliedToType(t)),
728+ ref(defn.NoneModule ))
729+ }
730+ val tpe = MethodType (List (nme.s))(_ => List (tp1), mth => defn.OptionClass .typeRef.appliedTo(mth.newParamRef(0 ) & tp2))
731+ val meth = ctx.newSymbol(ctx.owner, nme.ANON_FUN , Synthetic | Method , tpe, coord = span)
732+ val typeTestType = defn.TypeTestClass .typeRef.appliedTo(List (tp1, tp2))
733+ Closure (meth, tss => body(tss.head).changeOwner(ctx.owner, meth), targetType = typeTestType).withSpan(span)
734+ case _ =>
735+ EmptyTree
736+ }
737+
708738 /** Synthesize the tree for `'[T]` for an implicit `scala.quoted.Type[T]`.
709739 * `T` is deeply dealiased to avoid references to local type aliases.
710740 */
@@ -1076,6 +1106,7 @@ trait Implicits { self: Typer =>
10761106 if (mySpecialHandlers == null )
10771107 mySpecialHandlers = List (
10781108 defn.ClassTagClass -> synthesizedClassTag,
1109+ defn.TypeTestClass -> synthesizedTypeTest,
10791110 defn.QuotedTypeClass -> synthesizedTypeTag,
10801111 defn.QuoteContextClass -> synthesizedQuoteContext,
10811112 defn.EqlClass -> synthesizedEq,
0 commit comments