From 47bfd744177121de08fed489a5b0b1b59a1ae06a Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Wed, 21 Mar 2012 16:02:21 -0700 Subject: Ctor default-getters unique name and are typed in constructor context --- src/compiler/scala/reflect/internal/NameManglers.scala | 9 ++++++--- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/NameManglers.scala b/src/compiler/scala/reflect/internal/NameManglers.scala index 48f21721da..5ec8d08ffb 100644 --- a/src/compiler/scala/reflect/internal/NameManglers.scala +++ b/src/compiler/scala/reflect/internal/NameManglers.scala @@ -77,6 +77,7 @@ trait NameManglers { val PROTECTED_SET_PREFIX = PROTECTED_PREFIX + "set" val SINGLETON_SUFFIX = ".type" val SUPER_PREFIX_STRING = "super$" + val INIT_DEFAULT_PREFIX = "init$" val TRAIT_SETTER_SEPARATOR_STRING = "$_setter_$" val SETTER_SUFFIX: TermName = encode("_=") @@ -170,13 +171,15 @@ trait NameManglers { } def defaultGetterName(name: Name, pos: Int): TermName = { - val prefix = if (isConstructorName(name)) "init" else name + val prefix = if (isConstructorName(name)) INIT_DEFAULT_PREFIX else name newTermName(prefix + DEFAULT_GETTER_STRING + pos) } def defaultGetterToMethod(name: Name): TermName = { val p = name.pos(DEFAULT_GETTER_STRING) - if (p < name.length) name.toTermName.subName(0, p) - else name.toTermName + if (p < name.length) { + val q = name.toTermName.subName(0, p) + if (q.decoded == INIT_DEFAULT_PREFIX) CONSTRUCTOR else q + } else name.toTermName } // This isn't needed at the moment since I fixed $class$1 but diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index ad48712a32..c3a7453df0 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -4399,7 +4399,9 @@ trait Typers extends Modes with Adaptations with PatMatVirtualiser { typedValDef(vdef) case ddef @ DefDef(_, _, _, _, _, _) => - newTyper(context.makeNewScope(tree, sym)).typedDefDef(ddef) + // flag default getters for constructors. An actual flag would be nice. See SI-5543. + val flag = ddef.mods.hasDefaultFlag && nme.defaultGetterToMethod(sym.name) == nme.CONSTRUCTOR + newTyper(context.makeNewScope(tree, sym)).constrTyperIf(flag).typedDefDef(ddef) case tdef @ TypeDef(_, _, _, _) => typedTypeDef(tdef) -- cgit v1.2.3 From 77b577a5aeab782b64b39b3a812c35fdd8ab265a Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Fri, 27 Apr 2012 02:02:55 -0700 Subject: SI-5543: Ctor default arg wrongly scoped (revised) This patch fixes the motivating bug by detecting when a method is the default arg getter for a constructor parameter. That requires fixing a secondary bug where an arbitrary string was used to encode in lieu of .encode. There is no speculative mangling. --- src/compiler/scala/reflect/internal/Flags.scala | 2 +- src/compiler/scala/reflect/internal/StdNames.scala | 12 +++++++++--- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 4 +++- test/files/run/t5543.scala | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/Flags.scala b/src/compiler/scala/reflect/internal/Flags.scala index c6901d1cf6..e6820cf78a 100644 --- a/src/compiler/scala/reflect/internal/Flags.scala +++ b/src/compiler/scala/reflect/internal/Flags.scala @@ -260,7 +260,7 @@ class Flags extends ModifierFlags { /** When a symbol for a default getter is created, it inherits these * flags from the method with the default. Other flags applied at creation - * time are SYNTHETIC, DEFAULTPARAM, and possibly OVERRIDE. + * time are SYNTHETIC, DEFAULTPARAM, and possibly OVERRIDE, and maybe PRESUPER. */ final val DefaultGetterFlags = PRIVATE | PROTECTED | FINAL diff --git a/src/compiler/scala/reflect/internal/StdNames.scala b/src/compiler/scala/reflect/internal/StdNames.scala index a55efea2e6..76660ac3f1 100644 --- a/src/compiler/scala/reflect/internal/StdNames.scala +++ b/src/compiler/scala/reflect/internal/StdNames.scala @@ -272,6 +272,7 @@ trait StdNames { val BITMAP_PREFIX = "bitmap$" val CHECK_IF_REFUTABLE_STRING = "check$ifrefutable$" val DEFAULT_GETTER_STRING = "$default$" + val DEFAULT_GETTER_INIT_STRING = "$lessinit$greater" // CONSTRUCTOR.encoded, less is more val DO_WHILE_PREFIX = "doWhile$" val EVIDENCE_PARAM_PREFIX = "evidence$" val EXCEPTION_RESULT_PREFIX = "exceptionResult" @@ -413,14 +414,19 @@ trait StdNames { name.subName(0, name.length - SETTER_SUFFIX.length) } + // Nominally, name$default$N, encoded for def defaultGetterName(name: Name, pos: Int): TermName = { - val prefix = if (isConstructorName(name)) "init" else name + val prefix = if (isConstructorName(name)) DEFAULT_GETTER_INIT_STRING else name newTermName(prefix + DEFAULT_GETTER_STRING + pos) } + // Nominally, name from name$default$N, CONSTRUCTOR for def defaultGetterToMethod(name: Name): TermName = { val p = name.pos(DEFAULT_GETTER_STRING) - if (p < name.length) name.toTermName.subName(0, p) - else name.toTermName + if (p < name.length) { + val q = name.toTermName.subName(0, p) + // i.e., if (q.decoded == CONSTRUCTOR.toString) CONSTRUCTOR else q + if (q.toString == DEFAULT_GETTER_INIT_STRING) CONSTRUCTOR else q + } else name.toTermName } // If the name ends with $nn where nn are diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 1392f39c48..ccccf2de99 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -4649,7 +4649,9 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser case ddef @ DefDef(_, _, _, _, _, _) => // flag default getters for constructors. An actual flag would be nice. See SI-5543. - val flag = ddef.mods.hasDefaultFlag && nme.defaultGetterToMethod(sym.name) == nme.CONSTRUCTOR + //val flag = ddef.mods.hasDefaultFlag && ddef.mods.hasFlag(PRESUPER) + val flag = ddef.mods.hasDefaultFlag && sym.owner.isModuleClass && + nme.defaultGetterToMethod(sym.name) == nme.CONSTRUCTOR newTyper(context.makeNewScope(tree, sym)).constrTyperIf(flag).typedDefDef(ddef) case tdef @ TypeDef(_, _, _, _) => diff --git a/test/files/run/t5543.scala b/test/files/run/t5543.scala index 9d9c645d7a..651bc7f2b2 100644 --- a/test/files/run/t5543.scala +++ b/test/files/run/t5543.scala @@ -10,7 +10,7 @@ object Test extends Function0[Int] { } object A { val v = 5 - // should happily coexist with default getters + // should happily coexist with default getters, in a happier world def init(x: Function0[Int] = Test.this)(a: Int = v, b: Int = v * x()) = x.toString +", "+ a +", "+ b override def toString = "A" } -- cgit v1.2.3 From f004e99b2fb7450fbfd0c5d96a4b2406cb8fc142 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Fri, 27 Apr 2012 17:11:36 +0200 Subject: small tree attachment refactoring: firstAttachment --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 3 ++- src/library/scala/reflect/api/Trees.scala | 11 +++++------ 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 41b896eb93..2410117af7 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2209,7 +2209,8 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser def adaptCase(cdef: CaseDef, mode: Int, tpe: Type): CaseDef = deriveCaseDef(cdef)(adapt(_, mode, tpe)) // takes untyped sub-trees of a match and type checks them - def typedMatch(selector0: Tree, cases: List[CaseDef], mode: Int, resTp: Type) = { + def typedMatch(selector0: Tree, cases: List[CaseDef], mode: Int, resTp: Type): Match = { + // strip off the annotation as it won't type check val (selector, doTranslation) = selector0 match { case Annotated(Ident(nme.synthSwitch), selector) => (selector, false) case s => (s, true) diff --git a/src/library/scala/reflect/api/Trees.scala b/src/library/scala/reflect/api/Trees.scala index f1e9cc13ca..b82972c9bc 100644 --- a/src/library/scala/reflect/api/Trees.scala +++ b/src/library/scala/reflect/api/Trees.scala @@ -110,13 +110,12 @@ trait Trees { self: Universe => def withoutAttachment(att: Any): this.type = { detach(att); this } def attachment[T: ClassTag]: T = attachmentOpt[T] getOrElse { throw new Error("no attachment of type %s".format(classTag[T].erasure)) } def attachmentOpt[T: ClassTag]: Option[T] = + firstAttachment { case attachment if attachment.getClass == classTag[T].erasure => attachment.asInstanceOf[T] } + + def firstAttachment[T](p: PartialFunction[Any, T]): Option[T] = rawatt match { - case NontrivialAttachment(pos, payload) => - val index = payload.indexWhere(p => p.getClass == classTag[T].erasure) - if (index != -1) Some(payload(index).asInstanceOf[T]) - else None - case _ => - None + case NontrivialAttachment(pos, payload) => payload.collectFirst(p) + case _ => None } private[this] var rawtpe: Type = _ -- cgit v1.2.3 From bc860f3a31db8b6f37c9931f2bf4712fed06d486 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Fri, 27 Apr 2012 17:12:03 +0200 Subject: move more of match translation out of typers reduce duplication in [typed/translated]Match & co in preparation of moving match translation out of the type checker, setting everything up so that we can simply type Match nodes first, then translate them separately using DefaultOverrideMatchAttachment to remember the default override for a match that defines a PartialFunction only strip annotations when translating match or cps in matches fails widen selector type when translating match-derived partialfunction slightly less cps-specific --- .../scala/reflect/internal/Definitions.scala | 2 - .../tools/nsc/typechecker/PatMatVirtualiser.scala | 34 +++++- .../scala/tools/nsc/typechecker/Typers.scala | 121 +++++++++------------ 3 files changed, 78 insertions(+), 79 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/Definitions.scala b/src/compiler/scala/reflect/internal/Definitions.scala index 23d517eba9..7347249b76 100644 --- a/src/compiler/scala/reflect/internal/Definitions.scala +++ b/src/compiler/scala/reflect/internal/Definitions.scala @@ -412,8 +412,6 @@ trait Definitions extends reflect.api.StandardDefinitions { lazy val JavaRepeatedParamClass = specialPolyClass(tpnme.JAVA_REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => arrayType(tparam.tpe)) lazy val RepeatedParamClass = specialPolyClass(tpnme.REPEATED_PARAM_CLASS_NAME, COVARIANT)(tparam => seqType(tparam.tpe)) - lazy val MarkerCPSTypes = getClassIfDefined("scala.util.continuations.cpsParam") - def isByNameParamType(tp: Type) = tp.typeSymbol == ByNameParamClass def isScalaRepeatedParamType(tp: Type) = tp.typeSymbol == RepeatedParamClass def isJavaRepeatedParamType(tp: Type) = tp.typeSymbol == JavaRepeatedParamClass diff --git a/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala b/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala index e5b5746e8d..b3f4b10865 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala @@ -35,6 +35,9 @@ trait PatMatVirtualiser extends ast.TreeDSL { self: Analyzer => val SYNTH_CASE = Flags.CASE | SYNTHETIC + object TranslatedMatchAttachment + case class DefaultOverrideMatchAttachment(default: Tree) + object vpmName { val one = newTermName("one") val drop = newTermName("drop") @@ -136,15 +139,36 @@ trait PatMatVirtualiser extends ast.TreeDSL { self: Analyzer => * thus, you must typecheck the result (and that will in turn translate nested matches) * this could probably optimized... (but note that the matchStrategy must be solved for each nested patternmatch) */ - def translateMatch(scrut: Tree, cases: List[CaseDef], pt: Type, scrutType: Type, matchFailGenOverride: Option[Tree => Tree] = None): Tree = { + def translateMatch(match_ : Match): Tree = { + val Match(selector, cases) = match_ + // we don't transform after uncurry // (that would require more sophistication when generating trees, // and the only place that emits Matches after typers is for exception handling anyway) - if(phase.id >= currentRun.uncurryPhase.id) debugwarn("running translateMatch at "+ phase +" on "+ scrut +" match "+ cases) + if(phase.id >= currentRun.uncurryPhase.id) debugwarn("running translateMatch at "+ phase +" on "+ selector +" match "+ cases) // println("translating "+ cases.mkString("{", "\n", "}")) - val scrutSym = freshSym(scrut.pos, pureType(scrutType)) setFlag SYNTH_CASE + + def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { + case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) + case _ => tp + } + + val selectorTp = repeatedToSeq(elimAnonymousClass(selector.tpe.widen.withoutAnnotations)) + val pt0 = match_.tpe + + // we've packed the type for each case in typedMatch so that if all cases have the same existential case, we get a clean lub + // here, we should open up the existential again + // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala + // TODO: fix skolemizeExistential (it should preserve annotations, right?) + val pt = repeatedToSeq(pt0.skolemizeExistential(context.owner, context.tree) withAnnotations pt0.annotations) + + // the alternative to attaching the default case override would be to simply + // append the default to the list of cases and suppress the unreachable case error that may arise (once we detect that...) + val matchFailGenOverride = match_ firstAttachment {case DefaultOverrideMatchAttachment(default) => ((scrut: Tree) => default)} + + val selectorSym = freshSym(selector.pos, pureType(selectorTp)) setFlag SYNTH_CASE // pt = Any* occurs when compiling test/files/pos/annotDepMethType.scala with -Xexperimental - combineCases(scrut, scrutSym, cases map translateCase(scrutSym, pt), pt, matchOwner, matchFailGenOverride) + combineCases(selector, selectorSym, cases map translateCase(selectorSym, pt), pt, matchOwner, matchFailGenOverride) } // return list of typed CaseDefs that are supported by the backend (typed/bind/wildcard) @@ -1586,7 +1610,7 @@ class Foo(x: Other) { x._1 } // no error in this order else (REF(scrutSym) DOT (nme.toInt)) Some(BLOCK( VAL(scrutSym) === scrut, - Match(gen.mkSynthSwitchSelector(scrutToInt), caseDefsWithDefault) // add switch annotation + Match(scrutToInt, caseDefsWithDefault) withAttachment TranslatedMatchAttachment // add switch annotation )) } } else None diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 2410117af7..553cafe966 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2208,44 +2208,26 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser def adaptCase(cdef: CaseDef, mode: Int, tpe: Type): CaseDef = deriveCaseDef(cdef)(adapt(_, mode, tpe)) + def ptOrLub(tps: List[Type], pt: Type ) = if (isFullyDefined(pt)) (pt, false) else weakLub(tps map (_.deconst)) + def ptOrLubPacked(trees: List[Tree], pt: Type) = if (isFullyDefined(pt)) (pt, false) else weakLub(trees map (c => packedType(c, context.owner).deconst)) + // takes untyped sub-trees of a match and type checks them - def typedMatch(selector0: Tree, cases: List[CaseDef], mode: Int, resTp: Type): Match = { - // strip off the annotation as it won't type check - val (selector, doTranslation) = selector0 match { - case Annotated(Ident(nme.synthSwitch), selector) => (selector, false) - case s => (s, true) - } - val selector1 = checkDead(typed(selector, EXPRmode | BYVALmode, WildcardType)) - val selectorTp = packCaptured(selector1.tpe.widen.withoutAnnotations) + def typedMatch(selector: Tree, cases: List[CaseDef], mode: Int, pt: Type, tree: Tree = EmptyTree): Match = { + val selector1 = checkDead(typed(selector, EXPRmode | BYVALmode, WildcardType)) + val selectorTp = packCaptured(selector1.tpe.widen) + val casesTyped = typedCases(cases, selectorTp, pt) - val casesTyped = typedCases(cases, selectorTp, resTp) - val caseTypes = casesTyped map (c => packedType(c, context.owner).deconst) - val (ownType, needAdapt) = if (isFullyDefined(resTp)) (resTp, false) else weakLub(caseTypes) + val (resTp, needAdapt) = + if (opt.virtPatmat) ptOrLubPacked(casesTyped, pt) + else ptOrLub(casesTyped map (_.tpe), pt) - val casesAdapted = if (!needAdapt) casesTyped else casesTyped map (adaptCase(_, mode, ownType)) + val casesAdapted = if (!needAdapt) casesTyped else casesTyped map (adaptCase(_, mode, resTp)) - (selector1, selectorTp, casesAdapted, ownType, doTranslation) + treeCopy.Match(tree, selector1, casesAdapted) setType resTp } // match has been typed, now translate it - def translatedMatch(selector1: Tree, selectorTp: Type, casesAdapted: List[CaseDef], ownType: Type, doTranslation: Boolean, matchFailGen: Option[Tree => Tree] = None) = { - def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { - case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) - case _ => tp - } - - if (!doTranslation) { // a switch - Match(selector1, casesAdapted) setType ownType // setType of the Match to avoid recursing endlessly - } else { - val scrutType = repeatedToSeq(elimAnonymousClass(selectorTp)) - // we've packed the type for each case in typedMatch so that if all cases have the same existential case, we get a clean lub - // here, we should open up the existential again - // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala - // TODO: fix skolemizeExistential (it should preserve annotations, right?) - val ownTypeSkolemized = ownType.skolemizeExistential(context.owner, context.tree) withAnnotations ownType.annotations - MatchTranslator(this).translateMatch(selector1, casesAdapted, repeatedToSeq(ownTypeSkolemized), scrutType, matchFailGen) - } - } + def translatedMatch(match_ : Match) = MatchTranslator(this).translateMatch(match_) // synthesize and type check a (Partial)Function implementation based on a match specified by `cases` // Match(EmptyTree, cases) ==> new Function { def apply(params) = `translateMatch('`(param1,...,paramN)` match { cases }')` } @@ -2298,7 +2280,8 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) paramSyms foreach (methodBodyTyper.context.scope enter _) - val (selector1, selectorTp, casesAdapted, resTp, doTranslation) = methodBodyTyper.typedMatch(selector, cases, mode, ptRes) + val match_ = methodBodyTyper.typedMatch(selector, cases, mode, ptRes) + val resTp = match_.tpe val methFormals = paramSyms map (_.tpe) val parents = @@ -2308,7 +2291,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser anonClass setInfo ClassInfoType(parents, newScope, anonClass) methodSym setInfoAndEnter MethodType(paramSyms, resTp) - DefDef(methodSym, methodBodyTyper.translatedMatch(selector1, selectorTp, casesAdapted, resTp, doTranslation)) + DefDef(methodSym, methodBodyTyper.translatedMatch(match_)) } } @@ -2337,16 +2320,17 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser val methodBodyTyper = newTyper(context.makeNewScope(context.tree, methodSym)) // should use the DefDef for the context's tree, but it doesn't exist yet (we need the typer we're creating to create it) paramSyms foreach (methodBodyTyper.context.scope enter _) - val (selector1, selectorTp, casesAdapted, resTp, doTranslation) = methodBodyTyper.typedMatch(selector, cases, mode, ptRes) + val match_ = methodBodyTyper.typedMatch(selector, cases, mode, ptRes) + val resTp = match_.tpe anonClass setInfo ClassInfoType(parentsPartial(List(argTp, resTp)), newScope, anonClass) B1 setInfo TypeBounds.lower(resTp) anonClass.info.decls enter methodSym // methodSym's info need not change (B1's bound has been updated instead) - // use applyOrElse's first parameter since the scrut's type has been widened - def doDefault(scrut_ignored: Tree) = REF(default) APPLY (REF(x)) + match_ setType B1.tpe - val body = methodBodyTyper.translatedMatch(selector1, selectorTp, casesAdapted, B1.tpe, doTranslation, Some(doDefault)) + // the default uses applyOrElse's first parameter since the scrut's type has been widened + val body = methodBodyTyper.translatedMatch(match_ withAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x)))) DefDef(methodSym, body) } @@ -2363,17 +2347,18 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser paramSyms foreach (methodBodyTyper.context.scope enter _) methodSym setInfoAndEnter MethodType(paramSyms, BooleanClass.tpe) - val (selector1, selectorTp, casesAdapted, resTp, doTranslation) = methodBodyTyper.typedMatch(selector, casesTrue, mode, BooleanClass.tpe) - val body = methodBodyTyper.translatedMatch(selector1, selectorTp, casesAdapted, resTp, doTranslation, Some(scrutinee => FALSE_typed)) + val match_ = methodBodyTyper.typedMatch(selector, casesTrue, mode, BooleanClass.tpe) + val body = methodBodyTyper.translatedMatch(match_ withAttachment DefaultOverrideMatchAttachment(FALSE_typed)) DefDef(methodSym, body) } } val members = if (isPartial) { - // TODO: don't check for MarkerCPSTypes -- check whether all targs are subtype of any (which they are not under CPS) - if ((MarkerCPSTypes ne NoSymbol) && (targs exists (_ hasAnnotation MarkerCPSTypes))) List(applyMethod, isDefinedAtMethod) - else List(applyOrElseMethodDef, isDefinedAtMethod) + // somehow @cps annotations upset the typer when looking at applyOrElse's signature, but not apply's + // TODO: figure out the details (T @cps[U] is not a subtype of Any, but then why does it work for the apply method?) + if (targs forall (_ <:< AnyClass.tpe)) List(applyOrElseMethodDef, isDefinedAtMethod) + else List(applyMethod, isDefinedAtMethod) } else List(applyMethod) def translated = @@ -3639,8 +3624,6 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser def isPatternMode = inPatternMode(mode) //Console.println("typed1("+tree.getClass()+","+Integer.toHexString(mode)+","+pt+")") - def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) (pt, false) else weakLub(tps map (_.deconst)) - //@M! get the type of the qualifier in a Select tree, otherwise: NoType def prefixType(fun: Tree): Type = fun match { case Select(qualifier, _) => qualifier.tpe @@ -3830,7 +3813,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser && thenTp =:= elseTp ) (thenp1.tpe, false) // use unpacked type // TODO: skolemize (lub of packed types) when that no longer crashes on files/pos/t4070b.scala - else ptOrLub(List(thenp1.tpe, elsep1.tpe)) + else ptOrLub(List(thenp1.tpe, elsep1.tpe), pt) if (needAdapt) { //isNumericValueType(owntype)) { thenp1 = adapt(thenp1, mode, owntype) @@ -3840,34 +3823,28 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser } } - def typedTranslatedMatch(tree: Tree, selector: Tree, cases: List[CaseDef]): Tree = { - if (doMatchTranslation) { - if (selector ne EmptyTree) { - val (selector1, selectorTp, casesAdapted, ownType, doTranslation) = typedMatch(selector, cases, mode, pt) - typed(translatedMatch(selector1, selectorTp, casesAdapted, ownType, doTranslation), mode, pt) - } else (new MatchFunTyper(tree, cases, mode, pt)).translated - } else if (selector == EmptyTree) { - if (opt.virtPatmat) debugwarn("virtpatmat should not encounter empty-selector matches "+ tree) - val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1 - val params = for (i <- List.range(0, arity)) yield - atPos(tree.pos.focusStart) { - ValDef(Modifiers(PARAM | SYNTHETIC), - unit.freshTermName("x" + i + "$"), TypeTree(), EmptyTree) - } - val ids = for (p <- params) yield Ident(p.name) - val selector1 = atPos(tree.pos.focusStart) { if (arity == 1) ids.head else gen.mkTuple(ids) } - val body = treeCopy.Match(tree, selector1, cases) - typed1(atPos(tree.pos) { Function(params, body) }, mode, pt) - } else { - val selector1 = checkDead(typed(selector, EXPRmode | BYVALmode, WildcardType)) - var cases1 = typedCases(cases, packCaptured(selector1.tpe.widen), pt) - val (owntype, needAdapt) = ptOrLub(cases1 map (_.tpe)) - if (needAdapt) { - cases1 = cases1 map (adaptCase(_, mode, owntype)) + def typedTranslatedMatch(tree: Tree, selector: Tree, cases: List[CaseDef]): Tree = + if (selector == EmptyTree) { + if (doMatchTranslation) (new MatchFunTyper(tree, cases, mode, pt)).translated + else { + if (opt.virtPatmat) debugwarn("virtpatmat should not encounter empty-selector matches "+ tree) + val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1 + val params = for (i <- List.range(0, arity)) yield + atPos(tree.pos.focusStart) { + ValDef(Modifiers(PARAM | SYNTHETIC), + unit.freshTermName("x" + i + "$"), TypeTree(), EmptyTree) + } + val ids = for (p <- params) yield Ident(p.name) + val selector1 = atPos(tree.pos.focusStart) { if (arity == 1) ids.head else gen.mkTuple(ids) } + val body = treeCopy.Match(tree, selector1, cases) + typed1(atPos(tree.pos) { Function(params, body) }, mode, pt) } - treeCopy.Match(tree, selector1, cases1) setType owntype + } else { + if (!doMatchTranslation || (tree firstAttachment {case TranslatedMatchAttachment => } nonEmpty)) + typedMatch(selector, cases, mode, pt, tree) + else + typed(translatedMatch(typedMatch(selector, cases, mode, pt, tree)), mode, pt) } - } def typedReturn(expr: Tree) = { val enclMethod = context.enclMethod @@ -4719,7 +4696,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser var catches1 = typedCases(catches, ThrowableClass.tpe, pt) val finalizer1 = if (finalizer.isEmpty) finalizer else typed(finalizer, UnitClass.tpe) - val (owntype, needAdapt) = ptOrLub(block1.tpe :: (catches1 map (_.tpe))) + val (owntype, needAdapt) = ptOrLub(block1.tpe :: (catches1 map (_.tpe)), pt) if (needAdapt) { block1 = adapt(block1, mode, owntype) catches1 = catches1 map (adaptCase(_, mode, owntype)) -- cgit v1.2.3 From 1b8dc120dd156e34e43132134dfa1f228cd1f497 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Mon, 30 Apr 2012 13:35:06 +0200 Subject: moving patmat to its own phase sort field accessors, necessary after typers -- apparently... don't throw TypeError, use issueTypeError don't run patmat phase when -Xoldpatmat only virtualize matches when -Xexperimental recycle cps type of match for re-typechecking: when one of the internal cps-type-state annotations is present, strip all CPS annotations a cps-type-state-annotated type makes no sense as an expected type (matchX.tpe is used as pt in translateMatch) don't synth FunctionN impls during typer, only do this for PartialFunction updated check now function synth for match is deferred until uncurry patmat-transform try/catch with match in cps cleanup in selective anf remove TODO: can there be cases that are not CaseDefs -- nope --- src/compiler/scala/tools/nsc/Global.scala | 8 + src/compiler/scala/tools/nsc/ast/Trees.scala | 5 + .../tools/nsc/typechecker/PatMatVirtualiser.scala | 1792 ------------------- .../tools/nsc/typechecker/PatternMatching.scala | 1839 ++++++++++++++++++++ .../tools/nsc/typechecker/SyntheticMethods.scala | 1 + .../scala/tools/nsc/typechecker/Typers.scala | 74 +- .../tools/selectivecps/CPSAnnotationChecker.scala | 85 +- .../tools/selectivecps/SelectiveANFTransform.scala | 5 +- .../tools/selectivecps/SelectiveCPSTransform.scala | 3 +- test/files/neg/gadts1.check | 5 +- test/files/neg/patmat-type-check.check | 14 +- test/files/neg/t0418.check | 5 +- test/files/neg/t112706A.check | 5 +- test/files/neg/t3392.check | 5 +- test/files/neg/t418.check | 5 +- test/files/neg/t4515.check | 4 +- test/files/neg/t5589neg.check | 5 +- test/files/run/inner-parse.check | 1 + test/files/run/programmatic-main.check | 47 +- test/files/run/virtpatmat_staging.flags | 2 +- 20 files changed, 1975 insertions(+), 1935 deletions(-) delete mode 100644 src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 8c6c927640..959ce427bb 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -462,6 +462,13 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb val global: Global.this.type = Global.this } with Analyzer + // phaseName = "patmat" + object patmat extends { + val global: Global.this.type = Global.this + val runsAfter = List("typer") + val runsRightAfter = Some("typer") + } with PatternMatching + // phaseName = "superaccessors" object superAccessors extends { val global: Global.this.type = Global.this @@ -682,6 +689,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb analyzer.namerFactory -> "resolve names, attach symbols to named trees", analyzer.packageObjects -> "load package objects", analyzer.typerFactory -> "the meat and potatoes: type the trees", + patmat -> "translate match expressions", superAccessors -> "add super accessors in traits and nested classes", extensionMethods -> "add extension methods for inline classes", pickler -> "serialize symbol tables", diff --git a/src/compiler/scala/tools/nsc/ast/Trees.scala b/src/compiler/scala/tools/nsc/ast/Trees.scala index 34b37073fd..a355db4d9a 100644 --- a/src/compiler/scala/tools/nsc/ast/Trees.scala +++ b/src/compiler/scala/tools/nsc/ast/Trees.scala @@ -234,6 +234,11 @@ trait Trees extends reflect.internal.Trees { self: Global => } } + // used when a phase is disabled + object noopTransformer extends Transformer { + override def transformUnit(unit: CompilationUnit): Unit = {} + } + override protected def xtransform(transformer: super.Transformer, tree: Tree): Tree = tree match { case DocDef(comment, definition) => transformer.treeCopy.DocDef(tree, comment, transformer.transform(definition)) diff --git a/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala b/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala deleted file mode 100644 index b3f4b10865..0000000000 --- a/src/compiler/scala/tools/nsc/typechecker/PatMatVirtualiser.scala +++ /dev/null @@ -1,1792 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Adriaan Moors - */ - -package scala.tools.nsc -package typechecker - -import symtab._ -import Flags.{MUTABLE, METHOD, LABEL, SYNTHETIC} -import language.postfixOps - -/** Translate pattern matching into method calls (these methods form a zero-plus monad), similar in spirit to how for-comprehensions are compiled. - * - * For each case, express all patterns as extractor calls, guards as 0-ary extractors, and sequence them using `flatMap` - * (lifting the body of the case into the monad using `one`). - * - * Cases are combined into a pattern match using the `orElse` combinator (the implicit failure case is expressed using the monad's `zero`). - - * TODO: - * - interaction with CPS - * - Array patterns - * - implement spec more closely (see TODO's) - * - DCE - * - use TypeTags for type testing - * - * (longer-term) TODO: - * - user-defined unapplyProd - * - recover GADT typing by locally inserting implicit witnesses to type equalities derived from the current case, and considering these witnesses during subtyping (?) - * - recover exhaustivity and unreachability checking using a variation on the type-safe builder pattern - */ -trait PatMatVirtualiser extends ast.TreeDSL { self: Analyzer => - import global._ - import definitions._ - - val SYNTH_CASE = Flags.CASE | SYNTHETIC - - object TranslatedMatchAttachment - case class DefaultOverrideMatchAttachment(default: Tree) - - object vpmName { - val one = newTermName("one") - val drop = newTermName("drop") - val flatMap = newTermName("flatMap") - val get = newTermName("get") - val guard = newTermName("guard") - val isEmpty = newTermName("isEmpty") - val orElse = newTermName("orElse") - val outer = newTermName("") - val runOrElse = newTermName("runOrElse") - val zero = newTermName("zero") - val _match = newTermName("__match") // don't call the val __match, since that will trigger virtual pattern matching... - - def counted(str: String, i: Int) = newTermName(str+i) - } - - object MatchTranslator { - def apply(typer: Typer): MatchTranslation with CodegenCore = { - import typer._ - // typing `_match` to decide which MatchTranslator to create adds 4% to quick.comp.timer - val matchStrategy: Tree = ( - if (!context.isNameInScope(vpmName._match)) null // fast path, avoiding the next line if there's no __match to be seen - else newTyper(context.makeImplicit(reportAmbiguousErrors = false)).silent(_.typed(Ident(vpmName._match), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { - case SilentResultValue(ms) => ms - case _ => null - } - ) - if (matchStrategy eq null) new OptimizingMatchTranslator(typer) - else new PureMatchTranslator(typer, matchStrategy) - } - } - - class PureMatchTranslator(val typer: Typer, val matchStrategy: Tree) extends MatchTranslation with TreeMakers with PureCodegen - class OptimizingMatchTranslator(val typer: Typer) extends MatchTranslation with TreeMakers with MatchOptimizations - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// talking to userland -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - /** Interface with user-defined match monad? - * if there's a `__match` in scope, we use this as the match strategy, assuming it conforms to MatchStrategy as defined below: - - type Matcher[P[_], M[+_], A] = { - def flatMap[B](f: P[A] => M[B]): M[B] - def orElse[B >: A](alternative: => M[B]): M[B] - } - - abstract class MatchStrategy[P[_], M[+_]] { - // runs the matcher on the given input - def runOrElse[T, U](in: P[T])(matcher: P[T] => M[U]): P[U] - - def zero: M[Nothing] - def one[T](x: P[T]): M[T] - def guard[T](cond: P[Boolean], then: => P[T]): M[T] - def isSuccess[T, U](x: P[T])(f: P[T] => M[U]): P[Boolean] // used for isDefinedAt - } - - * P and M are derived from one's signature (`def one[T](x: P[T]): M[T]`) - - - * if no `__match` is found, we assume the following implementation (and generate optimized code accordingly) - - object __match extends MatchStrategy[({type Id[x] = x})#Id, Option] { - def zero = None - def one[T](x: T) = Some(x) - // NOTE: guard's return type must be of the shape M[T], where M is the monad in which the pattern match should be interpreted - def guard[T](cond: Boolean, then: => T): Option[T] = if(cond) Some(then) else None - def runOrElse[T, U](x: T)(f: T => Option[U]): U = f(x) getOrElse (throw new MatchError(x)) - def isSuccess[T, U](x: T)(f: T => Option[U]): Boolean = !f(x).isEmpty - } - - */ - trait MatchMonadInterface { - val typer: Typer - val matchOwner = typer.context.owner - - def inMatchMonad(tp: Type): Type - def pureType(tp: Type): Type - final def matchMonadResult(tp: Type): Type = - tp.baseType(matchMonadSym).typeArgs match { - case arg :: Nil => arg - case _ => ErrorType - } - - protected def matchMonadSym: Symbol - } - - trait MatchTranslation extends MatchMonadInterface { self: TreeMakers with CodegenCore => - import typer.{typed, context, silent, reallyExists} - // import typer.infer.containsUnchecked - - /** Implement a pattern match by turning its cases (including the implicit failure case) - * into the corresponding (monadic) extractors, and combining them with the `orElse` combinator. - * - * For `scrutinee match { case1 ... caseN }`, the resulting tree has the shape - * `runOrElse(scrutinee)(x => translateCase1(x).orElse(translateCase2(x)).....orElse(zero))` - * - * NOTE: the resulting tree is not type checked, nor are nested pattern matches transformed - * thus, you must typecheck the result (and that will in turn translate nested matches) - * this could probably optimized... (but note that the matchStrategy must be solved for each nested patternmatch) - */ - def translateMatch(match_ : Match): Tree = { - val Match(selector, cases) = match_ - - // we don't transform after uncurry - // (that would require more sophistication when generating trees, - // and the only place that emits Matches after typers is for exception handling anyway) - if(phase.id >= currentRun.uncurryPhase.id) debugwarn("running translateMatch at "+ phase +" on "+ selector +" match "+ cases) - // println("translating "+ cases.mkString("{", "\n", "}")) - - def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { - case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) - case _ => tp - } - - val selectorTp = repeatedToSeq(elimAnonymousClass(selector.tpe.widen.withoutAnnotations)) - val pt0 = match_.tpe - - // we've packed the type for each case in typedMatch so that if all cases have the same existential case, we get a clean lub - // here, we should open up the existential again - // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala - // TODO: fix skolemizeExistential (it should preserve annotations, right?) - val pt = repeatedToSeq(pt0.skolemizeExistential(context.owner, context.tree) withAnnotations pt0.annotations) - - // the alternative to attaching the default case override would be to simply - // append the default to the list of cases and suppress the unreachable case error that may arise (once we detect that...) - val matchFailGenOverride = match_ firstAttachment {case DefaultOverrideMatchAttachment(default) => ((scrut: Tree) => default)} - - val selectorSym = freshSym(selector.pos, pureType(selectorTp)) setFlag SYNTH_CASE - // pt = Any* occurs when compiling test/files/pos/annotDepMethType.scala with -Xexperimental - combineCases(selector, selectorSym, cases map translateCase(selectorSym, pt), pt, matchOwner, matchFailGenOverride) - } - - // return list of typed CaseDefs that are supported by the backend (typed/bind/wildcard) - // we don't have a global scrutinee -- the caught exception must be bound in each of the casedefs - // there's no need to check the scrutinee for null -- "throw null" becomes "throw new NullPointerException" - // try to simplify to a type-based switch, or fall back to a catch-all case that runs a normal pattern match - // unlike translateMatch, we type our result before returning it - def translateTry(caseDefs: List[CaseDef], pt: Type, pos: Position): List[CaseDef] = - // if they're already simple enough to be handled by the back-end, we're done - if (caseDefs forall treeInfo.isCatchCase) caseDefs - else { - val swatches = { // switch-catches - val bindersAndCases = caseDefs map { caseDef => - // generate a fresh symbol for each case, hoping we'll end up emitting a type-switch (we don't have a global scrut there) - // if we fail to emit a fine-grained switch, have to do translateCase again with a single scrutSym (TODO: uniformize substitution on treemakers so we can avoid this) - val caseScrutSym = freshSym(pos, pureType(ThrowableClass.tpe)) - (caseScrutSym, propagateSubstitution(translateCase(caseScrutSym, pt)(caseDef), EmptySubstitution)) - } - - for(cases <- emitTypeSwitch(bindersAndCases, pt).toList; - if cases forall treeInfo.isCatchCase; // must check again, since it's not guaranteed -- TODO: can we eliminate this? e.g., a type test could test for a trait or a non-trivial prefix, which are not handled by the back-end - cse <- cases) yield fixerUpper(matchOwner, pos)(cse).asInstanceOf[CaseDef] - } - - val catches = if (swatches.nonEmpty) swatches else { - val scrutSym = freshSym(pos, pureType(ThrowableClass.tpe)) - val casesNoSubstOnly = caseDefs map { caseDef => (propagateSubstitution(translateCase(scrutSym, pt)(caseDef), EmptySubstitution))} - - val exSym = freshSym(pos, pureType(ThrowableClass.tpe), "ex") - - List( - atPos(pos) { - CaseDef( - Bind(exSym, Ident(nme.WILDCARD)), // TODO: does this need fixing upping? - EmptyTree, - combineCasesNoSubstOnly(CODE.REF(exSym), scrutSym, casesNoSubstOnly, pt, matchOwner, Some(scrut => Throw(CODE.REF(exSym)))) - ) - }) - } - - typer.typedCases(catches, ThrowableClass.tpe, WildcardType) - } - - - - /** The translation of `pat if guard => body` has two aspects: - * 1) the substitution due to the variables bound by patterns - * 2) the combination of the extractor calls using `flatMap`. - * - * 2) is easy -- it looks like: `translatePattern_1.flatMap(translatePattern_2....flatMap(translatePattern_N.flatMap(translateGuard.flatMap((x_i) => success(Xbody(x_i)))))...)` - * this must be right-leaning tree, as can be seen intuitively by considering the scope of bound variables: - * variables bound by pat_1 must be visible from the function inside the left-most flatMap right up to Xbody all the way on the right - * 1) is tricky because translatePattern_i determines the shape of translatePattern_i+1: - * zoom in on `translatePattern_1.flatMap(translatePattern_2)` for example -- it actually looks more like: - * `translatePattern_1(x_scrut).flatMap((x_1) => {y_i -> x_1._i}translatePattern_2)` - * - * `x_1` references the result (inside the monad) of the extractor corresponding to `pat_1`, - * this result holds the values for the constructor arguments, which translatePattern_1 has extracted - * from the object pointed to by `x_scrut`. The `y_i` are the symbols bound by `pat_1` (in order) - * in the scope of the remainder of the pattern, and they must thus be replaced by: - * - (for 1-ary unapply) x_1 - * - (for n-ary unapply, n > 1) selection of the i'th tuple component of `x_1` - * - (for unapplySeq) x_1.apply(i) - * - * in the treemakers, - * - * Thus, the result type of `translatePattern_i`'s extractor must conform to `M[(T_1,..., T_n)]`. - * - * Operationally, phase 1) is a foldLeft, since we must consider the depth-first-flattening of - * the transformed patterns from left to right. For every pattern ast node, it produces a transformed ast and - * a function that will take care of binding and substitution of the next ast (to the right). - * - */ - def translateCase(scrutSym: Symbol, pt: Type)(caseDef: CaseDef) = caseDef match { case CaseDef(pattern, guard, body) => - translatePattern(scrutSym, pattern) ++ translateGuard(guard) :+ translateBody(body, pt) - } - - def translatePattern(patBinder: Symbol, patTree: Tree): List[TreeMaker] = { - // a list of TreeMakers that encode `patTree`, and a list of arguments for recursive invocations of `translatePattern` to encode its subpatterns - type TranslationStep = (List[TreeMaker], List[(Symbol, Tree)]) - @inline def withSubPats(treeMakers: List[TreeMaker], subpats: (Symbol, Tree)*): TranslationStep = (treeMakers, subpats.toList) - @inline def noFurtherSubPats(treeMakers: TreeMaker*): TranslationStep = (treeMakers.toList, Nil) - - val pos = patTree.pos - - def translateExtractorPattern(extractor: ExtractorCall): TranslationStep = { - if (!extractor.isTyped) throw new TypeError(pos, "Could not typecheck extractor call: "+ extractor) - // if (extractor.resultInMonad == ErrorType) throw new TypeError(pos, "Unsupported extractor type: "+ extractor.tpe) - - // must use type `tp`, which is provided by extractor's result, not the type expected by binder, - // as b.info may be based on a Typed type ascription, which has not been taken into account yet by the translation - // (it will later result in a type test when `tp` is not a subtype of `b.info`) - // TODO: can we simplify this, together with the Bound case? - (extractor.subPatBinders, extractor.subPatTypes).zipped foreach { case (b, tp) => b setInfo tp } // println("changing "+ b +" : "+ b.info +" -> "+ tp); - - // println("translateExtractorPattern checking parameter type: "+ (patBinder, patBinder.info.widen, extractor.paramType, patBinder.info.widen <:< extractor.paramType)) - // example check: List[Int] <:< ::[Int] - // TODO: extractor.paramType may contain unbound type params (run/t2800, run/t3530) - val (typeTestTreeMaker, patBinderOrCasted) = - if (needsTypeTest(patBinder.info.widen, extractor.paramType)) { - // chain a type-testing extractor before the actual extractor call - // it tests the type, checks the outer pointer and casts to the expected type - // TODO: the outer check is mandated by the spec for case classes, but we do it for user-defined unapplies as well [SPEC] - // (the prefix of the argument passed to the unapply must equal the prefix of the type of the binder) - val treeMaker = TypeTestTreeMaker(patBinder, extractor.paramType, pos) - (List(treeMaker), treeMaker.nextBinder) - } else (Nil, patBinder) - - withSubPats(typeTestTreeMaker :+ extractor.treeMaker(patBinderOrCasted, pos), extractor.subBindersAndPatterns: _*) - } - - - object MaybeBoundTyped { - /** Decompose the pattern in `tree`, of shape C(p_1, ..., p_N), into a list of N symbols, and a list of its N sub-trees - * The list of N symbols contains symbols for every bound name as well as the un-named sub-patterns (fresh symbols are generated here for these). - * The returned type is the one inferred by inferTypedPattern (`owntype`) - * - * @arg patBinder symbol used to refer to the result of the previous pattern's extractor (will later be replaced by the outer tree with the correct tree to refer to that patterns result) - */ - def unapply(tree: Tree): Option[(Symbol, Type)] = tree match { - // the Ident subpattern can be ignored, subpatBinder or patBinder tell us all we need to know about it - case Bound(subpatBinder, typed@Typed(Ident(_), tpt)) if typed.tpe ne null => Some((subpatBinder, typed.tpe)) - case Bind(_, typed@Typed(Ident(_), tpt)) if typed.tpe ne null => Some((patBinder, typed.tpe)) - case Typed(Ident(_), tpt) if tree.tpe ne null => Some((patBinder, tree.tpe)) - case _ => None - } - } - - val (treeMakers, subpats) = patTree match { - // skip wildcard trees -- no point in checking them - case WildcardPattern() => noFurtherSubPats() - case UnApply(unfun, args) => - // TODO: check unargs == args - // println("unfun: "+ (unfun.tpe, unfun.symbol.ownerChain, unfun.symbol.info, patBinder.info)) - translateExtractorPattern(ExtractorCall(unfun, args)) - - /** A constructor pattern is of the form c(p1, ..., pn) where n ≥ 0. - It consists of a stable identifier c, followed by element patterns p1, ..., pn. - The constructor c is a simple or qualified name which denotes a case class (§5.3.2). - - If the case class is monomorphic, then it must conform to the expected type of the pattern, - and the formal parameter types of x’s primary constructor (§5.3) are taken as the expected types of the element patterns p1, ..., pn. - - If the case class is polymorphic, then its type parameters are instantiated so that the instantiation of c conforms to the expected type of the pattern. - The instantiated formal parameter types of c’s primary constructor are then taken as the expected types of the component patterns p1, ..., pn. - - The pattern matches all objects created from constructor invocations c(v1, ..., vn) where each element pattern pi matches the corresponding value vi . - A special case arises when c’s formal parameter types end in a repeated parameter. This is further discussed in (§8.1.9). - **/ - case Apply(fun, args) => - ExtractorCall.fromCaseClass(fun, args) map translateExtractorPattern getOrElse { - error("cannot find unapply member for "+ fun +" with args "+ args) - noFurtherSubPats() - } - - /** A typed pattern x : T consists of a pattern variable x and a type pattern T. - The type of x is the type pattern T, where each type variable and wildcard is replaced by a fresh, unknown type. - This pattern matches any value matched by the type pattern T (§8.2); it binds the variable name to that value. - **/ - // must treat Typed and Bind together -- we need to know the patBinder of the Bind pattern to get at the actual type - case MaybeBoundTyped(subPatBinder, pt) => - // a typed pattern never has any subtrees - noFurtherSubPats(TypeAndEqualityTestTreeMaker(subPatBinder, patBinder, pt, pos)) - - /** A pattern binder x@p consists of a pattern variable x and a pattern p. - The type of the variable x is the static type T of the pattern p. - This pattern matches any value v matched by the pattern p, - provided the run-time type of v is also an instance of T, <-- TODO! https://issues.scala-lang.org/browse/SI-1503 - and it binds the variable name to that value. - **/ - case Bound(subpatBinder, p) => - // replace subpatBinder by patBinder (as if the Bind was not there) - withSubPats(List(SubstOnlyTreeMaker(subpatBinder, patBinder)), - // must be patBinder, as subpatBinder has the wrong info: even if the bind assumes a better type, this is not guaranteed until we cast - (patBinder, p) - ) - - /** 8.1.4 Literal Patterns - A literal pattern L matches any value that is equal (in terms of ==) to the literal L. - The type of L must conform to the expected type of the pattern. - - 8.1.5 Stable Identifier Patterns (a stable identifier r (see §3.1)) - The pattern matches any value v such that r == v (§12.1). - The type of r must conform to the expected type of the pattern. - **/ - case Literal(Constant(_)) | Ident(_) | Select(_, _) => - noFurtherSubPats(EqualityTestTreeMaker(patBinder, patTree, pos)) - - case Alternative(alts) => - noFurtherSubPats(AlternativesTreeMaker(patBinder, alts map (translatePattern(patBinder, _)), alts.head.pos)) - - /* TODO: Paul says about future version: I think this should work, and always intended to implement if I can get away with it. - case class Foo(x: Int, y: String) - case class Bar(z: Int) - - def f(x: Any) = x match { case Foo(x, _) | Bar(x) => x } // x is lub of course. - */ - - case Bind(n, p) => // this happens in certain ill-formed programs, there'll be an error later - // println("WARNING: Bind tree with unbound symbol "+ patTree) - noFurtherSubPats() // there's no symbol -- something's wrong... don't fail here though (or should we?) - - // case Star(_) | ArrayValue | This => error("stone age pattern relics encountered!") - - case _ => - error("unsupported pattern: "+ patTree +"(a "+ patTree.getClass +")") - noFurtherSubPats() - } - - treeMakers ++ subpats.flatMap { case (binder, pat) => - translatePattern(binder, pat) // recurse on subpatterns - } - } - - def translateGuard(guard: Tree): List[TreeMaker] = - if (guard == EmptyTree) Nil - else List(GuardTreeMaker(guard)) - - // TODO: 1) if we want to support a generalisation of Kotlin's patmat continue, must not hard-wire lifting into the monad (which is now done by codegen.one), - // so that user can generate failure when needed -- use implicit conversion to lift into monad on-demand? - // to enable this, probably need to move away from Option to a monad specific to pattern-match, - // so that we can return Option's from a match without ambiguity whether this indicates failure in the monad, or just some result in the monad - // 2) body.tpe is the type of the body after applying the substitution that represents the solution of GADT type inference - // need the explicit cast in case our substitutions in the body change the type to something that doesn't take GADT typing into account - def translateBody(body: Tree, matchPt: Type): TreeMaker = - BodyTreeMaker(body, matchPt) - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// helper methods: they analyze types and trees in isolation, but they are not (directly) concerned with the structure of the overall translation -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - object ExtractorCall { - def apply(unfun: Tree, args: List[Tree]): ExtractorCall = new ExtractorCallRegular(unfun, args) - - def fromCaseClass(fun: Tree, args: List[Tree]): Option[ExtractorCall] = Some(new ExtractorCallProd(fun, args)) - - // THE PRINCIPLED SLOW PATH -- NOT USED - // generate a call to the (synthetically generated) extractor of a case class - // NOTE: it's an apply, not a select, since in general an extractor call may have multiple argument lists (including an implicit one) - // that we need to preserve, so we supply the scrutinee as Ident(nme.SELECTOR_DUMMY), - // and replace that dummy by a reference to the actual binder in translateExtractorPattern - def fromCaseClassUnapply(fun: Tree, args: List[Tree]): Option[ExtractorCall] = { - // TODO: can we rework the typer so we don't have to do all this twice? - // undo rewrite performed in (5) of adapt - val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} - val origSym = orig.symbol - val extractor = unapplyMember(origSym.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe) - - if((fun.tpe eq null) || fun.tpe.isError || (extractor eq NoSymbol)) { - None - } else { - // this is a tricky balance: pos/t602.scala, pos/sudoku.scala, run/virtpatmat_alts.scala must all be happy - // bypass typing at own risk: val extractorCall = Select(orig, extractor) setType caseClassApplyToUnapplyTp(fun.tpe) - // can't always infer type arguments (pos/t602): - /* case class Span[K <: Ordered[K]](low: Option[K]) { - override def equals(x: Any): Boolean = x match { - case Span((low0 @ _)) if low0 equals low => true - } - }*/ - // so... leave undetermined type params floating around if we have to - // (if we don't infer types, uninstantiated type params show up later: pos/sudoku.scala) - // (see also run/virtpatmat_alts.scala) - val savedUndets = context.undetparams - val extractorCall = try { - context.undetparams = Nil - silent(_.typed(Apply(Select(orig, extractor), List(Ident(nme.SELECTOR_DUMMY) setType fun.tpe.finalResultType)), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { - case SilentResultValue(extractorCall) => extractorCall // if !extractorCall.containsError() - case _ => - // this fails to resolve overloading properly... - // Apply(typedOperator(Select(orig, extractor)), List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway - - // println("funtpe after = "+ fun.tpe.finalResultType) - // println("orig: "+(orig, orig.tpe)) - val tgt = typed(orig, EXPRmode | QUALmode | POLYmode, HasMember(extractor.name)) // can't specify fun.tpe.finalResultType as the type for the extractor's arg, - // as it may have been inferred incorrectly (see t602, where it's com.mosol.sl.Span[Any], instead of com.mosol.sl.Span[?K]) - // println("tgt = "+ (tgt, tgt.tpe)) - val oper = typed(Select(tgt, extractor.name), EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) - // println("oper: "+ (oper, oper.tpe)) - Apply(oper, List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway - } - } finally context.undetparams = savedUndets - - Some(this(extractorCall, args)) // TODO: simplify spliceApply? - } - } - } - - abstract class ExtractorCall(val args: List[Tree]) { - val nbSubPats = args.length - - // everything okay, captain? - def isTyped : Boolean - - def isSeq: Boolean - lazy val lastIsStar = (nbSubPats > 0) && treeInfo.isStar(args.last) - - // to which type should the previous binder be casted? - def paramType : Type - - // binder has been casted to paramType if necessary - def treeMaker(binder: Symbol, pos: Position): TreeMaker - - // `subPatBinders` are the variables bound by this pattern in the following patterns - // subPatBinders are replaced by references to the relevant part of the extractor's result (tuple component, seq element, the result as-is) - lazy val subPatBinders = args map { - case Bound(b, p) => b - case p => freshSym(p.pos, prefix = "p") - } - - lazy val subBindersAndPatterns: List[(Symbol, Tree)] = (subPatBinders zip args) map { - case (b, Bound(_, p)) => (b, p) - case bp => bp - } - - def subPatTypes: List[Type] = - if(isSeq) { - val TypeRef(pre, SeqClass, args) = seqTp - // do repeated-parameter expansion to match up with the expected number of arguments (in casu, subpatterns) - formalTypes(rawSubPatTypes.init :+ typeRef(pre, RepeatedParamClass, args), nbSubPats) - } else rawSubPatTypes - - protected def rawSubPatTypes: List[Type] - - protected def seqTp = rawSubPatTypes.last baseType SeqClass - protected def seqLenCmp = rawSubPatTypes.last member nme.lengthCompare - protected lazy val firstIndexingBinder = rawSubPatTypes.length - 1 // rawSubPatTypes.last is the Seq, thus there are `rawSubPatTypes.length - 1` non-seq elements in the tuple - protected lazy val lastIndexingBinder = if(lastIsStar) nbSubPats-2 else nbSubPats-1 - protected lazy val expectedLength = lastIndexingBinder - firstIndexingBinder + 1 - protected lazy val minLenToCheck = if(lastIsStar) 1 else 0 - protected def seqTree(binder: Symbol) = tupleSel(binder)(firstIndexingBinder+1) - protected def tupleSel(binder: Symbol)(i: Int): Tree = codegen.tupleSel(binder)(i) - - // the trees that select the subpatterns on the extractor's result, referenced by `binder` - // require isSeq - protected def subPatRefsSeq(binder: Symbol): List[Tree] = { - val indexingIndices = (0 to (lastIndexingBinder-firstIndexingBinder)) - val nbIndexingIndices = indexingIndices.length - - // this error-condition has already been checked by checkStarPatOK: - // if(isSeq) assert(firstIndexingBinder + nbIndexingIndices + (if(lastIsStar) 1 else 0) == nbSubPats, "(resultInMonad, ts, subPatTypes, subPats)= "+(resultInMonad, ts, subPatTypes, subPats)) - // there are `firstIndexingBinder` non-seq tuple elements preceding the Seq - (((1 to firstIndexingBinder) map tupleSel(binder)) ++ - // then we have to index the binder that represents the sequence for the remaining subpatterns, except for... - (indexingIndices map codegen.index(seqTree(binder))) ++ - // the last one -- if the last subpattern is a sequence wildcard: drop the prefix (indexed by the refs on the line above), return the remainder - (if(!lastIsStar) Nil else List( - if(nbIndexingIndices == 0) seqTree(binder) - else codegen.drop(seqTree(binder))(nbIndexingIndices)))).toList - } - - // the trees that select the subpatterns on the extractor's result, referenced by `binder` - // require (nbSubPats > 0 && (!lastIsStar || isSeq)) - protected def subPatRefs(binder: Symbol): List[Tree] = - if (nbSubPats == 0) Nil - else if (isSeq) subPatRefsSeq(binder) - else ((1 to nbSubPats) map tupleSel(binder)).toList - - protected def lengthGuard(binder: Symbol): Option[Tree] = - // no need to check unless it's an unapplySeq and the minimal length is non-trivially satisfied - if (!isSeq || (expectedLength < minLenToCheck)) None - else { import CODE._ - // `binder.lengthCompare(expectedLength)` - def checkExpectedLength = (seqTree(binder) DOT seqLenCmp)(LIT(expectedLength)) - - // the comparison to perform - // when the last subpattern is a wildcard-star the expectedLength is but a lower bound - // (otherwise equality is required) - def compareOp: (Tree, Tree) => Tree = - if (lastIsStar) _ INT_>= _ - else _ INT_== _ - - // `if (binder != null && $checkExpectedLength [== | >=] 0) then else zero` - Some((seqTree(binder) ANY_!= NULL) AND compareOp(checkExpectedLength, ZERO)) - } - } - - // TODO: to be called when there's a def unapplyProd(x: T): U - // U must have N members _1,..., _N -- the _i are type checked, call their type Ti, - // - // for now only used for case classes -- pretending there's an unapplyProd that's the identity (and don't call it) - class ExtractorCallProd(fun: Tree, args: List[Tree]) extends ExtractorCall(args) { - // TODO: fix the illegal type bound in pos/t602 -- type inference messes up before we get here: - /*override def equals(x$1: Any): Boolean = ... - val o5: Option[com.mosol.sl.Span[Any]] = // Span[Any] --> Any is not a legal type argument for Span! - */ - // private val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} - // private val origExtractorTp = unapplyMember(orig.symbol.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe).tpe - // private val extractorTp = if (wellKinded(fun.tpe)) fun.tpe else existentialAbstraction(origExtractorTp.typeParams, origExtractorTp.resultType) - // println("ExtractorCallProd: "+ (fun.tpe, existentialAbstraction(origExtractorTp.typeParams, origExtractorTp.resultType))) - // println("ExtractorCallProd: "+ (fun.tpe, args map (_.tpe))) - private def constructorTp = fun.tpe - - def isTyped = fun.isTyped - - // to which type should the previous binder be casted? - def paramType = constructorTp.finalResultType - - def isSeq: Boolean = rawSubPatTypes.nonEmpty && isRepeatedParamType(rawSubPatTypes.last) - protected def rawSubPatTypes = constructorTp.paramTypes - - // binder has type paramType - def treeMaker(binder: Symbol, pos: Position): TreeMaker = { - // checks binder ne null before chaining to the next extractor - ProductExtractorTreeMaker(binder, lengthGuard(binder), Substitution(subPatBinders, subPatRefs(binder))) - } - -/* TODO: remove special case when the following bug is fixed -class Foo(x: Other) { x._1 } // BUG: can't refer to _1 if its defining class has not been type checked yet -case class Other(y: String) --- this is ok: -case class Other(y: String) -class Foo(x: Other) { x._1 } // no error in this order -*/ - override protected def tupleSel(binder: Symbol)(i: Int): Tree = { import CODE._ - // reference the (i-1)th case accessor if it exists, otherwise the (i-1)th tuple component - val caseAccs = binder.info.typeSymbol.caseFieldAccessors - if (caseAccs isDefinedAt (i-1)) REF(binder) DOT caseAccs(i-1) - else codegen.tupleSel(binder)(i) - } - - override def toString(): String = "case class "+ (if (constructorTp eq null) fun else paramType.typeSymbol) +" with arguments "+ args - } - - class ExtractorCallRegular(extractorCallIncludingDummy: Tree, args: List[Tree]) extends ExtractorCall(args) { - private lazy val Some(Apply(extractorCall, _)) = extractorCallIncludingDummy.find{ case Apply(_, List(Ident(nme.SELECTOR_DUMMY))) => true case _ => false } - - def tpe = extractorCall.tpe - def isTyped = (tpe ne NoType) && extractorCall.isTyped && (resultInMonad ne ErrorType) - def paramType = tpe.paramTypes.head - def resultType = tpe.finalResultType - def isSeq = extractorCall.symbol.name == nme.unapplySeq - - def treeMaker(patBinderOrCasted: Symbol, pos: Position): TreeMaker = { - // the extractor call (applied to the binder bound by the flatMap corresponding to the previous (i.e., enclosing/outer) pattern) - val extractorApply = atPos(pos)(spliceApply(patBinderOrCasted)) - val binder = freshSym(pos, pureType(resultInMonad)) // can't simplify this when subPatBinders.isEmpty, since UnitClass.tpe is definitely wrong when isSeq, and resultInMonad should always be correct since it comes directly from the extractor's result type - ExtractorTreeMaker(extractorApply, lengthGuard(binder), binder, Substitution(subPatBinders, subPatRefs(binder)))(resultType.typeSymbol == BooleanClass) - } - - override protected def seqTree(binder: Symbol): Tree = - if (firstIndexingBinder == 0) CODE.REF(binder) - else super.seqTree(binder) - - // the trees that select the subpatterns on the extractor's result, referenced by `binder` - // require (nbSubPats > 0 && (!lastIsStar || isSeq)) - override protected def subPatRefs(binder: Symbol): List[Tree] = - if (!isSeq && nbSubPats == 1) List(CODE.REF(binder)) // special case for extractors - else super.subPatRefs(binder) - - protected def spliceApply(binder: Symbol): Tree = { - object splice extends Transformer { - override def transform(t: Tree) = t match { - case Apply(x, List(Ident(nme.SELECTOR_DUMMY))) => - treeCopy.Apply(t, x, List(CODE.REF(binder))) - case _ => super.transform(t) - } - } - splice.transform(extractorCallIncludingDummy) - } - - // what's the extractor's result type in the monad? - // turn an extractor's result type into something `monadTypeToSubPatTypesAndRefs` understands - protected lazy val resultInMonad: Type = if(!hasLength(tpe.paramTypes, 1)) ErrorType else { - if (resultType.typeSymbol == BooleanClass) UnitClass.tpe - else matchMonadResult(resultType) - } - - protected lazy val rawSubPatTypes = - if (resultInMonad.typeSymbol eq UnitClass) Nil - else if(nbSubPats == 1) List(resultInMonad) - else getProductArgs(resultInMonad) match { - case Nil => List(resultInMonad) - case x => x - } - - override def toString() = extractorCall +": "+ extractorCall.tpe +" (symbol= "+ extractorCall.symbol +")." - } - - /** A conservative approximation of which patterns do not discern anything. - * They are discarded during the translation. - */ - object WildcardPattern { - def unapply(pat: Tree): Boolean = pat match { - case Bind(nme.WILDCARD, WildcardPattern()) => true // don't skip when binding an interesting symbol! - case Ident(nme.WILDCARD) => true - case Star(WildcardPattern()) => true - case x: Ident => treeInfo.isVarPattern(x) - case Alternative(ps) => ps forall (WildcardPattern.unapply(_)) - case EmptyTree => true - case _ => false - } - } - - object Bound { - def unapply(t: Tree): Option[(Symbol, Tree)] = t match { - case t@Bind(n, p) if (t.symbol ne null) && (t.symbol ne NoSymbol) => // pos/t2429 does not satisfy these conditions - Some((t.symbol, p)) - case _ => None - } - } - } - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// substitution -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - trait TypedSubstitution extends MatchMonadInterface { - object Substitution { - def apply(from: Symbol, to: Tree) = new Substitution(List(from), List(to)) - // requires sameLength(from, to) - def apply(from: List[Symbol], to: List[Tree]) = - if (from nonEmpty) new Substitution(from, to) else EmptySubstitution - } - - class Substitution(val from: List[Symbol], val to: List[Tree]) { - // We must explicitly type the trees that we replace inside some other tree, since the latter may already have been typed, - // and will thus not be retyped. This means we might end up with untyped subtrees inside bigger, typed trees. - def apply(tree: Tree): Tree = { - // according to -Ystatistics 10% of translateMatch's time is spent in this method... - // since about half of the typedSubst's end up being no-ops, the check below shaves off 5% of the time spent in typedSubst - if (!tree.exists { case i@Ident(_) => from contains i.symbol case _ => false}) tree - else (new Transformer { - @inline private def typedIfOrigTyped(to: Tree, origTp: Type): Tree = - if (origTp == null || origTp == NoType) to - // important: only type when actually substing and when original tree was typed - // (don't need to use origTp as the expected type, though, and can't always do this anyway due to unknown type params stemming from polymorphic extractors) - else typer.typed(to, EXPRmode, WildcardType) - - override def transform(tree: Tree): Tree = { - def subst(from: List[Symbol], to: List[Tree]): Tree = - if (from.isEmpty) tree - else if (tree.symbol == from.head) typedIfOrigTyped(to.head.shallowDuplicate, tree.tpe) - else subst(from.tail, to.tail) - - tree match { - case Ident(_) => subst(from, to) - case _ => super.transform(tree) - } - } - }).transform(tree) - } - - - // the substitution that chains `other` before `this` substitution - // forall t: Tree. this(other(t)) == (this >> other)(t) - def >>(other: Substitution): Substitution = { - val (fromFiltered, toFiltered) = (from, to).zipped filter { (f, t) => !other.from.contains(f) } - new Substitution(other.from ++ fromFiltered, other.to.map(apply) ++ toFiltered) // a quick benchmarking run indicates the `.map(apply)` is not too costly - } - override def toString = (from zip to) mkString("Substitution(", ", ", ")") - } - - object EmptySubstitution extends Substitution(Nil, Nil) { - override def apply(tree: Tree): Tree = tree - override def >>(other: Substitution): Substitution = other - } - } - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// the making of the trees -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - trait TreeMakers extends TypedSubstitution { self: CodegenCore => - def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) = - (cases, Nil) - - def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Tree => Tree]): Option[Tree] = - None - - // for catch (no need to customize match failure) - def emitTypeSwitch(bindersAndCases: List[(Symbol, List[TreeMaker])], pt: Type): Option[List[CaseDef]] = - None - - abstract class TreeMaker { - /** captures the scope and the value of the bindings in patterns - * important *when* the substitution happens (can't accumulate and do at once after the full matcher has been constructed) - */ - def substitution: Substitution = - if (currSub eq null) localSubstitution - else currSub - - protected def localSubstitution: Substitution - - private[TreeMakers] def incorporateOuterSubstitution(outerSubst: Substitution): Unit = { - if (currSub ne null) { - println("BUG: incorporateOuterSubstitution called more than once for "+ (this, currSub, outerSubst)) - Thread.dumpStack() - } - else currSub = outerSubst >> substitution - } - private[this] var currSub: Substitution = null - - // build Tree that chains `next` after the current extractor - def chainBefore(next: Tree)(casegen: Casegen): Tree - } - - trait NoNewBinders extends TreeMaker { - protected val localSubstitution: Substitution = EmptySubstitution - } - - case class TrivialTreeMaker(tree: Tree) extends TreeMaker with NoNewBinders { - def chainBefore(next: Tree)(casegen: Casegen): Tree = tree - } - - case class BodyTreeMaker(body: Tree, matchPt: Type) extends TreeMaker with NoNewBinders { - def chainBefore(next: Tree)(casegen: Casegen): Tree = // assert(next eq EmptyTree) - atPos(body.pos)(casegen.one(substitution(body))) // since SubstOnly treemakers are dropped, need to do it here - } - - case class SubstOnlyTreeMaker(prevBinder: Symbol, nextBinder: Symbol) extends TreeMaker { - val localSubstitution = Substitution(prevBinder, CODE.REF(nextBinder)) - def chainBefore(next: Tree)(casegen: Casegen): Tree = substitution(next) - } - - abstract class FunTreeMaker extends TreeMaker { - val nextBinder: Symbol - } - - abstract class CondTreeMaker extends FunTreeMaker { - val pos: Position - val prevBinder: Symbol - val nextBinderTp: Type - val cond: Tree - val res: Tree - - lazy val nextBinder = freshSym(pos, nextBinderTp) - lazy val localSubstitution = Substitution(List(prevBinder), List(CODE.REF(nextBinder))) - - def chainBefore(next: Tree)(casegen: Casegen): Tree = - atPos(pos)(casegen.flatMapCond(cond, res, nextBinder, substitution(next))) - } - - /** - * Make a TreeMaker that will result in an extractor call specified by `extractor` - * the next TreeMaker (here, we don't know which it'll be) is chained after this one by flatMap'ing - * a function with binder `nextBinder` over our extractor's result - * the function's body is determined by the next TreeMaker - * in this function's body, and all the subsequent ones, references to the symbols in `from` will be replaced by the corresponding tree in `to` - */ - case class ExtractorTreeMaker(extractor: Tree, extraCond: Option[Tree], nextBinder: Symbol, localSubstitution: Substitution)(extractorReturnsBoolean: Boolean) extends FunTreeMaker { - def chainBefore(next: Tree)(casegen: Casegen): Tree = { - val condAndNext = extraCond map (casegen.ifThenElseZero(_, next)) getOrElse next - atPos(extractor.pos)( - if (extractorReturnsBoolean) casegen.flatMapCond(extractor, CODE.UNIT, nextBinder, substitution(condAndNext)) - else casegen.flatMap(extractor, nextBinder, substitution(condAndNext)) - ) - } - - override def toString = "X"+(extractor, nextBinder) - } - - // TODO: allow user-defined unapplyProduct - case class ProductExtractorTreeMaker(prevBinder: Symbol, extraCond: Option[Tree], localSubstitution: Substitution) extends TreeMaker { import CODE._ - def chainBefore(next: Tree)(casegen: Casegen): Tree = { - val nullCheck = REF(prevBinder) OBJ_NE NULL - val cond = extraCond map (nullCheck AND _) getOrElse nullCheck - casegen.ifThenElseZero(cond, substitution(next)) - } - - override def toString = "P"+(prevBinder, extraCond getOrElse "", localSubstitution) - } - - // tack an outer test onto `cond` if binder.info and expectedType warrant it - def maybeWithOuterCheck(binder: Symbol, expectedTp: Type)(cond: Tree): Tree = { import CODE._ - if ( !((expectedTp.prefix eq NoPrefix) || expectedTp.prefix.typeSymbol.isPackageClass) - && needsOuterTest(expectedTp, binder.info, matchOwner)) { - val expectedPrefix = expectedTp.prefix match { - case ThisType(clazz) => THIS(clazz) - case pre => REF(pre.prefix, pre.termSymbol) - } - - // ExplicitOuter replaces `Select(q, outerSym) OBJ_EQ expectedPrefix` by `Select(q, outerAccessor(outerSym.owner)) OBJ_EQ expectedPrefix` - // if there's an outer accessor, otherwise the condition becomes `true` -- TODO: can we improve needsOuterTest so there's always an outerAccessor? - val outer = expectedTp.typeSymbol.newMethod(vpmName.outer) setInfo expectedTp.prefix setFlag SYNTHETIC - val outerCheck = (Select(codegen._asInstanceOf(binder, expectedTp), outer)) OBJ_EQ expectedPrefix - - // first check cond, since that should ensure we're not selecting outer on null - codegen.and(cond, outerCheck) - } - else - cond - } - - // containsUnchecked: also need to test when erasing pt loses crucial information (maybe we can recover it using a TypeTag) - def needsTypeTest(tp: Type, pt: Type): Boolean = !(tp <:< pt) // || containsUnchecked(pt) - // TODO: try to find the TypeTag for the binder's type and the expected type, and if they exists, - // check that the TypeTag of the binder's type conforms to the TypeTag of the expected type - private def typeTest(binderToTest: Symbol, expectedTp: Type, disableOuterCheck: Boolean = false, dynamic: Boolean = false): Tree = { import CODE._ - // def coreTest = - if (disableOuterCheck) codegen._isInstanceOf(binderToTest, expectedTp) else maybeWithOuterCheck(binderToTest, expectedTp)(codegen._isInstanceOf(binderToTest, expectedTp)) - // [Eugene to Adriaan] use `resolveErasureTag` instead of `findManifest`. please, provide a meaningful position - // if (opt.experimental && containsUnchecked(expectedTp)) { - // if (dynamic) { - // val expectedTpTagTree = findManifest(expectedTp, true) - // if (!expectedTpTagTree.isEmpty) - // ((expectedTpTagTree DOT "erasure".toTermName) DOT "isAssignableFrom".toTermName)(REF(binderToTest) DOT nme.getClass_) - // else - // coreTest - // } else { - // val expectedTpTagTree = findManifest(expectedTp, true) - // val binderTpTagTree = findManifest(binderToTest.info, true) - // if(!(expectedTpTagTree.isEmpty || binderTpTagTree.isEmpty)) - // coreTest AND (binderTpTagTree DOT nme.CONFORMS)(expectedTpTagTree) - // else - // coreTest - // } - // } else coreTest - } - - // need to substitute since binder may be used outside of the next extractor call (say, in the body of the case) - case class TypeTestTreeMaker(prevBinder: Symbol, nextBinderTp: Type, pos: Position) extends CondTreeMaker { - val cond = typeTest(prevBinder, nextBinderTp, dynamic = true) - val res = codegen._asInstanceOf(prevBinder, nextBinderTp) - override def toString = "TT"+(prevBinder, nextBinderTp) - } - - // implements the run-time aspects of (§8.2) (typedPattern has already done the necessary type transformations) - // TODO: normalize construction, which yields a combination of a EqualityTestTreeMaker (when necessary) and a TypeTestTreeMaker - case class TypeAndEqualityTestTreeMaker(prevBinder: Symbol, patBinder: Symbol, pt: Type, pos: Position) extends CondTreeMaker { - val nextBinderTp = glb(List(patBinder.info.widen, pt)) - - /** Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms: - - A reference to a class C, p.C, or T#C. - This type pattern matches any non-null instance of the given class. - Note that the prefix of the class, if it is given, is relevant for determining class instances. - For instance, the pattern p.C matches only instances of classes C which were created with the path p as prefix. - The bottom types scala.Nothing and scala.Null cannot be used as type patterns, because they would match nothing in any case. - - - A singleton type p.type. - This type pattern matches only the value denoted by the path p - (that is, a pattern match involved a comparison of the matched value with p using method eq in class AnyRef). // TODO: the actual pattern matcher uses ==, so that's what I'm using for now - // https://issues.scala-lang.org/browse/SI-4577 "pattern matcher, still disappointing us at equality time" - - - A compound type pattern T1 with ... with Tn where each Ti is a type pat- tern. - This type pattern matches all values that are matched by each of the type patterns Ti. - - - A parameterized type pattern T[a1,...,an], where the ai are type variable patterns or wildcards _. - This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. - The bounds or alias type of these type variable are determined as described in (§8.3). - - - A parameterized type pattern scala.Array[T1], where T1 is a type pattern. // TODO - This type pattern matches any non-null instance of type scala.Array[U1], where U1 is a type matched by T1. - **/ - - // generate the tree for the run-time test that follows from the fact that - // a `scrut` of known type `scrutTp` is expected to have type `expectedTp` - // uses maybeWithOuterCheck to check the type's prefix - private def typeAndEqualityTest(patBinder: Symbol, pt: Type): Tree = { import CODE._ - // TODO: `null match { x : T }` will yield a check that (indirectly) tests whether `null ne null` - // don't bother (so that we don't end up with the warning "comparing values of types Null and Null using `ne' will always yield false") - def genEqualsAndInstanceOf(sym: Symbol): Tree - = codegen._equals(REF(sym), patBinder) AND typeTest(patBinder, pt.widen, disableOuterCheck = true) - - def isRefTp(tp: Type) = tp <:< AnyRefClass.tpe - - val patBinderTp = patBinder.info.widen - def isMatchUnlessNull = isRefTp(pt) && !needsTypeTest(patBinderTp, pt) - - // TODO: [SPEC] type test for Array - // TODO: use TypeTags to improve tests (for erased types we can do better when we have a TypeTag) - pt match { - case SingleType(_, sym) /*this implies sym.isStable*/ => genEqualsAndInstanceOf(sym) // TODO: [SPEC] the spec requires `eq` instead of `==` here - case ThisType(sym) if sym.isModule => genEqualsAndInstanceOf(sym) // must use == to support e.g. List() == Nil - case ThisType(sym) => REF(patBinder) OBJ_EQ This(sym) - case ConstantType(Constant(null)) if isRefTp(patBinderTp) => REF(patBinder) OBJ_EQ NULL - case ConstantType(const) => codegen._equals(Literal(const), patBinder) - case _ if isMatchUnlessNull => maybeWithOuterCheck(patBinder, pt)(REF(patBinder) OBJ_NE NULL) - case _ => typeTest(patBinder, pt) - } - } - - val cond = typeAndEqualityTest(patBinder, pt) - val res = codegen._asInstanceOf(patBinder, nextBinderTp) - - // TODO: remove this - def isStraightTypeTest = cond match { case TypeApply(_, _) => cond.symbol == Any_isInstanceOf case _ => false } - - override def toString = "TET"+(patBinder, pt) - } - - // need to substitute to deal with existential types -- TODO: deal with existentials better, don't substitute (see RichClass during quick.comp) - case class EqualityTestTreeMaker(prevBinder: Symbol, patTree: Tree, pos: Position) extends CondTreeMaker { - val nextBinderTp = prevBinder.info.widen - - // NOTE: generate `patTree == patBinder`, since the extractor must be in control of the equals method (also, patBinder may be null) - // equals need not be well-behaved, so don't intersect with pattern's (stabilized) type (unlike MaybeBoundTyped's accumType, where it's required) - val cond = codegen._equals(patTree, prevBinder) - val res = CODE.REF(prevBinder) - override def toString = "ET"+(prevBinder, patTree) - } - - case class AlternativesTreeMaker(prevBinder: Symbol, var altss: List[List[TreeMaker]], pos: Position) extends TreeMaker with NoNewBinders { - // don't substitute prevBinder to nextBinder, a set of alternatives does not need to introduce a new binder, simply reuse the previous one - - override private[TreeMakers] def incorporateOuterSubstitution(outerSubst: Substitution): Unit = { - super.incorporateOuterSubstitution(outerSubst) - altss = altss map (alts => propagateSubstitution(alts, substitution)) - } - - def chainBefore(next: Tree)(codegenAlt: Casegen): Tree = { import CODE._ - atPos(pos){ - // one alternative may still generate multiple trees (e.g., an extractor call + equality test) - // (for now,) alternatives may not bind variables (except wildcards), so we don't care about the final substitution built internally by makeTreeMakers - val combinedAlts = altss map (altTreeMakers => - ((casegen: Casegen) => combineExtractors(altTreeMakers :+ TrivialTreeMaker(casegen.one(TRUE_typed)))(casegen)) - ) - - val findAltMatcher = codegenAlt.matcher(EmptyTree, NoSymbol, BooleanClass.tpe)(combinedAlts, Some(x => FALSE_typed)) - codegenAlt.ifThenElseZero(findAltMatcher, substitution(next)) - } - } - } - - case class GuardTreeMaker(guardTree: Tree) extends TreeMaker with NoNewBinders { - def chainBefore(next: Tree)(casegen: Casegen): Tree = casegen.flatMapGuard(substitution(guardTree), next) - override def toString = "G("+ guardTree +")" - } - - // combineExtractors changes the current substitution's of the tree makers in `treeMakers` - // requires propagateSubstitution(treeMakers) has been called - def combineExtractors(treeMakers: List[TreeMaker])(casegen: Casegen): Tree = - treeMakers.foldRight(EmptyTree: Tree)((a, b) => a.chainBefore(b)(casegen)) - - - def removeSubstOnly(makers: List[TreeMaker]) = makers filterNot (_.isInstanceOf[SubstOnlyTreeMaker]) - - // a foldLeft to accumulate the localSubstitution left-to-right - // it drops SubstOnly tree makers, since their only goal in life is to propagate substitutions to the next tree maker, which is fullfilled by propagateSubstitution - def propagateSubstitution(treeMakers: List[TreeMaker], initial: Substitution): List[TreeMaker] = { - var accumSubst: Substitution = initial - treeMakers foreach { maker => - maker incorporateOuterSubstitution accumSubst - accumSubst = maker.substitution - } - removeSubstOnly(treeMakers) - } - - // calls propagateSubstitution on the treemakers - def combineCases(scrut: Tree, scrutSym: Symbol, casesRaw: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Tree => Tree]): Tree = { - // drops SubstOnlyTreeMakers, since their effect is now contained in the TreeMakers that follow them - val casesNoSubstOnly = casesRaw map (propagateSubstitution(_, EmptySubstitution)) - combineCasesNoSubstOnly(scrut, scrutSym, casesNoSubstOnly, pt, owner, matchFailGenOverride) - } - - def combineCasesNoSubstOnly(scrut: Tree, scrutSym: Symbol, casesNoSubstOnly: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Tree => Tree]): Tree = - fixerUpper(owner, scrut.pos){ - val ptDefined = if (isFullyDefined(pt)) pt else NoType - def matchFailGen = (matchFailGenOverride orElse Some(CODE.MATCHERROR(_: Tree))) - // println("combining cases: "+ (casesNoSubstOnly.map(_.mkString(" >> ")).mkString("{", "\n", "}"))) - - emitSwitch(scrut, scrutSym, casesNoSubstOnly, pt, matchFailGenOverride).getOrElse{ - if (casesNoSubstOnly nonEmpty) { - // before optimizing, check casesNoSubstOnly for presence of a default case, - // since DCE will eliminate trivial cases like `case _ =>`, even if they're the last one - // exhaustivity and reachability must be checked before optimization as well - // TODO: improve notion of trivial/irrefutable -- a trivial type test before the body still makes for a default case - // ("trivial" depends on whether we're emitting a straight match or an exception, or more generally, any supertype of scrutSym.tpe is a no-op) - // irrefutability checking should use the approximation framework also used for CSE, unreachability and exhaustivity checking - val synthCatchAll = - if (casesNoSubstOnly.nonEmpty && { - val nonTrivLast = casesNoSubstOnly.last - nonTrivLast.nonEmpty && nonTrivLast.head.isInstanceOf[BodyTreeMaker] - }) None - else matchFailGen - - val (cases, toHoist) = optimizeCases(scrutSym, casesNoSubstOnly, pt) - - val matchRes = codegen.matcher(scrut, scrutSym, pt)(cases map combineExtractors, synthCatchAll) - - if (toHoist isEmpty) matchRes else Block(toHoist, matchRes) - } else { - codegen.matcher(scrut, scrutSym, pt)(Nil, matchFailGen) - } - } - } - - // TODO: do this during tree construction, but that will require tracking the current owner in treemakers - // TODO: assign more fine-grained positions - // fixes symbol nesting, assigns positions - protected def fixerUpper(origOwner: Symbol, pos: Position) = new Traverser { - currentOwner = origOwner - - override def traverse(t: Tree) { - if (t != EmptyTree && t.pos == NoPosition) { - t.setPos(pos) - } - t match { - case Function(_, _) if t.symbol == NoSymbol => - t.symbol = currentOwner.newAnonymousFunctionValue(t.pos) - // println("new symbol for "+ (t, t.symbol.ownerChain)) - case Function(_, _) if (t.symbol.owner == NoSymbol) || (t.symbol.owner == origOwner) => - // println("fundef: "+ (t, t.symbol.ownerChain, currentOwner.ownerChain)) - t.symbol.owner = currentOwner - case d : DefTree if (d.symbol != NoSymbol) && ((d.symbol.owner == NoSymbol) || (d.symbol.owner == origOwner)) => // don't indiscriminately change existing owners! (see e.g., pos/t3440, pos/t3534, pos/unapplyContexts2) - // println("def: "+ (d, d.symbol.ownerChain, currentOwner.ownerChain)) - if(d.symbol.isLazy) { // for lazy val's accessor -- is there no tree?? - assert(d.symbol.lazyAccessor != NoSymbol && d.symbol.lazyAccessor.owner == d.symbol.owner, d.symbol.lazyAccessor) - d.symbol.lazyAccessor.owner = currentOwner - } - if(d.symbol.moduleClass ne NoSymbol) - d.symbol.moduleClass.owner = currentOwner - - d.symbol.owner = currentOwner - // case _ if (t.symbol != NoSymbol) && (t.symbol ne null) => - // println("untouched "+ (t, t.getClass, t.symbol.ownerChain, currentOwner.ownerChain)) - case _ => - } - super.traverse(t) - } - - // override def apply - // println("before fixerupper: "+ xTree) - // currentRun.trackerFactory.snapshot() - // println("after fixerupper") - // currentRun.trackerFactory.snapshot() - } - } - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// generate actual trees -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - trait CodegenCore extends MatchMonadInterface { - private var ctr = 0 - def freshName(prefix: String) = {ctr += 1; vpmName.counted(prefix, ctr)} - - // assert(owner ne null); assert(owner ne NoSymbol) - def freshSym(pos: Position, tp: Type = NoType, prefix: String = "x") = - NoSymbol.newTermSymbol(freshName(prefix), pos) setInfo tp - - // codegen relevant to the structure of the translation (how extractors are combined) - trait AbsCodegen { - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree - - // local / context-free - def _asInstanceOf(b: Symbol, tp: Type): Tree - def _equals(checker: Tree, binder: Symbol): Tree - def _isInstanceOf(b: Symbol, tp: Type): Tree - def and(a: Tree, b: Tree): Tree - def drop(tgt: Tree)(n: Int): Tree - def index(tgt: Tree)(i: Int): Tree - def mkZero(tp: Type): Tree - def tupleSel(binder: Symbol)(i: Int): Tree - } - - // structure - trait Casegen extends AbsCodegen { import CODE._ - def one(res: Tree): Tree - - def flatMap(prev: Tree, b: Symbol, next: Tree): Tree - def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree - def flatMapGuard(cond: Tree, next: Tree): Tree - def ifThenElseZero(c: Tree, then: Tree): Tree = IF (c) THEN then ELSE zero - protected def zero: Tree - } - - def codegen: AbsCodegen - - def typesConform(tp: Type, pt: Type) = ((tp eq pt) || (tp <:< pt)) - - abstract class CommonCodegen extends AbsCodegen { import CODE._ - def fun(arg: Symbol, body: Tree): Tree = Function(List(ValDef(arg)), body) - def genTypeApply(tfun: Tree, args: Type*): Tree = if(args contains NoType) tfun else TypeApply(tfun, args.toList map TypeTree) - def tupleSel(binder: Symbol)(i: Int): Tree = (REF(binder) DOT nme.productAccessorName(i)) // make tree that accesses the i'th component of the tuple referenced by binder - def index(tgt: Tree)(i: Int): Tree = tgt APPLY (LIT(i)) - def drop(tgt: Tree)(n: Int): Tree = (tgt DOT vpmName.drop) (LIT(n)) - def _equals(checker: Tree, binder: Symbol): Tree = checker MEMBER_== REF(binder) // NOTE: checker must be the target of the ==, that's the patmat semantics for ya - def and(a: Tree, b: Tree): Tree = a AND b - - // drop annotations generated by CPS plugin etc, since its annotationchecker rejects T @cps[U] <: Any - // let's assume for now annotations don't affect casts, drop them there, and bring them back using the outer Typed tree - private def mkCast(t: Tree, tp: Type) = - Typed(gen.mkAsInstanceOf(t, tp.withoutAnnotations, true, false), TypeTree() setType tp) - - // the force is needed mainly to deal with the GADT typing hack (we can't detect it otherwise as tp nor pt need contain an abstract type, we're just casting wildly) - def _asInstanceOf(t: Tree, tp: Type, force: Boolean = false): Tree = if (!force && (t.tpe ne NoType) && t.isTyped && typesConform(t.tpe, tp)) t else mkCast(t, tp) - def _asInstanceOf(b: Symbol, tp: Type): Tree = if (typesConform(b.info, tp)) REF(b) else mkCast(REF(b), tp) - def _isInstanceOf(b: Symbol, tp: Type): Tree = gen.mkIsInstanceOf(REF(b), tp.withoutAnnotations, true, false) - // if (typesConform(b.info, tpX)) { println("warning: emitted spurious isInstanceOf: "+(b, tp)); TRUE } - - // duplicated out of frustration with cast generation - def mkZero(tp: Type): Tree = { - tp.typeSymbol match { - case UnitClass => Literal(Constant()) - case BooleanClass => Literal(Constant(false)) - case FloatClass => Literal(Constant(0.0f)) - case DoubleClass => Literal(Constant(0.0d)) - case ByteClass => Literal(Constant(0.toByte)) - case ShortClass => Literal(Constant(0.toShort)) - case IntClass => Literal(Constant(0)) - case LongClass => Literal(Constant(0L)) - case CharClass => Literal(Constant(0.toChar)) - case _ => gen.mkAsInstanceOf(Literal(Constant(null)), tp, any = true, wrapInApply = false) // the magic incantation is true/false here - } - } - } - } - - trait PureMatchMonadInterface extends MatchMonadInterface { - val matchStrategy: Tree - - def inMatchMonad(tp: Type): Type = appliedType(oneSig, List(tp)).finalResultType - def pureType(tp: Type): Type = appliedType(oneSig, List(tp)).paramTypes.headOption getOrElse NoType // fail gracefully (otherwise we get crashes) - protected def matchMonadSym = oneSig.finalResultType.typeSymbol - - import CODE._ - def _match(n: Name): SelectStart = matchStrategy DOT n - - private lazy val oneSig: Type = - typer.typed(_match(vpmName.one), EXPRmode | POLYmode | TAPPmode | FUNmode, WildcardType).tpe // TODO: error message - } - - trait PureCodegen extends CodegenCore with PureMatchMonadInterface { - def codegen: AbsCodegen = pureCodegen - - object pureCodegen extends CommonCodegen with Casegen { import CODE._ - //// methods in MatchingStrategy (the monad companion) -- used directly in translation - // __match.runOrElse(`scrut`)(`scrutSym` => `matcher`) - // TODO: consider catchAll, or virtualized matching will break in exception handlers - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = - _match(vpmName.runOrElse) APPLY (scrut) APPLY (fun(scrutSym, cases map (f => f(this)) reduceLeft typedOrElse)) - - // __match.one(`res`) - def one(res: Tree): Tree = (_match(vpmName.one)) (res) - // __match.zero - protected def zero: Tree = _match(vpmName.zero) - // __match.guard(`c`, `then`) - def guard(c: Tree, then: Tree): Tree = _match(vpmName.guard) APPLY (c, then) - - //// methods in the monad instance -- used directly in translation - // `prev`.flatMap(`b` => `next`) - def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = (prev DOT vpmName.flatMap)(fun(b, next)) - // `thisCase`.orElse(`elseCase`) - def typedOrElse(thisCase: Tree, elseCase: Tree): Tree = (thisCase DOT vpmName.orElse) APPLY (elseCase) - // __match.guard(`cond`, `res`).flatMap(`nextBinder` => `next`) - def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = flatMap(guard(cond, res), nextBinder, next) - // __match.guard(`guardTree`, ()).flatMap((_: P[Unit]) => `next`) - def flatMapGuard(guardTree: Tree, next: Tree): Tree = flatMapCond(guardTree, CODE.UNIT, freshSym(guardTree.pos, pureType(UnitClass.tpe)), next) - } - } - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// OPTIMIZATIONS -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// decisions, decisions -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - trait TreeMakerApproximation extends TreeMakers { self: CodegenCore => - object Test { - var currId = 0 - } - case class Test(cond: Cond, treeMaker: TreeMaker) { - // def <:<(other: Test) = cond <:< other.cond - // def andThen_: (prev: List[Test]): List[Test] = - // prev.filterNot(this <:< _) :+ this - - private val reusedBy = new collection.mutable.HashSet[Test] - var reuses: Option[Test] = None - def registerReuseBy(later: Test): Unit = { - assert(later.reuses.isEmpty, later.reuses) - reusedBy += later - later.reuses = Some(this) - } - - val id = { Test.currId += 1; Test.currId} - override def toString = - if (cond eq Top) "T" - else if(cond eq Havoc) "!?" - else "T"+ id + (if(reusedBy nonEmpty) "!["+ treeMaker +"]" else (if(reuses.isEmpty) "["+ treeMaker +"]" else " cf. T"+reuses.get.id)) - } - - object Cond { - // def refines(self: Cond, other: Cond): Boolean = (self, other) match { - // case (Bottom, _) => true - // case (Havoc , _) => true - // case (_ , Top) => true - // case (_ , _) => false - // } - var currId = 0 - } - - abstract class Cond { - // def testedPath: Tree - // def <:<(other: Cond) = Cond.refines(this, other) - - val id = { Cond.currId += 1; Cond.currId} - } - - // does not contribute any knowledge - case object Top extends Cond - - // takes away knowledge. e.g., a user-defined guard - case object Havoc extends Cond - - // we know everything! everything! - // this either means the case is unreachable, - // or that it is statically known to be picked -- at this point in the decision tree --> no point in emitting further alternatives - // case object Bottom extends Cond - - - object EqualityCond { - private val uniques = new collection.mutable.HashMap[(Tree, Tree), EqualityCond] - def apply(testedPath: Tree, rhs: Tree): EqualityCond = uniques getOrElseUpdate((testedPath, rhs), new EqualityCond(testedPath, rhs)) - } - class EqualityCond(testedPath: Tree, rhs: Tree) extends Cond { - // def negation = TopCond // inequality doesn't teach us anything - // do simplification when we know enough about the tree statically: - // - collapse equal trees - // - accumulate tests when (in)equality not known statically - // - become bottom when we statically know this can never match - - override def toString = testedPath +" == "+ rhs +"#"+ id - } - - object TypeCond { - private val uniques = new collection.mutable.HashMap[(Tree, Type), TypeCond] - def apply(testedPath: Tree, pt: Type): TypeCond = uniques getOrElseUpdate((testedPath, pt), new TypeCond(testedPath, pt)) - } - class TypeCond(testedPath: Tree, pt: Type) extends Cond { - // def negation = TopCond // inequality doesn't teach us anything - // do simplification when we know enough about the tree statically: - // - collapse equal trees - // - accumulate tests when (in)equality not known statically - // - become bottom when we statically know this can never match - override def toString = testedPath +" <: "+ pt +"#"+ id - } - - object TypeAndEqualityCond { - private val uniques = new collection.mutable.HashMap[(Tree, Type), TypeAndEqualityCond] - def apply(testedPath: Tree, pt: Type): TypeAndEqualityCond = uniques getOrElseUpdate((testedPath, pt), new TypeAndEqualityCond(testedPath, pt)) - } - class TypeAndEqualityCond(testedPath: Tree, pt: Type) extends Cond { - // def negation = TopCond // inequality doesn't teach us anything - // do simplification when we know enough about the tree statically: - // - collapse equal trees - // - accumulate tests when (in)equality not known statically - // - become bottom when we statically know this can never match - override def toString = testedPath +" (<: && ==) "+ pt +"#"+ id - } - - def approximateMatch(root: Symbol, cases: List[List[TreeMaker]]): List[List[Test]] = { - // a variable in this set should never be replaced by a tree that "does not consist of a selection on a variable in this set" (intuitively) - val pointsToBound = collection.mutable.HashSet(root) - - // the substitution that renames variables to variables in pointsToBound - var normalize: Substitution = EmptySubstitution - - // replaces a variable (in pointsToBound) by a selection on another variable in pointsToBound - // TODO check: - // pointsToBound -- accumSubst.from == Set(root) && (accumSubst.from.toSet -- pointsToBound) isEmpty - var accumSubst: Substitution = EmptySubstitution - - val trees = new collection.mutable.HashSet[Tree] - - def approximateTreeMaker(tm: TreeMaker): Test = { - val subst = tm.substitution - - // find part of substitution that replaces bound symbols by new symbols, and reverse that part - // so that we don't introduce new aliases for existing symbols, thus keeping the set of bound symbols minimal - val (boundSubst, unboundSubst) = (subst.from zip subst.to) partition {case (f, t) => - t.isInstanceOf[Ident] && (t.symbol ne NoSymbol) && pointsToBound(f) - } - val (boundFrom, boundTo) = boundSubst.unzip - normalize >>= Substitution(boundTo map (_.symbol), boundFrom map (CODE.REF(_))) - // println("normalize: "+ normalize) - - val (unboundFrom, unboundTo) = unboundSubst unzip - val okSubst = Substitution(unboundFrom, unboundTo map (normalize(_))) // it's important substitution does not duplicate trees here -- it helps to keep hash consing simple, anyway - pointsToBound ++= ((okSubst.from, okSubst.to).zipped filter { (f, t) => pointsToBound exists (sym => t.exists(_.symbol == sym)) })._1 - // println("pointsToBound: "+ pointsToBound) - - accumSubst >>= okSubst - // println("accumSubst: "+ accumSubst) - - // TODO: improve, e.g., for constants - def sameValue(a: Tree, b: Tree): Boolean = (a eq b) || ((a, b) match { - case (_ : Ident, _ : Ident) => a.symbol eq b.symbol - case _ => false - }) - - // hashconsing trees (modulo value-equality) - def unique(t: Tree): Tree = - trees find (a => a.equalsStructure0(t)(sameValue)) match { - case Some(orig) => orig // println("unique: "+ (t eq orig, orig)); - case _ => trees += t; t - } - - def uniqueTp(tp: Type): Type = tp match { - // typerefs etc are already hashconsed - case _ : UniqueType => tp - case tp@RefinedType(parents, EmptyScope) => tp.memo(tp: Type)(identity) // TODO: does this help? - case _ => tp - } - - def binderToUniqueTree(b: Symbol) = unique(accumSubst(normalize(CODE.REF(b)))) - - Test(tm match { - case ProductExtractorTreeMaker(pb, None, subst) => Top // TODO: NotNullTest(prevBinder) - case tm@TypeTestTreeMaker(prevBinder, nextBinderTp, _) => TypeCond(binderToUniqueTree(prevBinder), uniqueTp(nextBinderTp)) - case tm@TypeAndEqualityTestTreeMaker(_, patBinder, pt, _) => TypeAndEqualityCond(binderToUniqueTree(patBinder), uniqueTp(pt)) - case tm@EqualityTestTreeMaker(prevBinder, patTree, _) => EqualityCond(binderToUniqueTree(prevBinder), unique(patTree)) - case ExtractorTreeMaker(_, _, _, _) - | GuardTreeMaker(_) - | ProductExtractorTreeMaker(_, Some(_), _) => Havoc - case AlternativesTreeMaker(_, _, _) => Havoc // TODO: can do better here - case SubstOnlyTreeMaker(_, _) => Top - case BodyTreeMaker(_, _) => Havoc - }, tm) - } - - cases.map { _ map approximateTreeMaker } - } - } - -//// - trait CommonSubconditionElimination extends TreeMakerApproximation { self: OptimizedCodegen => - /** a flow-sensitive, generalised, common sub-expression elimination - * reuse knowledge from performed tests - * the only sub-expressions we consider are the conditions and results of the three tests (type, type&equality, equality) - * when a sub-expression is share, it is stored in a mutable variable - * the variable is floated up so that its scope includes all of the program that shares it - * we generalize sharing to implication, where b reuses a if a => b and priors(a) => priors(b) (the priors of a sub expression form the path through the decision tree) - * - * intended to be generalised to exhaustivity/reachability checking - */ - def doCSE(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): List[List[TreeMaker]] = { - val testss = approximateMatch(prevBinder, cases) - - // interpret: - val dependencies = new collection.mutable.LinkedHashMap[Test, Set[Cond]] - val tested = new collection.mutable.HashSet[Cond] - testss foreach { tests => - tested.clear() - tests dropWhile { test => - val cond = test.cond - if ((cond eq Havoc) || (cond eq Top)) (cond eq Top) // stop when we encounter a havoc, skip top - else { - tested += cond - - // is there an earlier test that checks our condition and whose dependencies are implied by ours? - dependencies find { case (priorTest, deps) => - ((priorTest.cond eq cond) || (deps contains cond)) && (deps subsetOf tested) - } foreach { case (priorTest, deps) => - // if so, note the dependency in both tests - priorTest registerReuseBy test - } - - dependencies(test) = tested.toSet // copies - true - } - } - } - - // find longest prefix of tests that reuse a prior test, and whose dependent conditions monotonically increase - // then, collapse these contiguous sequences of reusing tests - // store the result of the final test and the intermediate results in hoisted mutable variables (TODO: optimize: don't store intermediate results that aren't used) - // replace each reference to a variable originally bound by a collapsed test by a reference to the hoisted variable - val reused = new collection.mutable.HashMap[TreeMaker, ReusedCondTreeMaker] - var okToCall = false - val reusedOrOrig = (tm: TreeMaker) => {assert(okToCall); reused.getOrElse(tm, tm)} - - val res = testss map { tests => - var currDeps = Set[Cond]() - val (sharedPrefix, suffix) = tests span { test => - (test.cond eq Top) || (for( - reusedTest <- test.reuses; - nextDeps <- dependencies.get(reusedTest); - diff <- (nextDeps -- currDeps).headOption; - _ <- Some(currDeps = nextDeps)) - yield diff).nonEmpty - } - - val collapsedTreeMakers = if (sharedPrefix.nonEmpty) { // even sharing prefixes of length 1 brings some benefit (overhead-percentage for compiler: 26->24%, lib: 19->16%) - for (test <- sharedPrefix; reusedTest <- test.reuses) reusedTest.treeMaker match { - case reusedCTM: CondTreeMaker => reused(reusedCTM) = ReusedCondTreeMaker(reusedCTM) - case _ => - } - - // println("sharedPrefix: "+ sharedPrefix) - for (lastShared <- sharedPrefix.reverse.dropWhile(_.cond eq Top).headOption; - lastReused <- lastShared.reuses) - yield ReusingCondTreeMaker(sharedPrefix, reusedOrOrig) :: suffix.map(_.treeMaker) - } else None - - collapsedTreeMakers getOrElse tests.map(_.treeMaker) // sharedPrefix need not be empty (but it only contains Top-tests, which are dropped above) - } - okToCall = true // TODO: remove (debugging) - - res mapConserve (_ mapConserve reusedOrOrig) - } - - object ReusedCondTreeMaker { - def apply(orig: CondTreeMaker) = new ReusedCondTreeMaker(orig.prevBinder, orig.nextBinder, orig.cond, orig.res, orig.pos) - } - class ReusedCondTreeMaker(prevBinder: Symbol, val nextBinder: Symbol, cond: Tree, res: Tree, pos: Position) extends TreeMaker { import CODE._ - lazy val localSubstitution = Substitution(List(prevBinder), List(CODE.REF(nextBinder))) - lazy val storedCond = freshSym(pos, BooleanClass.tpe, "rc") setFlag MUTABLE - lazy val treesToHoist: List[Tree] = { - nextBinder setFlag MUTABLE - List(storedCond, nextBinder) map { b => VAL(b) === codegen.mkZero(b.info) } - } - - // TODO: finer-grained duplication - def chainBefore(next: Tree)(casegen: Casegen): Tree = // assert(codegen eq optimizedCodegen) - atPos(pos)(casegen.asInstanceOf[optimizedCodegen.OptimizedCasegen].flatMapCondStored(cond, storedCond, res, nextBinder, substitution(next).duplicate)) - } - - case class ReusingCondTreeMaker(sharedPrefix: List[Test], toReused: TreeMaker => TreeMaker) extends TreeMaker { import CODE._ - lazy val dropped_priors = sharedPrefix map (t => (toReused(t.treeMaker), t.reuses map (test => toReused(test.treeMaker)))) - lazy val localSubstitution = { - val (from, to) = dropped_priors.collect { - case (dropped: CondTreeMaker, Some(prior: ReusedCondTreeMaker)) => - (dropped.nextBinder, REF(prior.nextBinder)) - }.unzip - val oldSubs = dropped_priors.collect { - case (dropped: TreeMaker, _) => - dropped.substitution - } - oldSubs.foldLeft(Substitution(from, to))(_ >> _) - } - - def chainBefore(next: Tree)(casegen: Casegen): Tree = { - val cond = REF(dropped_priors.reverse.collectFirst{case (_, Some(ctm: ReusedCondTreeMaker)) => ctm}.get.storedCond) - - // TODO: finer-grained duplication -- MUST duplicate though, or we'll get VerifyErrors since sharing trees confuses lambdalift, and its confusion it emits illegal casts (diagnosed by Grzegorz: checkcast T ; invokevirtual S.m, where T not a subtype of S) - casegen.ifThenElseZero(cond, substitution(next).duplicate) - } - } - } - - - //// DCE - trait DeadCodeElimination extends TreeMakers { self: CodegenCore => - // TODO: non-trivial dead-code elimination - // e.g., the following match should compile to a simple instanceof: - // case class Ident(name: String) - // for (Ident(name) <- ts) println(name) - def doDCE(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): List[List[TreeMaker]] = { - // do minimal DCE - cases - } - } - - //// SWITCHES -- TODO: operate on Tests rather than TreeMakers - trait SwitchEmission extends TreeMakers with OptimizedMatchMonadInterface { self: CodegenCore => - abstract class SwitchMaker { - abstract class SwitchableTreeMakerExtractor { def unapply(x: TreeMaker): Option[Tree] } - val SwitchableTreeMaker: SwitchableTreeMakerExtractor - - def alternativesSupported: Boolean - - def isDefault(x: CaseDef): Boolean - def defaultSym: Symbol - def defaultBody: Tree - def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef - - private def sequence[T](xs: List[Option[T]]): Option[List[T]] = - if (xs exists (_.isEmpty)) None else Some(xs.flatten) - - // empty list ==> failure - def apply(cases: List[(Symbol, List[TreeMaker])], pt: Type): List[CaseDef] = { - val caseDefs = cases map { case (scrutSym, makers) => - makers match { - // default case - case (btm@BodyTreeMaker(body, _)) :: Nil => - Some(defaultCase(scrutSym, btm.substitution(body))) - // constant (or typetest for typeSwitch) - case SwitchableTreeMaker(pattern) :: (btm@BodyTreeMaker(body, _)) :: Nil => - Some(CaseDef(pattern, EmptyTree, btm.substitution(body))) - // alternatives - case AlternativesTreeMaker(_, altss, _) :: (btm@BodyTreeMaker(body, _)) :: Nil if alternativesSupported => - val casePatterns = altss map { - case SwitchableTreeMaker(pattern) :: Nil => - Some(pattern) - case _ => - None - } - - sequence(casePatterns) map { patterns => - val substedBody = btm.substitution(body) - CaseDef(Alternative(patterns), EmptyTree, substedBody) - } - case _ => //println("can't emit switch for "+ makers) - None //failure (can't translate pattern to a switch) - } - } - - (for( - caseDefs <- sequence(caseDefs)) yield - if (caseDefs exists isDefault) caseDefs - else { - caseDefs :+ defaultCase() - } - ) getOrElse Nil - } - } - - class RegularSwitchMaker(scrutSym: Symbol, matchFailGenOverride: Option[Tree => Tree]) extends SwitchMaker { - val switchableTpe = Set(ByteClass.tpe, ShortClass.tpe, IntClass.tpe, CharClass.tpe) - val alternativesSupported = true - - object SwitchablePattern { def unapply(pat: Tree): Option[Tree] = pat match { - case Literal(const@Constant((_: Byte ) | (_: Short) | (_: Int ) | (_: Char ))) => - Some(Literal(Constant(const.intValue))) // TODO: Java 7 allows strings in switches - case _ => None - }} - - object SwitchableTreeMaker extends SwitchableTreeMakerExtractor { - def unapply(x: TreeMaker): Option[Tree] = x match { - case EqualityTestTreeMaker(_, SwitchablePattern(const), _) => Some(const) - case _ => None - } - } - - def isDefault(x: CaseDef): Boolean = x match { - case CaseDef(Ident(nme.WILDCARD), EmptyTree, _) => true - case _ => false - } - - def defaultSym: Symbol = scrutSym - def defaultBody: Tree = { import CODE._; matchFailGenOverride map (gen => gen(REF(scrutSym))) getOrElse MATCHERROR(REF(scrutSym)) } - def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef = { import CODE._; atPos(body.pos) { - DEFAULT ==> body - }} - } - - override def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Tree => Tree]): Option[Tree] = { import CODE._ - val regularSwitchMaker = new RegularSwitchMaker(scrutSym, matchFailGenOverride) - // TODO: if patterns allow switch but the type of the scrutinee doesn't, cast (type-test) the scrutinee to the corresponding switchable type and switch on the result - if (regularSwitchMaker.switchableTpe(scrutSym.tpe)) { - val caseDefsWithDefault = regularSwitchMaker(cases map {c => (scrutSym, c)}, pt) - if (caseDefsWithDefault.length <= 2) None // not worth emitting a switch... also, the optimizer has trouble digesting tiny switches, apparently, so let's be nice and not generate them - else { - // match on scrutSym -- converted to an int if necessary -- not on scrut directly (to avoid duplicating scrut) - val scrutToInt: Tree = - if (scrutSym.tpe =:= IntClass.tpe) REF(scrutSym) - else (REF(scrutSym) DOT (nme.toInt)) - Some(BLOCK( - VAL(scrutSym) === scrut, - Match(scrutToInt, caseDefsWithDefault) withAttachment TranslatedMatchAttachment // add switch annotation - )) - } - } else None - } - - // for the catch-cases in a try/catch - private object typeSwitchMaker extends SwitchMaker { - def switchableTpe(tp: Type) = true - val alternativesSupported = false // TODO: needs either back-end support of flattening of alternatives during typers - - // TODO: there are more treemaker-sequences that can be handled by type tests - // analyze the result of approximateTreeMaker rather than the TreeMaker itself - object SwitchableTreeMaker extends SwitchableTreeMakerExtractor { - def unapply(x: TreeMaker): Option[Tree] = x match { - case tm@TypeTestTreeMaker(_, _, _) => - Some(Bind(tm.nextBinder, Typed(Ident(nme.WILDCARD), TypeTree(tm.nextBinderTp)) /* not used by back-end */)) // -- TODO: use this if binder does not occur in the body - case tm@TypeAndEqualityTestTreeMaker(_, patBinder, pt, _) if tm.isStraightTypeTest => - Some(Bind(tm.nextBinder, Typed(Ident(nme.WILDCARD), TypeTree(tm.nextBinderTp)) /* not used by back-end */)) - case _ => - None - } - } - - def isDefault(x: CaseDef): Boolean = x match { - case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) if (tpt.tpe =:= ThrowableClass.tpe) => true - case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) if (tpt.tpe =:= ThrowableClass.tpe) => true - case CaseDef(Ident(nme.WILDCARD), EmptyTree, _) => true - case _ => false - } - - lazy val defaultSym: Symbol = freshSym(NoPosition, ThrowableClass.tpe) - def defaultBody: Tree = Throw(CODE.REF(defaultSym)) - def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef = { import CODE._; atPos(body.pos) { - CASE (Bind(scrutSym, Typed(Ident(nme.WILDCARD), TypeTree(ThrowableClass.tpe)))) ==> body - }} - } - - // TODO: drop null checks - override def emitTypeSwitch(bindersAndCases: List[(Symbol, List[TreeMaker])], pt: Type): Option[List[CaseDef]] = { - val caseDefsWithDefault = typeSwitchMaker(bindersAndCases, pt) - if (caseDefsWithDefault isEmpty) None - else Some(caseDefsWithDefault) - } - } - - trait OptimizedMatchMonadInterface extends MatchMonadInterface { - override def inMatchMonad(tp: Type): Type = optionType(tp) - override def pureType(tp: Type): Type = tp - override protected def matchMonadSym = OptionClass - } - - trait OptimizedCodegen extends CodegenCore with TypedSubstitution with OptimizedMatchMonadInterface { - override def codegen: AbsCodegen = optimizedCodegen - - // trait AbsOptimizedCodegen extends AbsCodegen { - // def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree - // } - // def optimizedCodegen: AbsOptimizedCodegen - - // when we know we're targetting Option, do some inlining the optimizer won't do - // for example, `o.flatMap(f)` becomes `if(o == None) None else f(o.get)`, similarly for orElse and guard - // this is a special instance of the advanced inlining optimization that takes a method call on - // an object of a type that only has two concrete subclasses, and inlines both bodies, guarded by an if to distinguish the two cases - object optimizedCodegen extends CommonCodegen { import CODE._ - - /** Inline runOrElse and get rid of Option allocations - * - * runOrElse(scrut: scrutTp)(matcher): resTp = matcher(scrut) getOrElse ${catchAll(`scrut`)} - * the matcher's optional result is encoded as a flag, keepGoing, where keepGoing == true encodes result.isEmpty, - * if keepGoing is false, the result Some(x) of the naive translation is encoded as matchRes == x - */ - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = { - val matchEnd = NoSymbol.newLabel(freshName("matchEnd"), NoPosition) setFlag SYNTH_CASE - val matchRes = NoSymbol.newValueParameter(newTermName("x"), NoPosition, SYNTHETIC) setInfo restpe.withoutAnnotations // - matchEnd setInfo MethodType(List(matchRes), restpe) - - def newCaseSym = NoSymbol.newLabel(freshName("case"), NoPosition) setInfo MethodType(Nil, restpe) setFlag SYNTH_CASE - var nextCase = newCaseSym - def caseDef(mkCase: Casegen => Tree): Tree = { - val currCase = nextCase - nextCase = newCaseSym - val casegen = new OptimizedCasegen(matchEnd, nextCase, restpe) - LabelDef(currCase, Nil, mkCase(casegen)) - } - - def catchAll = matchFailGen map { matchFailGen => - val scrutRef = if(scrutSym ne NoSymbol) REF(scrutSym) else EmptyTree // for alternatives - // must jump to matchEnd, use result generated by matchFailGen (could be `FALSE` for isDefinedAt) - LabelDef(nextCase, Nil, matchEnd APPLY (matchFailGen(scrutRef))) - // don't cast the arg to matchEnd when using PartialFun synth in uncurry, since it won't detect the throw (see gen.withDefaultCase) - // the cast is necessary when using typedMatchAnonFun-style PartialFun synth: - // (_asInstanceOf(matchFailGen(scrutRef), restpe)) - } toList - // catchAll.isEmpty iff no synthetic default case needed (the (last) user-defined case is a default) - // if the last user-defined case is a default, it will never jump to the next case; it will go immediately to matchEnd - - // the generated block is taken apart in TailCalls under the following assumptions - // the assumption is once we encounter a case, the remainder of the block will consist of cases - // the prologue may be empty, usually it is the valdef that stores the scrut - // val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) - - // scrutSym == NoSymbol when generating an alternatives matcher - val scrutDef = if(scrutSym ne NoSymbol) List(VAL(scrutSym) === scrut) else Nil // for alternatives - Block( - scrutDef ++ (cases map caseDef) ++ catchAll, - LabelDef(matchEnd, List(matchRes), REF(matchRes)) - ) - } - - class OptimizedCasegen(matchEnd: Symbol, nextCase: Symbol, restpe: Type) extends CommonCodegen with Casegen { - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = - optimizedCodegen.matcher(scrut, scrutSym, restpe)(cases, matchFailGen) - - // only used to wrap the RHS of a body - // res: T - // returns MatchMonad[T] - def one(res: Tree): Tree = matchEnd APPLY (_asInstanceOf(res, restpe)) // need cast for GADT magic - protected def zero: Tree = nextCase APPLY () - - // prev: MatchMonad[T] - // b: T - // next: MatchMonad[U] - // returns MatchMonad[U] - def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = { - val tp = inMatchMonad(b.tpe) - val prevSym = freshSym(prev.pos, tp, "o") - val isEmpty = tp member vpmName.isEmpty - val get = tp member vpmName.get - - BLOCK( - VAL(prevSym) === prev, - // must be isEmpty and get as we don't control the target of the call (prev is an extractor call) - ifThenElseZero(NOT(prevSym DOT isEmpty), Substitution(b, prevSym DOT get)(next)) - ) - } - - // cond: Boolean - // res: T - // nextBinder: T - // next == MatchMonad[U] - // returns MatchMonad[U] - def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = - ifThenElseZero(cond, BLOCK( - VAL(nextBinder) === res, - next - )) - - // guardTree: Boolean - // next: MatchMonad[T] - // returns MatchMonad[T] - def flatMapGuard(guardTree: Tree, next: Tree): Tree = - ifThenElseZero(guardTree, next) - - def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree = - ifThenElseZero(cond, BLOCK( - condSym === TRUE_typed, - nextBinder === res, - next - )) - } - - } - } - - - trait MatchOptimizations extends CommonSubconditionElimination - with DeadCodeElimination - with SwitchEmission - with OptimizedCodegen { self: TreeMakers => - override def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) = { - val optCases = doCSE(prevBinder, doDCE(prevBinder, cases, pt), pt) - val toHoist = ( - for (treeMakers <- optCases) - yield treeMakers.collect{case tm: ReusedCondTreeMaker => tm.treesToHoist} - ).flatten.flatten.toList - (optCases, toHoist) - } - } -} diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala new file mode 100644 index 0000000000..702f279596 --- /dev/null +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -0,0 +1,1839 @@ +/* NSC -- new Scala compiler + * + * Copyright 2012 LAMP/EPFL + * @author Adriaan Moors + */ + +package scala.tools.nsc +package typechecker + +import symtab._ +import Flags.{MUTABLE, METHOD, LABEL, SYNTHETIC} +import language.postfixOps +import scala.tools.nsc.transform.TypingTransformers +import scala.tools.nsc.transform.Transform + +/** Translate pattern matching. + * + * Either into optimized if/then/else's, + * or virtualized as method calls (these methods form a zero-plus monad), similar in spirit to how for-comprehensions are compiled. + * + * For each case, express all patterns as extractor calls, guards as 0-ary extractors, and sequence them using `flatMap` + * (lifting the body of the case into the monad using `one`). + * + * Cases are combined into a pattern match using the `orElse` combinator (the implicit failure case is expressed using the monad's `zero`). + * + * TODO: + * - exhaustivity + * - DCE (unreachability/refutability/optimization) + * - use TypeTags for type testing + * - Array patterns + * - implement spec more closely (see TODO's) + * + * (longer-term) TODO: + * - user-defined unapplyProd + * - recover GADT typing by locally inserting implicit witnesses to type equalities derived from the current case, and considering these witnesses during subtyping (?) + * - recover exhaustivity and unreachability checking using a variation on the type-safe builder pattern + */ +trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL { // self: Analyzer => + val global: Global // need to repeat here because otherwise last mixin defines global as + // SymbolTable. If we had DOT this would not be an issue + import global._ // the global environment + import definitions._ // standard classes and methods + import CODE._ + + val phaseName: String = "patmat" + + def newTransformer(unit: CompilationUnit): Transformer = + if (opt.virtPatmat) new MatchTransformer(unit) + else noopTransformer + + // duplicated from CPSUtils (avoid dependency from compiler -> cps plugin...) + private lazy val MarkerCPSAdaptPlus = definitions.getClassIfDefined("scala.util.continuations.cpsPlus") + private lazy val MarkerCPSAdaptMinus = definitions.getClassIfDefined("scala.util.continuations.cpsMinus") + private lazy val MarkerCPSSynth = definitions.getClassIfDefined("scala.util.continuations.cpsSynth") + private lazy val stripTriggerCPSAnns = List(MarkerCPSSynth, MarkerCPSAdaptMinus, MarkerCPSAdaptPlus) + private lazy val MarkerCPSTypes = definitions.getClassIfDefined("scala.util.continuations.cpsParam") + private lazy val strippedCPSAnns = MarkerCPSTypes :: stripTriggerCPSAnns + private def removeCPSAdaptAnnotations(tp: Type) = tp filterAnnotations (ann => !(strippedCPSAnns exists (ann matches _))) + + class MatchTransformer(unit: CompilationUnit) extends TypingTransformer(unit) { + override def transform(tree: Tree): Tree = tree match { + case Match(sel, cases) => + val selX = transform(sel) + val casesX = transformTrees(cases).asInstanceOf[List[CaseDef]] + + val origTp = tree.tpe + val matchX = treeCopy.Match(tree, selX, casesX) + + // when one of the internal cps-type-state annotations is present, strip all CPS annotations + // a cps-type-state-annotated type makes no sense as an expected type (matchX.tpe is used as pt in translateMatch) + // (only test availability of MarkerCPSAdaptPlus assuming they are either all available or none of them are) + if (MarkerCPSAdaptPlus != NoSymbol && (stripTriggerCPSAnns exists tree.tpe.hasAnnotation)) + matchX modifyType removeCPSAdaptAnnotations + + localTyper.typed(translator.translateMatch(matchX)) setType origTp + case Try(block, catches, finalizer) => + treeCopy.Try(tree, transform(block), translator.translateTry(transformTrees(catches).asInstanceOf[List[CaseDef]], tree.tpe, tree.pos), transform(finalizer)) + case _ => super.transform(tree) + } + + def translator: MatchTranslation with CodegenCore = { + new OptimizingMatchTranslator(localTyper) + } + } + + import definitions._ + import analyzer._ //Typer + + val SYNTH_CASE = Flags.CASE | SYNTHETIC + + case class DefaultOverrideMatchAttachment(default: Tree) + + object vpmName { + val one = newTermName("one") + val drop = newTermName("drop") + val flatMap = newTermName("flatMap") + val get = newTermName("get") + val guard = newTermName("guard") + val isEmpty = newTermName("isEmpty") + val orElse = newTermName("orElse") + val outer = newTermName("") + val runOrElse = newTermName("runOrElse") + val zero = newTermName("zero") + val _match = newTermName("__match") // don't call the val __match, since that will trigger virtual pattern matching... + + def counted(str: String, i: Int) = newTermName(str+i) + } + + class PureMatchTranslator(val typer: Typer, val matchStrategy: Tree) extends MatchTranslation with TreeMakers with PureCodegen + class OptimizingMatchTranslator(val typer: Typer) extends MatchTranslation with TreeMakers with MatchOptimizations + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// talking to userland +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /** Interface with user-defined match monad? + * if there's a `__match` in scope, we use this as the match strategy, assuming it conforms to MatchStrategy as defined below: + + type Matcher[P[_], M[+_], A] = { + def flatMap[B](f: P[A] => M[B]): M[B] + def orElse[B >: A](alternative: => M[B]): M[B] + } + + abstract class MatchStrategy[P[_], M[+_]] { + // runs the matcher on the given input + def runOrElse[T, U](in: P[T])(matcher: P[T] => M[U]): P[U] + + def zero: M[Nothing] + def one[T](x: P[T]): M[T] + def guard[T](cond: P[Boolean], then: => P[T]): M[T] + def isSuccess[T, U](x: P[T])(f: P[T] => M[U]): P[Boolean] // used for isDefinedAt + } + + * P and M are derived from one's signature (`def one[T](x: P[T]): M[T]`) + + + * if no `__match` is found, we assume the following implementation (and generate optimized code accordingly) + + object __match extends MatchStrategy[({type Id[x] = x})#Id, Option] { + def zero = None + def one[T](x: T) = Some(x) + // NOTE: guard's return type must be of the shape M[T], where M is the monad in which the pattern match should be interpreted + def guard[T](cond: Boolean, then: => T): Option[T] = if(cond) Some(then) else None + def runOrElse[T, U](x: T)(f: T => Option[U]): U = f(x) getOrElse (throw new MatchError(x)) + def isSuccess[T, U](x: T)(f: T => Option[U]): Boolean = !f(x).isEmpty + } + + */ + trait MatchMonadInterface { + val typer: Typer + val matchOwner = typer.context.owner + + def inMatchMonad(tp: Type): Type + def pureType(tp: Type): Type + final def matchMonadResult(tp: Type): Type = + tp.baseType(matchMonadSym).typeArgs match { + case arg :: Nil => arg + case _ => ErrorType + } + + protected def matchMonadSym: Symbol + } + + trait MatchTranslation extends MatchMonadInterface { self: TreeMakers with CodegenCore => + import typer.{typed, context, silent, reallyExists} + // import typer.infer.containsUnchecked + + /** Implement a pattern match by turning its cases (including the implicit failure case) + * into the corresponding (monadic) extractors, and combining them with the `orElse` combinator. + * + * For `scrutinee match { case1 ... caseN }`, the resulting tree has the shape + * `runOrElse(scrutinee)(x => translateCase1(x).orElse(translateCase2(x)).....orElse(zero))` + * + * NOTE: the resulting tree is not type checked, nor are nested pattern matches transformed + * thus, you must typecheck the result (and that will in turn translate nested matches) + * this could probably optimized... (but note that the matchStrategy must be solved for each nested patternmatch) + */ + def translateMatch(match_ : Match): Tree = { + val Match(selector, cases) = match_ + + // we don't transform after uncurry + // (that would require more sophistication when generating trees, + // and the only place that emits Matches after typers is for exception handling anyway) + if(phase.id >= currentRun.uncurryPhase.id) debugwarn("running translateMatch at "+ phase +" on "+ selector +" match "+ cases) + // println("translating "+ cases.mkString("{", "\n", "}")) + + def repeatedToSeq(tp: Type): Type = (tp baseType RepeatedParamClass) match { + case TypeRef(_, RepeatedParamClass, arg :: Nil) => seqType(arg) + case _ => tp + } + + val selectorTp = repeatedToSeq(elimAnonymousClass(selector.tpe.widen.withoutAnnotations)) + val pt0 = match_.tpe + + // we've packed the type for each case in typedMatch so that if all cases have the same existential case, we get a clean lub + // here, we should open up the existential again + // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala + // TODO: fix skolemizeExistential (it should preserve annotations, right?) + val pt = repeatedToSeq(pt0.skolemizeExistential(context.owner, context.tree) withAnnotations pt0.annotations) + + // the alternative to attaching the default case override would be to simply + // append the default to the list of cases and suppress the unreachable case error that may arise (once we detect that...) + val matchFailGenOverride = match_ firstAttachment {case DefaultOverrideMatchAttachment(default) => ((scrut: Tree) => default)} + + val selectorSym = freshSym(selector.pos, pureType(selectorTp)) setFlag SYNTH_CASE + // pt = Any* occurs when compiling test/files/pos/annotDepMethType.scala with -Xexperimental + combineCases(selector, selectorSym, cases map translateCase(selectorSym, pt), pt, matchOwner, matchFailGenOverride) + } + + // return list of typed CaseDefs that are supported by the backend (typed/bind/wildcard) + // we don't have a global scrutinee -- the caught exception must be bound in each of the casedefs + // there's no need to check the scrutinee for null -- "throw null" becomes "throw new NullPointerException" + // try to simplify to a type-based switch, or fall back to a catch-all case that runs a normal pattern match + // unlike translateMatch, we type our result before returning it + def translateTry(caseDefs: List[CaseDef], pt: Type, pos: Position): List[CaseDef] = + // if they're already simple enough to be handled by the back-end, we're done + if (caseDefs forall treeInfo.isCatchCase) caseDefs + else { + val swatches = { // switch-catches + val bindersAndCases = caseDefs map { caseDef => + // generate a fresh symbol for each case, hoping we'll end up emitting a type-switch (we don't have a global scrut there) + // if we fail to emit a fine-grained switch, have to do translateCase again with a single scrutSym (TODO: uniformize substitution on treemakers so we can avoid this) + val caseScrutSym = freshSym(pos, pureType(ThrowableClass.tpe)) + (caseScrutSym, propagateSubstitution(translateCase(caseScrutSym, pt)(caseDef), EmptySubstitution)) + } + + for(cases <- emitTypeSwitch(bindersAndCases, pt).toList; + if cases forall treeInfo.isCatchCase; // must check again, since it's not guaranteed -- TODO: can we eliminate this? e.g., a type test could test for a trait or a non-trivial prefix, which are not handled by the back-end + cse <- cases) yield fixerUpper(matchOwner, pos)(cse).asInstanceOf[CaseDef] + } + + val catches = if (swatches.nonEmpty) swatches else { + val scrutSym = freshSym(pos, pureType(ThrowableClass.tpe)) + val casesNoSubstOnly = caseDefs map { caseDef => (propagateSubstitution(translateCase(scrutSym, pt)(caseDef), EmptySubstitution))} + + val exSym = freshSym(pos, pureType(ThrowableClass.tpe), "ex") + + List( + atPos(pos) { + CaseDef( + Bind(exSym, Ident(nme.WILDCARD)), // TODO: does this need fixing upping? + EmptyTree, + combineCasesNoSubstOnly(CODE.REF(exSym), scrutSym, casesNoSubstOnly, pt, matchOwner, Some(scrut => Throw(CODE.REF(exSym)))) + ) + }) + } + + typer.typedCases(catches, ThrowableClass.tpe, WildcardType) + } + + + + /** The translation of `pat if guard => body` has two aspects: + * 1) the substitution due to the variables bound by patterns + * 2) the combination of the extractor calls using `flatMap`. + * + * 2) is easy -- it looks like: `translatePattern_1.flatMap(translatePattern_2....flatMap(translatePattern_N.flatMap(translateGuard.flatMap((x_i) => success(Xbody(x_i)))))...)` + * this must be right-leaning tree, as can be seen intuitively by considering the scope of bound variables: + * variables bound by pat_1 must be visible from the function inside the left-most flatMap right up to Xbody all the way on the right + * 1) is tricky because translatePattern_i determines the shape of translatePattern_i+1: + * zoom in on `translatePattern_1.flatMap(translatePattern_2)` for example -- it actually looks more like: + * `translatePattern_1(x_scrut).flatMap((x_1) => {y_i -> x_1._i}translatePattern_2)` + * + * `x_1` references the result (inside the monad) of the extractor corresponding to `pat_1`, + * this result holds the values for the constructor arguments, which translatePattern_1 has extracted + * from the object pointed to by `x_scrut`. The `y_i` are the symbols bound by `pat_1` (in order) + * in the scope of the remainder of the pattern, and they must thus be replaced by: + * - (for 1-ary unapply) x_1 + * - (for n-ary unapply, n > 1) selection of the i'th tuple component of `x_1` + * - (for unapplySeq) x_1.apply(i) + * + * in the treemakers, + * + * Thus, the result type of `translatePattern_i`'s extractor must conform to `M[(T_1,..., T_n)]`. + * + * Operationally, phase 1) is a foldLeft, since we must consider the depth-first-flattening of + * the transformed patterns from left to right. For every pattern ast node, it produces a transformed ast and + * a function that will take care of binding and substitution of the next ast (to the right). + * + */ + def translateCase(scrutSym: Symbol, pt: Type)(caseDef: CaseDef) = caseDef match { case CaseDef(pattern, guard, body) => + translatePattern(scrutSym, pattern) ++ translateGuard(guard) :+ translateBody(body, pt) + } + + def translatePattern(patBinder: Symbol, patTree: Tree): List[TreeMaker] = { + // a list of TreeMakers that encode `patTree`, and a list of arguments for recursive invocations of `translatePattern` to encode its subpatterns + type TranslationStep = (List[TreeMaker], List[(Symbol, Tree)]) + @inline def withSubPats(treeMakers: List[TreeMaker], subpats: (Symbol, Tree)*): TranslationStep = (treeMakers, subpats.toList) + @inline def noFurtherSubPats(treeMakers: TreeMaker*): TranslationStep = (treeMakers.toList, Nil) + + val pos = patTree.pos + + def translateExtractorPattern(extractor: ExtractorCall): TranslationStep = { + if (!extractor.isTyped) ErrorUtils.issueNormalTypeError(patTree, "Could not typecheck extractor call: "+ extractor)(context) + // if (extractor.resultInMonad == ErrorType) throw new TypeError(pos, "Unsupported extractor type: "+ extractor.tpe) + + // must use type `tp`, which is provided by extractor's result, not the type expected by binder, + // as b.info may be based on a Typed type ascription, which has not been taken into account yet by the translation + // (it will later result in a type test when `tp` is not a subtype of `b.info`) + // TODO: can we simplify this, together with the Bound case? + (extractor.subPatBinders, extractor.subPatTypes).zipped foreach { case (b, tp) => b setInfo tp } // println("changing "+ b +" : "+ b.info +" -> "+ tp); + + // println("translateExtractorPattern checking parameter type: "+ (patBinder, patBinder.info.widen, extractor.paramType, patBinder.info.widen <:< extractor.paramType)) + // example check: List[Int] <:< ::[Int] + // TODO: extractor.paramType may contain unbound type params (run/t2800, run/t3530) + val (typeTestTreeMaker, patBinderOrCasted) = + if (needsTypeTest(patBinder.info.widen, extractor.paramType)) { + // chain a type-testing extractor before the actual extractor call + // it tests the type, checks the outer pointer and casts to the expected type + // TODO: the outer check is mandated by the spec for case classes, but we do it for user-defined unapplies as well [SPEC] + // (the prefix of the argument passed to the unapply must equal the prefix of the type of the binder) + val treeMaker = TypeTestTreeMaker(patBinder, extractor.paramType, pos) + (List(treeMaker), treeMaker.nextBinder) + } else (Nil, patBinder) + + withSubPats(typeTestTreeMaker :+ extractor.treeMaker(patBinderOrCasted, pos), extractor.subBindersAndPatterns: _*) + } + + + object MaybeBoundTyped { + /** Decompose the pattern in `tree`, of shape C(p_1, ..., p_N), into a list of N symbols, and a list of its N sub-trees + * The list of N symbols contains symbols for every bound name as well as the un-named sub-patterns (fresh symbols are generated here for these). + * The returned type is the one inferred by inferTypedPattern (`owntype`) + * + * @arg patBinder symbol used to refer to the result of the previous pattern's extractor (will later be replaced by the outer tree with the correct tree to refer to that patterns result) + */ + def unapply(tree: Tree): Option[(Symbol, Type)] = tree match { + // the Ident subpattern can be ignored, subpatBinder or patBinder tell us all we need to know about it + case Bound(subpatBinder, typed@Typed(Ident(_), tpt)) if typed.tpe ne null => Some((subpatBinder, typed.tpe)) + case Bind(_, typed@Typed(Ident(_), tpt)) if typed.tpe ne null => Some((patBinder, typed.tpe)) + case Typed(Ident(_), tpt) if tree.tpe ne null => Some((patBinder, tree.tpe)) + case _ => None + } + } + + val (treeMakers, subpats) = patTree match { + // skip wildcard trees -- no point in checking them + case WildcardPattern() => noFurtherSubPats() + case UnApply(unfun, args) => + // TODO: check unargs == args + // println("unfun: "+ (unfun.tpe, unfun.symbol.ownerChain, unfun.symbol.info, patBinder.info)) + translateExtractorPattern(ExtractorCall(unfun, args)) + + /** A constructor pattern is of the form c(p1, ..., pn) where n ≥ 0. + It consists of a stable identifier c, followed by element patterns p1, ..., pn. + The constructor c is a simple or qualified name which denotes a case class (§5.3.2). + + If the case class is monomorphic, then it must conform to the expected type of the pattern, + and the formal parameter types of x’s primary constructor (§5.3) are taken as the expected types of the element patterns p1, ..., pn. + + If the case class is polymorphic, then its type parameters are instantiated so that the instantiation of c conforms to the expected type of the pattern. + The instantiated formal parameter types of c’s primary constructor are then taken as the expected types of the component patterns p1, ..., pn. + + The pattern matches all objects created from constructor invocations c(v1, ..., vn) where each element pattern pi matches the corresponding value vi . + A special case arises when c’s formal parameter types end in a repeated parameter. This is further discussed in (§8.1.9). + **/ + case Apply(fun, args) => + ExtractorCall.fromCaseClass(fun, args) map translateExtractorPattern getOrElse { + ErrorUtils.issueNormalTypeError(patTree, "Could not find unapply member for "+ fun +" with args "+ args)(context) + noFurtherSubPats() + } + + /** A typed pattern x : T consists of a pattern variable x and a type pattern T. + The type of x is the type pattern T, where each type variable and wildcard is replaced by a fresh, unknown type. + This pattern matches any value matched by the type pattern T (§8.2); it binds the variable name to that value. + **/ + // must treat Typed and Bind together -- we need to know the patBinder of the Bind pattern to get at the actual type + case MaybeBoundTyped(subPatBinder, pt) => + // a typed pattern never has any subtrees + noFurtherSubPats(TypeAndEqualityTestTreeMaker(subPatBinder, patBinder, pt, pos)) + + /** A pattern binder x@p consists of a pattern variable x and a pattern p. + The type of the variable x is the static type T of the pattern p. + This pattern matches any value v matched by the pattern p, + provided the run-time type of v is also an instance of T, <-- TODO! https://issues.scala-lang.org/browse/SI-1503 + and it binds the variable name to that value. + **/ + case Bound(subpatBinder, p) => + // replace subpatBinder by patBinder (as if the Bind was not there) + withSubPats(List(SubstOnlyTreeMaker(subpatBinder, patBinder)), + // must be patBinder, as subpatBinder has the wrong info: even if the bind assumes a better type, this is not guaranteed until we cast + (patBinder, p) + ) + + /** 8.1.4 Literal Patterns + A literal pattern L matches any value that is equal (in terms of ==) to the literal L. + The type of L must conform to the expected type of the pattern. + + 8.1.5 Stable Identifier Patterns (a stable identifier r (see §3.1)) + The pattern matches any value v such that r == v (§12.1). + The type of r must conform to the expected type of the pattern. + **/ + case Literal(Constant(_)) | Ident(_) | Select(_, _) => + noFurtherSubPats(EqualityTestTreeMaker(patBinder, patTree, pos)) + + case Alternative(alts) => + noFurtherSubPats(AlternativesTreeMaker(patBinder, alts map (translatePattern(patBinder, _)), alts.head.pos)) + + /* TODO: Paul says about future version: I think this should work, and always intended to implement if I can get away with it. + case class Foo(x: Int, y: String) + case class Bar(z: Int) + + def f(x: Any) = x match { case Foo(x, _) | Bar(x) => x } // x is lub of course. + */ + + case Bind(n, p) => // this happens in certain ill-formed programs, there'll be an error later + // println("WARNING: Bind tree with unbound symbol "+ patTree) + noFurtherSubPats() // there's no symbol -- something's wrong... don't fail here though (or should we?) + + // case Star(_) | ArrayValue | This => error("stone age pattern relics encountered!") + + case _ => + error("unsupported pattern: "+ patTree +"(a "+ patTree.getClass +")") + noFurtherSubPats() + } + + treeMakers ++ subpats.flatMap { case (binder, pat) => + translatePattern(binder, pat) // recurse on subpatterns + } + } + + def translateGuard(guard: Tree): List[TreeMaker] = + if (guard == EmptyTree) Nil + else List(GuardTreeMaker(guard)) + + // TODO: 1) if we want to support a generalisation of Kotlin's patmat continue, must not hard-wire lifting into the monad (which is now done by codegen.one), + // so that user can generate failure when needed -- use implicit conversion to lift into monad on-demand? + // to enable this, probably need to move away from Option to a monad specific to pattern-match, + // so that we can return Option's from a match without ambiguity whether this indicates failure in the monad, or just some result in the monad + // 2) body.tpe is the type of the body after applying the substitution that represents the solution of GADT type inference + // need the explicit cast in case our substitutions in the body change the type to something that doesn't take GADT typing into account + def translateBody(body: Tree, matchPt: Type): TreeMaker = + BodyTreeMaker(body, matchPt) + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// helper methods: they analyze types and trees in isolation, but they are not (directly) concerned with the structure of the overall translation +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + object ExtractorCall { + def apply(unfun: Tree, args: List[Tree]): ExtractorCall = new ExtractorCallRegular(unfun, args) + + def fromCaseClass(fun: Tree, args: List[Tree]): Option[ExtractorCall] = Some(new ExtractorCallProd(fun, args)) + + // THE PRINCIPLED SLOW PATH -- NOT USED + // generate a call to the (synthetically generated) extractor of a case class + // NOTE: it's an apply, not a select, since in general an extractor call may have multiple argument lists (including an implicit one) + // that we need to preserve, so we supply the scrutinee as Ident(nme.SELECTOR_DUMMY), + // and replace that dummy by a reference to the actual binder in translateExtractorPattern + def fromCaseClassUnapply(fun: Tree, args: List[Tree]): Option[ExtractorCall] = { + // TODO: can we rework the typer so we don't have to do all this twice? + // undo rewrite performed in (5) of adapt + val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} + val origSym = orig.symbol + val extractor = unapplyMember(origSym.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe) + + if((fun.tpe eq null) || fun.tpe.isError || (extractor eq NoSymbol)) { + None + } else { + // this is a tricky balance: pos/t602.scala, pos/sudoku.scala, run/virtpatmat_alts.scala must all be happy + // bypass typing at own risk: val extractorCall = Select(orig, extractor) setType caseClassApplyToUnapplyTp(fun.tpe) + // can't always infer type arguments (pos/t602): + /* case class Span[K <: Ordered[K]](low: Option[K]) { + override def equals(x: Any): Boolean = x match { + case Span((low0 @ _)) if low0 equals low => true + } + }*/ + // so... leave undetermined type params floating around if we have to + // (if we don't infer types, uninstantiated type params show up later: pos/sudoku.scala) + // (see also run/virtpatmat_alts.scala) + val savedUndets = context.undetparams + val extractorCall = try { + context.undetparams = Nil + silent(_.typed(Apply(Select(orig, extractor), List(Ident(nme.SELECTOR_DUMMY) setType fun.tpe.finalResultType)), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { + case SilentResultValue(extractorCall) => extractorCall // if !extractorCall.containsError() + case _ => + // this fails to resolve overloading properly... + // Apply(typedOperator(Select(orig, extractor)), List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway + + // println("funtpe after = "+ fun.tpe.finalResultType) + // println("orig: "+(orig, orig.tpe)) + val tgt = typed(orig, EXPRmode | QUALmode | POLYmode, HasMember(extractor.name)) // can't specify fun.tpe.finalResultType as the type for the extractor's arg, + // as it may have been inferred incorrectly (see t602, where it's com.mosol.sl.Span[Any], instead of com.mosol.sl.Span[?K]) + // println("tgt = "+ (tgt, tgt.tpe)) + val oper = typed(Select(tgt, extractor.name), EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType) + // println("oper: "+ (oper, oper.tpe)) + Apply(oper, List(Ident(nme.SELECTOR_DUMMY))) // no need to set the type of the dummy arg, it will be replaced anyway + } + } finally context.undetparams = savedUndets + + Some(this(extractorCall, args)) // TODO: simplify spliceApply? + } + } + } + + abstract class ExtractorCall(val args: List[Tree]) { + val nbSubPats = args.length + + // everything okay, captain? + def isTyped : Boolean + + def isSeq: Boolean + lazy val lastIsStar = (nbSubPats > 0) && treeInfo.isStar(args.last) + + // to which type should the previous binder be casted? + def paramType : Type + + // binder has been casted to paramType if necessary + def treeMaker(binder: Symbol, pos: Position): TreeMaker + + // `subPatBinders` are the variables bound by this pattern in the following patterns + // subPatBinders are replaced by references to the relevant part of the extractor's result (tuple component, seq element, the result as-is) + lazy val subPatBinders = args map { + case Bound(b, p) => b + case p => freshSym(p.pos, prefix = "p") + } + + lazy val subBindersAndPatterns: List[(Symbol, Tree)] = (subPatBinders zip args) map { + case (b, Bound(_, p)) => (b, p) + case bp => bp + } + + def subPatTypes: List[Type] = + if(isSeq) { + val TypeRef(pre, SeqClass, args) = seqTp + // do repeated-parameter expansion to match up with the expected number of arguments (in casu, subpatterns) + formalTypes(rawSubPatTypes.init :+ typeRef(pre, RepeatedParamClass, args), nbSubPats) + } else rawSubPatTypes + + protected def rawSubPatTypes: List[Type] + + protected def seqTp = rawSubPatTypes.last baseType SeqClass + protected def seqLenCmp = rawSubPatTypes.last member nme.lengthCompare + protected lazy val firstIndexingBinder = rawSubPatTypes.length - 1 // rawSubPatTypes.last is the Seq, thus there are `rawSubPatTypes.length - 1` non-seq elements in the tuple + protected lazy val lastIndexingBinder = if(lastIsStar) nbSubPats-2 else nbSubPats-1 + protected lazy val expectedLength = lastIndexingBinder - firstIndexingBinder + 1 + protected lazy val minLenToCheck = if(lastIsStar) 1 else 0 + protected def seqTree(binder: Symbol) = tupleSel(binder)(firstIndexingBinder+1) + protected def tupleSel(binder: Symbol)(i: Int): Tree = codegen.tupleSel(binder)(i) + + // the trees that select the subpatterns on the extractor's result, referenced by `binder` + // require isSeq + protected def subPatRefsSeq(binder: Symbol): List[Tree] = { + val indexingIndices = (0 to (lastIndexingBinder-firstIndexingBinder)) + val nbIndexingIndices = indexingIndices.length + + // this error-condition has already been checked by checkStarPatOK: + // if(isSeq) assert(firstIndexingBinder + nbIndexingIndices + (if(lastIsStar) 1 else 0) == nbSubPats, "(resultInMonad, ts, subPatTypes, subPats)= "+(resultInMonad, ts, subPatTypes, subPats)) + // there are `firstIndexingBinder` non-seq tuple elements preceding the Seq + (((1 to firstIndexingBinder) map tupleSel(binder)) ++ + // then we have to index the binder that represents the sequence for the remaining subpatterns, except for... + (indexingIndices map codegen.index(seqTree(binder))) ++ + // the last one -- if the last subpattern is a sequence wildcard: drop the prefix (indexed by the refs on the line above), return the remainder + (if(!lastIsStar) Nil else List( + if(nbIndexingIndices == 0) seqTree(binder) + else codegen.drop(seqTree(binder))(nbIndexingIndices)))).toList + } + + // the trees that select the subpatterns on the extractor's result, referenced by `binder` + // require (nbSubPats > 0 && (!lastIsStar || isSeq)) + protected def subPatRefs(binder: Symbol): List[Tree] = + if (nbSubPats == 0) Nil + else if (isSeq) subPatRefsSeq(binder) + else ((1 to nbSubPats) map tupleSel(binder)).toList + + protected def lengthGuard(binder: Symbol): Option[Tree] = + // no need to check unless it's an unapplySeq and the minimal length is non-trivially satisfied + if (!isSeq || (expectedLength < minLenToCheck)) None + else { import CODE._ + // `binder.lengthCompare(expectedLength)` + def checkExpectedLength = (seqTree(binder) DOT seqLenCmp)(LIT(expectedLength)) + + // the comparison to perform + // when the last subpattern is a wildcard-star the expectedLength is but a lower bound + // (otherwise equality is required) + def compareOp: (Tree, Tree) => Tree = + if (lastIsStar) _ INT_>= _ + else _ INT_== _ + + // `if (binder != null && $checkExpectedLength [== | >=] 0) then else zero` + Some((seqTree(binder) ANY_!= NULL) AND compareOp(checkExpectedLength, ZERO)) + } + } + + // TODO: to be called when there's a def unapplyProd(x: T): U + // U must have N members _1,..., _N -- the _i are type checked, call their type Ti, + // + // for now only used for case classes -- pretending there's an unapplyProd that's the identity (and don't call it) + class ExtractorCallProd(fun: Tree, args: List[Tree]) extends ExtractorCall(args) { + // TODO: fix the illegal type bound in pos/t602 -- type inference messes up before we get here: + /*override def equals(x$1: Any): Boolean = ... + val o5: Option[com.mosol.sl.Span[Any]] = // Span[Any] --> Any is not a legal type argument for Span! + */ + // private val orig = fun match {case tpt: TypeTree => tpt.original case _ => fun} + // private val origExtractorTp = unapplyMember(orig.symbol.filter(sym => reallyExists(unapplyMember(sym.tpe))).tpe).tpe + // private val extractorTp = if (wellKinded(fun.tpe)) fun.tpe else existentialAbstraction(origExtractorTp.typeParams, origExtractorTp.resultType) + // println("ExtractorCallProd: "+ (fun.tpe, existentialAbstraction(origExtractorTp.typeParams, origExtractorTp.resultType))) + // println("ExtractorCallProd: "+ (fun.tpe, args map (_.tpe))) + private def constructorTp = fun.tpe + + def isTyped = fun.isTyped + + // to which type should the previous binder be casted? + def paramType = constructorTp.finalResultType + + def isSeq: Boolean = rawSubPatTypes.nonEmpty && isRepeatedParamType(rawSubPatTypes.last) + protected def rawSubPatTypes = constructorTp.paramTypes + + // binder has type paramType + def treeMaker(binder: Symbol, pos: Position): TreeMaker = { + // checks binder ne null before chaining to the next extractor + ProductExtractorTreeMaker(binder, lengthGuard(binder), Substitution(subPatBinders, subPatRefs(binder))) + } + + // reference the (i-1)th case accessor if it exists, otherwise the (i-1)th tuple component + override protected def tupleSel(binder: Symbol)(i: Int): Tree = { import CODE._ + // caseFieldAccessors is messed up after typers (reversed, names mangled for non-public fields) + // TODO: figure out why... + val accessors = binder.caseFieldAccessors + // luckily, the constrParamAccessors are still sorted properly, so sort the field-accessors using them + // (need to undo name-mangling, including the sneaky trailing whitespace) + val constrParamAccessors = binder.constrParamAccessors + + def indexInCPA(acc: Symbol) = + constrParamAccessors indexWhere { orig => + // println("compare: "+ (orig, acc, orig.name, acc.name, (acc.name == orig.name), (acc.name startsWith (orig.name append "$")))) + val origName = orig.name.toString.trim + val accName = acc.name.toString.trim + (accName == origName) || (accName startsWith (origName + "$")) + } + + // println("caseFieldAccessors: "+ (accessors, binder.caseFieldAccessors map indexInCPA)) + // println("constrParamAccessors: "+ constrParamAccessors) + + val accessorsSorted = accessors sortBy indexInCPA + if (accessorsSorted isDefinedAt (i-1)) REF(binder) DOT accessorsSorted(i-1) + else codegen.tupleSel(binder)(i) // this won't type check for case classes, as they do not inherit ProductN + } + + override def toString(): String = "case class "+ (if (constructorTp eq null) fun else paramType.typeSymbol) +" with arguments "+ args + } + + class ExtractorCallRegular(extractorCallIncludingDummy: Tree, args: List[Tree]) extends ExtractorCall(args) { + private lazy val Some(Apply(extractorCall, _)) = extractorCallIncludingDummy.find{ case Apply(_, List(Ident(nme.SELECTOR_DUMMY))) => true case _ => false } + + def tpe = extractorCall.tpe + def isTyped = (tpe ne NoType) && extractorCall.isTyped && (resultInMonad ne ErrorType) + def paramType = tpe.paramTypes.head + def resultType = tpe.finalResultType + def isSeq = extractorCall.symbol.name == nme.unapplySeq + + def treeMaker(patBinderOrCasted: Symbol, pos: Position): TreeMaker = { + // the extractor call (applied to the binder bound by the flatMap corresponding to the previous (i.e., enclosing/outer) pattern) + val extractorApply = atPos(pos)(spliceApply(patBinderOrCasted)) + val binder = freshSym(pos, pureType(resultInMonad)) // can't simplify this when subPatBinders.isEmpty, since UnitClass.tpe is definitely wrong when isSeq, and resultInMonad should always be correct since it comes directly from the extractor's result type + ExtractorTreeMaker(extractorApply, lengthGuard(binder), binder, Substitution(subPatBinders, subPatRefs(binder)))(resultType.typeSymbol == BooleanClass) + } + + override protected def seqTree(binder: Symbol): Tree = + if (firstIndexingBinder == 0) CODE.REF(binder) + else super.seqTree(binder) + + // the trees that select the subpatterns on the extractor's result, referenced by `binder` + // require (nbSubPats > 0 && (!lastIsStar || isSeq)) + override protected def subPatRefs(binder: Symbol): List[Tree] = + if (!isSeq && nbSubPats == 1) List(CODE.REF(binder)) // special case for extractors + else super.subPatRefs(binder) + + protected def spliceApply(binder: Symbol): Tree = { + object splice extends Transformer { + override def transform(t: Tree) = t match { + case Apply(x, List(Ident(nme.SELECTOR_DUMMY))) => + treeCopy.Apply(t, x, List(CODE.REF(binder))) + case _ => super.transform(t) + } + } + splice.transform(extractorCallIncludingDummy) + } + + // what's the extractor's result type in the monad? + // turn an extractor's result type into something `monadTypeToSubPatTypesAndRefs` understands + protected lazy val resultInMonad: Type = if(!hasLength(tpe.paramTypes, 1)) ErrorType else { + if (resultType.typeSymbol == BooleanClass) UnitClass.tpe + else matchMonadResult(resultType) + } + + protected lazy val rawSubPatTypes = + if (resultInMonad.typeSymbol eq UnitClass) Nil + else if(nbSubPats == 1) List(resultInMonad) + else getProductArgs(resultInMonad) match { + case Nil => List(resultInMonad) + case x => x + } + + override def toString() = extractorCall +": "+ extractorCall.tpe +" (symbol= "+ extractorCall.symbol +")." + } + + /** A conservative approximation of which patterns do not discern anything. + * They are discarded during the translation. + */ + object WildcardPattern { + def unapply(pat: Tree): Boolean = pat match { + case Bind(nme.WILDCARD, WildcardPattern()) => true // don't skip when binding an interesting symbol! + case Ident(nme.WILDCARD) => true + case Star(WildcardPattern()) => true + case x: Ident => treeInfo.isVarPattern(x) + case Alternative(ps) => ps forall (WildcardPattern.unapply(_)) + case EmptyTree => true + case _ => false + } + } + + object Bound { + def unapply(t: Tree): Option[(Symbol, Tree)] = t match { + case t@Bind(n, p) if (t.symbol ne null) && (t.symbol ne NoSymbol) => // pos/t2429 does not satisfy these conditions + Some((t.symbol, p)) + case _ => None + } + } + } + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// substitution +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + trait TypedSubstitution extends MatchMonadInterface { + object Substitution { + def apply(from: Symbol, to: Tree) = new Substitution(List(from), List(to)) + // requires sameLength(from, to) + def apply(from: List[Symbol], to: List[Tree]) = + if (from nonEmpty) new Substitution(from, to) else EmptySubstitution + } + + class Substitution(val from: List[Symbol], val to: List[Tree]) { + // We must explicitly type the trees that we replace inside some other tree, since the latter may already have been typed, + // and will thus not be retyped. This means we might end up with untyped subtrees inside bigger, typed trees. + def apply(tree: Tree): Tree = { + // according to -Ystatistics 10% of translateMatch's time is spent in this method... + // since about half of the typedSubst's end up being no-ops, the check below shaves off 5% of the time spent in typedSubst + if (!tree.exists { case i@Ident(_) => from contains i.symbol case _ => false}) tree + else (new Transformer { + @inline private def typedIfOrigTyped(to: Tree, origTp: Type): Tree = + if (origTp == null || origTp == NoType) to + // important: only type when actually substing and when original tree was typed + // (don't need to use origTp as the expected type, though, and can't always do this anyway due to unknown type params stemming from polymorphic extractors) + else typer.typed(to, EXPRmode, WildcardType) + + override def transform(tree: Tree): Tree = { + def subst(from: List[Symbol], to: List[Tree]): Tree = + if (from.isEmpty) tree + else if (tree.symbol == from.head) typedIfOrigTyped(to.head.shallowDuplicate, tree.tpe) + else subst(from.tail, to.tail) + + tree match { + case Ident(_) => subst(from, to) + case _ => super.transform(tree) + } + } + }).transform(tree) + } + + + // the substitution that chains `other` before `this` substitution + // forall t: Tree. this(other(t)) == (this >> other)(t) + def >>(other: Substitution): Substitution = { + val (fromFiltered, toFiltered) = (from, to).zipped filter { (f, t) => !other.from.contains(f) } + new Substitution(other.from ++ fromFiltered, other.to.map(apply) ++ toFiltered) // a quick benchmarking run indicates the `.map(apply)` is not too costly + } + override def toString = (from zip to) mkString("Substitution(", ", ", ")") + } + + object EmptySubstitution extends Substitution(Nil, Nil) { + override def apply(tree: Tree): Tree = tree + override def >>(other: Substitution): Substitution = other + } + } + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// the making of the trees +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + trait TreeMakers extends TypedSubstitution { self: CodegenCore => + def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) = + (cases, Nil) + + def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Tree => Tree]): Option[Tree] = + None + + // for catch (no need to customize match failure) + def emitTypeSwitch(bindersAndCases: List[(Symbol, List[TreeMaker])], pt: Type): Option[List[CaseDef]] = + None + + abstract class TreeMaker { + /** captures the scope and the value of the bindings in patterns + * important *when* the substitution happens (can't accumulate and do at once after the full matcher has been constructed) + */ + def substitution: Substitution = + if (currSub eq null) localSubstitution + else currSub + + protected def localSubstitution: Substitution + + private[TreeMakers] def incorporateOuterSubstitution(outerSubst: Substitution): Unit = { + if (currSub ne null) { + println("BUG: incorporateOuterSubstitution called more than once for "+ (this, currSub, outerSubst)) + Thread.dumpStack() + } + else currSub = outerSubst >> substitution + } + private[this] var currSub: Substitution = null + + // build Tree that chains `next` after the current extractor + def chainBefore(next: Tree)(casegen: Casegen): Tree + } + + trait NoNewBinders extends TreeMaker { + protected val localSubstitution: Substitution = EmptySubstitution + } + + case class TrivialTreeMaker(tree: Tree) extends TreeMaker with NoNewBinders { + def chainBefore(next: Tree)(casegen: Casegen): Tree = tree + } + + case class BodyTreeMaker(body: Tree, matchPt: Type) extends TreeMaker with NoNewBinders { + def chainBefore(next: Tree)(casegen: Casegen): Tree = // assert(next eq EmptyTree) + atPos(body.pos)(casegen.one(substitution(body))) // since SubstOnly treemakers are dropped, need to do it here + } + + case class SubstOnlyTreeMaker(prevBinder: Symbol, nextBinder: Symbol) extends TreeMaker { + val localSubstitution = Substitution(prevBinder, CODE.REF(nextBinder)) + def chainBefore(next: Tree)(casegen: Casegen): Tree = substitution(next) + } + + abstract class FunTreeMaker extends TreeMaker { + val nextBinder: Symbol + } + + abstract class CondTreeMaker extends FunTreeMaker { + val pos: Position + val prevBinder: Symbol + val nextBinderTp: Type + val cond: Tree + val res: Tree + + lazy val nextBinder = freshSym(pos, nextBinderTp) + lazy val localSubstitution = Substitution(List(prevBinder), List(CODE.REF(nextBinder))) + + def chainBefore(next: Tree)(casegen: Casegen): Tree = + atPos(pos)(casegen.flatMapCond(cond, res, nextBinder, substitution(next))) + } + + /** + * Make a TreeMaker that will result in an extractor call specified by `extractor` + * the next TreeMaker (here, we don't know which it'll be) is chained after this one by flatMap'ing + * a function with binder `nextBinder` over our extractor's result + * the function's body is determined by the next TreeMaker + * in this function's body, and all the subsequent ones, references to the symbols in `from` will be replaced by the corresponding tree in `to` + */ + case class ExtractorTreeMaker(extractor: Tree, extraCond: Option[Tree], nextBinder: Symbol, localSubstitution: Substitution)(extractorReturnsBoolean: Boolean) extends FunTreeMaker { + def chainBefore(next: Tree)(casegen: Casegen): Tree = { + val condAndNext = extraCond map (casegen.ifThenElseZero(_, next)) getOrElse next + atPos(extractor.pos)( + if (extractorReturnsBoolean) casegen.flatMapCond(extractor, CODE.UNIT, nextBinder, substitution(condAndNext)) + else casegen.flatMap(extractor, nextBinder, substitution(condAndNext)) + ) + } + + override def toString = "X"+(extractor, nextBinder) + } + + // TODO: allow user-defined unapplyProduct + case class ProductExtractorTreeMaker(prevBinder: Symbol, extraCond: Option[Tree], localSubstitution: Substitution) extends TreeMaker { import CODE._ + def chainBefore(next: Tree)(casegen: Casegen): Tree = { + val nullCheck = REF(prevBinder) OBJ_NE NULL + val cond = extraCond map (nullCheck AND _) getOrElse nullCheck + casegen.ifThenElseZero(cond, substitution(next)) + } + + override def toString = "P"+(prevBinder, extraCond getOrElse "", localSubstitution) + } + + // tack an outer test onto `cond` if binder.info and expectedType warrant it + def maybeWithOuterCheck(binder: Symbol, expectedTp: Type)(cond: Tree): Tree = { import CODE._ + if ( !((expectedTp.prefix eq NoPrefix) || expectedTp.prefix.typeSymbol.isPackageClass) + && needsOuterTest(expectedTp, binder.info, matchOwner)) { + val expectedPrefix = expectedTp.prefix match { + case ThisType(clazz) => THIS(clazz) + case pre => REF(pre.prefix, pre.termSymbol) + } + + // ExplicitOuter replaces `Select(q, outerSym) OBJ_EQ expectedPrefix` by `Select(q, outerAccessor(outerSym.owner)) OBJ_EQ expectedPrefix` + // if there's an outer accessor, otherwise the condition becomes `true` -- TODO: can we improve needsOuterTest so there's always an outerAccessor? + val outer = expectedTp.typeSymbol.newMethod(vpmName.outer) setInfo expectedTp.prefix setFlag SYNTHETIC + val outerCheck = (Select(codegen._asInstanceOf(binder, expectedTp), outer)) OBJ_EQ expectedPrefix + + // first check cond, since that should ensure we're not selecting outer on null + codegen.and(cond, outerCheck) + } + else + cond + } + + // containsUnchecked: also need to test when erasing pt loses crucial information (maybe we can recover it using a TypeTag) + def needsTypeTest(tp: Type, pt: Type): Boolean = !(tp <:< pt) // || containsUnchecked(pt) + // TODO: try to find the TypeTag for the binder's type and the expected type, and if they exists, + // check that the TypeTag of the binder's type conforms to the TypeTag of the expected type + private def typeTest(binderToTest: Symbol, expectedTp: Type, disableOuterCheck: Boolean = false, dynamic: Boolean = false): Tree = { import CODE._ + // def coreTest = + if (disableOuterCheck) codegen._isInstanceOf(binderToTest, expectedTp) else maybeWithOuterCheck(binderToTest, expectedTp)(codegen._isInstanceOf(binderToTest, expectedTp)) + // [Eugene to Adriaan] use `resolveErasureTag` instead of `findManifest`. please, provide a meaningful position + // if (opt.experimental && containsUnchecked(expectedTp)) { + // if (dynamic) { + // val expectedTpTagTree = findManifest(expectedTp, true) + // if (!expectedTpTagTree.isEmpty) + // ((expectedTpTagTree DOT "erasure".toTermName) DOT "isAssignableFrom".toTermName)(REF(binderToTest) DOT nme.getClass_) + // else + // coreTest + // } else { + // val expectedTpTagTree = findManifest(expectedTp, true) + // val binderTpTagTree = findManifest(binderToTest.info, true) + // if(!(expectedTpTagTree.isEmpty || binderTpTagTree.isEmpty)) + // coreTest AND (binderTpTagTree DOT nme.CONFORMS)(expectedTpTagTree) + // else + // coreTest + // } + // } else coreTest + } + + // need to substitute since binder may be used outside of the next extractor call (say, in the body of the case) + case class TypeTestTreeMaker(prevBinder: Symbol, nextBinderTp: Type, pos: Position) extends CondTreeMaker { + val cond = typeTest(prevBinder, nextBinderTp, dynamic = true) + val res = codegen._asInstanceOf(prevBinder, nextBinderTp) + override def toString = "TT"+(prevBinder, nextBinderTp) + } + + // implements the run-time aspects of (§8.2) (typedPattern has already done the necessary type transformations) + // TODO: normalize construction, which yields a combination of a EqualityTestTreeMaker (when necessary) and a TypeTestTreeMaker + case class TypeAndEqualityTestTreeMaker(prevBinder: Symbol, patBinder: Symbol, pt: Type, pos: Position) extends CondTreeMaker { + val nextBinderTp = glb(List(patBinder.info.widen, pt)) + + /** Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms: + - A reference to a class C, p.C, or T#C. + This type pattern matches any non-null instance of the given class. + Note that the prefix of the class, if it is given, is relevant for determining class instances. + For instance, the pattern p.C matches only instances of classes C which were created with the path p as prefix. + The bottom types scala.Nothing and scala.Null cannot be used as type patterns, because they would match nothing in any case. + + - A singleton type p.type. + This type pattern matches only the value denoted by the path p + (that is, a pattern match involved a comparison of the matched value with p using method eq in class AnyRef). // TODO: the actual pattern matcher uses ==, so that's what I'm using for now + // https://issues.scala-lang.org/browse/SI-4577 "pattern matcher, still disappointing us at equality time" + + - A compound type pattern T1 with ... with Tn where each Ti is a type pat- tern. + This type pattern matches all values that are matched by each of the type patterns Ti. + + - A parameterized type pattern T[a1,...,an], where the ai are type variable patterns or wildcards _. + This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. + The bounds or alias type of these type variable are determined as described in (§8.3). + + - A parameterized type pattern scala.Array[T1], where T1 is a type pattern. // TODO + This type pattern matches any non-null instance of type scala.Array[U1], where U1 is a type matched by T1. + **/ + + // generate the tree for the run-time test that follows from the fact that + // a `scrut` of known type `scrutTp` is expected to have type `expectedTp` + // uses maybeWithOuterCheck to check the type's prefix + private def typeAndEqualityTest(patBinder: Symbol, pt: Type): Tree = { import CODE._ + // TODO: `null match { x : T }` will yield a check that (indirectly) tests whether `null ne null` + // don't bother (so that we don't end up with the warning "comparing values of types Null and Null using `ne' will always yield false") + def genEqualsAndInstanceOf(sym: Symbol): Tree + = codegen._equals(REF(sym), patBinder) AND typeTest(patBinder, pt.widen, disableOuterCheck = true) + + def isRefTp(tp: Type) = tp <:< AnyRefClass.tpe + + val patBinderTp = patBinder.info.widen + def isMatchUnlessNull = isRefTp(pt) && !needsTypeTest(patBinderTp, pt) + + // TODO: [SPEC] type test for Array + // TODO: use TypeTags to improve tests (for erased types we can do better when we have a TypeTag) + pt match { + case SingleType(_, sym) /*this implies sym.isStable*/ => genEqualsAndInstanceOf(sym) // TODO: [SPEC] the spec requires `eq` instead of `==` here + case ThisType(sym) if sym.isModule => genEqualsAndInstanceOf(sym) // must use == to support e.g. List() == Nil + case ThisType(sym) => REF(patBinder) OBJ_EQ This(sym) + case ConstantType(Constant(null)) if isRefTp(patBinderTp) => REF(patBinder) OBJ_EQ NULL + case ConstantType(const) => codegen._equals(Literal(const), patBinder) + case _ if isMatchUnlessNull => maybeWithOuterCheck(patBinder, pt)(REF(patBinder) OBJ_NE NULL) + case _ => typeTest(patBinder, pt) + } + } + + val cond = typeAndEqualityTest(patBinder, pt) + val res = codegen._asInstanceOf(patBinder, nextBinderTp) + + // TODO: remove this + def isStraightTypeTest = cond match { case TypeApply(_, _) => cond.symbol == Any_isInstanceOf case _ => false } + + override def toString = "TET"+(patBinder, pt) + } + + // need to substitute to deal with existential types -- TODO: deal with existentials better, don't substitute (see RichClass during quick.comp) + case class EqualityTestTreeMaker(prevBinder: Symbol, patTree: Tree, pos: Position) extends CondTreeMaker { + val nextBinderTp = prevBinder.info.widen + + // NOTE: generate `patTree == patBinder`, since the extractor must be in control of the equals method (also, patBinder may be null) + // equals need not be well-behaved, so don't intersect with pattern's (stabilized) type (unlike MaybeBoundTyped's accumType, where it's required) + val cond = codegen._equals(patTree, prevBinder) + val res = CODE.REF(prevBinder) + override def toString = "ET"+(prevBinder, patTree) + } + + case class AlternativesTreeMaker(prevBinder: Symbol, var altss: List[List[TreeMaker]], pos: Position) extends TreeMaker with NoNewBinders { + // don't substitute prevBinder to nextBinder, a set of alternatives does not need to introduce a new binder, simply reuse the previous one + + override private[TreeMakers] def incorporateOuterSubstitution(outerSubst: Substitution): Unit = { + super.incorporateOuterSubstitution(outerSubst) + altss = altss map (alts => propagateSubstitution(alts, substitution)) + } + + def chainBefore(next: Tree)(codegenAlt: Casegen): Tree = { import CODE._ + atPos(pos){ + // one alternative may still generate multiple trees (e.g., an extractor call + equality test) + // (for now,) alternatives may not bind variables (except wildcards), so we don't care about the final substitution built internally by makeTreeMakers + val combinedAlts = altss map (altTreeMakers => + ((casegen: Casegen) => combineExtractors(altTreeMakers :+ TrivialTreeMaker(casegen.one(TRUE_typed)))(casegen)) + ) + + val findAltMatcher = codegenAlt.matcher(EmptyTree, NoSymbol, BooleanClass.tpe)(combinedAlts, Some(x => FALSE_typed)) + codegenAlt.ifThenElseZero(findAltMatcher, substitution(next)) + } + } + } + + case class GuardTreeMaker(guardTree: Tree) extends TreeMaker with NoNewBinders { + def chainBefore(next: Tree)(casegen: Casegen): Tree = casegen.flatMapGuard(substitution(guardTree), next) + override def toString = "G("+ guardTree +")" + } + + // combineExtractors changes the current substitution's of the tree makers in `treeMakers` + // requires propagateSubstitution(treeMakers) has been called + def combineExtractors(treeMakers: List[TreeMaker])(casegen: Casegen): Tree = + treeMakers.foldRight(EmptyTree: Tree)((a, b) => a.chainBefore(b)(casegen)) + + + def removeSubstOnly(makers: List[TreeMaker]) = makers filterNot (_.isInstanceOf[SubstOnlyTreeMaker]) + + // a foldLeft to accumulate the localSubstitution left-to-right + // it drops SubstOnly tree makers, since their only goal in life is to propagate substitutions to the next tree maker, which is fullfilled by propagateSubstitution + def propagateSubstitution(treeMakers: List[TreeMaker], initial: Substitution): List[TreeMaker] = { + var accumSubst: Substitution = initial + treeMakers foreach { maker => + maker incorporateOuterSubstitution accumSubst + accumSubst = maker.substitution + } + removeSubstOnly(treeMakers) + } + + // calls propagateSubstitution on the treemakers + def combineCases(scrut: Tree, scrutSym: Symbol, casesRaw: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Tree => Tree]): Tree = { + // drops SubstOnlyTreeMakers, since their effect is now contained in the TreeMakers that follow them + val casesNoSubstOnly = casesRaw map (propagateSubstitution(_, EmptySubstitution)) + combineCasesNoSubstOnly(scrut, scrutSym, casesNoSubstOnly, pt, owner, matchFailGenOverride) + } + + def combineCasesNoSubstOnly(scrut: Tree, scrutSym: Symbol, casesNoSubstOnly: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Tree => Tree]): Tree = + fixerUpper(owner, scrut.pos){ + val ptDefined = if (isFullyDefined(pt)) pt else NoType + def matchFailGen = (matchFailGenOverride orElse Some(CODE.MATCHERROR(_: Tree))) + // println("combining cases: "+ (casesNoSubstOnly.map(_.mkString(" >> ")).mkString("{", "\n", "}"))) + + emitSwitch(scrut, scrutSym, casesNoSubstOnly, pt, matchFailGenOverride).getOrElse{ + if (casesNoSubstOnly nonEmpty) { + // before optimizing, check casesNoSubstOnly for presence of a default case, + // since DCE will eliminate trivial cases like `case _ =>`, even if they're the last one + // exhaustivity and reachability must be checked before optimization as well + // TODO: improve notion of trivial/irrefutable -- a trivial type test before the body still makes for a default case + // ("trivial" depends on whether we're emitting a straight match or an exception, or more generally, any supertype of scrutSym.tpe is a no-op) + // irrefutability checking should use the approximation framework also used for CSE, unreachability and exhaustivity checking + val synthCatchAll = + if (casesNoSubstOnly.nonEmpty && { + val nonTrivLast = casesNoSubstOnly.last + nonTrivLast.nonEmpty && nonTrivLast.head.isInstanceOf[BodyTreeMaker] + }) None + else matchFailGen + + val (cases, toHoist) = optimizeCases(scrutSym, casesNoSubstOnly, pt) + + val matchRes = codegen.matcher(scrut, scrutSym, pt)(cases map combineExtractors, synthCatchAll) + + if (toHoist isEmpty) matchRes else Block(toHoist, matchRes) + } else { + codegen.matcher(scrut, scrutSym, pt)(Nil, matchFailGen) + } + } + } + + // TODO: do this during tree construction, but that will require tracking the current owner in treemakers + // TODO: assign more fine-grained positions + // fixes symbol nesting, assigns positions + protected def fixerUpper(origOwner: Symbol, pos: Position) = new Traverser { + currentOwner = origOwner + + override def traverse(t: Tree) { + if (t != EmptyTree && t.pos == NoPosition) { + t.setPos(pos) + } + t match { + case Function(_, _) if t.symbol == NoSymbol => + t.symbol = currentOwner.newAnonymousFunctionValue(t.pos) + // println("new symbol for "+ (t, t.symbol.ownerChain)) + case Function(_, _) if (t.symbol.owner == NoSymbol) || (t.symbol.owner == origOwner) => + // println("fundef: "+ (t, t.symbol.ownerChain, currentOwner.ownerChain)) + t.symbol.owner = currentOwner + case d : DefTree if (d.symbol != NoSymbol) && ((d.symbol.owner == NoSymbol) || (d.symbol.owner == origOwner)) => // don't indiscriminately change existing owners! (see e.g., pos/t3440, pos/t3534, pos/unapplyContexts2) + // println("def: "+ (d, d.symbol.ownerChain, currentOwner.ownerChain)) + if(d.symbol.isLazy) { // for lazy val's accessor -- is there no tree?? + assert(d.symbol.lazyAccessor != NoSymbol && d.symbol.lazyAccessor.owner == d.symbol.owner, d.symbol.lazyAccessor) + d.symbol.lazyAccessor.owner = currentOwner + } + if(d.symbol.moduleClass ne NoSymbol) + d.symbol.moduleClass.owner = currentOwner + + d.symbol.owner = currentOwner + // case _ if (t.symbol != NoSymbol) && (t.symbol ne null) => + // println("untouched "+ (t, t.getClass, t.symbol.ownerChain, currentOwner.ownerChain)) + case _ => + } + super.traverse(t) + } + + // override def apply + // println("before fixerupper: "+ xTree) + // currentRun.trackerFactory.snapshot() + // println("after fixerupper") + // currentRun.trackerFactory.snapshot() + } + } + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// generate actual trees +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + trait CodegenCore extends MatchMonadInterface { + private var ctr = 0 + def freshName(prefix: String) = {ctr += 1; vpmName.counted(prefix, ctr)} + + // assert(owner ne null); assert(owner ne NoSymbol) + def freshSym(pos: Position, tp: Type = NoType, prefix: String = "x") = + NoSymbol.newTermSymbol(freshName(prefix), pos) setInfo tp + + // codegen relevant to the structure of the translation (how extractors are combined) + trait AbsCodegen { + def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree + + // local / context-free + def _asInstanceOf(b: Symbol, tp: Type): Tree + def _equals(checker: Tree, binder: Symbol): Tree + def _isInstanceOf(b: Symbol, tp: Type): Tree + def and(a: Tree, b: Tree): Tree + def drop(tgt: Tree)(n: Int): Tree + def index(tgt: Tree)(i: Int): Tree + def mkZero(tp: Type): Tree + def tupleSel(binder: Symbol)(i: Int): Tree + } + + // structure + trait Casegen extends AbsCodegen { import CODE._ + def one(res: Tree): Tree + + def flatMap(prev: Tree, b: Symbol, next: Tree): Tree + def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree + def flatMapGuard(cond: Tree, next: Tree): Tree + def ifThenElseZero(c: Tree, then: Tree): Tree = IF (c) THEN then ELSE zero + protected def zero: Tree + } + + def codegen: AbsCodegen + + def typesConform(tp: Type, pt: Type) = ((tp eq pt) || (tp <:< pt)) + + abstract class CommonCodegen extends AbsCodegen { import CODE._ + def fun(arg: Symbol, body: Tree): Tree = Function(List(ValDef(arg)), body) + def genTypeApply(tfun: Tree, args: Type*): Tree = if(args contains NoType) tfun else TypeApply(tfun, args.toList map TypeTree) + def tupleSel(binder: Symbol)(i: Int): Tree = (REF(binder) DOT nme.productAccessorName(i)) // make tree that accesses the i'th component of the tuple referenced by binder + def index(tgt: Tree)(i: Int): Tree = tgt APPLY (LIT(i)) + def drop(tgt: Tree)(n: Int): Tree = (tgt DOT vpmName.drop) (LIT(n)) + def _equals(checker: Tree, binder: Symbol): Tree = checker MEMBER_== REF(binder) // NOTE: checker must be the target of the ==, that's the patmat semantics for ya + def and(a: Tree, b: Tree): Tree = a AND b + + // drop annotations generated by CPS plugin etc, since its annotationchecker rejects T @cps[U] <: Any + // let's assume for now annotations don't affect casts, drop them there, and bring them back using the outer Typed tree + private def mkCast(t: Tree, tp: Type) = + Typed(gen.mkAsInstanceOf(t, tp.withoutAnnotations, true, false), TypeTree() setType tp) + + // the force is needed mainly to deal with the GADT typing hack (we can't detect it otherwise as tp nor pt need contain an abstract type, we're just casting wildly) + def _asInstanceOf(t: Tree, tp: Type, force: Boolean = false): Tree = if (!force && (t.tpe ne NoType) && t.isTyped && typesConform(t.tpe, tp)) t else mkCast(t, tp) + def _asInstanceOf(b: Symbol, tp: Type): Tree = if (typesConform(b.info, tp)) REF(b) else mkCast(REF(b), tp) + def _isInstanceOf(b: Symbol, tp: Type): Tree = gen.mkIsInstanceOf(REF(b), tp.withoutAnnotations, true, false) + // if (typesConform(b.info, tpX)) { println("warning: emitted spurious isInstanceOf: "+(b, tp)); TRUE } + + // duplicated out of frustration with cast generation + def mkZero(tp: Type): Tree = { + tp.typeSymbol match { + case UnitClass => Literal(Constant()) + case BooleanClass => Literal(Constant(false)) + case FloatClass => Literal(Constant(0.0f)) + case DoubleClass => Literal(Constant(0.0d)) + case ByteClass => Literal(Constant(0.toByte)) + case ShortClass => Literal(Constant(0.toShort)) + case IntClass => Literal(Constant(0)) + case LongClass => Literal(Constant(0L)) + case CharClass => Literal(Constant(0.toChar)) + case _ => gen.mkAsInstanceOf(Literal(Constant(null)), tp, any = true, wrapInApply = false) // the magic incantation is true/false here + } + } + } + } + + trait PureMatchMonadInterface extends MatchMonadInterface { + val matchStrategy: Tree + + def inMatchMonad(tp: Type): Type = appliedType(oneSig, List(tp)).finalResultType + def pureType(tp: Type): Type = appliedType(oneSig, List(tp)).paramTypes.headOption getOrElse NoType // fail gracefully (otherwise we get crashes) + protected def matchMonadSym = oneSig.finalResultType.typeSymbol + + import CODE._ + def _match(n: Name): SelectStart = matchStrategy DOT n + + private lazy val oneSig: Type = + typer.typed(_match(vpmName.one), EXPRmode | POLYmode | TAPPmode | FUNmode, WildcardType).tpe // TODO: error message + } + + trait PureCodegen extends CodegenCore with PureMatchMonadInterface { + def codegen: AbsCodegen = pureCodegen + + object pureCodegen extends CommonCodegen with Casegen { import CODE._ + //// methods in MatchingStrategy (the monad companion) -- used directly in translation + // __match.runOrElse(`scrut`)(`scrutSym` => `matcher`) + // TODO: consider catchAll, or virtualized matching will break in exception handlers + def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = + _match(vpmName.runOrElse) APPLY (scrut) APPLY (fun(scrutSym, cases map (f => f(this)) reduceLeft typedOrElse)) + + // __match.one(`res`) + def one(res: Tree): Tree = (_match(vpmName.one)) (res) + // __match.zero + protected def zero: Tree = _match(vpmName.zero) + // __match.guard(`c`, `then`) + def guard(c: Tree, then: Tree): Tree = _match(vpmName.guard) APPLY (c, then) + + //// methods in the monad instance -- used directly in translation + // `prev`.flatMap(`b` => `next`) + def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = (prev DOT vpmName.flatMap)(fun(b, next)) + // `thisCase`.orElse(`elseCase`) + def typedOrElse(thisCase: Tree, elseCase: Tree): Tree = (thisCase DOT vpmName.orElse) APPLY (elseCase) + // __match.guard(`cond`, `res`).flatMap(`nextBinder` => `next`) + def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = flatMap(guard(cond, res), nextBinder, next) + // __match.guard(`guardTree`, ()).flatMap((_: P[Unit]) => `next`) + def flatMapGuard(guardTree: Tree, next: Tree): Tree = flatMapCond(guardTree, CODE.UNIT, freshSym(guardTree.pos, pureType(UnitClass.tpe)), next) + } + } + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// OPTIMIZATIONS +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// decisions, decisions +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + trait TreeMakerApproximation extends TreeMakers { self: CodegenCore => + object Test { + var currId = 0 + } + case class Test(cond: Cond, treeMaker: TreeMaker) { + // def <:<(other: Test) = cond <:< other.cond + // def andThen_: (prev: List[Test]): List[Test] = + // prev.filterNot(this <:< _) :+ this + + private val reusedBy = new collection.mutable.HashSet[Test] + var reuses: Option[Test] = None + def registerReuseBy(later: Test): Unit = { + assert(later.reuses.isEmpty, later.reuses) + reusedBy += later + later.reuses = Some(this) + } + + val id = { Test.currId += 1; Test.currId} + override def toString = + if (cond eq Top) "T" + else if(cond eq Havoc) "!?" + else "T"+ id + (if(reusedBy nonEmpty) "!["+ treeMaker +"]" else (if(reuses.isEmpty) "["+ treeMaker +"]" else " cf. T"+reuses.get.id)) + } + + object Cond { + // def refines(self: Cond, other: Cond): Boolean = (self, other) match { + // case (Bottom, _) => true + // case (Havoc , _) => true + // case (_ , Top) => true + // case (_ , _) => false + // } + var currId = 0 + } + + abstract class Cond { + // def testedPath: Tree + // def <:<(other: Cond) = Cond.refines(this, other) + + val id = { Cond.currId += 1; Cond.currId} + } + + // does not contribute any knowledge + case object Top extends Cond + + // takes away knowledge. e.g., a user-defined guard + case object Havoc extends Cond + + // we know everything! everything! + // this either means the case is unreachable, + // or that it is statically known to be picked -- at this point in the decision tree --> no point in emitting further alternatives + // case object Bottom extends Cond + + + object EqualityCond { + private val uniques = new collection.mutable.HashMap[(Tree, Tree), EqualityCond] + def apply(testedPath: Tree, rhs: Tree): EqualityCond = uniques getOrElseUpdate((testedPath, rhs), new EqualityCond(testedPath, rhs)) + } + class EqualityCond(testedPath: Tree, rhs: Tree) extends Cond { + // def negation = TopCond // inequality doesn't teach us anything + // do simplification when we know enough about the tree statically: + // - collapse equal trees + // - accumulate tests when (in)equality not known statically + // - become bottom when we statically know this can never match + + override def toString = testedPath +" == "+ rhs +"#"+ id + } + + object TypeCond { + private val uniques = new collection.mutable.HashMap[(Tree, Type), TypeCond] + def apply(testedPath: Tree, pt: Type): TypeCond = uniques getOrElseUpdate((testedPath, pt), new TypeCond(testedPath, pt)) + } + class TypeCond(testedPath: Tree, pt: Type) extends Cond { + // def negation = TopCond // inequality doesn't teach us anything + // do simplification when we know enough about the tree statically: + // - collapse equal trees + // - accumulate tests when (in)equality not known statically + // - become bottom when we statically know this can never match + override def toString = testedPath +" <: "+ pt +"#"+ id + } + + object TypeAndEqualityCond { + private val uniques = new collection.mutable.HashMap[(Tree, Type), TypeAndEqualityCond] + def apply(testedPath: Tree, pt: Type): TypeAndEqualityCond = uniques getOrElseUpdate((testedPath, pt), new TypeAndEqualityCond(testedPath, pt)) + } + class TypeAndEqualityCond(testedPath: Tree, pt: Type) extends Cond { + // def negation = TopCond // inequality doesn't teach us anything + // do simplification when we know enough about the tree statically: + // - collapse equal trees + // - accumulate tests when (in)equality not known statically + // - become bottom when we statically know this can never match + override def toString = testedPath +" (<: && ==) "+ pt +"#"+ id + } + + def approximateMatch(root: Symbol, cases: List[List[TreeMaker]]): List[List[Test]] = { + // a variable in this set should never be replaced by a tree that "does not consist of a selection on a variable in this set" (intuitively) + val pointsToBound = collection.mutable.HashSet(root) + + // the substitution that renames variables to variables in pointsToBound + var normalize: Substitution = EmptySubstitution + + // replaces a variable (in pointsToBound) by a selection on another variable in pointsToBound + // TODO check: + // pointsToBound -- accumSubst.from == Set(root) && (accumSubst.from.toSet -- pointsToBound) isEmpty + var accumSubst: Substitution = EmptySubstitution + + val trees = new collection.mutable.HashSet[Tree] + + def approximateTreeMaker(tm: TreeMaker): Test = { + val subst = tm.substitution + + // find part of substitution that replaces bound symbols by new symbols, and reverse that part + // so that we don't introduce new aliases for existing symbols, thus keeping the set of bound symbols minimal + val (boundSubst, unboundSubst) = (subst.from zip subst.to) partition {case (f, t) => + t.isInstanceOf[Ident] && (t.symbol ne NoSymbol) && pointsToBound(f) + } + val (boundFrom, boundTo) = boundSubst.unzip + normalize >>= Substitution(boundTo map (_.symbol), boundFrom map (CODE.REF(_))) + // println("normalize: "+ normalize) + + val (unboundFrom, unboundTo) = unboundSubst unzip + val okSubst = Substitution(unboundFrom, unboundTo map (normalize(_))) // it's important substitution does not duplicate trees here -- it helps to keep hash consing simple, anyway + pointsToBound ++= ((okSubst.from, okSubst.to).zipped filter { (f, t) => pointsToBound exists (sym => t.exists(_.symbol == sym)) })._1 + // println("pointsToBound: "+ pointsToBound) + + accumSubst >>= okSubst + // println("accumSubst: "+ accumSubst) + + // TODO: improve, e.g., for constants + def sameValue(a: Tree, b: Tree): Boolean = (a eq b) || ((a, b) match { + case (_ : Ident, _ : Ident) => a.symbol eq b.symbol + case _ => false + }) + + // hashconsing trees (modulo value-equality) + def unique(t: Tree): Tree = + trees find (a => a.equalsStructure0(t)(sameValue)) match { + case Some(orig) => orig // println("unique: "+ (t eq orig, orig)); + case _ => trees += t; t + } + + def uniqueTp(tp: Type): Type = tp match { + // typerefs etc are already hashconsed + case _ : UniqueType => tp + case tp@RefinedType(parents, EmptyScope) => tp.memo(tp: Type)(identity) // TODO: does this help? + case _ => tp + } + + def binderToUniqueTree(b: Symbol) = unique(accumSubst(normalize(CODE.REF(b)))) + + Test(tm match { + case ProductExtractorTreeMaker(pb, None, subst) => Top // TODO: NotNullTest(prevBinder) + case tm@TypeTestTreeMaker(prevBinder, nextBinderTp, _) => TypeCond(binderToUniqueTree(prevBinder), uniqueTp(nextBinderTp)) + case tm@TypeAndEqualityTestTreeMaker(_, patBinder, pt, _) => TypeAndEqualityCond(binderToUniqueTree(patBinder), uniqueTp(pt)) + case tm@EqualityTestTreeMaker(prevBinder, patTree, _) => EqualityCond(binderToUniqueTree(prevBinder), unique(patTree)) + case ExtractorTreeMaker(_, _, _, _) + | GuardTreeMaker(_) + | ProductExtractorTreeMaker(_, Some(_), _) => Havoc + case AlternativesTreeMaker(_, _, _) => Havoc // TODO: can do better here + case SubstOnlyTreeMaker(_, _) => Top + case BodyTreeMaker(_, _) => Havoc + }, tm) + } + + cases.map { _ map approximateTreeMaker } + } + } + +//// + trait CommonSubconditionElimination extends TreeMakerApproximation { self: OptimizedCodegen => + /** a flow-sensitive, generalised, common sub-expression elimination + * reuse knowledge from performed tests + * the only sub-expressions we consider are the conditions and results of the three tests (type, type&equality, equality) + * when a sub-expression is share, it is stored in a mutable variable + * the variable is floated up so that its scope includes all of the program that shares it + * we generalize sharing to implication, where b reuses a if a => b and priors(a) => priors(b) (the priors of a sub expression form the path through the decision tree) + * + * intended to be generalised to exhaustivity/reachability checking + */ + def doCSE(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): List[List[TreeMaker]] = { + val testss = approximateMatch(prevBinder, cases) + + // interpret: + val dependencies = new collection.mutable.LinkedHashMap[Test, Set[Cond]] + val tested = new collection.mutable.HashSet[Cond] + testss foreach { tests => + tested.clear() + tests dropWhile { test => + val cond = test.cond + if ((cond eq Havoc) || (cond eq Top)) (cond eq Top) // stop when we encounter a havoc, skip top + else { + tested += cond + + // is there an earlier test that checks our condition and whose dependencies are implied by ours? + dependencies find { case (priorTest, deps) => + ((priorTest.cond eq cond) || (deps contains cond)) && (deps subsetOf tested) + } foreach { case (priorTest, deps) => + // if so, note the dependency in both tests + priorTest registerReuseBy test + } + + dependencies(test) = tested.toSet // copies + true + } + } + } + + // find longest prefix of tests that reuse a prior test, and whose dependent conditions monotonically increase + // then, collapse these contiguous sequences of reusing tests + // store the result of the final test and the intermediate results in hoisted mutable variables (TODO: optimize: don't store intermediate results that aren't used) + // replace each reference to a variable originally bound by a collapsed test by a reference to the hoisted variable + val reused = new collection.mutable.HashMap[TreeMaker, ReusedCondTreeMaker] + var okToCall = false + val reusedOrOrig = (tm: TreeMaker) => {assert(okToCall); reused.getOrElse(tm, tm)} + + val res = testss map { tests => + var currDeps = Set[Cond]() + val (sharedPrefix, suffix) = tests span { test => + (test.cond eq Top) || (for( + reusedTest <- test.reuses; + nextDeps <- dependencies.get(reusedTest); + diff <- (nextDeps -- currDeps).headOption; + _ <- Some(currDeps = nextDeps)) + yield diff).nonEmpty + } + + val collapsedTreeMakers = if (sharedPrefix.nonEmpty) { // even sharing prefixes of length 1 brings some benefit (overhead-percentage for compiler: 26->24%, lib: 19->16%) + for (test <- sharedPrefix; reusedTest <- test.reuses) reusedTest.treeMaker match { + case reusedCTM: CondTreeMaker => reused(reusedCTM) = ReusedCondTreeMaker(reusedCTM) + case _ => + } + + // println("sharedPrefix: "+ sharedPrefix) + for (lastShared <- sharedPrefix.reverse.dropWhile(_.cond eq Top).headOption; + lastReused <- lastShared.reuses) + yield ReusingCondTreeMaker(sharedPrefix, reusedOrOrig) :: suffix.map(_.treeMaker) + } else None + + collapsedTreeMakers getOrElse tests.map(_.treeMaker) // sharedPrefix need not be empty (but it only contains Top-tests, which are dropped above) + } + okToCall = true // TODO: remove (debugging) + + res mapConserve (_ mapConserve reusedOrOrig) + } + + object ReusedCondTreeMaker { + def apply(orig: CondTreeMaker) = new ReusedCondTreeMaker(orig.prevBinder, orig.nextBinder, orig.cond, orig.res, orig.pos) + } + class ReusedCondTreeMaker(prevBinder: Symbol, val nextBinder: Symbol, cond: Tree, res: Tree, pos: Position) extends TreeMaker { import CODE._ + lazy val localSubstitution = Substitution(List(prevBinder), List(CODE.REF(nextBinder))) + lazy val storedCond = freshSym(pos, BooleanClass.tpe, "rc") setFlag MUTABLE + lazy val treesToHoist: List[Tree] = { + nextBinder setFlag MUTABLE + List(storedCond, nextBinder) map { b => VAL(b) === codegen.mkZero(b.info) } + } + + // TODO: finer-grained duplication + def chainBefore(next: Tree)(casegen: Casegen): Tree = // assert(codegen eq optimizedCodegen) + atPos(pos)(casegen.asInstanceOf[optimizedCodegen.OptimizedCasegen].flatMapCondStored(cond, storedCond, res, nextBinder, substitution(next).duplicate)) + } + + case class ReusingCondTreeMaker(sharedPrefix: List[Test], toReused: TreeMaker => TreeMaker) extends TreeMaker { import CODE._ + lazy val dropped_priors = sharedPrefix map (t => (toReused(t.treeMaker), t.reuses map (test => toReused(test.treeMaker)))) + lazy val localSubstitution = { + val (from, to) = dropped_priors.collect { + case (dropped: CondTreeMaker, Some(prior: ReusedCondTreeMaker)) => + (dropped.nextBinder, REF(prior.nextBinder)) + }.unzip + val oldSubs = dropped_priors.collect { + case (dropped: TreeMaker, _) => + dropped.substitution + } + oldSubs.foldLeft(Substitution(from, to))(_ >> _) + } + + def chainBefore(next: Tree)(casegen: Casegen): Tree = { + val cond = REF(dropped_priors.reverse.collectFirst{case (_, Some(ctm: ReusedCondTreeMaker)) => ctm}.get.storedCond) + + // TODO: finer-grained duplication -- MUST duplicate though, or we'll get VerifyErrors since sharing trees confuses lambdalift, and its confusion it emits illegal casts (diagnosed by Grzegorz: checkcast T ; invokevirtual S.m, where T not a subtype of S) + casegen.ifThenElseZero(cond, substitution(next).duplicate) + } + } + } + + + //// DCE + trait DeadCodeElimination extends TreeMakers { self: CodegenCore => + // TODO: non-trivial dead-code elimination + // e.g., the following match should compile to a simple instanceof: + // case class Ident(name: String) + // for (Ident(name) <- ts) println(name) + def doDCE(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): List[List[TreeMaker]] = { + // do minimal DCE + cases + } + } + + //// SWITCHES -- TODO: operate on Tests rather than TreeMakers + trait SwitchEmission extends TreeMakers with OptimizedMatchMonadInterface { self: CodegenCore => + abstract class SwitchMaker { + abstract class SwitchableTreeMakerExtractor { def unapply(x: TreeMaker): Option[Tree] } + val SwitchableTreeMaker: SwitchableTreeMakerExtractor + + def alternativesSupported: Boolean + + def isDefault(x: CaseDef): Boolean + def defaultSym: Symbol + def defaultBody: Tree + def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef + + private def sequence[T](xs: List[Option[T]]): Option[List[T]] = + if (xs exists (_.isEmpty)) None else Some(xs.flatten) + + // empty list ==> failure + def apply(cases: List[(Symbol, List[TreeMaker])], pt: Type): List[CaseDef] = { + val caseDefs = cases map { case (scrutSym, makers) => + makers match { + // default case + case (btm@BodyTreeMaker(body, _)) :: Nil => + Some(defaultCase(scrutSym, btm.substitution(body))) + // constant (or typetest for typeSwitch) + case SwitchableTreeMaker(pattern) :: (btm@BodyTreeMaker(body, _)) :: Nil => + Some(CaseDef(pattern, EmptyTree, btm.substitution(body))) + // alternatives + case AlternativesTreeMaker(_, altss, _) :: (btm@BodyTreeMaker(body, _)) :: Nil if alternativesSupported => + val casePatterns = altss map { + case SwitchableTreeMaker(pattern) :: Nil => + Some(pattern) + case _ => + None + } + + sequence(casePatterns) map { patterns => + val substedBody = btm.substitution(body) + CaseDef(Alternative(patterns), EmptyTree, substedBody) + } + case _ => //println("can't emit switch for "+ makers) + None //failure (can't translate pattern to a switch) + } + } + + (for( + caseDefs <- sequence(caseDefs)) yield + if (caseDefs exists isDefault) caseDefs + else { + caseDefs :+ defaultCase() + } + ) getOrElse Nil + } + } + + class RegularSwitchMaker(scrutSym: Symbol, matchFailGenOverride: Option[Tree => Tree]) extends SwitchMaker { + val switchableTpe = Set(ByteClass.tpe, ShortClass.tpe, IntClass.tpe, CharClass.tpe) + val alternativesSupported = true + + object SwitchablePattern { def unapply(pat: Tree): Option[Tree] = pat match { + case Literal(const@Constant((_: Byte ) | (_: Short) | (_: Int ) | (_: Char ))) => + Some(Literal(Constant(const.intValue))) // TODO: Java 7 allows strings in switches + case _ => None + }} + + object SwitchableTreeMaker extends SwitchableTreeMakerExtractor { + def unapply(x: TreeMaker): Option[Tree] = x match { + case EqualityTestTreeMaker(_, SwitchablePattern(const), _) => Some(const) + case _ => None + } + } + + def isDefault(x: CaseDef): Boolean = x match { + case CaseDef(Ident(nme.WILDCARD), EmptyTree, _) => true + case _ => false + } + + def defaultSym: Symbol = scrutSym + def defaultBody: Tree = { import CODE._; matchFailGenOverride map (gen => gen(REF(scrutSym))) getOrElse MATCHERROR(REF(scrutSym)) } + def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef = { import CODE._; atPos(body.pos) { + DEFAULT ==> body + }} + } + + override def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Tree => Tree]): Option[Tree] = { import CODE._ + val regularSwitchMaker = new RegularSwitchMaker(scrutSym, matchFailGenOverride) + // TODO: if patterns allow switch but the type of the scrutinee doesn't, cast (type-test) the scrutinee to the corresponding switchable type and switch on the result + if (regularSwitchMaker.switchableTpe(scrutSym.tpe)) { + val caseDefsWithDefault = regularSwitchMaker(cases map {c => (scrutSym, c)}, pt) + if (caseDefsWithDefault.length <= 2) None // not worth emitting a switch... also, the optimizer has trouble digesting tiny switches, apparently, so let's be nice and not generate them + else { + // match on scrutSym -- converted to an int if necessary -- not on scrut directly (to avoid duplicating scrut) + val scrutToInt: Tree = + if (scrutSym.tpe =:= IntClass.tpe) REF(scrutSym) + else (REF(scrutSym) DOT (nme.toInt)) + Some(BLOCK( + VAL(scrutSym) === scrut, + Match(scrutToInt, caseDefsWithDefault) // a switch + )) + } + } else None + } + + // for the catch-cases in a try/catch + private object typeSwitchMaker extends SwitchMaker { + def switchableTpe(tp: Type) = true + val alternativesSupported = false // TODO: needs either back-end support of flattening of alternatives during typers + + // TODO: there are more treemaker-sequences that can be handled by type tests + // analyze the result of approximateTreeMaker rather than the TreeMaker itself + object SwitchableTreeMaker extends SwitchableTreeMakerExtractor { + def unapply(x: TreeMaker): Option[Tree] = x match { + case tm@TypeTestTreeMaker(_, _, _) => + Some(Bind(tm.nextBinder, Typed(Ident(nme.WILDCARD), TypeTree(tm.nextBinderTp)) /* not used by back-end */)) // -- TODO: use this if binder does not occur in the body + case tm@TypeAndEqualityTestTreeMaker(_, patBinder, pt, _) if tm.isStraightTypeTest => + Some(Bind(tm.nextBinder, Typed(Ident(nme.WILDCARD), TypeTree(tm.nextBinderTp)) /* not used by back-end */)) + case _ => + None + } + } + + def isDefault(x: CaseDef): Boolean = x match { + case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) if (tpt.tpe =:= ThrowableClass.tpe) => true + case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) if (tpt.tpe =:= ThrowableClass.tpe) => true + case CaseDef(Ident(nme.WILDCARD), EmptyTree, _) => true + case _ => false + } + + lazy val defaultSym: Symbol = freshSym(NoPosition, ThrowableClass.tpe) + def defaultBody: Tree = Throw(CODE.REF(defaultSym)) + def defaultCase(scrutSym: Symbol = defaultSym, body: Tree = defaultBody): CaseDef = { import CODE._; atPos(body.pos) { + CASE (Bind(scrutSym, Typed(Ident(nme.WILDCARD), TypeTree(ThrowableClass.tpe)))) ==> body + }} + } + + // TODO: drop null checks + override def emitTypeSwitch(bindersAndCases: List[(Symbol, List[TreeMaker])], pt: Type): Option[List[CaseDef]] = { + val caseDefsWithDefault = typeSwitchMaker(bindersAndCases, pt) + if (caseDefsWithDefault isEmpty) None + else Some(caseDefsWithDefault) + } + } + + trait OptimizedMatchMonadInterface extends MatchMonadInterface { + override def inMatchMonad(tp: Type): Type = optionType(tp) + override def pureType(tp: Type): Type = tp + override protected def matchMonadSym = OptionClass + } + + trait OptimizedCodegen extends CodegenCore with TypedSubstitution with OptimizedMatchMonadInterface { + override def codegen: AbsCodegen = optimizedCodegen + + // trait AbsOptimizedCodegen extends AbsCodegen { + // def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree + // } + // def optimizedCodegen: AbsOptimizedCodegen + + // when we know we're targetting Option, do some inlining the optimizer won't do + // for example, `o.flatMap(f)` becomes `if(o == None) None else f(o.get)`, similarly for orElse and guard + // this is a special instance of the advanced inlining optimization that takes a method call on + // an object of a type that only has two concrete subclasses, and inlines both bodies, guarded by an if to distinguish the two cases + object optimizedCodegen extends CommonCodegen { import CODE._ + + /** Inline runOrElse and get rid of Option allocations + * + * runOrElse(scrut: scrutTp)(matcher): resTp = matcher(scrut) getOrElse ${catchAll(`scrut`)} + * the matcher's optional result is encoded as a flag, keepGoing, where keepGoing == true encodes result.isEmpty, + * if keepGoing is false, the result Some(x) of the naive translation is encoded as matchRes == x + */ + def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = { + val matchEnd = NoSymbol.newLabel(freshName("matchEnd"), NoPosition) setFlag SYNTH_CASE + val matchRes = NoSymbol.newValueParameter(newTermName("x"), NoPosition, SYNTHETIC) setInfo restpe.withoutAnnotations // + matchEnd setInfo MethodType(List(matchRes), restpe) + + def newCaseSym = NoSymbol.newLabel(freshName("case"), NoPosition) setInfo MethodType(Nil, restpe) setFlag SYNTH_CASE + var nextCase = newCaseSym + def caseDef(mkCase: Casegen => Tree): Tree = { + val currCase = nextCase + nextCase = newCaseSym + val casegen = new OptimizedCasegen(matchEnd, nextCase, restpe) + LabelDef(currCase, Nil, mkCase(casegen)) + } + + def catchAll = matchFailGen map { matchFailGen => + val scrutRef = if(scrutSym ne NoSymbol) REF(scrutSym) else EmptyTree // for alternatives + // must jump to matchEnd, use result generated by matchFailGen (could be `FALSE` for isDefinedAt) + LabelDef(nextCase, Nil, matchEnd APPLY (matchFailGen(scrutRef))) + // don't cast the arg to matchEnd when using PartialFun synth in uncurry, since it won't detect the throw (see gen.withDefaultCase) + // the cast is necessary when using typedMatchAnonFun-style PartialFun synth: + // (_asInstanceOf(matchFailGen(scrutRef), restpe)) + } toList + // catchAll.isEmpty iff no synthetic default case needed (the (last) user-defined case is a default) + // if the last user-defined case is a default, it will never jump to the next case; it will go immediately to matchEnd + + // the generated block is taken apart in TailCalls under the following assumptions + // the assumption is once we encounter a case, the remainder of the block will consist of cases + // the prologue may be empty, usually it is the valdef that stores the scrut + // val (prologue, cases) = stats span (s => !s.isInstanceOf[LabelDef]) + + // scrutSym == NoSymbol when generating an alternatives matcher + val scrutDef = if(scrutSym ne NoSymbol) List(VAL(scrutSym) === scrut) else Nil // for alternatives + Block( + scrutDef ++ (cases map caseDef) ++ catchAll, + LabelDef(matchEnd, List(matchRes), REF(matchRes)) + ) + } + + class OptimizedCasegen(matchEnd: Symbol, nextCase: Symbol, restpe: Type) extends CommonCodegen with Casegen { + def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = + optimizedCodegen.matcher(scrut, scrutSym, restpe)(cases, matchFailGen) + + // only used to wrap the RHS of a body + // res: T + // returns MatchMonad[T] + def one(res: Tree): Tree = matchEnd APPLY (_asInstanceOf(res, restpe)) // need cast for GADT magic + protected def zero: Tree = nextCase APPLY () + + // prev: MatchMonad[T] + // b: T + // next: MatchMonad[U] + // returns MatchMonad[U] + def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = { + val tp = inMatchMonad(b.tpe) + val prevSym = freshSym(prev.pos, tp, "o") + val isEmpty = tp member vpmName.isEmpty + val get = tp member vpmName.get + + BLOCK( + VAL(prevSym) === prev, + // must be isEmpty and get as we don't control the target of the call (prev is an extractor call) + ifThenElseZero(NOT(prevSym DOT isEmpty), Substitution(b, prevSym DOT get)(next)) + ) + } + + // cond: Boolean + // res: T + // nextBinder: T + // next == MatchMonad[U] + // returns MatchMonad[U] + def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = + ifThenElseZero(cond, BLOCK( + VAL(nextBinder) === res, + next + )) + + // guardTree: Boolean + // next: MatchMonad[T] + // returns MatchMonad[T] + def flatMapGuard(guardTree: Tree, next: Tree): Tree = + ifThenElseZero(guardTree, next) + + def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree = + ifThenElseZero(cond, BLOCK( + condSym === TRUE_typed, + nextBinder === res, + next + )) + } + + } + } + + + trait MatchOptimizations extends CommonSubconditionElimination + with DeadCodeElimination + with SwitchEmission + with OptimizedCodegen { self: TreeMakers => + override def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) = { + val optCases = doCSE(prevBinder, doDCE(prevBinder, cases, pt), pt) + val toHoist = ( + for (treeMakers <- optCases) + yield treeMakers.collect{case tm: ReusedCondTreeMaker => tm.treesToHoist} + ).flatten.flatten.toList + (optCases, toHoist) + } + } +} diff --git a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala index 31d064c824..57e82ed706 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala @@ -299,6 +299,7 @@ trait SyntheticMethods extends ast.TreeDSL { newAcc resetFlag (ACCESSOR | PARAMACCESSOR) ddef.rhs.duplicate } + // TODO: shouldn't the next line be: `original resetFlag CASEACCESSOR`? ddef.symbol resetFlag CASEACCESSOR lb += logResult("case accessor new")(newAcc) } diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 553cafe966..b827f2ac1a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -26,12 +26,14 @@ import util.Statistics._ * @author Martin Odersky * @version 1.0 */ -trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser { +trait Typers extends Modes with Adaptations with Taggings { self: Analyzer => import global._ import definitions._ + import patmat.DefaultOverrideMatchAttachment + final def forArgMode(fun: Tree, mode: Int) = if (treeInfo.isSelfOrSuperConstrCall(fun)) mode | SCCmode else mode @@ -83,8 +85,11 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser private def isPastTyper = phase.id > currentRun.typerPhase.id - // don't translate matches in presentation compiler: it loses vital symbols that are needed to do hyperlinking - @inline private def doMatchTranslation = !forInteractive && opt.virtPatmat && (phase.id < currentRun.uncurryPhase.id) + // when true: + // - we may virtualize matches (if -Xexperimental and there's a suitable __match in scope) + // - we synthesize PartialFunction implementations for `x => x match {...}` and `match {...}` when the expected type is PartialFunction + // this is disabled by: -Xoldpatmat, scaladoc or interactive compilation + @inline private def newPatternMatching = opt.virtPatmat && !forScaladoc && !forInteractive // && (phase.id < currentRun.uncurryPhase.id) abstract class Typer(context0: Context) extends TyperDiagnostics with Adaptation with Tagging with TyperContextErrors { import context0.unit @@ -2226,19 +2231,43 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser treeCopy.Match(tree, selector1, casesAdapted) setType resTp } - // match has been typed, now translate it - def translatedMatch(match_ : Match) = MatchTranslator(this).translateMatch(match_) + // match has been typed -- virtualize it if we're feeling experimental + // (virtualized matches are expanded during type checking so they have the full context available) + // otherwise, do nothing: matches are translated during phase `patmat` (unless -Xoldpatmat) + def virtualizedMatch(match_ : Match, mode: Int, pt: Type) = { + import patmat.{vpmName, PureMatchTranslator, OptimizingMatchTranslator} + + // TODO: add fallback __match sentinel to predef + val matchStrategy: Tree = + if (!(newPatternMatching && opt.experimental && context.isNameInScope(vpmName._match))) null // fast path, avoiding the next line if there's no __match to be seen + else newTyper(context.makeImplicit(reportAmbiguousErrors = false)).silent(_.typed(Ident(vpmName._match), EXPRmode, WildcardType), reportAmbiguousErrors = false) match { + case SilentResultValue(ms) => ms + case _ => null + } - // synthesize and type check a (Partial)Function implementation based on a match specified by `cases` - // Match(EmptyTree, cases) ==> new Function { def apply(params) = `translateMatch('`(param1,...,paramN)` match { cases }')` } + if (matchStrategy ne null) // virtualize + typed((new PureMatchTranslator(this.asInstanceOf[patmat.global.analyzer.Typer] /*TODO*/, matchStrategy)).translateMatch(match_), mode, pt) + else + match_ // will be translated in phase `patmat` + } + + // synthesize and type check a PartialFunction implementation based on a match specified by `cases` + // Match(EmptyTree, cases) ==> new PartialFunction { def apply(params) = `translateMatch('`(param1,...,paramN)` match { cases }')` } // for fresh params, the selector of the match we'll translated simply gathers those in a tuple + // NOTE: restricted to PartialFunction -- leave Function trees if the expected type does not demand a partial function class MatchFunTyper(tree: Tree, cases: List[CaseDef], mode: Int, pt0: Type) { + // TODO: remove FunctionN support -- this is currently designed so that it can emit FunctionN and PartialFunction subclasses + // however, we should leave Function nodes until Uncurry so phases after typer can still detect normal Function trees + // we need to synthesize PartialFunction impls, though, to avoid nastiness in Uncurry in transforming&duplicating generated pattern matcher trees + // TODO: remove PartialFunction support from UnCurry private val pt = deskolemizeGADTSkolems(pt0) private val targs = pt.normalize.typeArgs private val arity = if (isFunctionType(pt)) targs.length - 1 else 1 // TODO pt should always be a (Partial)Function, right? private val ptRes = if (targs.isEmpty) WildcardType else targs.last // may not be fully defined private val isPartial = pt.typeSymbol == PartialFunctionClass + assert(isPartial) + private val anonClass = context.owner.newAnonymousFunctionClass(tree.pos) private val funThis = This(anonClass) @@ -2291,7 +2320,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser anonClass setInfo ClassInfoType(parents, newScope, anonClass) methodSym setInfoAndEnter MethodType(paramSyms, resTp) - DefDef(methodSym, methodBodyTyper.translatedMatch(match_)) + DefDef(methodSym, methodBodyTyper.virtualizedMatch(match_, mode, pt)) } } @@ -2330,7 +2359,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser match_ setType B1.tpe // the default uses applyOrElse's first parameter since the scrut's type has been widened - val body = methodBodyTyper.translatedMatch(match_ withAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x)))) + val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x))), mode, pt) DefDef(methodSym, body) } @@ -2348,13 +2377,13 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser methodSym setInfoAndEnter MethodType(paramSyms, BooleanClass.tpe) val match_ = methodBodyTyper.typedMatch(selector, casesTrue, mode, BooleanClass.tpe) - val body = methodBodyTyper.translatedMatch(match_ withAttachment DefaultOverrideMatchAttachment(FALSE_typed)) + val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(FALSE_typed), mode, pt) DefDef(methodSym, body) } } - val members = if (isPartial) { + lazy val members = if (isPartial) { // somehow @cps annotations upset the typer when looking at applyOrElse's signature, but not apply's // TODO: figure out the details (T @cps[U] is not a subtype of Any, but then why does it work for the apply method?) if (targs forall (_ <:< AnyClass.tpe)) List(applyOrElseMethodDef, isDefinedAtMethod) @@ -2433,7 +2462,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser fun.body match { // later phase indicates scaladoc is calling (where shit is messed up, I tell you) // -- so fall back to old patmat, which is more forgiving - case Match(sel, cases) if (sel ne EmptyTree) && doMatchTranslation => + case Match(sel, cases) if (sel ne EmptyTree) && newPatternMatching && (pt.typeSymbol == PartialFunctionClass) => // go to outer context -- must discard the context that was created for the Function since we're discarding the function // thus, its symbol, which serves as the current context.owner, is not the right owner // you won't know you're using the wrong owner until lambda lift crashes (unless you know better than to use the wrong owner) @@ -3823,11 +3852,13 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser } } - def typedTranslatedMatch(tree: Tree, selector: Tree, cases: List[CaseDef]): Tree = + // under -Xexperimental (and not -Xoldpatmat), and when there's a suitable __match in scope, virtualize the pattern match + // otherwise, type the Match and leave it until phase `patmat` (immediately after typer) + // empty-selector matches are transformed into synthetic PartialFunction implementations when the expected type demands it + def typedVirtualizedMatch(tree: Tree, selector: Tree, cases: List[CaseDef]): Tree = if (selector == EmptyTree) { - if (doMatchTranslation) (new MatchFunTyper(tree, cases, mode, pt)).translated + if (newPatternMatching && (pt.typeSymbol == PartialFunctionClass)) (new MatchFunTyper(tree, cases, mode, pt)).translated else { - if (opt.virtPatmat) debugwarn("virtpatmat should not encounter empty-selector matches "+ tree) val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1 val params = for (i <- List.range(0, arity)) yield atPos(tree.pos.focusStart) { @@ -3839,12 +3870,8 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser val body = treeCopy.Match(tree, selector1, cases) typed1(atPos(tree.pos) { Function(params, body) }, mode, pt) } - } else { - if (!doMatchTranslation || (tree firstAttachment {case TranslatedMatchAttachment => } nonEmpty)) - typedMatch(selector, cases, mode, pt, tree) - else - typed(translatedMatch(typedMatch(selector, cases, mode, pt, tree)), mode, pt) - } + } else + virtualizedMatch(typedMatch(selector, cases, mode, pt, tree), mode, pt) def typedReturn(expr: Tree) = { val enclMethod = context.enclMethod @@ -4686,7 +4713,7 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser typedIf(cond, thenp, elsep) case tree @ Match(selector, cases) => - typedTranslatedMatch(tree, selector, cases) + typedVirtualizedMatch(tree, selector, cases) case Return(expr) => typedReturn(expr) @@ -4702,9 +4729,6 @@ trait Typers extends Modes with Adaptations with Taggings with PatMatVirtualiser catches1 = catches1 map (adaptCase(_, mode, owntype)) } - if (doMatchTranslation) - catches1 = (MatchTranslator(this)).translateTry(catches1, owntype, tree.pos) - treeCopy.Try(tree, block1, catches1, finalizer1) setType owntype case Throw(expr) => diff --git a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala index bed8e93d1b..862b19d0a4 100644 --- a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala +++ b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala @@ -3,8 +3,9 @@ package scala.tools.selectivecps import scala.tools.nsc.Global +import scala.tools.nsc.typechecker.Modes -abstract class CPSAnnotationChecker extends CPSUtils { +abstract class CPSAnnotationChecker extends CPSUtils with Modes { val global: Global import global._ import definitions._ @@ -177,59 +178,38 @@ abstract class CPSAnnotationChecker extends CPSUtils { override def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = { if (!cpsEnabled) return tree - vprintln("adapt annotations " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt) + vprintln("adapt annotations " + tree + " / " + tree.tpe + " / " + modeString(mode) + " / " + pt) - val annots1 = cpsParamAnnotation(tree.tpe) - val annots2 = cpsParamAnnotation(pt) + val patMode = (mode & global.analyzer.PATTERNmode) != 0 + val exprMode = (mode & global.analyzer.EXPRmode) != 0 + val byValMode = (mode & global.analyzer.BYVALmode) != 0 - if ((mode & global.analyzer.PATTERNmode) != 0) { - if (!annots1.isEmpty) { - return tree modifyType removeAllCPSAnnotations - } - } + val annotsTree = cpsParamAnnotation(tree.tpe) + val annotsExpected = cpsParamAnnotation(pt) -/* + // not sure I rephrased this comment correctly: + // replacing `patMode` in the condition below by `patMode || ((mode & global.analyzer.TYPEmode) != 0 && (mode & global.analyzer.BYVALmode))` // doesn't work correctly -- still relying on addAnnotations to remove things from ValDef symbols - if ((mode & global.analyzer.TYPEmode) != 0 && (mode & global.analyzer.BYVALmode) != 0) { - if (!annots1.isEmpty) { - println("removing annotation from " + tree + "/" + tree.tpe) - val s = tree.setType(removeAllCPSAnnotations(tree.tpe)) - println(s) - s - } - } -*/ - - if ((mode & global.analyzer.EXPRmode) != 0) { - if (annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.BYVALmode) == 0)) { // shiftUnit - // add a marker annotation that will make tree.tpe behave as pt, subtyping wise - // tree will look like having any possible annotation - //println("adapt annotations " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt) - //val same = annots2 forall { case AnnotationInfo(atp: TypeRef, _, _) => atp.typeArgs(0) =:= atp.typeArgs(1) } - // TBD: use same or not? see infer0.scala/infer1.scala - - // CAVEAT: - // for monomorphic answer types we want to have @plus @cps (for better checking) - // for answer type modification we want to have only @plus (because actual answer type may differ from pt) - - //val known = global.analyzer.isFullyDefined(pt) - - if (/*same &&*/ !hasPlusMarker(tree.tpe)) { - //if (known) - return tree modifyType (_ withAnnotations newPlusMarker() :: annots2) // needed for #1807 - //else - // return tree.setType(tree.tpe.withAnnotations(adapt::Nil)) - } - tree - } else if (!annots1.isEmpty && ((mode & global.analyzer.BYVALmode) != 0)) { // dropping annotation - // add a marker annotation that will make tree.tpe behave as pt, subtyping wise - // tree will look like having no annotation - if (!hasMinusMarker(tree.tpe)) { - return tree modifyType addMinusMarker - } - } - } - tree + if (patMode && !annotsTree.isEmpty) tree modifyType removeAllCPSAnnotations + else if (exprMode && !byValMode && !hasPlusMarker(tree.tpe) && annotsTree.isEmpty && annotsExpected.nonEmpty) { // shiftUnit + // add a marker annotation that will make tree.tpe behave as pt, subtyping wise + // tree will look like having any possible annotation + //println("adapt annotations " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt) + + // CAVEAT: + // for monomorphic answer types we want to have @plus @cps (for better checking) + // for answer type modification we want to have only @plus (because actual answer type may differ from pt) + + val res = tree modifyType (_ withAnnotations newPlusMarker() :: annotsExpected) // needed for #1807 + vprintln("adapted annotations (not by val) of " + tree + " to " + res.tpe) + res + } else if (exprMode && byValMode && !hasMinusMarker(tree.tpe) && annotsTree.nonEmpty) { // dropping annotation + // add a marker annotation that will make tree.tpe behave as pt, subtyping wise + // tree will look like having no annotation + val res = tree modifyType addMinusMarker + vprintln("adapted annotations (by val) of " + tree + " to " + res.tpe) + res + } else tree } def updateAttributesFromChildren(tpe: Type, childAnnots: List[AnnotationInfo], byName: List[Tree]): Type = { @@ -454,11 +434,10 @@ abstract class CPSAnnotationChecker extends CPSUtils { transChildrenInOrder(tree, tpe, List(cond), List(thenp, elsep)) case Match(select, cases) => - // TODO: can there be cases that are not CaseDefs?? check collect vs map! - transChildrenInOrder(tree, tpe, List(select), cases:::(cases collect { case CaseDef(_, _, body) => body })) + transChildrenInOrder(tree, tpe, List(select), cases:::(cases map { case CaseDef(_, _, body) => body })) case Try(block, catches, finalizer) => - val tpe1 = transChildrenInOrder(tree, tpe, Nil, block::catches:::(catches collect { case CaseDef(_, _, body) => body })) + val tpe1 = transChildrenInOrder(tree, tpe, Nil, block::catches:::(catches map { case CaseDef(_, _, body) => body })) val annots = cpsParamAnnotation(tpe1) if (annots.nonEmpty) { diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala index e1d699debc..e9e9cf0fab 100644 --- a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala +++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala @@ -241,6 +241,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with // where D$idef = def L$i(..) = {L$i.body; L${i+1}(..)} case ldef @ LabelDef(name, params, rhs) => + // println("trans LABELDEF "+(name, params, tree.tpe, hasAnswerTypeAnn(tree.tpe))) + // TODO why does the labeldef's type have a cpsMinus annotation, whereas the rhs does not? (BYVALmode missing/too much somewhere?) if (hasAnswerTypeAnn(tree.tpe)) { // currentOwner.newMethod(name, tree.pos, Flags.SYNTHETIC) setInfo ldef.symbol.info val sym = ldef.symbol resetFlag Flags.LABEL @@ -456,10 +458,11 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with val (anfStats, anfExpr) = rec(stms, cpsA, List()) // println("\nanf-block:\n"+ ((stms :+ expr) mkString ("{", "\n", "}")) +"\nBECAME\n"+ ((anfStats :+ anfExpr) mkString ("{", "\n", "}"))) - + // println("synth case? "+ (anfStats map (t => (t, t.isDef, gen.hasSynthCaseSymbol(t))))) // SUPER UGLY HACK: handle virtpatmat-style matches, whose labels have already been turned into DefDefs if (anfStats.nonEmpty && (anfStats forall (t => !t.isDef || gen.hasSynthCaseSymbol(t)))) { val (prologue, rest) = (anfStats :+ anfExpr) span (s => !s.isInstanceOf[DefDef]) // find first case + // println("rest: "+ rest) // val (defs, calls) = rest partition (_.isInstanceOf[DefDef]) if (rest nonEmpty){ // the filter drops the ()'s emitted when transValue encountered a LabelDef diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala index a78de8e6c8..dcb7cd601f 100644 --- a/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala +++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala @@ -65,6 +65,7 @@ abstract class SelectiveCPSTransform extends PluginComponent with class CPSTransformer(unit: CompilationUnit) extends TypingTransformer(unit) { + private val patmatTransformer = patmat.newTransformer(unit) override def transform(tree: Tree): Tree = { if (!cpsEnabled) return tree @@ -212,7 +213,7 @@ abstract class SelectiveCPSTransform extends PluginComponent with val catch2 = localTyper.typedCases(List(catchIfDefined), ThrowableClass.tpe, targettp) //typedCases(tree, catches, ThrowableClass.tpe, pt) - localTyper.typed(Block(List(funDef), treeCopy.Try(tree, treeCopy.Block(block1, stms, expr2), catch2, finalizer1))) + patmatTransformer.transform(localTyper.typed(Block(List(funDef), treeCopy.Try(tree, treeCopy.Block(block1, stms, expr2), catch2, finalizer1)))) /* diff --git a/test/files/neg/gadts1.check b/test/files/neg/gadts1.check index 0441f604c9..44d2b114d6 100644 --- a/test/files/neg/gadts1.check +++ b/test/files/neg/gadts1.check @@ -11,7 +11,4 @@ gadts1.scala:20: error: type mismatch; required: a case Cell[a](x: Int) => c.x = 5 ^ -gadts1.scala:20: error: Could not typecheck extractor call: case class with arguments List((x @ (_: Int))) - case Cell[a](x: Int) => c.x = 5 - ^ -four errors found +three errors found diff --git a/test/files/neg/patmat-type-check.check b/test/files/neg/patmat-type-check.check index ab4451f089..e045841ce1 100644 --- a/test/files/neg/patmat-type-check.check +++ b/test/files/neg/patmat-type-check.check @@ -3,31 +3,19 @@ patmat-type-check.scala:22: error: scrutinee is incompatible with pattern type; required: String def f1 = "bob".reverse match { case Seq('b', 'o', 'b') => true } // fail ^ -patmat-type-check.scala:22: error: value _1 is not a member of object Seq - def f1 = "bob".reverse match { case Seq('b', 'o', 'b') => true } // fail - ^ patmat-type-check.scala:23: error: scrutinee is incompatible with pattern type; found : Seq[A] required: Array[Char] def f2 = "bob".toArray match { case Seq('b', 'o', 'b') => true } // fail ^ -patmat-type-check.scala:23: error: value _1 is not a member of object Seq - def f2 = "bob".toArray match { case Seq('b', 'o', 'b') => true } // fail - ^ patmat-type-check.scala:27: error: scrutinee is incompatible with pattern type; found : Seq[A] required: Test.Bop2 def f3(x: Bop2) = x match { case Seq('b', 'o', 'b') => true } // fail ^ -patmat-type-check.scala:27: error: value _1 is not a member of object Seq - def f3(x: Bop2) = x match { case Seq('b', 'o', 'b') => true } // fail - ^ patmat-type-check.scala:30: error: scrutinee is incompatible with pattern type; found : Seq[A] required: Test.Bop3[Char] def f4[T](x: Bop3[Char]) = x match { case Seq('b', 'o', 'b') => true } // fail ^ -patmat-type-check.scala:30: error: value _1 is not a member of object Seq - def f4[T](x: Bop3[Char]) = x match { case Seq('b', 'o', 'b') => true } // fail - ^ -8 errors found +four errors found diff --git a/test/files/neg/t0418.check b/test/files/neg/t0418.check index 50931a1bca..4e9ad2f9ae 100644 --- a/test/files/neg/t0418.check +++ b/test/files/neg/t0418.check @@ -4,7 +4,4 @@ t0418.scala:2: error: not found: value Foo12340771 t0418.scala:2: error: not found: value x null match { case Foo12340771.Bar(x) => x } ^ -t0418.scala:2: error: Could not typecheck extractor call: case class with arguments List((x @ _)) - null match { case Foo12340771.Bar(x) => x } - ^ -three errors found +two errors found diff --git a/test/files/neg/t112706A.check b/test/files/neg/t112706A.check index fb18b31be1..30d0c3ec91 100644 --- a/test/files/neg/t112706A.check +++ b/test/files/neg/t112706A.check @@ -3,7 +3,4 @@ t112706A.scala:5: error: constructor cannot be instantiated to expected type; required: String case Tuple2(node,_) => ^ -t112706A.scala:5: error: Could not typecheck extractor call: case class Tuple2 with arguments List((node @ _), _) - case Tuple2(node,_) => - ^ -two errors found +one error found diff --git a/test/files/neg/t3392.check b/test/files/neg/t3392.check index 3a39098c4e..842d63eec9 100644 --- a/test/files/neg/t3392.check +++ b/test/files/neg/t3392.check @@ -1,7 +1,4 @@ t3392.scala:9: error: not found: value x case x@A(x/*<-- refers to the pattern that includes this comment*/.Ex(42)) => ^ -t3392.scala:9: error: Could not typecheck extractor call: case class with arguments List(42) - case x@A(x/*<-- refers to the pattern that includes this comment*/.Ex(42)) => - ^ -two errors found +one error found diff --git a/test/files/neg/t418.check b/test/files/neg/t418.check index c06088ba9d..1489547823 100644 --- a/test/files/neg/t418.check +++ b/test/files/neg/t418.check @@ -4,7 +4,4 @@ t418.scala:2: error: not found: value Foo12340771 t418.scala:2: error: not found: value x null match { case Foo12340771.Bar(x) => x } ^ -t418.scala:2: error: Could not typecheck extractor call: case class with arguments List((x @ _)) - null match { case Foo12340771.Bar(x) => x } - ^ -three errors found +two errors found diff --git a/test/files/neg/t4515.check b/test/files/neg/t4515.check index 856d252a0f..a60d16295f 100644 --- a/test/files/neg/t4515.check +++ b/test/files/neg/t4515.check @@ -1,6 +1,6 @@ t4515.scala:37: error: type mismatch; - found : _0(in method apply) where type _0(in method apply) - required: (some other)_0(in method apply) + found : _0(in value $anonfun) where type _0(in value $anonfun) + required: (some other)_0(in value $anonfun) handler.onEvent(target, ctx.getEvent, node, ctx) ^ one error found diff --git a/test/files/neg/t5589neg.check b/test/files/neg/t5589neg.check index fb6858a397..b3ff16d7e4 100644 --- a/test/files/neg/t5589neg.check +++ b/test/files/neg/t5589neg.check @@ -22,9 +22,6 @@ t5589neg.scala:4: error: constructor cannot be instantiated to expected type; t5589neg.scala:4: error: not found: value y2 def f7(x: Either[Int, (String, Int)]) = for (y1 @ Tuple1(y2) <- x.right) yield ((y1, y2)) ^ -t5589neg.scala:4: error: Could not typecheck extractor call: case class Tuple1 with arguments List((y2 @ _)) - def f7(x: Either[Int, (String, Int)]) = for (y1 @ Tuple1(y2) <- x.right) yield ((y1, y2)) - ^ t5589neg.scala:5: error: constructor cannot be instantiated to expected type; found : (T1, T2, T3) required: (String, Int) @@ -37,4 +34,4 @@ t5589neg.scala:5: error: not found: value y2 def f8(x: Either[Int, (String, Int)]) = for ((y1, y2, y3) <- x.right) yield ((y1, y2)) ^ two warnings found -8 errors found +7 errors found diff --git a/test/files/run/inner-parse.check b/test/files/run/inner-parse.check index 87ea9ddeb5..e4a30714bd 100644 --- a/test/files/run/inner-parse.check +++ b/test/files/run/inner-parse.check @@ -5,6 +5,7 @@ class Test$$anonfun$main$1 extends scala.runtime.AbstractFunction1$mcVL$sp descriptor ()V descriptor apply (Lscala/Tuple2;)V descriptor apply (Ljava/lang/Object;)Ljava/lang/Object; + descriptor apply (Ljava/lang/Object;)V descriptor cwd$1 Ljava/lang/String; descriptor serialVersionUID J descriptor (Ljava/lang/String;)V diff --git a/test/files/run/programmatic-main.check b/test/files/run/programmatic-main.check index d16e2c5178..bdf76ddce1 100644 --- a/test/files/run/programmatic-main.check +++ b/test/files/run/programmatic-main.check @@ -4,27 +4,28 @@ namer 2 resolve names, attach symbols to named trees packageobjects 3 load package objects typer 4 the meat and potatoes: type the trees - superaccessors 5 add super accessors in traits and nested classes - extmethods 6 add extension methods for inline classes - pickler 7 serialize symbol tables - refchecks 8 reference/override checking, translate nested objects - uncurry 9 uncurry, translate function values to anonymous classes - tailcalls 10 replace tail calls by jumps - specialize 11 @specialized-driven class and method specialization - explicitouter 12 this refs to outer pointers, translate patterns - erasure 13 erase types, add interfaces for traits - posterasure 14 clean up erased inline classes - lazyvals 15 allocate bitmaps, translate lazy vals into lazified defs - lambdalift 16 move nested functions to top level - constructors 17 move field definitions into constructors - flatten 18 eliminate inner classes - mixin 19 mixin composition - cleanup 20 platform-specific cleanups, generate reflective calls - icode 21 generate portable intermediate code - inliner 22 optimization: do inlining -inlineExceptionHandlers 23 optimization: inline exception handlers - closelim 24 optimization: eliminate uncalled closures - dce 25 optimization: eliminate dead code - jvm 26 generate JVM bytecode - terminal 27 The last phase in the compiler chain + patmat 5 translate match expressions + superaccessors 6 add super accessors in traits and nested classes + extmethods 7 add extension methods for inline classes + pickler 8 serialize symbol tables + refchecks 9 reference/override checking, translate nested objects + uncurry 10 uncurry, translate function values to anonymous classes + tailcalls 11 replace tail calls by jumps + specialize 12 @specialized-driven class and method specialization + explicitouter 13 this refs to outer pointers, translate patterns + erasure 14 erase types, add interfaces for traits + posterasure 15 clean up erased inline classes + lazyvals 16 allocate bitmaps, translate lazy vals into lazified defs + lambdalift 17 move nested functions to top level + constructors 18 move field definitions into constructors + flatten 19 eliminate inner classes + mixin 20 mixin composition + cleanup 21 platform-specific cleanups, generate reflective calls + icode 22 generate portable intermediate code + inliner 23 optimization: do inlining +inlineExceptionHandlers 24 optimization: inline exception handlers + closelim 25 optimization: eliminate uncalled closures + dce 26 optimization: eliminate dead code + jvm 27 generate JVM bytecode + terminal 28 The last phase in the compiler chain diff --git a/test/files/run/virtpatmat_staging.flags b/test/files/run/virtpatmat_staging.flags index 3f5a3100e4..48fd867160 100644 --- a/test/files/run/virtpatmat_staging.flags +++ b/test/files/run/virtpatmat_staging.flags @@ -1 +1 @@ - -Xexperimental +-Xexperimental -- cgit v1.2.3 From 9df576db2d315fca23ece4af822b130ae15d032d Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Tue, 1 May 2012 15:22:52 +0200 Subject: partial fun synth typing under correct pt --- src/compiler/scala/tools/nsc/typechecker/Typers.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index b827f2ac1a..b55406761d 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -2320,7 +2320,7 @@ trait Typers extends Modes with Adaptations with Taggings { anonClass setInfo ClassInfoType(parents, newScope, anonClass) methodSym setInfoAndEnter MethodType(paramSyms, resTp) - DefDef(methodSym, methodBodyTyper.virtualizedMatch(match_, mode, pt)) + DefDef(methodSym, methodBodyTyper.virtualizedMatch(match_, mode, resTp)) } } @@ -2359,7 +2359,7 @@ trait Typers extends Modes with Adaptations with Taggings { match_ setType B1.tpe // the default uses applyOrElse's first parameter since the scrut's type has been widened - val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x))), mode, pt) + val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(REF(default) APPLY (REF(x))), mode, B1.tpe) DefDef(methodSym, body) } @@ -2377,7 +2377,7 @@ trait Typers extends Modes with Adaptations with Taggings { methodSym setInfoAndEnter MethodType(paramSyms, BooleanClass.tpe) val match_ = methodBodyTyper.typedMatch(selector, casesTrue, mode, BooleanClass.tpe) - val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(FALSE_typed), mode, pt) + val body = methodBodyTyper.virtualizedMatch(match_ withAttachment DefaultOverrideMatchAttachment(FALSE_typed), mode, BooleanClass.tpe) DefDef(methodSym, body) } -- cgit v1.2.3 From 3e20bebd192444d8c1b079489292011e8030b532 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Wed, 2 May 2012 10:42:48 +0200 Subject: SI-5729: TypeVar experimentals iff -Xexperimental it used to also be enabled by -Yvirtpatmat, which is now on by default, but this type hackery is no longer necessary to bootstrap under the new pattern matching scheme, so let's only turn it on when people are feeling -Xexperimental --- src/compiler/scala/reflect/internal/Types.scala | 3 ++- src/compiler/scala/tools/nsc/Global.scala | 4 +--- src/library/scala/concurrent/package.scala | 2 +- test/files/pos/t5729.scala | 6 ++++++ 4 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 test/files/pos/t5729.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/Types.scala b/src/compiler/scala/reflect/internal/Types.scala index 026cd35d23..b8346a663d 100644 --- a/src/compiler/scala/reflect/internal/Types.scala +++ b/src/compiler/scala/reflect/internal/Types.scala @@ -97,7 +97,7 @@ trait Types extends api.Types { self: SymbolTable => */ private final val propagateParameterBoundsToTypeVars = sys.props contains "scalac.debug.prop-constraints" - protected val enableTypeVarExperimentals = settings.Xexperimental.value || !settings.XoldPatmat.value + protected val enableTypeVarExperimentals = settings.Xexperimental.value /** Empty immutable maps to avoid allocations. */ private val emptySymMap = immutable.Map[Symbol, Symbol]() @@ -2898,6 +2898,7 @@ trait Types extends api.Types { self: SymbolTable => // existential. // were we compared to skolems at a higher skolemizationLevel? // EXPERIMENTAL: value will not be considered unless enableTypeVarExperimentals is true + // see SI-5729 for why this is still experimental private var encounteredHigherLevel = false private def shouldRepackType = enableTypeVarExperimentals && encounteredHigherLevel diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 8c6c927640..d662a52682 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -354,9 +354,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb // where I need it, and then an override in Global with the setting. override protected val etaExpandKeepsStar = settings.etaExpandKeepsStar.value // Here comes another one... - override protected val enableTypeVarExperimentals = ( - settings.Xexperimental.value || !settings.XoldPatmat.value - ) + override protected val enableTypeVarExperimentals = settings.Xexperimental.value // True if -Xscript has been set, indicating a script run. def isScriptRun = opt.script.isDefined diff --git a/src/library/scala/concurrent/package.scala b/src/library/scala/concurrent/package.scala index 169826034b..e8921ef531 100644 --- a/src/library/scala/concurrent/package.scala +++ b/src/library/scala/concurrent/package.scala @@ -26,7 +26,7 @@ package concurrent { object Await { private[concurrent] implicit val canAwaitEvidence = new CanAwait {} - def ready[T <: Awaitable[_]](awaitable: T, atMost: Duration): T = { + def ready[T](awaitable: Awaitable[T], atMost: Duration): awaitable.type = { blocking(awaitable, atMost) awaitable } diff --git a/test/files/pos/t5729.scala b/test/files/pos/t5729.scala new file mode 100644 index 0000000000..9fd9c9ffbb --- /dev/null +++ b/test/files/pos/t5729.scala @@ -0,0 +1,6 @@ +trait T[X] +object Test { + def join(in: Seq[T[_]]): Int = ??? + def join[S](in: Seq[T[S]]): String = ??? + join(null: Seq[T[_]]) +} \ No newline at end of file -- cgit v1.2.3 From 89d069792717c206da21abecf3f825756182f465 Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Wed, 2 May 2012 15:32:27 +0200 Subject: un-cps expected type in translateMatch ... where it belongs, instead of in MatchTransformer --- .../tools/nsc/typechecker/PatternMatching.scala | 27 ++++++++++------------ 1 file changed, 12 insertions(+), 15 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index 702f279596..c3a7f2bbc5 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -40,7 +40,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // SymbolTable. If we had DOT this would not be an issue import global._ // the global environment import definitions._ // standard classes and methods - import CODE._ val phaseName: String = "patmat" @@ -60,19 +59,9 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL class MatchTransformer(unit: CompilationUnit) extends TypingTransformer(unit) { override def transform(tree: Tree): Tree = tree match { case Match(sel, cases) => - val selX = transform(sel) - val casesX = transformTrees(cases).asInstanceOf[List[CaseDef]] - val origTp = tree.tpe - val matchX = treeCopy.Match(tree, selX, casesX) - - // when one of the internal cps-type-state annotations is present, strip all CPS annotations - // a cps-type-state-annotated type makes no sense as an expected type (matchX.tpe is used as pt in translateMatch) - // (only test availability of MarkerCPSAdaptPlus assuming they are either all available or none of them are) - if (MarkerCPSAdaptPlus != NoSymbol && (stripTriggerCPSAnns exists tree.tpe.hasAnnotation)) - matchX modifyType removeCPSAdaptAnnotations - - localTyper.typed(translator.translateMatch(matchX)) setType origTp + // setType origTp intended for CPS -- TODO: is it necessary? + localTyper.typed(translator.translateMatch(treeCopy.Match(tree, transform(sel), transformTrees(cases).asInstanceOf[List[CaseDef]]))) setType origTp case Try(block, catches, finalizer) => treeCopy.Try(tree, transform(block), translator.translateTry(transformTrees(catches).asInstanceOf[List[CaseDef]], tree.tpe, tree.pos), transform(finalizer)) case _ => super.transform(tree) @@ -190,13 +179,21 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL } val selectorTp = repeatedToSeq(elimAnonymousClass(selector.tpe.widen.withoutAnnotations)) - val pt0 = match_.tpe + + val origPt = match_.tpe + // when one of the internal cps-type-state annotations is present, strip all CPS annotations + // a cps-type-state-annotated type makes no sense as an expected type (matchX.tpe is used as pt in translateMatch) + // (only test availability of MarkerCPSAdaptPlus assuming they are either all available or none of them are) + val ptUnCPS = + if (MarkerCPSAdaptPlus != NoSymbol && (stripTriggerCPSAnns exists origPt.hasAnnotation)) + removeCPSAdaptAnnotations(origPt) + else origPt // we've packed the type for each case in typedMatch so that if all cases have the same existential case, we get a clean lub // here, we should open up the existential again // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala // TODO: fix skolemizeExistential (it should preserve annotations, right?) - val pt = repeatedToSeq(pt0.skolemizeExistential(context.owner, context.tree) withAnnotations pt0.annotations) + val pt = repeatedToSeq(ptUnCPS.skolemizeExistential(context.owner, context.tree) withAnnotations ptUnCPS.annotations) // the alternative to attaching the default case override would be to simply // append the default to the list of cases and suppress the unreachable case error that may arise (once we detect that...) -- cgit v1.2.3 From 24b62e616ba2d18eee0a3bbffaf5c76abc6cc4b6 Mon Sep 17 00:00:00 2001 From: Lukas Rytz Date: Wed, 2 May 2012 16:33:59 +0200 Subject: fix SI-5682 --- src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala | 9 ++++----- test/files/jvm/annotations.scala | 4 +++- 2 files changed, 7 insertions(+), 6 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala index 4c71772929..7dc105690c 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -248,13 +248,12 @@ trait MethodSynthesis { else List(Getter(vd)) ) def beanAccessors(vd: ValDef): List[DerivedFromValDef] = { + val setter = if (vd.mods.isMutable) List(BeanSetter(vd)) else Nil if (forMSIL) Nil - else if (vd.symbol hasAnnotation BeanPropertyAttr) { - if (vd.mods.isMutable) List(BeanGetter(vd), BeanSetter(vd)) - else List(BeanGetter(vd)) - } + else if (vd.symbol hasAnnotation BeanPropertyAttr) + BeanGetter(vd) :: setter else if (vd.symbol hasAnnotation BooleanBeanPropertyAttr) - List(BooleanBeanGetter(vd)) + BooleanBeanGetter(vd) :: setter else Nil } def allValDefDerived(vd: ValDef) = { diff --git a/test/files/jvm/annotations.scala b/test/files/jvm/annotations.scala index b1c3c8ba40..66ebde592b 100644 --- a/test/files/jvm/annotations.scala +++ b/test/files/jvm/annotations.scala @@ -193,7 +193,9 @@ object Test6 { val c = new C("bob") c.setText("dylan") println(c.getText()) - if (new D(true).isProp()) { + val d = new D(true) + d.setProp(false) + if (!d.isProp()) { println(new D(false).getM()) } } -- cgit v1.2.3 From 5b9a37529b0cd103cd25c11600b8ed8320a424fe Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Wed, 2 May 2012 16:45:49 +0200 Subject: cleaned up partialfun synth in uncurry removed dead code due to new-style matches getting their partialfun treatment during typers --- .../scala/tools/nsc/transform/UnCurry.scala | 288 ++++++++------------- 1 file changed, 102 insertions(+), 186 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 35e26b39b5..ef70271371 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -237,22 +237,21 @@ abstract class UnCurry extends InfoTransform deEta(fun) match { // nullary or parameterless case fun1 if fun1 ne fun => fun1 + case _ if fun.tpe.typeSymbol == PartialFunctionClass => + // only get here when running under -Xoldpatmat + synthPartialFunction(fun) case _ => - def owner = fun.symbol.owner - def targs = fun.tpe.typeArgs - def isPartial = fun.tpe.typeSymbol == PartialFunctionClass - - def parents = + val parents = if (isFunctionType(fun.tpe)) List(abstractFunctionForFunctionType(fun.tpe), SerializableClass.tpe) - else if (isPartial) List(appliedType(AbstractPartialFunctionClass, targs: _*), SerializableClass.tpe) else List(ObjectClass.tpe, fun.tpe, SerializableClass.tpe) - val anonClass = owner newAnonymousFunctionClass(fun.pos, inConstructorFlag) addAnnotation serialVersionUIDAnnotation + val anonClass = fun.symbol.owner newAnonymousFunctionClass(fun.pos, inConstructorFlag) addAnnotation serialVersionUIDAnnotation anonClass setInfo ClassInfoType(parents, newScope, anonClass) + val targs = fun.tpe.typeArgs val (formals, restpe) = (targs.init, targs.last) - def applyMethodDef = { + val applyMethodDef = { val methSym = anonClass.newMethod(nme.apply, fun.pos, FINAL) methSym setInfoAndEnter MethodType(methSym newSyntheticValueParams formals, restpe) @@ -268,198 +267,115 @@ abstract class UnCurry extends InfoTransform methDef } - // def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1 = - def applyOrElseMethodDef = { - val methSym = anonClass.newMethod(fun.pos, nme.applyOrElse) setFlag (FINAL | OVERRIDE) - - val List(argtpe) = formals - val A1 = methSym newTypeParameter(newTypeName("A1")) setInfo TypeBounds.upper(argtpe) - val B1 = methSym newTypeParameter(newTypeName("B1")) setInfo TypeBounds.lower(restpe) - val methFormals = List(A1.tpe, functionType(List(A1.tpe), B1.tpe)) - val params@List(x, default) = methSym newSyntheticValueParams methFormals - methSym setInfoAndEnter polyType(List(A1, B1), MethodType(params, B1.tpe)) - - val substParam = new TreeSymSubstituter(fun.vparams map (_.symbol), List(x)) - val body = localTyper.typedPos(fun.pos) { import CODE._ - def defaultAction(scrut: Tree) = REF(default) APPLY (REF(x)) - - object withDefaultTransformer extends gen.MatchMatcher { - override def caseMatch(orig: Tree, selector: Tree, cases: List[CaseDef], wrap: Tree => Tree): Tree = { - val casesNoSynthCatchAll = dropSyntheticCatchAll(cases) - if (casesNoSynthCatchAll exists treeInfo.isDefaultCase) orig - else { - val defaultCase = CaseDef(Ident(nme.WILDCARD), EmptyTree, defaultAction(selector.duplicate)) - wrap(Match(/*gen.mkUnchecked*/(selector), casesNoSynthCatchAll :+ defaultCase)) - } - } - override def caseVirtualizedMatch(orig: Tree, _match: Tree, targs: List[Tree], scrut: Tree, matcher: Tree): Tree = { import CODE._ - ((matcher APPLY (scrut)) DOT nme.getOrElse) APPLY (defaultAction(scrut.duplicate)) // TODO: pass targs - } - override def caseVirtualizedMatchOpt(orig: Tree, prologue: List[Tree], cases: List[Tree], matchEndDef: Tree, wrap: Tree => Tree): Tree = { import CODE._ - val scrutRef = REF(prologue.head.symbol) // scrut valdef is always emitted (except for nested matchers that handle alternatives) - - val casesNewSynthCatchAll = cases.init :+ (deriveLabelDef(cases.last){ - case Apply(matchEnd, List(Throw(Apply(Select(New(exTpt), nme.CONSTRUCTOR), _)))) if exTpt.tpe.typeSymbol eq MatchErrorClass => - assert(matchEnd.symbol == matchEndDef.symbol, "matchEnd discrepancy "+(matchEnd, matchEndDef)) - matchEnd APPLY (defaultAction(scrutRef)) - case x => x - } setSymbol cases.last.symbol setType null) - - val LabelDef(_, List(matchRes), rhs) = matchEndDef - val matchEnd = matchEndDef.symbol - matchRes setType B1.tpe - rhs setType B1.tpe - matchEndDef setType B1.tpe - matchRes.symbol setInfo B1.tpe - matchEnd setInfo MethodType(List(matchRes.symbol), B1.tpe) - cases foreach (c => c.symbol setInfo MethodType(List(), B1.tpe)) - - wrap(Block(prologue ++ casesNewSynthCatchAll, matchEndDef)) - } - } + localTyper.typedPos(fun.pos) { + Block( + List(ClassDef(anonClass, NoMods, List(List()), List(List()), List(applyMethodDef), fun.pos)), + Typed(New(anonClass.tpe), TypeTree(fun.tpe))) + } - withDefaultTransformer(substParam(fun.body)) - } - body.changeOwner(fun.symbol -> methSym) + } - val methDef = DefDef(methSym, body) + def synthPartialFunction(fun: Function) = { + if (!settings.XoldPatmat.value) debugwarn("Under the new pattern matching scheme, PartialFunction should have been synthesized during typers.") + + val targs = fun.tpe.typeArgs + val (formals, restpe) = (targs.init, targs.last) + + val anonClass = fun.symbol.owner newAnonymousFunctionClass(fun.pos, inConstructorFlag) addAnnotation serialVersionUIDAnnotation + val parents = List(appliedType(AbstractPartialFunctionClass, targs: _*), SerializableClass.tpe) + anonClass setInfo ClassInfoType(parents, newScope, anonClass) + + // duplicate before applyOrElseMethodDef is run so that it does not mess up our trees and label symbols (we have a fresh set) + // otherwise `TreeSymSubstituter(fun.vparams map (_.symbol), params)` won't work as the subst has been run already + val bodyForIDA = { + val duped = fun.body.duplicate + val oldParams = new mutable.ListBuffer[Symbol]() + val newParams = new mutable.ListBuffer[Symbol]() + + val oldSyms0 = + duped filter { + case l@LabelDef(_, params, _) => + params foreach {p => + val oldSym = p.symbol + p.symbol = oldSym.cloneSymbol + oldParams += oldSym + newParams += p.symbol + } + true + case _ => false + } map (_.symbol) + val oldSyms = oldParams.toList ++ oldSyms0 + val newSyms = newParams.toList ++ (oldSyms0 map (_.cloneSymbol)) + // println("duping "+ oldSyms +" --> "+ (newSyms map (_.ownerChain))) - // Have to repack the type to avoid mismatches when existentials - // appear in the result - see SI-4869. - methDef.tpt setType localTyper.packedType(body, methSym) - methDef - } + val substLabels = new TreeSymSubstituter(oldSyms, newSyms) - // duplicate before applyOrElseMethodDef is run so that it does not mess up our trees and label symbols (we have a fresh set) - // otherwise `TreeSymSubstituter(fun.vparams map (_.symbol), params)` won't work as the subst has been run already - val bodyForIDA = { - val duped = fun.body.duplicate - val oldParams = new mutable.ListBuffer[Symbol]() - val newParams = new mutable.ListBuffer[Symbol]() - - val oldSyms0 = - duped filter { - case l@LabelDef(_, params, _) => - params foreach {p => - val oldSym = p.symbol - p.symbol = oldSym.cloneSymbol - oldParams += oldSym - newParams += p.symbol - } - true - case _ => false - } map (_.symbol) - val oldSyms = oldParams.toList ++ oldSyms0 - val newSyms = newParams.toList ++ (oldSyms0 map (_.cloneSymbol)) - // println("duping "+ oldSyms +" --> "+ (newSyms map (_.ownerChain))) + substLabels(duped) + } - val substLabels = new TreeSymSubstituter(oldSyms, newSyms) + // def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1 = + val applyOrElseMethodDef = { + val methSym = anonClass.newMethod(fun.pos, nme.applyOrElse) setFlag (FINAL | OVERRIDE) + + val List(argtpe) = formals + val A1 = methSym newTypeParameter(newTypeName("A1")) setInfo TypeBounds.upper(argtpe) + val B1 = methSym newTypeParameter(newTypeName("B1")) setInfo TypeBounds.lower(restpe) + val methFormals = List(A1.tpe, functionType(List(A1.tpe), B1.tpe)) + val params@List(x, default) = methSym newSyntheticValueParams methFormals + methSym setInfoAndEnter polyType(List(A1, B1), MethodType(params, B1.tpe)) + + val substParam = new TreeSymSubstituter(fun.vparams map (_.symbol), List(x)) + val body = localTyper.typedPos(fun.pos) { import CODE._ + def defaultAction(scrut: Tree) = REF(default) APPLY (REF(x)) + + substParam(fun.body) match { + case orig@Match(selector, cases) => + if (cases exists treeInfo.isDefaultCase) orig + else { + val defaultCase = CaseDef(Ident(nme.WILDCARD), EmptyTree, defaultAction(selector.duplicate)) + Match(/*gen.mkUnchecked*/(selector), cases :+ defaultCase) + } - substLabels(duped) } + } + body.changeOwner(fun.symbol -> methSym) - def isDefinedAtMethodDef = { - val methSym = anonClass.newMethod(nme.isDefinedAt, fun.pos, FINAL) - val params = methSym newSyntheticValueParams formals - methSym setInfoAndEnter MethodType(params, BooleanClass.tpe) - - val substParam = new TreeSymSubstituter(fun.vparams map (_.symbol), params) - def doSubst(x: Tree) = substParam(resetLocalAttrsKeepLabels(x)) // see pos/t1761 for why `resetLocalAttrs`, but must keep label symbols around - - object isDefinedAtTransformer extends gen.MatchMatcher { - // TODO: optimize duplication, but make sure ValDef's introduced by wrap are treated correctly - override def caseMatch(orig: Tree, selector: Tree, cases: List[CaseDef], wrap: Tree => Tree): Tree = { import CODE._ - val casesNoSynthCatchAll = dropSyntheticCatchAll(cases) - if (casesNoSynthCatchAll exists treeInfo.isDefaultCase) TRUE_typed - else - doSubst(wrap( - Match(/*gen.mkUnchecked*/(selector), - (casesNoSynthCatchAll map (c => deriveCaseDef(c)(x => TRUE_typed))) :+ ( - DEFAULT ==> FALSE_typed) - ))) - } - override def caseVirtualizedMatch(orig: Tree, _match: Tree, targs: List[Tree], scrut: Tree, matcher: Tree): Tree = { - object noOne extends Transformer { - override val treeCopy = newStrictTreeCopier // must duplicate everything - val one = _match.tpe member newTermName("one") - override def transform(tree: Tree): Tree = tree match { - case Apply(fun, List(a)) if fun.symbol == one => - // blow one's argument away since all we want to know is whether the match succeeds or not - // (the alternative, making `one` CBN, would entail moving away from Option) - Apply(fun.duplicate, List(gen.mkZeroContravariantAfterTyper(a.tpe))) - case _ => - super.transform(tree) - } - } - doSubst(Apply(Apply(TypeApply(Select(_match.duplicate, _match.tpe.member(newTermName("isSuccess"))), targs map (_.duplicate)), List(scrut.duplicate)), List(noOne.transform(matcher)))) - } + val methDef = DefDef(methSym, body) - override def caseVirtualizedMatchOpt(orig: Tree, prologue: List[Tree], cases: List[Tree], matchEndDef: Tree, wrap: Tree => Tree) = { - val matchEnd = matchEndDef.symbol - val LabelDef(_, List(matchRes), rhs) = matchEndDef - matchRes setType BooleanClass.tpe - rhs setType BooleanClass.tpe - matchEndDef setType BooleanClass.tpe - matchRes.symbol setInfo BooleanClass.tpe - matchEnd setInfo MethodType(List(matchRes.symbol), BooleanClass.tpe) - cases foreach (c => c.symbol setInfo MethodType(List(), BooleanClass.tpe)) - // println("matchEnd: "+ matchEnd) - - // when the type of the selector contains a skolem owned by the applyOrElseMethod, should reskolemize everything, - // for now, just cast the RHS (since we're just trying to keep the typer happy, the cast is meaningless) - // ARGH -- this is why I would prefer the typedMatchAnonFun approach (but alas, CPS blocks that) - val newPrologue = prologue match { - case List(vd@ValDef(mods, name, tpt, rhs)) => List(treeCopy.ValDef(vd, mods, name, tpt, gen.mkAsInstanceOf(rhs, tpt.tpe, true, false))) - case _ => prologue - } - object casesReturnTrue extends Transformer { - // override val treeCopy = newStrictTreeCopier // will duplicate below - override def transform(tree: Tree): Tree = tree match { - // don't compute the result of the match, return true instead - case Apply(fun, List(res)) if fun.symbol eq matchEnd => - // println("matchend call "+ fun.symbol) - Apply(fun, List(TRUE_typed)) setType BooleanClass.tpe - case _ => super.transform(tree) - } - } - val newCatchAll = cases.last match { - case LabelDef(n, ps, Apply(matchEnd1, List(Throw(Apply(Select(New(exTpt), nme.CONSTRUCTOR), _))))) if exTpt.tpe.typeSymbol eq MatchErrorClass => - assert(matchEnd1.symbol == matchEnd, "matchEnd discrepancy "+(matchEnd, matchEndDef)) - List(treeCopy.LabelDef(cases.last, n, ps, matchEnd APPLY (FALSE_typed)) setSymbol cases.last.symbol) - case x => Nil - } - val casesWithoutCatchAll = if(newCatchAll.isEmpty) cases else cases.init - doSubst(wrap(Block(newPrologue ++ casesReturnTrue.transformTrees(casesWithoutCatchAll) ++ newCatchAll, matchEndDef))) - - // val duped = idaBlock //.duplicate // TODO: duplication of labeldefs is BROKEN - // duped foreach { - // case l@LabelDef(name, params, rhs) if gen.hasSynthCaseSymbol(l) => println("newInfo"+ l.symbol.info) - // case _ => - // } - } - } + // Have to repack the type to avoid mismatches when existentials + // appear in the result - see SI-4869. + methDef.tpt setType localTyper.packedType(body, methSym) + methDef + } - val body = isDefinedAtTransformer(bodyForIDA) - body.changeOwner(fun.symbol -> methSym) + val isDefinedAtMethodDef = { + val methSym = anonClass.newMethod(nme.isDefinedAt, fun.pos, FINAL) + val params = methSym newSyntheticValueParams formals + methSym setInfoAndEnter MethodType(params, BooleanClass.tpe) - DefDef(methSym, body) - } + val substParam = new TreeSymSubstituter(fun.vparams map (_.symbol), params) + def doSubst(x: Tree) = substParam(resetLocalAttrsKeepLabels(x)) // see pos/t1761 for why `resetLocalAttrs`, but must keep label symbols around - val members = - if (isPartial) { - assert(!opt.virtPatmat, "PartialFunction should have been synthesized during typer "+ fun); - List(applyOrElseMethodDef, isDefinedAtMethodDef) - } else List(applyMethodDef) + val body = bodyForIDA match { + case Match(selector, cases) => + if (cases exists treeInfo.isDefaultCase) TRUE_typed + else + doSubst(Match(/*gen.mkUnchecked*/(selector), + (cases map (c => deriveCaseDef(c)(x => TRUE_typed))) :+ ( + DEFAULT ==> FALSE_typed))) - // println("MEMBERS "+ members) - val res = localTyper.typedPos(fun.pos) { - Block( - List(ClassDef(anonClass, NoMods, List(List()), List(List()), members, fun.pos)), - Typed(New(anonClass.tpe), TypeTree(fun.tpe))) - } - // println("MEMBERS TYPED "+ members) - res } + body.changeOwner(fun.symbol -> methSym) + + DefDef(methSym, body) + } + + localTyper.typedPos(fun.pos) { + Block( + List(ClassDef(anonClass, NoMods, List(List()), List(List()), List(applyOrElseMethodDef, isDefinedAtMethodDef), fun.pos)), + Typed(New(anonClass.tpe), TypeTree(fun.tpe))) + } + } def transformArgs(pos: Position, fun: Symbol, args: List[Tree], formals: List[Type]) = { val isJava = fun.isJavaDefined -- cgit v1.2.3 From b446a06be481fb0217631993e492d252542ca311 Mon Sep 17 00:00:00 2001 From: Kato Kazuyoshi Date: Thu, 3 May 2012 00:16:42 +0900 Subject: Add a link to "z" in Scaladoc We have index/index-z.html but there is no link in HTML. --- src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js index e9ed7181e4..b767722b8c 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js @@ -454,7 +454,7 @@ function resizeFilterBlock() { function printAlphabet() { var html = '#'; var c; - for (c = 'a'; c < 'z'; c = String.fromCharCode(c.charCodeAt(0) + 1)) { + for (c = 'a'; c <= 'z'; c = String.fromCharCode(c.charCodeAt(0) + 1)) { html += [ '{ templatesToHtml(tpl.inTemplate.toRoot.reverse.tail, xml.Text(".")) }

} - +
{ tpl.companion match { -- cgit v1.2.3 From 65b9fec4b1981c3e10c27cd41fd8cac054e7b05c Mon Sep 17 00:00:00 2001 From: Simon Ochsenreither Date: Wed, 2 May 2012 02:58:54 +0200 Subject: Fixes SI-4478. - Replaced/simplified usages of "wrt". - Added backticks to $Coll definitions, so stuff like "immutable.Stack" hopefully stops being interpreted as the end of a sentence and shown like that in the summary line of ScalaDoc's method description. See collection.immutable.Stack's sortBy. Additionally, it looks nicer this way. - Fixes the typo mentioned in SI-5666. --- src/compiler/scala/tools/nsc/backend/icode/GenICode.scala | 2 +- src/library/rootdoc.txt | 4 ++-- src/library/scala/Array.scala | 2 +- src/library/scala/Option.scala | 2 +- src/library/scala/collection/BitSet.scala | 2 +- src/library/scala/collection/BitSetLike.scala | 2 +- src/library/scala/collection/GenIterableLike.scala | 2 +- src/library/scala/collection/GenMapLike.scala | 2 +- src/library/scala/collection/GenTraversableLike.scala | 2 +- src/library/scala/collection/GenTraversableOnce.scala | 2 +- src/library/scala/collection/IndexedSeq.scala | 2 +- src/library/scala/collection/IndexedSeqLike.scala | 2 +- src/library/scala/collection/Iterable.scala | 2 +- src/library/scala/collection/LinearSeq.scala | 2 +- src/library/scala/collection/Map.scala | 2 +- src/library/scala/collection/Seq.scala | 2 +- src/library/scala/collection/SeqLike.scala | 14 +++++++------- src/library/scala/collection/Set.scala | 2 +- src/library/scala/collection/concurrent/Map.scala | 2 +- .../collection/generic/ArrayTagTraversableFactory.scala | 2 +- src/library/scala/collection/generic/BitSetFactory.scala | 2 +- src/library/scala/collection/generic/GenMapFactory.scala | 2 +- src/library/scala/collection/generic/GenSetFactory.scala | 2 +- .../scala/collection/generic/GenTraversableFactory.scala | 2 +- .../scala/collection/generic/GenericCompanion.scala | 2 +- .../scala/collection/generic/GenericParCompanion.scala | 2 +- src/library/scala/collection/generic/Growable.scala | 2 +- .../collection/generic/ImmutableSortedMapFactory.scala | 2 +- .../collection/generic/ImmutableSortedSetFactory.scala | 4 ++-- .../scala/collection/generic/MutableSortedSetFactory.scala | 4 ++-- src/library/scala/collection/generic/ParFactory.scala | 2 +- src/library/scala/collection/generic/ParMapFactory.scala | 2 +- src/library/scala/collection/generic/Shrinkable.scala | 2 +- src/library/scala/collection/immutable/BitSet.scala | 4 ++-- .../scala/collection/immutable/GenSeq.scala.disabled | 2 +- .../scala/collection/immutable/GenSet.scala.disabled | 2 +- src/library/scala/collection/immutable/HashMap.scala | 4 ++-- src/library/scala/collection/immutable/HashSet.scala | 6 +++--- src/library/scala/collection/immutable/IndexedSeq.scala | 2 +- src/library/scala/collection/immutable/IntMap.scala | 4 ++-- src/library/scala/collection/immutable/Iterable.scala | 4 ++-- src/library/scala/collection/immutable/LinearSeq.scala | 2 +- src/library/scala/collection/immutable/List.scala | 4 ++-- src/library/scala/collection/immutable/LongMap.scala | 4 ++-- src/library/scala/collection/immutable/Map.scala | 2 +- src/library/scala/collection/immutable/NumericRange.scala | 2 +- src/library/scala/collection/immutable/PagedSeq.scala | 2 +- src/library/scala/collection/immutable/Queue.scala | 4 ++-- src/library/scala/collection/immutable/Seq.scala | 4 ++-- src/library/scala/collection/immutable/Set.scala | 4 ++-- src/library/scala/collection/immutable/SortedSet.scala | 4 ++-- src/library/scala/collection/immutable/Stack.scala | 4 ++-- src/library/scala/collection/immutable/Stream.scala | 8 ++++---- src/library/scala/collection/immutable/StringLike.scala | 2 +- src/library/scala/collection/immutable/StringOps.scala | 2 +- src/library/scala/collection/immutable/Traversable.scala | 2 +- src/library/scala/collection/immutable/TreeSet.scala | 4 ++-- src/library/scala/collection/immutable/Vector.scala | 2 +- src/library/scala/collection/immutable/WrappedString.scala | 2 +- src/library/scala/collection/mutable/ArrayBuffer.scala | 4 ++-- src/library/scala/collection/mutable/ArrayLike.scala | 2 +- src/library/scala/collection/mutable/ArrayOps.scala | 2 +- src/library/scala/collection/mutable/ArraySeq.scala | 4 ++-- src/library/scala/collection/mutable/ArrayStack.scala | 4 ++-- src/library/scala/collection/mutable/BitSet.scala | 4 ++-- src/library/scala/collection/mutable/Buffer.scala | 4 ++-- src/library/scala/collection/mutable/BufferProxy.scala | 2 +- src/library/scala/collection/mutable/ConcurrentMap.scala | 2 +- .../scala/collection/mutable/DoubleLinkedList.scala | 4 ++-- .../scala/collection/mutable/DoubleLinkedListLike.scala | 2 +- src/library/scala/collection/mutable/GenSeq.scala.disabled | 2 +- src/library/scala/collection/mutable/GenSet.scala.disabled | 2 +- src/library/scala/collection/mutable/GrowingBuilder.scala | 2 +- src/library/scala/collection/mutable/HashMap.scala | 4 ++-- src/library/scala/collection/mutable/HashSet.scala | 4 ++-- src/library/scala/collection/mutable/IndexedSeq.scala | 2 +- src/library/scala/collection/mutable/IndexedSeqLike.scala | 2 +- src/library/scala/collection/mutable/Iterable.scala | 2 +- src/library/scala/collection/mutable/LinearSeq.scala | 4 ++-- src/library/scala/collection/mutable/LinkedHashMap.scala | 4 ++-- src/library/scala/collection/mutable/LinkedHashSet.scala | 4 ++-- src/library/scala/collection/mutable/LinkedList.scala | 4 ++-- src/library/scala/collection/mutable/LinkedListLike.scala | 2 +- src/library/scala/collection/mutable/ListBuffer.scala | 4 ++-- src/library/scala/collection/mutable/ListMap.scala | 4 ++-- src/library/scala/collection/mutable/Map.scala | 2 +- src/library/scala/collection/mutable/MultiMap.scala | 2 +- src/library/scala/collection/mutable/OpenHashMap.scala | 4 ++-- src/library/scala/collection/mutable/Queue.scala | 2 +- src/library/scala/collection/mutable/Seq.scala | 4 ++-- src/library/scala/collection/mutable/Set.scala | 4 ++-- src/library/scala/collection/mutable/SortedSet.scala | 4 ++-- src/library/scala/collection/mutable/Stack.scala | 4 ++-- .../scala/collection/mutable/SynchronizedBuffer.scala | 2 +- src/library/scala/collection/mutable/SynchronizedMap.scala | 2 +- .../collection/mutable/SynchronizedPriorityQueue.scala | 2 +- .../scala/collection/mutable/SynchronizedQueue.scala | 2 +- src/library/scala/collection/mutable/SynchronizedSet.scala | 2 +- .../scala/collection/mutable/SynchronizedStack.scala | 2 +- src/library/scala/collection/mutable/Traversable.scala | 2 +- src/library/scala/collection/mutable/TreeSet.scala | 2 +- src/library/scala/collection/mutable/UnrolledBuffer.scala | 2 +- src/library/scala/collection/mutable/WeakHashMap.scala | 4 ++-- src/library/scala/collection/mutable/WrappedArray.scala | 2 +- src/library/scala/collection/parallel/ParIterable.scala | 2 +- .../scala/collection/parallel/immutable/ParHashMap.scala | 4 ++-- .../scala/collection/parallel/immutable/ParHashSet.scala | 4 ++-- .../parallel/immutable/ParNumericRange.scala.disabled | 2 +- .../scala/collection/parallel/immutable/ParRange.scala | 2 +- .../scala/collection/parallel/immutable/ParSeq.scala | 4 ++-- .../scala/collection/parallel/immutable/ParSet.scala | 4 ++-- .../scala/collection/parallel/immutable/ParVector.scala | 4 ++-- .../scala/collection/parallel/mutable/ParArray.scala | 4 ++-- .../collection/parallel/mutable/ParFlatHashTable.scala | 2 +- .../scala/collection/parallel/mutable/ParHashMap.scala | 4 ++-- .../scala/collection/parallel/mutable/ParHashSet.scala | 4 ++-- src/library/scala/collection/parallel/mutable/ParSeq.scala | 4 ++-- src/library/scala/collection/parallel/mutable/ParSet.scala | 4 ++-- src/library/scala/reflect/api/Types.scala | 14 ++++++++------ 119 files changed, 182 insertions(+), 180 deletions(-) (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala index 5e5b09405c..4aeb537f9b 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala @@ -821,7 +821,7 @@ abstract class GenICode extends SubComponent { ctx2 case _ => - abort("Cannot instantiate " + tpt + "of kind: " + generatedType) + abort("Cannot instantiate " + tpt + " of kind: " + generatedType) } case Apply(fun @ _, List(expr)) if (definitions.isBox(fun.symbol)) => diff --git a/src/library/rootdoc.txt b/src/library/rootdoc.txt index 6145429f1e..da27a0084b 100644 --- a/src/library/rootdoc.txt +++ b/src/library/rootdoc.txt @@ -22,6 +22,6 @@ Many other packages exist. See the complete list on the left. Identifiers in the scala package and the [[scala.Predef]] object are always in scope by default. -Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, List is an alias for scala.collection.immutable.[[scala.collection.immutable.List]]. +Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, `List` is an alias for scala.collection.immutable.[[scala.collection.immutable.List]]. -Other aliases refer to classes providing by the underlying platform. For example, on the JVM, String is an alias for java.lang.String. +Other aliases refer to classes provided by the underlying platform. For example, on the JVM, `String` is an alias for `java.lang.String`. diff --git a/src/library/scala/Array.scala b/src/library/scala/Array.scala index fd61cfd0a1..36e95b303d 100644 --- a/src/library/scala/Array.scala +++ b/src/library/scala/Array.scala @@ -468,7 +468,7 @@ object Array extends FallbackArrayBuilding { * @see [[http://www.scala-lang.org/docu/files/collections-api/collections_38.html#anchor "The Scala 2.8 Collections' API"]] * section on `Array` by Martin Odersky for more information. * @define coll array - * @define Coll Array + * @define Coll `Array` * @define orderDependent * @define orderDependentFold * @define mayNotTerminateInf diff --git a/src/library/scala/Option.scala b/src/library/scala/Option.scala index a58297d7d4..44c8fba45f 100644 --- a/src/library/scala/Option.scala +++ b/src/library/scala/Option.scala @@ -83,7 +83,7 @@ object Option { * @define p `p` * @define f `f` * @define coll option - * @define Coll Option + * @define Coll `Option` * @define orderDependent * @define orderDependentFold * @define mayNotTerminateInf diff --git a/src/library/scala/collection/BitSet.scala b/src/library/scala/collection/BitSet.scala index 59b53faf7e..90e837b219 100644 --- a/src/library/scala/collection/BitSet.scala +++ b/src/library/scala/collection/BitSet.scala @@ -22,7 +22,7 @@ trait BitSet extends SortedSet[Int] /** $factoryInfo * @define coll bitset - * @define Coll BitSet + * @define Coll `BitSet` */ object BitSet extends BitSetFactory[BitSet] { val empty: BitSet = immutable.BitSet.empty diff --git a/src/library/scala/collection/BitSetLike.scala b/src/library/scala/collection/BitSetLike.scala index e4f9fd436a..c0aaa9f28e 100644 --- a/src/library/scala/collection/BitSetLike.scala +++ b/src/library/scala/collection/BitSetLike.scala @@ -30,7 +30,7 @@ import mutable.StringBuilder * @version 2.8 * @since 2.8 * @define coll bitset - * @define Coll BitSet + * @define Coll `BitSet` */ trait BitSetLike[+This <: BitSetLike[This] with SortedSet[Int]] extends SortedSetLike[Int, This] { self => diff --git a/src/library/scala/collection/GenIterableLike.scala b/src/library/scala/collection/GenIterableLike.scala index 8fa5981969..79113ddaa7 100644 --- a/src/library/scala/collection/GenIterableLike.scala +++ b/src/library/scala/collection/GenIterableLike.scala @@ -16,7 +16,7 @@ import generic.{ CanBuildFrom => CBF, _ } * This trait contains abstract methods and methods that can be implemented * directly in terms of other methods. * - * @define Coll GenIterable + * @define Coll `GenIterable` * @define coll general iterable collection * * @author Martin Odersky diff --git a/src/library/scala/collection/GenMapLike.scala b/src/library/scala/collection/GenMapLike.scala index 114169c849..d611eaea43 100644 --- a/src/library/scala/collection/GenMapLike.scala +++ b/src/library/scala/collection/GenMapLike.scala @@ -11,7 +11,7 @@ package scala.collection /** A trait for all maps upon which operations may be * implemented in parallel. * - * @define Coll GenMap + * @define Coll `GenMap` * @define coll general map * @author Martin Odersky * @author Aleksandar Prokopec diff --git a/src/library/scala/collection/GenTraversableLike.scala b/src/library/scala/collection/GenTraversableLike.scala index 4500a849b1..903594b69d 100644 --- a/src/library/scala/collection/GenTraversableLike.scala +++ b/src/library/scala/collection/GenTraversableLike.scala @@ -43,7 +43,7 @@ import annotation.migration * @define traversableInfo * This is a base trait of all kinds of Scala collections. * - * @define Coll GenTraversable + * @define Coll `GenTraversable` * @define coll general collection * @define collectExample * @tparam A the collection element type. diff --git a/src/library/scala/collection/GenTraversableOnce.scala b/src/library/scala/collection/GenTraversableOnce.scala index fd8595ccb8..f4e3848d98 100644 --- a/src/library/scala/collection/GenTraversableOnce.scala +++ b/src/library/scala/collection/GenTraversableOnce.scala @@ -14,7 +14,7 @@ package scala.collection * Methods in this trait are either abstract or can be implemented in terms * of other methods. * - * @define Coll GenTraversableOnce + * @define Coll `GenTraversableOnce` * @define coll collection or iterator * @define possiblyparinfo * This trait may possibly have operations implemented in parallel. diff --git a/src/library/scala/collection/IndexedSeq.scala b/src/library/scala/collection/IndexedSeq.scala index 4a3586a375..56dd0bffff 100644 --- a/src/library/scala/collection/IndexedSeq.scala +++ b/src/library/scala/collection/IndexedSeq.scala @@ -26,7 +26,7 @@ trait IndexedSeq[+A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is a `Vector`. * @define coll indexed sequence - * @define Coll IndexedSeq + * @define Coll `IndexedSeq` */ object IndexedSeq extends SeqFactory[IndexedSeq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/IndexedSeqLike.scala b/src/library/scala/collection/IndexedSeqLike.scala index d1f7d1cb36..11f481e425 100644 --- a/src/library/scala/collection/IndexedSeqLike.scala +++ b/src/library/scala/collection/IndexedSeqLike.scala @@ -26,7 +26,7 @@ import scala.annotation.tailrec * access and length computation. They are defined in terms of abstract methods * `apply` for indexing and `length`. * - * Indexed sequences do not add any new methods wrt `Seq`, but promise + * Indexed sequences do not add any new methods to `Seq`, but promise * efficient implementations of random access patterns. * * @tparam A the element type of the $coll diff --git a/src/library/scala/collection/Iterable.scala b/src/library/scala/collection/Iterable.scala index b1752a5c67..f543c6f80f 100644 --- a/src/library/scala/collection/Iterable.scala +++ b/src/library/scala/collection/Iterable.scala @@ -40,7 +40,7 @@ trait Iterable[+A] extends Traversable[A] /** $factoryInfo * The current default implementation of a $Coll is a `Vector`. * @define coll iterable collection - * @define Coll Iterable + * @define Coll `Iterable` */ object Iterable extends TraversableFactory[Iterable] { diff --git a/src/library/scala/collection/LinearSeq.scala b/src/library/scala/collection/LinearSeq.scala index be143cf96b..21ed91f7f3 100644 --- a/src/library/scala/collection/LinearSeq.scala +++ b/src/library/scala/collection/LinearSeq.scala @@ -26,7 +26,7 @@ trait LinearSeq[+A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is a `Vector`. * @define coll linear sequence - * @define Coll LinearSeq + * @define Coll `LinearSeq` */ object LinearSeq extends SeqFactory[LinearSeq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/Map.scala b/src/library/scala/collection/Map.scala index 0c07d5bb74..a124e60c96 100644 --- a/src/library/scala/collection/Map.scala +++ b/src/library/scala/collection/Map.scala @@ -33,7 +33,7 @@ trait Map[A, +B] extends Iterable[(A, B)] with GenMap[A, B] with MapLike[A, B, M } /** $factoryInfo - * @define Coll Map + * @define Coll `Map` * @define coll map */ object Map extends MapFactory[Map] { diff --git a/src/library/scala/collection/Seq.scala b/src/library/scala/collection/Seq.scala index fd03a49af4..34705ee058 100644 --- a/src/library/scala/collection/Seq.scala +++ b/src/library/scala/collection/Seq.scala @@ -27,7 +27,7 @@ trait Seq[+A] extends PartialFunction[Int, A] /** $factoryInfo * The current default implementation of a $Coll is a `List`. * @define coll sequence - * @define Coll Seq + * @define Coll `Seq` */ object Seq extends SeqFactory[Seq] { /** $genericCanBuildFromInfo */ diff --git a/src/library/scala/collection/SeqLike.scala b/src/library/scala/collection/SeqLike.scala index a9535adc23..044bd624ae 100644 --- a/src/library/scala/collection/SeqLike.scala +++ b/src/library/scala/collection/SeqLike.scala @@ -45,7 +45,7 @@ import scala.math.Ordering * @version 1.0, 16/07/2003 * @since 2.8 * - * @define Coll Seq + * @define Coll `Seq` * @define coll sequence * @define thatinfo the class of the returned collection. Where possible, `That` is * the same class as the current collection class `Repr`, but this @@ -380,8 +380,8 @@ trait SeqLike[+A, +Repr] extends Any with IterableLike[A, Repr] with GenSeqLike[ * $mayNotTerminateInf * * @param elem the element to test. - * @return `true` if this $coll has an element that is - * is equal (wrt `==`) to `elem`, `false` otherwise. + * @return `true` if this $coll has an element that is equal (as + * determined by `==`) to `elem`, `false` otherwise. */ def contains(elem: Any): Boolean = exists (_ == elem) @@ -553,8 +553,8 @@ trait SeqLike[+A, +Repr] extends Any with IterableLike[A, Repr] with GenSeqLike[ /** Sorts this $coll according to a comparison function. * $willNotTerminateInf * - * The sort is stable. That is, elements that are equal wrt `lt` appear in the - * same order in the sorted sequence as in the original. + * The sort is stable. That is, elements that are equal (as determined by + * `lt`) appear in the same order in the sorted sequence as in the original. * * @param lt the comparison function which tests whether * its first argument precedes its second argument in @@ -592,8 +592,8 @@ trait SeqLike[+A, +Repr] extends Any with IterableLike[A, Repr] with GenSeqLike[ /** Sorts this $coll according to an Ordering. * - * The sort is stable. That is, elements that are equal wrt `lt` appear in the - * same order in the sorted sequence as in the original. + * The sort is stable. That is, elements that are equal (as determined by + * `lt`) appear in the same order in the sorted sequence as in the original. * * @see scala.math.Ordering * diff --git a/src/library/scala/collection/Set.scala b/src/library/scala/collection/Set.scala index 4c67aad603..7424c9cb9a 100644 --- a/src/library/scala/collection/Set.scala +++ b/src/library/scala/collection/Set.scala @@ -35,7 +35,7 @@ trait Set[A] extends (A => Boolean) * The current default implementation of a $Coll is one of `EmptySet`, `Set1`, `Set2`, `Set3`, `Set4` in * class `immutable.Set` for sets of sizes up to 4, and a `immutable.HashSet` for sets of larger sizes. * @define coll set - * @define Coll Set + * @define Coll `Set` */ object Set extends SetFactory[Set] { def newBuilder[A] = immutable.Set.newBuilder[A] diff --git a/src/library/scala/collection/concurrent/Map.scala b/src/library/scala/collection/concurrent/Map.scala index 83445738d9..a724be42cc 100644 --- a/src/library/scala/collection/concurrent/Map.scala +++ b/src/library/scala/collection/concurrent/Map.scala @@ -19,7 +19,7 @@ package scala.collection.concurrent * @tparam A the key type of the map * @tparam B the value type of the map * - * @define Coll ConcurrentMap + * @define Coll `ConcurrentMap` * @define coll concurrent map * @define concurrentmapinfo * This is a base trait for all Scala concurrent map implementations. It diff --git a/src/library/scala/collection/generic/ArrayTagTraversableFactory.scala b/src/library/scala/collection/generic/ArrayTagTraversableFactory.scala index d9ab17559e..ddae0a4d64 100644 --- a/src/library/scala/collection/generic/ArrayTagTraversableFactory.scala +++ b/src/library/scala/collection/generic/ArrayTagTraversableFactory.scala @@ -15,7 +15,7 @@ import language.higherKinds * subclasses thereof. * * @define coll collection - * @define Coll Traversable + * @define Coll `Traversable` * @define genericCanBuildFromInfo * The standard `CanBuildFrom` instance for $Coll objects. * @author Aleksandar Prokopec diff --git a/src/library/scala/collection/generic/BitSetFactory.scala b/src/library/scala/collection/generic/BitSetFactory.scala index 796b12b0ac..da80b3964b 100644 --- a/src/library/scala/collection/generic/BitSetFactory.scala +++ b/src/library/scala/collection/generic/BitSetFactory.scala @@ -15,7 +15,7 @@ import scala.collection._ import mutable.Builder /** @define coll collection - * @define Coll Traversable + * @define Coll `Traversable` * @define factoryInfo * This object provides a set of operations to create `$Coll` values. * @author Martin Odersky diff --git a/src/library/scala/collection/generic/GenMapFactory.scala b/src/library/scala/collection/generic/GenMapFactory.scala index b3faf0497b..31fe4e100d 100644 --- a/src/library/scala/collection/generic/GenMapFactory.scala +++ b/src/library/scala/collection/generic/GenMapFactory.scala @@ -15,7 +15,7 @@ import language.higherKinds /** A template for companion objects of `Map` and subclasses thereof. * * @define coll map - * @define Coll Map + * @define Coll `Map` * @define factoryInfo * This object provides a set of operations needed to create `$Coll` values. * @author Martin Odersky diff --git a/src/library/scala/collection/generic/GenSetFactory.scala b/src/library/scala/collection/generic/GenSetFactory.scala index caae8afa1c..4f812b337c 100644 --- a/src/library/scala/collection/generic/GenSetFactory.scala +++ b/src/library/scala/collection/generic/GenSetFactory.scala @@ -17,7 +17,7 @@ import language.higherKinds /** A template for companion objects of `Set` and subclasses thereof. * * @define coll set - * @define Coll Set + * @define Coll `Set` * @define factoryInfo * This object provides a set of operations needed to create `$Coll` values. * @author Martin Odersky diff --git a/src/library/scala/collection/generic/GenTraversableFactory.scala b/src/library/scala/collection/generic/GenTraversableFactory.scala index f233a40d35..94def7ab5d 100644 --- a/src/library/scala/collection/generic/GenTraversableFactory.scala +++ b/src/library/scala/collection/generic/GenTraversableFactory.scala @@ -19,7 +19,7 @@ import language.higherKinds * @since 2.8 * * @define coll collection - * @define Coll Traversable + * @define Coll `Traversable` * @define factoryInfo * This object provides a set of operations to create `$Coll` values. * @author Martin Odersky diff --git a/src/library/scala/collection/generic/GenericCompanion.scala b/src/library/scala/collection/generic/GenericCompanion.scala index cf01cf5f08..badceac713 100644 --- a/src/library/scala/collection/generic/GenericCompanion.scala +++ b/src/library/scala/collection/generic/GenericCompanion.scala @@ -20,7 +20,7 @@ import language.higherKinds * @author Martin Odersky * @since 2.8 * @define coll collection - * @define Coll CC + * @define Coll `CC` */ abstract class GenericCompanion[+CC[X] <: GenTraversable[X]] { /** The underlying collection type with unknown element type */ diff --git a/src/library/scala/collection/generic/GenericParCompanion.scala b/src/library/scala/collection/generic/GenericParCompanion.scala index 93c166b7ba..484da5c6d9 100644 --- a/src/library/scala/collection/generic/GenericParCompanion.scala +++ b/src/library/scala/collection/generic/GenericParCompanion.scala @@ -16,7 +16,7 @@ import language.higherKinds /** A template class for companion objects of parallel collection classes. * They should be mixed in together with `GenericCompanion` type. * - * @define Coll ParIterable + * @define Coll `ParIterable` * @tparam CC the type constructor representing the collection class * @since 2.8 */ diff --git a/src/library/scala/collection/generic/Growable.scala b/src/library/scala/collection/generic/Growable.scala index f0a70c2b88..baf332fcd8 100644 --- a/src/library/scala/collection/generic/Growable.scala +++ b/src/library/scala/collection/generic/Growable.scala @@ -18,7 +18,7 @@ package generic * @version 2.8 * @since 2.8 * @define coll growable collection - * @define Coll Growable + * @define Coll `Growable` * @define add add * @define Add add */ diff --git a/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala index 93aae0e355..f415a52b4d 100644 --- a/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala +++ b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala @@ -16,7 +16,7 @@ import language.higherKinds /** A template for companion objects of `SortedMap` and subclasses thereof. * * @since 2.8 - * @define Coll SortedMap + * @define Coll `SortedMap` * @define coll sorted map * @define factoryInfo * This object provides a set of operations needed to create sorted maps of type `$Coll`. diff --git a/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala index 67fb72270c..1317bb4796 100644 --- a/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala +++ b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala @@ -16,8 +16,8 @@ import language.higherKinds /** A template for companion objects of `SortedSet` and subclasses thereof. * * @since 2.8 - * @define Coll immutable.SortedSet - * @define coll immutable sorted + * @define Coll `immutable.SortedSet` + * @define coll immutable sorted set * @define factoryInfo * This object provides a set of operations needed to create sorted sets of type `$Coll`. * @author Martin Odersky diff --git a/src/library/scala/collection/generic/MutableSortedSetFactory.scala b/src/library/scala/collection/generic/MutableSortedSetFactory.scala index b0dd23ee1a..0e90ed999c 100644 --- a/src/library/scala/collection/generic/MutableSortedSetFactory.scala +++ b/src/library/scala/collection/generic/MutableSortedSetFactory.scala @@ -13,8 +13,8 @@ import scala.collection.mutable.{ Builder, GrowingBuilder } import language.higherKinds /** - * @define Coll mutable.SortedSet - * @define coll mutable sorted + * @define Coll `mutable.SortedSet` + * @define coll mutable sorted set * * @author Lucien Pereira * diff --git a/src/library/scala/collection/generic/ParFactory.scala b/src/library/scala/collection/generic/ParFactory.scala index 0829ba6616..41dca8fbe9 100644 --- a/src/library/scala/collection/generic/ParFactory.scala +++ b/src/library/scala/collection/generic/ParFactory.scala @@ -17,7 +17,7 @@ import language.higherKinds * operations to create `$Coll` objects. * * @define coll parallel collection - * @define Coll ParIterable + * @define Coll `ParIterable` * @since 2.8 */ abstract class ParFactory[CC[X] <: ParIterable[X] with GenericParTemplate[X, CC]] diff --git a/src/library/scala/collection/generic/ParMapFactory.scala b/src/library/scala/collection/generic/ParMapFactory.scala index c05ab73431..5aedf67924 100644 --- a/src/library/scala/collection/generic/ParMapFactory.scala +++ b/src/library/scala/collection/generic/ParMapFactory.scala @@ -19,7 +19,7 @@ import language.higherKinds * to create `$Coll` objects. * * @define coll parallel map - * @define Coll ParMap + * @define Coll `ParMap` * @author Aleksandar Prokopec * @since 2.8 */ diff --git a/src/library/scala/collection/generic/Shrinkable.scala b/src/library/scala/collection/generic/Shrinkable.scala index 88c7ce3a3d..0c9dafefb1 100644 --- a/src/library/scala/collection/generic/Shrinkable.scala +++ b/src/library/scala/collection/generic/Shrinkable.scala @@ -17,7 +17,7 @@ package generic * @version 2.8 * @since 2.8 * @define coll shrinkable collection - * @define Coll Shrinkable + * @define Coll `Shrinkable` */ trait Shrinkable[-A] { diff --git a/src/library/scala/collection/immutable/BitSet.scala b/src/library/scala/collection/immutable/BitSet.scala index 870d5534dc..1b676e2d2f 100644 --- a/src/library/scala/collection/immutable/BitSet.scala +++ b/src/library/scala/collection/immutable/BitSet.scala @@ -20,7 +20,7 @@ import mutable.{ Builder, SetBuilder } * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#immutable_bitsets "Scala's Collection Library overview"]] * section on `Immutable BitSets` for more information. * - * @define Coll immutable.BitSet + * @define Coll `immutable.BitSet` * @define coll immutable bitset */ @SerialVersionUID(1611436763290191562L) @@ -63,7 +63,7 @@ abstract class BitSet extends scala.collection.AbstractSet[Int] } /** $factoryInfo - * @define Coll immutable.BitSet + * @define Coll `immutable.BitSet` * @define coll immutable bitset */ object BitSet extends BitSetFactory[BitSet] { diff --git a/src/library/scala/collection/immutable/GenSeq.scala.disabled b/src/library/scala/collection/immutable/GenSeq.scala.disabled index 5b59418b9f..b8bc420ec3 100644 --- a/src/library/scala/collection/immutable/GenSeq.scala.disabled +++ b/src/library/scala/collection/immutable/GenSeq.scala.disabled @@ -25,7 +25,7 @@ import mutable.Builder * * The class adds an `update` method to `collection.Seq`. * - * @define Coll mutable.Seq + * @define Coll `mutable.Seq` * @define coll mutable sequence */ trait GenSeq[+A] extends GenIterable[A] diff --git a/src/library/scala/collection/immutable/GenSet.scala.disabled b/src/library/scala/collection/immutable/GenSet.scala.disabled index dc921b5245..828219580e 100644 --- a/src/library/scala/collection/immutable/GenSet.scala.disabled +++ b/src/library/scala/collection/immutable/GenSet.scala.disabled @@ -24,7 +24,7 @@ import mutable.Builder * * @since 1.0 * @author Matthias Zenger - * @define Coll mutable.Set + * @define Coll `mutable.Set` * @define coll mutable set */ trait GenSet[A] extends GenIterable[A] diff --git a/src/library/scala/collection/immutable/HashMap.scala b/src/library/scala/collection/immutable/HashMap.scala index 6b11371bec..13a0febfee 100644 --- a/src/library/scala/collection/immutable/HashMap.scala +++ b/src/library/scala/collection/immutable/HashMap.scala @@ -27,7 +27,7 @@ import parallel.immutable.ParHashMap * @since 2.3 * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#hash_tries "Scala's Collection Library overview"]] * section on `Hash Tries` for more information. - * @define Coll immutable.HashMap + * @define Coll `immutable.HashMap` * @define coll immutable hash map * @define mayNotTerminateInf * @define willNotTerminateInf @@ -96,7 +96,7 @@ class HashMap[A, +B] extends AbstractMap[A, B] } /** $factoryInfo - * @define Coll immutable.HashMap + * @define Coll `immutable.HashMap` * @define coll immutable hash map * * @author Tiark Rompf diff --git a/src/library/scala/collection/immutable/HashSet.scala b/src/library/scala/collection/immutable/HashSet.scala index 79d2fb71cc..b956a4d838 100644 --- a/src/library/scala/collection/immutable/HashSet.scala +++ b/src/library/scala/collection/immutable/HashSet.scala @@ -26,7 +26,7 @@ import collection.parallel.immutable.ParHashSet * @author Tiark Rompf * @version 2.8 * @since 2.3 - * @define Coll immutable.HashSet + * @define Coll `immutable.HashSet` * @define coll immutable hash set */ @SerialVersionUID(2L) @@ -85,12 +85,12 @@ class HashSet[A] extends AbstractSet[A] } /** $factoryInfo - * @define Coll immutable.HashSet + * @define Coll `immutable.HashSet` * @define coll immutable hash set * * @author Tiark Rompf * @since 2.3 - * @define Coll immutable.HashSet + * @define Coll `immutable.HashSet` * @define coll immutable hash set * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/immutable/IndexedSeq.scala b/src/library/scala/collection/immutable/IndexedSeq.scala index e3939001d8..b37edc4254 100644 --- a/src/library/scala/collection/immutable/IndexedSeq.scala +++ b/src/library/scala/collection/immutable/IndexedSeq.scala @@ -29,7 +29,7 @@ trait IndexedSeq[+A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is a `Vector`. * @define coll indexed sequence - * @define Coll IndexedSeq + * @define Coll `IndexedSeq` */ object IndexedSeq extends SeqFactory[IndexedSeq] { class Impl[A](buf: ArrayBuffer[A]) extends AbstractSeq[A] with IndexedSeq[A] with Serializable { diff --git a/src/library/scala/collection/immutable/IntMap.scala b/src/library/scala/collection/immutable/IntMap.scala index 3c9c0c2f24..039a57041c 100644 --- a/src/library/scala/collection/immutable/IntMap.scala +++ b/src/library/scala/collection/immutable/IntMap.scala @@ -36,7 +36,7 @@ import IntMapUtils._ /** A companion object for integer maps. * - * @define Coll IntMap + * @define Coll `IntMap` * @define mapCanBuildFromInfo * The standard `CanBuildFrom` instance for `$Coll` objects. * The created value is an instance of class `MapCanBuildFrom`. @@ -150,7 +150,7 @@ import IntMap._ * @tparam T type of the values associated with integer keys. * * @since 2.7 - * @define Coll immutable.IntMap + * @define Coll `immutable.IntMap` * @define coll immutable integer map * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/immutable/Iterable.scala b/src/library/scala/collection/immutable/Iterable.scala index d5fca2bdff..a1390ba189 100644 --- a/src/library/scala/collection/immutable/Iterable.scala +++ b/src/library/scala/collection/immutable/Iterable.scala @@ -18,7 +18,7 @@ import parallel.immutable.ParIterable /** A base trait for iterable collections that are guaranteed immutable. * $iterableInfo * - * @define Coll immutable.Iterable + * @define Coll `immutable.Iterable` * @define coll immutable iterable collection */ trait Iterable[+A] extends Traversable[A] @@ -34,7 +34,7 @@ trait Iterable[+A] extends Traversable[A] } /** $factoryInfo - * @define Coll immutable.Iterable + * @define Coll `immutable.Iterable` * @define coll immutable iterable collection */ object Iterable extends TraversableFactory[Iterable] { diff --git a/src/library/scala/collection/immutable/LinearSeq.scala b/src/library/scala/collection/immutable/LinearSeq.scala index 536894c287..2d6986740a 100644 --- a/src/library/scala/collection/immutable/LinearSeq.scala +++ b/src/library/scala/collection/immutable/LinearSeq.scala @@ -29,7 +29,7 @@ trait LinearSeq[+A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is a `List`. * @define coll immutable linear sequence - * @define Coll immutable.LinearSeq + * @define Coll `immutable.LinearSeq` */ object LinearSeq extends SeqFactory[LinearSeq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/immutable/List.scala b/src/library/scala/collection/immutable/List.scala index 1b75c10113..b4c22c3b6c 100644 --- a/src/library/scala/collection/immutable/List.scala +++ b/src/library/scala/collection/immutable/List.scala @@ -141,7 +141,7 @@ sealed abstract class List[+A] extends AbstractSeq[A] /** Builds a new list by applying a function to all elements of this list. * Like `xs map f`, but returns `xs` unchanged if function - * `f` maps all elements to themselves (wrt eq). + * `f` maps all elements to themselves (as determined by `eq`). * * @param f the function to apply to each element. * @tparam B the element type of the returned collection. @@ -382,7 +382,7 @@ final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extend /** $factoryInfo * @define coll list - * @define Coll List + * @define Coll `List` */ object List extends SeqFactory[List] { diff --git a/src/library/scala/collection/immutable/LongMap.scala b/src/library/scala/collection/immutable/LongMap.scala index 11b5d1e311..8a316f37de 100644 --- a/src/library/scala/collection/immutable/LongMap.scala +++ b/src/library/scala/collection/immutable/LongMap.scala @@ -36,7 +36,7 @@ import LongMapUtils._ /** A companion object for long maps. * - * @define Coll LongMap + * @define Coll `LongMap` * @define mapCanBuildFromInfo * The standard `CanBuildFrom` instance for `$Coll` objects. * The created value is an instance of class `MapCanBuildFrom`. @@ -147,7 +147,7 @@ import LongMap._; * @tparam T type of the values associated with the long keys. * * @since 2.7 - * @define Coll immutable.LongMap + * @define Coll `immutable.LongMap` * @define coll immutable long integer map * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/immutable/Map.scala b/src/library/scala/collection/immutable/Map.scala index bbefd983fd..e73da01ac4 100644 --- a/src/library/scala/collection/immutable/Map.scala +++ b/src/library/scala/collection/immutable/Map.scala @@ -66,7 +66,7 @@ trait Map[A, +B] extends Iterable[(A, B)] } /** $factoryInfo - * @define Coll immutable.Map + * @define Coll `immutable.Map` * @define coll immutable map */ object Map extends ImmutableMapFactory[Map] { diff --git a/src/library/scala/collection/immutable/NumericRange.scala b/src/library/scala/collection/immutable/NumericRange.scala index 0966fa035f..4c82d99c03 100644 --- a/src/library/scala/collection/immutable/NumericRange.scala +++ b/src/library/scala/collection/immutable/NumericRange.scala @@ -34,7 +34,7 @@ import generic._ * * @author Paul Phillips * @version 2.8 - * @define Coll NumericRange + * @define Coll `NumericRange` * @define coll numeric range * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/immutable/PagedSeq.scala b/src/library/scala/collection/immutable/PagedSeq.scala index 68c75ee586..94953ce38b 100644 --- a/src/library/scala/collection/immutable/PagedSeq.scala +++ b/src/library/scala/collection/immutable/PagedSeq.scala @@ -119,7 +119,7 @@ import PagedSeq._ * * @author Martin Odersky * @since 2.7 - * @define Coll PagedSeq + * @define Coll `PagedSeq` * @define coll paged sequence * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/immutable/Queue.scala b/src/library/scala/collection/immutable/Queue.scala index da04446281..e980dda847 100644 --- a/src/library/scala/collection/immutable/Queue.scala +++ b/src/library/scala/collection/immutable/Queue.scala @@ -30,7 +30,7 @@ import annotation.tailrec * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#immutable_queues "Scala's Collection Library overview"]] * section on `Immutable Queues` for more information. * - * @define Coll immutable.Queue + * @define Coll `immutable.Queue` * @define coll immutable queue * @define mayNotTerminateInf * @define willNotTerminateInf @@ -131,7 +131,7 @@ class Queue[+A] protected(protected val in: List[A], protected val out: List[A]) } /** $factoryInfo - * @define Coll immutable.Queue + * @define Coll `immutable.Queue` * @define coll immutable queue */ object Queue extends SeqFactory[Queue] { diff --git a/src/library/scala/collection/immutable/Seq.scala b/src/library/scala/collection/immutable/Seq.scala index 882ca12612..1104eb1b4f 100644 --- a/src/library/scala/collection/immutable/Seq.scala +++ b/src/library/scala/collection/immutable/Seq.scala @@ -19,7 +19,7 @@ import parallel.immutable.ParSeq * that are guaranteed immutable. * * $seqInfo - * @define Coll immutable.Seq + * @define Coll `immutable.Seq` * @define coll immutable sequence */ trait Seq[+A] extends Iterable[A] @@ -36,7 +36,7 @@ trait Seq[+A] extends Iterable[A] } /** $factoryInfo - * @define Coll immutable.Seq + * @define Coll `immutable.Seq` * @define coll immutable sequence */ object Seq extends SeqFactory[Seq] { diff --git a/src/library/scala/collection/immutable/Set.scala b/src/library/scala/collection/immutable/Set.scala index cd972d6c30..f783f2d562 100644 --- a/src/library/scala/collection/immutable/Set.scala +++ b/src/library/scala/collection/immutable/Set.scala @@ -21,7 +21,7 @@ import parallel.immutable.ParSet * @since 1.0 * @author Matthias Zenger * @author Martin Odersky - * @define Coll immutable.Set + * @define Coll `immutable.Set` * @define coll immutable set */ trait Set[A] extends Iterable[A] @@ -38,7 +38,7 @@ trait Set[A] extends Iterable[A] } /** $factoryInfo - * @define Coll immutable.Set + * @define Coll `immutable.Set` * @define coll immutable set */ object Set extends ImmutableSetFactory[Set] { diff --git a/src/library/scala/collection/immutable/SortedSet.scala b/src/library/scala/collection/immutable/SortedSet.scala index e1637ce78b..62fa4e0335 100644 --- a/src/library/scala/collection/immutable/SortedSet.scala +++ b/src/library/scala/collection/immutable/SortedSet.scala @@ -21,7 +21,7 @@ import mutable.Builder * @author Martin Odersky * @version 2.8 * @since 2.4 - * @define Coll immutable.SortedSet + * @define Coll `immutable.SortedSet` * @define coll immutable sorted set */ trait SortedSet[A] extends Set[A] with scala.collection.SortedSet[A] with SortedSetLike[A, SortedSet[A]] { @@ -30,7 +30,7 @@ trait SortedSet[A] extends Set[A] with scala.collection.SortedSet[A] with Sorted } /** $factoryInfo - * @define Coll immutable.SortedSet + * @define Coll `immutable.SortedSet` * @define coll immutable sorted set */ object SortedSet extends ImmutableSortedSetFactory[SortedSet] { diff --git a/src/library/scala/collection/immutable/Stack.scala b/src/library/scala/collection/immutable/Stack.scala index 50fc2795c0..c63c1ce232 100644 --- a/src/library/scala/collection/immutable/Stack.scala +++ b/src/library/scala/collection/immutable/Stack.scala @@ -13,7 +13,7 @@ import generic._ import mutable.{ ArrayBuffer, Builder } /** $factoryInfo - * @define Coll immutable.Stack + * @define Coll `immutable.Stack` * @define coll immutable stack */ object Stack extends SeqFactory[Stack] { @@ -37,7 +37,7 @@ object Stack extends SeqFactory[Stack] { * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#immutable_stacks "Scala's Collection Library overview"]] * section on `Immutable stacks` for more information. * - * @define Coll immutable.Stack + * @define Coll `immutable.Stack` * @define coll immutable stack * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala index 2df4ed70c7..f3e7214c5f 100644 --- a/src/library/scala/collection/immutable/Stream.scala +++ b/src/library/scala/collection/immutable/Stream.scala @@ -177,7 +177,7 @@ import language.implicitConversions * section on `Streams` for more information. * @define naturalsEx def naturalsFrom(i: Int): Stream[Int] = i #:: naturalsFrom(i + 1) - * @define Coll Stream + * @define Coll `Stream` * @define coll stream * @define orderDependent * @define orderDependentFold @@ -805,9 +805,9 @@ self => these } - /** Builds a new stream from this stream in which any duplicates (wrt to ==) - * have been removed. Among duplicate elements, only the first one is - * retained in the resulting `Stream`. + /** Builds a new stream from this stream in which any duplicates (as + * determined by `==`) have been removed. Among duplicate elements, only the + * first one is retained in the resulting `Stream`. * * @return A new `Stream` representing the result of applying distinctness to * the original `Stream`. diff --git a/src/library/scala/collection/immutable/StringLike.scala b/src/library/scala/collection/immutable/StringLike.scala index 52032a1cde..d1605bf637 100644 --- a/src/library/scala/collection/immutable/StringLike.scala +++ b/src/library/scala/collection/immutable/StringLike.scala @@ -33,7 +33,7 @@ import StringLike._ * @tparam Repr The type of the actual collection inheriting `StringLike`. * * @since 2.8 - * @define Coll String + * @define Coll `String` * @define coll string * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/immutable/StringOps.scala b/src/library/scala/collection/immutable/StringOps.scala index 97609b4c4d..633821ecea 100644 --- a/src/library/scala/collection/immutable/StringOps.scala +++ b/src/library/scala/collection/immutable/StringOps.scala @@ -25,7 +25,7 @@ import mutable.StringBuilder * @param repr the actual representation of this string operations object. * * @since 2.8 - * @define Coll StringOps + * @define Coll `StringOps` * @define coll string */ final class StringOps(override val repr: String) extends AnyVal with StringLike[String] { diff --git a/src/library/scala/collection/immutable/Traversable.scala b/src/library/scala/collection/immutable/Traversable.scala index 7830b38d69..59d3b4e029 100644 --- a/src/library/scala/collection/immutable/Traversable.scala +++ b/src/library/scala/collection/immutable/Traversable.scala @@ -30,7 +30,7 @@ trait Traversable[+A] extends scala.collection.Traversable[A] /** $factoryInfo * The current default implementation of a $Coll is a `Vector`. * @define coll immutable traversable collection - * @define Coll immutable.Traversable + * @define Coll `immutable.Traversable` */ object Traversable extends TraversableFactory[Traversable] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Traversable[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/immutable/TreeSet.scala b/src/library/scala/collection/immutable/TreeSet.scala index 1b3d72ceb7..882e828c5b 100644 --- a/src/library/scala/collection/immutable/TreeSet.scala +++ b/src/library/scala/collection/immutable/TreeSet.scala @@ -16,7 +16,7 @@ import immutable.{RedBlackTree => RB} import mutable.{ Builder, SetBuilder } /** $factoryInfo - * @define Coll immutable.TreeSet + * @define Coll `immutable.TreeSet` * @define coll immutable tree set */ object TreeSet extends ImmutableSortedSetFactory[TreeSet] { @@ -40,7 +40,7 @@ object TreeSet extends ImmutableSortedSetFactory[TreeSet] { * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#redblack_trees "Scala's Collection Library overview"]] * section on `Red-Black Trees` for more information. * - * @define Coll immutable.TreeSet + * @define Coll `immutable.TreeSet` * @define coll immutable tree set * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/immutable/Vector.scala b/src/library/scala/collection/immutable/Vector.scala index 55c31feec2..1395a8f52d 100644 --- a/src/library/scala/collection/immutable/Vector.scala +++ b/src/library/scala/collection/immutable/Vector.scala @@ -40,7 +40,7 @@ object Vector extends SeqFactory[Vector] { * * @tparam A the element type * - * @define Coll Vector + * @define Coll `Vector` * @define coll vector * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `Vector[B]` because an implicit of type `CanBuildFrom[Vector, B, That]` diff --git a/src/library/scala/collection/immutable/WrappedString.scala b/src/library/scala/collection/immutable/WrappedString.scala index de8aeea7e1..aa7e5b3c4a 100644 --- a/src/library/scala/collection/immutable/WrappedString.scala +++ b/src/library/scala/collection/immutable/WrappedString.scala @@ -25,7 +25,7 @@ import mutable.{Builder, StringBuilder} * @param self a string contained within this wrapped string * * @since 2.8 - * @define Coll WrappedString + * @define Coll `WrappedString` * @define coll wrapped string */ class WrappedString(val self: String) extends AbstractSeq[Char] with IndexedSeq[Char] with StringLike[WrappedString] { diff --git a/src/library/scala/collection/mutable/ArrayBuffer.scala b/src/library/scala/collection/mutable/ArrayBuffer.scala index bfdc08536c..3034fc2bce 100644 --- a/src/library/scala/collection/mutable/ArrayBuffer.scala +++ b/src/library/scala/collection/mutable/ArrayBuffer.scala @@ -29,7 +29,7 @@ import parallel.mutable.ParArray * * @tparam A the type of this arraybuffer's elements. * - * @define Coll ArrayBuffer + * @define Coll `ArrayBuffer` * @define coll arraybuffer * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `ArrayBuffer[B]` because an implicit of type `CanBuildFrom[ArrayBuffer, B, ArrayBuffer[B]]` @@ -187,7 +187,7 @@ class ArrayBuffer[A](override protected val initialSize: Int) * * $factoryInfo * @define coll array buffer - * @define Coll ArrayBuffer + * @define Coll `ArrayBuffer` */ object ArrayBuffer extends SeqFactory[ArrayBuffer] { /** $genericCanBuildFromInfo */ diff --git a/src/library/scala/collection/mutable/ArrayLike.scala b/src/library/scala/collection/mutable/ArrayLike.scala index 23d36252d2..04601845c4 100644 --- a/src/library/scala/collection/mutable/ArrayLike.scala +++ b/src/library/scala/collection/mutable/ArrayLike.scala @@ -18,7 +18,7 @@ import generic._ * @tparam A type of the elements contained in the array like object. * @tparam Repr the type of the actual collection containing the elements. * - * @define Coll ArrayLike + * @define Coll `ArrayLike` * @version 2.8 * @since 2.8 */ diff --git a/src/library/scala/collection/mutable/ArrayOps.scala b/src/library/scala/collection/mutable/ArrayOps.scala index 5f0e1e1071..57e81fdb9c 100644 --- a/src/library/scala/collection/mutable/ArrayOps.scala +++ b/src/library/scala/collection/mutable/ArrayOps.scala @@ -30,7 +30,7 @@ import parallel.mutable.ParArray * * @tparam T type of the elements contained in this array. * - * @define Coll ArrayOps + * @define Coll `ArrayOps` * @define orderDependent * @define orderDependentFold * @define mayNotTerminateInf diff --git a/src/library/scala/collection/mutable/ArraySeq.scala b/src/library/scala/collection/mutable/ArraySeq.scala index cb86c416fe..d0eaee348b 100644 --- a/src/library/scala/collection/mutable/ArraySeq.scala +++ b/src/library/scala/collection/mutable/ArraySeq.scala @@ -27,7 +27,7 @@ import parallel.mutable.ParArray * @tparam A type of the elements contained in this array sequence. * @param length the length of the underlying array. * - * @define Coll ArraySeq + * @define Coll `ArraySeq` * @define coll array sequence * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `ArraySeq[B]` because an implicit of type `CanBuildFrom[ArraySeq, B, ArraySeq[B]]` @@ -93,7 +93,7 @@ extends AbstractSeq[A] /** $factoryInfo * @define coll array sequence - * @define Coll ArraySeq + * @define Coll `ArraySeq` */ object ArraySeq extends SeqFactory[ArraySeq] { /** $genericCanBuildFromInfo */ diff --git a/src/library/scala/collection/mutable/ArrayStack.scala b/src/library/scala/collection/mutable/ArrayStack.scala index b3a0534826..04a318d0c3 100644 --- a/src/library/scala/collection/mutable/ArrayStack.scala +++ b/src/library/scala/collection/mutable/ArrayStack.scala @@ -15,7 +15,7 @@ import generic._ * * $factoryInfo * @define coll array stack - * @define Coll ArrayStack + * @define Coll `ArrayStack` */ object ArrayStack extends SeqFactory[ArrayStack] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ArrayStack[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] @@ -51,7 +51,7 @@ object ArrayStack extends SeqFactory[ArrayStack] { * * @tparam T type of the elements contained in this array stack. * - * @define Coll ArrayStack + * @define Coll `ArrayStack` * @define coll array stack * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/mutable/BitSet.scala b/src/library/scala/collection/mutable/BitSet.scala index 6b9673dae6..58b45aa2a2 100644 --- a/src/library/scala/collection/mutable/BitSet.scala +++ b/src/library/scala/collection/mutable/BitSet.scala @@ -21,7 +21,7 @@ import BitSetLike.{LogWL, updateArray} * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#mutable_bitsets "Scala's Collection Library overview"]] * section on `Mutable Bitsets` for more information. * - * @define Coll BitSet + * @define Coll `BitSet` * @define coll bitset * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `BitSet[B]` because an implicit of type `CanBuildFrom[BitSet, B, BitSet]` @@ -114,7 +114,7 @@ class BitSet(protected var elems: Array[Long]) extends AbstractSet[Int] /** $factoryInfo * @define coll bitset - * @define Coll BitSet + * @define Coll `BitSet` */ object BitSet extends BitSetFactory[BitSet] { def empty: BitSet = new BitSet diff --git a/src/library/scala/collection/mutable/Buffer.scala b/src/library/scala/collection/mutable/Buffer.scala index 7326d5ec5b..dd225cfab9 100644 --- a/src/library/scala/collection/mutable/Buffer.scala +++ b/src/library/scala/collection/mutable/Buffer.scala @@ -25,7 +25,7 @@ import generic._ * * @tparam A type of the elements contained in this buffer. * - * @define Coll Buffer + * @define Coll `Buffer` * @define coll buffer */ @cloneable @@ -37,7 +37,7 @@ trait Buffer[A] extends Seq[A] /** $factoryInfo * @define coll buffer - * @define Coll Buffer + * @define Coll `Buffer` */ object Buffer extends SeqFactory[Buffer] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Buffer[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/BufferProxy.scala b/src/library/scala/collection/mutable/BufferProxy.scala index 6a6bdd0077..aa1b20d240 100644 --- a/src/library/scala/collection/mutable/BufferProxy.scala +++ b/src/library/scala/collection/mutable/BufferProxy.scala @@ -25,7 +25,7 @@ import script._ * * @tparam A type of the elements the buffer proxy contains. * - * @define Coll BufferProxy + * @define Coll `BufferProxy` * @define coll buffer proxy */ trait BufferProxy[A] extends Buffer[A] with Proxy { diff --git a/src/library/scala/collection/mutable/ConcurrentMap.scala b/src/library/scala/collection/mutable/ConcurrentMap.scala index f2b44d6737..ad6b609862 100644 --- a/src/library/scala/collection/mutable/ConcurrentMap.scala +++ b/src/library/scala/collection/mutable/ConcurrentMap.scala @@ -20,7 +20,7 @@ package mutable * @tparam A the key type of the map * @tparam B the value type of the map * - * @define Coll ConcurrentMap + * @define Coll `ConcurrentMap` * @define coll concurrent map * @define concurrentmapinfo * This is a base trait for all Scala concurrent map implementations. It diff --git a/src/library/scala/collection/mutable/DoubleLinkedList.scala b/src/library/scala/collection/mutable/DoubleLinkedList.scala index 49378a4f4e..cba4e9725e 100644 --- a/src/library/scala/collection/mutable/DoubleLinkedList.scala +++ b/src/library/scala/collection/mutable/DoubleLinkedList.scala @@ -26,7 +26,7 @@ import generic._ * * @tparam A the type of the elements contained in this double linked list. * - * @define Coll DoubleLinkedList + * @define Coll `DoubleLinkedList` * @define coll double linked list * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `DoubleLinkedList[B]` because an implicit of type `CanBuildFrom[DoubleLinkedList, B, DoubleLinkedList[B]]` @@ -67,7 +67,7 @@ class DoubleLinkedList[A]() extends AbstractSeq[A] /** $factoryInfo * @define coll double linked list - * @define Coll DoubleLinkedList + * @define Coll `DoubleLinkedList` */ object DoubleLinkedList extends SeqFactory[DoubleLinkedList] { /** $genericCanBuildFromInfo */ diff --git a/src/library/scala/collection/mutable/DoubleLinkedListLike.scala b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala index dfb70beeda..ebccacf976 100644 --- a/src/library/scala/collection/mutable/DoubleLinkedListLike.scala +++ b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala @@ -52,7 +52,7 @@ import annotation.migration * @tparam A type of the elements contained in the double linked list * @tparam This the type of the actual linked list holding the elements * - * @define Coll DoubleLinkedList + * @define Coll `DoubleLinkedList` * @define coll double linked list */ trait DoubleLinkedListLike[A, This <: Seq[A] with DoubleLinkedListLike[A, This]] extends SeqLike[A, This] with LinkedListLike[A, This] { self => diff --git a/src/library/scala/collection/mutable/GenSeq.scala.disabled b/src/library/scala/collection/mutable/GenSeq.scala.disabled index 85e4065183..53ec5acc34 100644 --- a/src/library/scala/collection/mutable/GenSeq.scala.disabled +++ b/src/library/scala/collection/mutable/GenSeq.scala.disabled @@ -24,7 +24,7 @@ import generic._ * * The class adds an `update` method to `collection.Seq`. * - * @define Coll mutable.Seq + * @define Coll `mutable.Seq` * @define coll mutable sequence */ trait GenSeq[A] extends GenIterable[A] diff --git a/src/library/scala/collection/mutable/GenSet.scala.disabled b/src/library/scala/collection/mutable/GenSet.scala.disabled index ac11e634e8..9080abaf38 100644 --- a/src/library/scala/collection/mutable/GenSet.scala.disabled +++ b/src/library/scala/collection/mutable/GenSet.scala.disabled @@ -24,7 +24,7 @@ import generic._ * * @since 1.0 * @author Matthias Zenger - * @define Coll mutable.Set + * @define Coll `mutable.Set` * @define coll mutable set */ trait GenSet[A] extends GenIterable[A] diff --git a/src/library/scala/collection/mutable/GrowingBuilder.scala b/src/library/scala/collection/mutable/GrowingBuilder.scala index 0b7385194e..df63177b87 100644 --- a/src/library/scala/collection/mutable/GrowingBuilder.scala +++ b/src/library/scala/collection/mutable/GrowingBuilder.scala @@ -18,7 +18,7 @@ import generic._ * @version 2.8 * @since 2.8 * - * @define Coll GrowingBuilder + * @define Coll `GrowingBuilder` * @define coll growing builder */ class GrowingBuilder[Elem, To <: Growable[Elem]](empty: To) extends Builder[Elem, To] { diff --git a/src/library/scala/collection/mutable/HashMap.scala b/src/library/scala/collection/mutable/HashMap.scala index 65a10f4ba9..bf640cdb90 100644 --- a/src/library/scala/collection/mutable/HashMap.scala +++ b/src/library/scala/collection/mutable/HashMap.scala @@ -21,7 +21,7 @@ import scala.collection.parallel.mutable.ParHashMap * @tparam A the type of the keys contained in this hash map. * @tparam B the type of the values assigned to keys in this hash map. * - * @define Coll mutable.HashMap + * @define Coll `mutable.HashMap` * @define coll mutable hash map * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `HashMap[A, B]` if the elements contained in the resulting collection are @@ -138,7 +138,7 @@ extends AbstractMap[A, B] } /** $factoryInfo - * @define Coll mutable.HashMap + * @define Coll `mutable.HashMap` * @define coll mutable hash map */ object HashMap extends MutableMapFactory[HashMap] { diff --git a/src/library/scala/collection/mutable/HashSet.scala b/src/library/scala/collection/mutable/HashSet.scala index 8ed6b925aa..e040d1e421 100644 --- a/src/library/scala/collection/mutable/HashSet.scala +++ b/src/library/scala/collection/mutable/HashSet.scala @@ -25,7 +25,7 @@ import collection.parallel.mutable.ParHashSet * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#hash_tables "Scala's Collection Library overview"]] * section on `Hash Tables` for more information. * - * @define Coll mutable.HashSet + * @define Coll `mutable.HashSet` * @define coll mutable hash set * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `HashSet[B]` because an implicit of type `CanBuildFrom[HashSet, B, HashSet[B]]` @@ -98,7 +98,7 @@ extends AbstractSet[A] } /** $factoryInfo - * @define Coll mutable.HashSet + * @define Coll `mutable.HashSet` * @define coll mutable hash set */ object HashSet extends MutableSetFactory[HashSet] { diff --git a/src/library/scala/collection/mutable/IndexedSeq.scala b/src/library/scala/collection/mutable/IndexedSeq.scala index 0e2e06df84..686f90c9e8 100644 --- a/src/library/scala/collection/mutable/IndexedSeq.scala +++ b/src/library/scala/collection/mutable/IndexedSeq.scala @@ -29,7 +29,7 @@ trait IndexedSeq[A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is an `ArrayBuffer`. * @define coll mutable indexed sequence - * @define Coll mutable.IndexedSeq + * @define Coll `mutable.IndexedSeq` */ object IndexedSeq extends SeqFactory[IndexedSeq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/IndexedSeqLike.scala b/src/library/scala/collection/mutable/IndexedSeqLike.scala index 0c1df17ead..4bd5ea1e89 100644 --- a/src/library/scala/collection/mutable/IndexedSeqLike.scala +++ b/src/library/scala/collection/mutable/IndexedSeqLike.scala @@ -27,7 +27,7 @@ import generic._ * @tparam A the element type of the $coll * @tparam Repr the type of the actual $coll containing the elements. * - * @define Coll IndexedSeq + * @define Coll `IndexedSeq` * @define coll mutable indexed sequence * @define indexedSeqInfo * @author Martin Odersky diff --git a/src/library/scala/collection/mutable/Iterable.scala b/src/library/scala/collection/mutable/Iterable.scala index 54fe11f98c..3b5ee63ea3 100644 --- a/src/library/scala/collection/mutable/Iterable.scala +++ b/src/library/scala/collection/mutable/Iterable.scala @@ -29,7 +29,7 @@ trait Iterable[A] extends Traversable[A] /** $factoryInfo * The current default implementation of a $Coll is an `ArrayBuffer`. * @define coll mutable iterable collection - * @define Coll mutable.Iterable + * @define Coll `mutable.Iterable` */ object Iterable extends TraversableFactory[Iterable] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Iterable[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/LinearSeq.scala b/src/library/scala/collection/mutable/LinearSeq.scala index 522ebfd277..443b458342 100644 --- a/src/library/scala/collection/mutable/LinearSeq.scala +++ b/src/library/scala/collection/mutable/LinearSeq.scala @@ -17,7 +17,7 @@ import generic._ * that can be mutated. * $linearSeqInfo * - * @define Coll LinearSeq + * @define Coll `LinearSeq` * @define coll linear sequence * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#mutable_lists "Scala's Collection Library overview"]] * section on `Mutable Lists` for more information. @@ -33,7 +33,7 @@ trait LinearSeq[A] extends Seq[A] /** $factoryInfo * The current default implementation of a $Coll is a `MutableList`. * @define coll mutable linear sequence - * @define Coll mutable.LinearSeq + * @define Coll `mutable.LinearSeq` */ object LinearSeq extends SeqFactory[LinearSeq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/LinkedHashMap.scala b/src/library/scala/collection/mutable/LinkedHashMap.scala index e4090637ec..cd174523b1 100644 --- a/src/library/scala/collection/mutable/LinkedHashMap.scala +++ b/src/library/scala/collection/mutable/LinkedHashMap.scala @@ -14,7 +14,7 @@ package mutable import generic._ /** $factoryInfo - * @define Coll LinkedHashMap + * @define Coll `LinkedHashMap` * @define coll linked hash map */ object LinkedHashMap extends MutableMapFactory[LinkedHashMap] { @@ -28,7 +28,7 @@ object LinkedHashMap extends MutableMapFactory[LinkedHashMap] { * @tparam A the type of the keys contained in this hash map. * @tparam B the type of the values assigned to keys in this hash map. * - * @define Coll LinkedHashMap + * @define Coll `LinkedHashMap` * @define coll linked hash map * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `LinkedHashMap[A, B]` if the elements contained in the resulting collection are diff --git a/src/library/scala/collection/mutable/LinkedHashSet.scala b/src/library/scala/collection/mutable/LinkedHashSet.scala index d2815cf9de..3f789f9fa2 100644 --- a/src/library/scala/collection/mutable/LinkedHashSet.scala +++ b/src/library/scala/collection/mutable/LinkedHashSet.scala @@ -24,7 +24,7 @@ import generic._ * * @tparam A the type of the elements contained in this set. * - * @define Coll LinkedHashSet + * @define Coll `LinkedHashSet` * @define coll linked hash set * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `LinkedHashSet[B]` because an implicit of type `CanBuildFrom[LinkedHashSet, B, LinkedHashSet[B]]` @@ -87,7 +87,7 @@ class LinkedHashSet[A] extends AbstractSet[A] } /** $factoryInfo - * @define Coll LinkedHashSet + * @define Coll `LinkedHashSet` * @define coll linked hash set */ object LinkedHashSet extends MutableSetFactory[LinkedHashSet] { diff --git a/src/library/scala/collection/mutable/LinkedList.scala b/src/library/scala/collection/mutable/LinkedList.scala index 8510827697..335ddccf56 100644 --- a/src/library/scala/collection/mutable/LinkedList.scala +++ b/src/library/scala/collection/mutable/LinkedList.scala @@ -40,7 +40,7 @@ import generic._ * * @constructor Creates an "empty" list, defined as a single node with no data element and next pointing to itself. - * @define Coll LinkedList + * @define Coll `LinkedList` * @define coll linked list * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `LinkedList[B]` because an implicit of type `CanBuildFrom[LinkedList, B, LinkedList[B]]` @@ -109,7 +109,7 @@ class LinkedList[A]() extends AbstractSeq[A] } /** $factoryInfo - * @define Coll LinkedList + * @define Coll `LinkedList` * @define coll linked list */ object LinkedList extends SeqFactory[LinkedList] { diff --git a/src/library/scala/collection/mutable/LinkedListLike.scala b/src/library/scala/collection/mutable/LinkedListLike.scala index ebec31ca98..07a8501ca4 100644 --- a/src/library/scala/collection/mutable/LinkedListLike.scala +++ b/src/library/scala/collection/mutable/LinkedListLike.scala @@ -29,7 +29,7 @@ import annotation.tailrec * @tparam A type of the elements contained in the linked list * @tparam This the type of the actual linked list holding the elements * - * @define Coll LinkedList + * @define Coll `LinkedList` * @define coll linked list * * @define singleLinkedListExample diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala index 96e73522b6..5c580f9c09 100644 --- a/src/library/scala/collection/mutable/ListBuffer.scala +++ b/src/library/scala/collection/mutable/ListBuffer.scala @@ -27,7 +27,7 @@ import java.io._ * * @tparam A the type of this list buffer's elements. * - * @define Coll ListBuffer + * @define Coll `ListBuffer` * @define coll list buffer * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `ListBuffer[B]` because an implicit of type `CanBuildFrom[ListBuffer, B, ListBuffer[B]]` @@ -425,7 +425,7 @@ final class ListBuffer[A] } /** $factoryInfo - * @define Coll ListBuffer + * @define Coll `ListBuffer` * @define coll list buffer */ object ListBuffer extends SeqFactory[ListBuffer] { diff --git a/src/library/scala/collection/mutable/ListMap.scala b/src/library/scala/collection/mutable/ListMap.scala index d8d60d1c9a..61810c4ddf 100644 --- a/src/library/scala/collection/mutable/ListMap.scala +++ b/src/library/scala/collection/mutable/ListMap.scala @@ -18,7 +18,7 @@ import generic._ * @tparam A the type of the keys contained in this list map. * @tparam B the type of the values assigned to keys in this list map. * - * @define Coll mutable.ListMap + * @define Coll `mutable.ListMap` * @define coll mutable list map * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `ListMap[A, B]` if the elements contained in the resulting collection are @@ -60,7 +60,7 @@ extends AbstractMap[A, B] } /** $factoryInfo - * @define Coll mutable.ListMap + * @define Coll `mutable.ListMap` * @define coll mutable list map */ object ListMap extends MutableMapFactory[ListMap] { diff --git a/src/library/scala/collection/mutable/Map.scala b/src/library/scala/collection/mutable/Map.scala index 0d40a1c70d..207b3f3324 100644 --- a/src/library/scala/collection/mutable/Map.scala +++ b/src/library/scala/collection/mutable/Map.scala @@ -63,7 +63,7 @@ trait Map[A, B] /** $factoryInfo * The current default implementation of a $Coll is a `HashMap`. * @define coll mutable map - * @define Coll mutable.Map + * @define Coll `mutable.Map` */ object Map extends MutableMapFactory[Map] { /** $canBuildFromInfo */ diff --git a/src/library/scala/collection/mutable/MultiMap.scala b/src/library/scala/collection/mutable/MultiMap.scala index 0f298c4a8a..d21624759d 100644 --- a/src/library/scala/collection/mutable/MultiMap.scala +++ b/src/library/scala/collection/mutable/MultiMap.scala @@ -19,7 +19,7 @@ package mutable * `B` objects. * * @define coll multimap - * @define Coll MultiMap + * @define Coll `MultiMap` * @author Matthias Zenger * @author Martin Odersky * @version 2.8 diff --git a/src/library/scala/collection/mutable/OpenHashMap.scala b/src/library/scala/collection/mutable/OpenHashMap.scala index 87e5c061fa..2634deb819 100644 --- a/src/library/scala/collection/mutable/OpenHashMap.scala +++ b/src/library/scala/collection/mutable/OpenHashMap.scala @@ -10,7 +10,7 @@ package scala.collection package mutable /** - * @define Coll OpenHashMap + * @define Coll `OpenHashMap` * @define coll open hash map * * @since 2.7 @@ -42,7 +42,7 @@ object OpenHashMap { * @author David MacIver * @since 2.7 * - * @define Coll OpenHashMap + * @define Coll `OpenHashMap` * @define coll open hash map * @define mayNotTerminateInf * @define willNotTerminateInf diff --git a/src/library/scala/collection/mutable/Queue.scala b/src/library/scala/collection/mutable/Queue.scala index 77b1ae21cb..605d37aec6 100644 --- a/src/library/scala/collection/mutable/Queue.scala +++ b/src/library/scala/collection/mutable/Queue.scala @@ -23,7 +23,7 @@ import generic._ * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#mutable_queues "Scala's Collection Library overview"]] * section on `Queues` for more information. * - * @define Coll mutable.Queue + * @define Coll `mutable.Queue` * @define coll mutable queue * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/mutable/Seq.scala b/src/library/scala/collection/mutable/Seq.scala index 89b930e36f..ceed76cf88 100644 --- a/src/library/scala/collection/mutable/Seq.scala +++ b/src/library/scala/collection/mutable/Seq.scala @@ -21,7 +21,7 @@ import generic._ * * The class adds an `update` method to `collection.Seq`. * - * @define Coll mutable.Seq + * @define Coll `mutable.Seq` * @define coll mutable sequence */ trait Seq[A] extends Iterable[A] @@ -36,7 +36,7 @@ trait Seq[A] extends Iterable[A] /** $factoryInfo * The current default implementation of a $Coll is an `ArrayBuffer`. * @define coll mutable sequence - * @define Coll mutable.Seq + * @define Coll `mutable.Seq` */ object Seq extends SeqFactory[Seq] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Seq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/Set.scala b/src/library/scala/collection/mutable/Set.scala index 744768e8dd..33a99e9474 100644 --- a/src/library/scala/collection/mutable/Set.scala +++ b/src/library/scala/collection/mutable/Set.scala @@ -19,7 +19,7 @@ import generic._ * * @since 1.0 * @author Matthias Zenger - * @define Coll mutable.Set + * @define Coll `mutable.Set` * @define coll mutable set */ trait Set[A] extends Iterable[A] @@ -34,7 +34,7 @@ trait Set[A] extends Iterable[A] /** $factoryInfo * The current default implementation of a $Coll is a `HashSet`. * @define coll mutable set - * @define Coll mutable.Set + * @define Coll `mutable.Set` */ object Set extends MutableSetFactory[Set] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Set[A]] = setCanBuildFrom[A] diff --git a/src/library/scala/collection/mutable/SortedSet.scala b/src/library/scala/collection/mutable/SortedSet.scala index f41a51d3ef..78d12f3d64 100644 --- a/src/library/scala/collection/mutable/SortedSet.scala +++ b/src/library/scala/collection/mutable/SortedSet.scala @@ -14,7 +14,7 @@ import generic._ /** * Base trait for mutable sorted set. * - * @define Coll mutable.SortedSet + * @define Coll `mutable.SortedSet` * @define coll mutable sorted set * * @author Lucien Pereira @@ -31,7 +31,7 @@ trait SortedSet[A] extends collection.SortedSet[A] with collection.SortedSetLike /** * A template for mutable sorted set companion objects. * - * @define Coll mutable.SortedSet + * @define Coll `mutable.SortedSet` * @define coll mutable sorted set * @define factoryInfo * This object provides a set of operations needed to create sorted sets of type mutable.SortedSet. diff --git a/src/library/scala/collection/mutable/Stack.scala b/src/library/scala/collection/mutable/Stack.scala index b70df05c55..042eac517a 100644 --- a/src/library/scala/collection/mutable/Stack.scala +++ b/src/library/scala/collection/mutable/Stack.scala @@ -20,7 +20,7 @@ import annotation.migration * * $factoryInfo * @define coll mutable stack - * @define Coll mutable.Stack + * @define Coll `mutable.Stack` */ object Stack extends SeqFactory[Stack] { class StackBuilder[A] extends Builder[A, Stack[A]] { @@ -46,7 +46,7 @@ object Stack extends SeqFactory[Stack] { * @since 1 * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#stacks "Scala's Collection Library overview"]] * section on `Stacks` for more information. - * @define Coll Stack + * @define Coll `Stack` * @define coll stack * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/mutable/SynchronizedBuffer.scala b/src/library/scala/collection/mutable/SynchronizedBuffer.scala index 23552e9d52..a14605d60a 100644 --- a/src/library/scala/collection/mutable/SynchronizedBuffer.scala +++ b/src/library/scala/collection/mutable/SynchronizedBuffer.scala @@ -21,7 +21,7 @@ import script._ * @author Matthias Zenger * @version 1.0, 08/07/2003 * @since 1 - * @define Coll SynchronizedBuffer + * @define Coll `SynchronizedBuffer` * @define coll synchronized buffer */ trait SynchronizedBuffer[A] extends Buffer[A] { diff --git a/src/library/scala/collection/mutable/SynchronizedMap.scala b/src/library/scala/collection/mutable/SynchronizedMap.scala index 6e3ae13ada..037b8ec5f5 100644 --- a/src/library/scala/collection/mutable/SynchronizedMap.scala +++ b/src/library/scala/collection/mutable/SynchronizedMap.scala @@ -22,7 +22,7 @@ import annotation.migration * @author Matthias Zenger, Martin Odersky * @version 2.0, 31/12/2006 * @since 1 - * @define Coll SynchronizedMap + * @define Coll `SynchronizedMap` * @define coll synchronized map */ trait SynchronizedMap[A, B] extends Map[A, B] { diff --git a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala index 159b8312b2..bc32537798 100644 --- a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala +++ b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala @@ -20,7 +20,7 @@ package mutable * @author Matthias Zenger * @version 1.0, 03/05/2004 * @since 1 - * @define Coll SynchronizedPriorityQueue + * @define Coll `SynchronizedPriorityQueue` * @define coll synchronized priority queue */ class SynchronizedPriorityQueue[A](implicit ord: Ordering[A]) extends PriorityQueue[A] { diff --git a/src/library/scala/collection/mutable/SynchronizedQueue.scala b/src/library/scala/collection/mutable/SynchronizedQueue.scala index 56f74a5b9b..9e00c5d6fd 100644 --- a/src/library/scala/collection/mutable/SynchronizedQueue.scala +++ b/src/library/scala/collection/mutable/SynchronizedQueue.scala @@ -21,7 +21,7 @@ package mutable * @author Matthias Zenger * @version 1.0, 03/05/2004 * @since 1 - * @define Coll SynchronizedQueue + * @define Coll `SynchronizedQueue` * @define coll synchronized queue */ class SynchronizedQueue[A] extends Queue[A] { diff --git a/src/library/scala/collection/mutable/SynchronizedSet.scala b/src/library/scala/collection/mutable/SynchronizedSet.scala index c945a859f3..c28764ff68 100644 --- a/src/library/scala/collection/mutable/SynchronizedSet.scala +++ b/src/library/scala/collection/mutable/SynchronizedSet.scala @@ -20,7 +20,7 @@ import script._ * @author Matthias Zenger * @version 1.0, 08/07/2003 * @since 1 - * @define Coll SynchronizedSet + * @define Coll `SynchronizedSet` * @define coll synchronized set */ trait SynchronizedSet[A] extends Set[A] { diff --git a/src/library/scala/collection/mutable/SynchronizedStack.scala b/src/library/scala/collection/mutable/SynchronizedStack.scala index a09ae21901..8363222295 100644 --- a/src/library/scala/collection/mutable/SynchronizedStack.scala +++ b/src/library/scala/collection/mutable/SynchronizedStack.scala @@ -21,7 +21,7 @@ package mutable * @author Matthias Zenger * @version 1.0, 03/05/2004 * @since 1 - * @define Coll SynchronizedStack + * @define Coll `SynchronizedStack` * @define coll synchronized stack */ class SynchronizedStack[A] extends Stack[A] { diff --git a/src/library/scala/collection/mutable/Traversable.scala b/src/library/scala/collection/mutable/Traversable.scala index 04b67c0bad..28241fdec9 100644 --- a/src/library/scala/collection/mutable/Traversable.scala +++ b/src/library/scala/collection/mutable/Traversable.scala @@ -29,7 +29,7 @@ trait Traversable[A] extends scala.collection.Traversable[A] /** $factoryInfo * The current default implementation of a $Coll is an `ArrayBuffer`. * @define coll mutable traversable collection - * @define Coll mutable.Traversable + * @define Coll `mutable.Traversable` */ object Traversable extends TraversableFactory[Traversable] { implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Traversable[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]] diff --git a/src/library/scala/collection/mutable/TreeSet.scala b/src/library/scala/collection/mutable/TreeSet.scala index 02ee811193..00675b9119 100644 --- a/src/library/scala/collection/mutable/TreeSet.scala +++ b/src/library/scala/collection/mutable/TreeSet.scala @@ -12,7 +12,7 @@ package mutable import generic._ /** - * @define Coll mutable.TreeSet + * @define Coll `mutable.TreeSet` * @define coll mutable tree set * @factoryInfo * Companion object of TreeSet providing factory related utilities. diff --git a/src/library/scala/collection/mutable/UnrolledBuffer.scala b/src/library/scala/collection/mutable/UnrolledBuffer.scala index 889768d471..cd76c7de4e 100644 --- a/src/library/scala/collection/mutable/UnrolledBuffer.scala +++ b/src/library/scala/collection/mutable/UnrolledBuffer.scala @@ -36,7 +36,7 @@ import annotation.tailrec * should still be avoided for such a purpose. * * @define coll unrolled buffer - * @define Coll UnrolledBuffer + * @define Coll `UnrolledBuffer` * @author Aleksandar Prokopec * */ diff --git a/src/library/scala/collection/mutable/WeakHashMap.scala b/src/library/scala/collection/mutable/WeakHashMap.scala index 4e09755acf..ec99197bb9 100644 --- a/src/library/scala/collection/mutable/WeakHashMap.scala +++ b/src/library/scala/collection/mutable/WeakHashMap.scala @@ -23,7 +23,7 @@ import convert.Wrappers._ * @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#weak_hash_maps "Scala's Collection Library overview"]] * section on `Weak Hash Maps` for more information. * - * @define Coll WeakHashMap + * @define Coll `WeakHashMap` * @define coll weak hash map * @define thatinfo the class of the returned collection. In the standard library configuration, * `That` is always `WeakHashMap[A, B]` if the elements contained in the resulting collection are @@ -43,7 +43,7 @@ class WeakHashMap[A, B] extends JMapWrapper[A, B](new java.util.WeakHashMap) } /** $factoryInfo - * @define Coll WeakHashMap + * @define Coll `WeakHashMap` * @define coll weak hash map */ object WeakHashMap extends MutableMapFactory[WeakHashMap] { diff --git a/src/library/scala/collection/mutable/WrappedArray.scala b/src/library/scala/collection/mutable/WrappedArray.scala index 9d170b2832..86317819a1 100644 --- a/src/library/scala/collection/mutable/WrappedArray.scala +++ b/src/library/scala/collection/mutable/WrappedArray.scala @@ -24,7 +24,7 @@ import scala.collection.parallel.mutable.ParArray * @author Martin Odersky, Stephane Micheloud * @version 1.0 * @since 2.8 - * @define Coll WrappedArray + * @define Coll `WrappedArray` * @define coll wrapped array * @define orderDependent * @define orderDependentFold diff --git a/src/library/scala/collection/parallel/ParIterable.scala b/src/library/scala/collection/parallel/ParIterable.scala index 0b5faf15ee..0bd6abaf78 100644 --- a/src/library/scala/collection/parallel/ParIterable.scala +++ b/src/library/scala/collection/parallel/ParIterable.scala @@ -24,7 +24,7 @@ import scala.collection.parallel.mutable.ParArray * @author Aleksandar Prokopec * @since 2.9 * - * @define Coll ParIterable + * @define Coll `ParIterable` * @define coll parallel iterable */ trait ParIterable[+T] diff --git a/src/library/scala/collection/parallel/immutable/ParHashMap.scala b/src/library/scala/collection/parallel/immutable/ParHashMap.scala index e630a9dbed..ad882390c8 100644 --- a/src/library/scala/collection/parallel/immutable/ParHashMap.scala +++ b/src/library/scala/collection/parallel/immutable/ParHashMap.scala @@ -39,7 +39,7 @@ import collection.parallel.Task * @see [[http://docs.scala-lang.org/overviews/parallel-collections/concrete-parallel-collections.html#parallel_hash_tries Scala's Parallel Collections Library overview]] * section on Parallel Hash Tries for more information. * - * @define Coll immutable.ParHashMap + * @define Coll `immutable.ParHashMap` * @define coll immutable parallel hash map */ @SerialVersionUID(1L) @@ -140,7 +140,7 @@ self => /** $factoryInfo - * @define Coll immutable.ParHashMap + * @define Coll `immutable.ParHashMap` * @define coll immutable parallel hash map */ object ParHashMap extends ParMapFactory[ParHashMap] { diff --git a/src/library/scala/collection/parallel/immutable/ParHashSet.scala b/src/library/scala/collection/parallel/immutable/ParHashSet.scala index 084637c5dc..d1899601d7 100644 --- a/src/library/scala/collection/parallel/immutable/ParHashSet.scala +++ b/src/library/scala/collection/parallel/immutable/ParHashSet.scala @@ -38,7 +38,7 @@ import collection.parallel.Task * @see [[http://docs.scala-lang.org/overviews/parallel-collections/concrete-parallel-collections.html#parallel_hash_tries Scala's Parallel Collections Library overview]] * section on Parallel Hash Tries for more information. * - * @define Coll immutable.ParHashSet + * @define Coll `immutable.ParHashSet` * @define coll immutable parallel hash set */ @SerialVersionUID(1L) @@ -118,7 +118,7 @@ self => /** $factoryInfo - * @define Coll immutable.ParHashSet + * @define Coll `immutable.ParHashSet` * @define coll immutable parallel hash set */ object ParHashSet extends ParSetFactory[ParHashSet] { diff --git a/src/library/scala/collection/parallel/immutable/ParNumericRange.scala.disabled b/src/library/scala/collection/parallel/immutable/ParNumericRange.scala.disabled index fb411ec0ac..04bc8b8d29 100644 --- a/src/library/scala/collection/parallel/immutable/ParNumericRange.scala.disabled +++ b/src/library/scala/collection/parallel/immutable/ParNumericRange.scala.disabled @@ -29,7 +29,7 @@ import scala.collection.parallel.ParIterableIterator * @author Aleksandar Prokopec * @since 2.9 * - * @define Coll immutable.ParRange + * @define Coll `immutable.ParRange` * @define coll immutable parallel range */ @SerialVersionUID(1L) diff --git a/src/library/scala/collection/parallel/immutable/ParRange.scala b/src/library/scala/collection/parallel/immutable/ParRange.scala index 277fd5fdd3..9553704caa 100644 --- a/src/library/scala/collection/parallel/immutable/ParRange.scala +++ b/src/library/scala/collection/parallel/immutable/ParRange.scala @@ -28,7 +28,7 @@ import scala.collection.Iterator * @see [[http://docs.scala-lang.org/overviews/parallel-collections/concrete-parallel-collections.html#parallel_range Scala's Parallel Collections Library overview]] * section on `ParRange` for more information. * - * @define Coll immutable.ParRange + * @define Coll `immutable.ParRange` * @define coll immutable parallel range */ @SerialVersionUID(1L) diff --git a/src/library/scala/collection/parallel/immutable/ParSeq.scala b/src/library/scala/collection/parallel/immutable/ParSeq.scala index bf3d3a5aa8..dde6533c82 100644 --- a/src/library/scala/collection/parallel/immutable/ParSeq.scala +++ b/src/library/scala/collection/parallel/immutable/ParSeq.scala @@ -24,7 +24,7 @@ import scala.collection.GenSeq /** An immutable variant of `ParSeq`. * - * @define Coll mutable.ParSeq + * @define Coll `mutable.ParSeq` * @define coll mutable parallel sequence */ trait ParSeq[+T] @@ -40,7 +40,7 @@ extends collection/*.immutable*/.GenSeq[T] /** $factoryInfo - * @define Coll mutable.ParSeq + * @define Coll `mutable.ParSeq` * @define coll mutable parallel sequence */ object ParSeq extends ParFactory[ParSeq] { diff --git a/src/library/scala/collection/parallel/immutable/ParSet.scala b/src/library/scala/collection/parallel/immutable/ParSet.scala index d64858ed10..40429280ac 100644 --- a/src/library/scala/collection/parallel/immutable/ParSet.scala +++ b/src/library/scala/collection/parallel/immutable/ParSet.scala @@ -16,7 +16,7 @@ import scala.collection.parallel.Combiner /** An immutable variant of `ParSet`. * - * @define Coll mutable.ParSet + * @define Coll `mutable.ParSet` * @define coll mutable parallel set */ trait ParSet[T] @@ -38,7 +38,7 @@ self => } /** $factoryInfo - * @define Coll mutable.ParSet + * @define Coll `mutable.ParSet` * @define coll mutable parallel set */ object ParSet extends ParSetFactory[ParSet] { diff --git a/src/library/scala/collection/parallel/immutable/ParVector.scala b/src/library/scala/collection/parallel/immutable/ParVector.scala index 8baa84b77c..1ece663a1d 100644 --- a/src/library/scala/collection/parallel/immutable/ParVector.scala +++ b/src/library/scala/collection/parallel/immutable/ParVector.scala @@ -37,7 +37,7 @@ import immutable.VectorIterator * @see [[http://docs.scala-lang.org/overviews/parallel-collections/concrete-parallel-collections.html#parallel_vector Scala's Parallel Collections Library overview]] * section on `ParVector` for more information. * - * @define Coll immutable.ParVector + * @define Coll `immutable.ParVector` * @define coll immutable parallel vector */ class ParVector[+T](private[this] val vector: Vector[T]) @@ -86,7 +86,7 @@ extends ParSeq[T] /** $factoryInfo - * @define Coll immutable.ParVector + * @define Coll `immutable.ParVector` * @define coll immutable parallel vector */ object ParVector extends ParFactory[ParVector] { diff --git a/src/library/scala/collection/parallel/mutable/ParArray.scala b/src/library/scala/collection/parallel/mutable/ParArray.scala index 92ba701f7c..29d84408db 100644 --- a/src/library/scala/collection/parallel/mutable/ParArray.scala +++ b/src/library/scala/collection/parallel/mutable/ParArray.scala @@ -49,7 +49,7 @@ import scala.collection.GenTraversableOnce * @see [[http://docs.scala-lang.org/overviews/parallel-collections/concrete-parallel-collections.html#parallel_array Scala's Parallel Collections Library overview]] * section on `ParArray` for more information. * - * @define Coll ParArray + * @define Coll `ParArray` * @define coll parallel array * */ @@ -685,7 +685,7 @@ self => /** $factoryInfo - * @define Coll mutable.ParArray + * @define Coll `mutable.ParArray` * @define coll parallel array */ object ParArray extends ParFactory[ParArray] { diff --git a/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala b/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala index 35c748916c..d0c7f6050e 100644 --- a/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala +++ b/src/library/scala/collection/parallel/mutable/ParFlatHashTable.scala @@ -15,7 +15,7 @@ import collection.parallel.IterableSplitter * * @tparam T type of the elements in the $coll. * @define coll table - * @define Coll flat hash table + * @define Coll `ParFlatHashTable` * * @author Aleksandar Prokopec */ diff --git a/src/library/scala/collection/parallel/mutable/ParHashMap.scala b/src/library/scala/collection/parallel/mutable/ParHashMap.scala index 23b23d55a1..05b3f89fa1 100644 --- a/src/library/scala/collection/parallel/mutable/ParHashMap.scala +++ b/src/library/scala/collection/parallel/mutable/ParHashMap.scala @@ -28,7 +28,7 @@ import collection.parallel.Task * * @tparam T type of the elements in the parallel hash map * - * @define Coll ParHashMap + * @define Coll `ParHashMap` * @define coll parallel hash map * * @author Aleksandar Prokopec @@ -141,7 +141,7 @@ self => /** $factoryInfo - * @define Coll mutable.ParHashMap + * @define Coll `mutable.ParHashMap` * @define coll parallel hash map */ object ParHashMap extends ParMapFactory[ParHashMap] { diff --git a/src/library/scala/collection/parallel/mutable/ParHashSet.scala b/src/library/scala/collection/parallel/mutable/ParHashSet.scala index 4e9a38c13f..783f8dce77 100644 --- a/src/library/scala/collection/parallel/mutable/ParHashSet.scala +++ b/src/library/scala/collection/parallel/mutable/ParHashSet.scala @@ -25,7 +25,7 @@ import collection.parallel.Task * * @tparam T type of the elements in the $coll. * - * @define Coll ParHashSet + * @define Coll `ParHashSet` * @define coll parallel hash set * * @author Aleksandar Prokopec @@ -104,7 +104,7 @@ extends ParSet[T] /** $factoryInfo - * @define Coll mutable.ParHashSet + * @define Coll `mutable.ParHashSet` * @define coll parallel hash set */ object ParHashSet extends ParSetFactory[ParHashSet] { diff --git a/src/library/scala/collection/parallel/mutable/ParSeq.scala b/src/library/scala/collection/parallel/mutable/ParSeq.scala index a48ba48d56..f46b369494 100644 --- a/src/library/scala/collection/parallel/mutable/ParSeq.scala +++ b/src/library/scala/collection/parallel/mutable/ParSeq.scala @@ -26,7 +26,7 @@ import scala.collection.GenSeq /** A mutable variant of `ParSeq`. * - * @define Coll mutable.ParSeq + * @define Coll `mutable.ParSeq` * @define coll mutable parallel sequence */ trait ParSeq[T] extends collection/*.mutable*/.GenSeq[T] // was: collection.mutable.Seq[T] @@ -47,7 +47,7 @@ self => /** $factoryInfo - * @define Coll mutable.ParSeq + * @define Coll `mutable.ParSeq` * @define coll mutable parallel sequence */ object ParSeq extends ParFactory[ParSeq] { diff --git a/src/library/scala/collection/parallel/mutable/ParSet.scala b/src/library/scala/collection/parallel/mutable/ParSet.scala index 1d295fd5fe..6da4c8a7bc 100644 --- a/src/library/scala/collection/parallel/mutable/ParSet.scala +++ b/src/library/scala/collection/parallel/mutable/ParSet.scala @@ -21,7 +21,7 @@ import scala.collection.GenSet /** A mutable variant of `ParSet`. * - * @define Coll mutable.ParSet + * @define Coll `mutable.ParSet` * @define coll mutable parallel set * * @author Aleksandar Prokopec @@ -41,7 +41,7 @@ self => /** $factoryInfo - * @define Coll mutable.ParSet + * @define Coll `mutable.ParSet` * @define coll mutable parallel set */ object ParSet extends ParSetFactory[ParSet] { diff --git a/src/library/scala/reflect/api/Types.scala b/src/library/scala/reflect/api/Types.scala index e06bb37cba..5c7563c2c5 100755 --- a/src/library/scala/reflect/api/Types.scala +++ b/src/library/scala/reflect/api/Types.scala @@ -464,10 +464,10 @@ trait Types { self: Universe => def unapply(tpe: AnnotatedType): Option[(List[AnnotationInfo], Type, Symbol)] } - /** The least upper bound wrt <:< of a list of types */ + /** The least upper bound of a list of types, as determined by `<:<`. */ def lub(xs: List[Type]): Type - /** The greatest lower bound wrt <:< of a list of types */ + /** The greatest lower bound of a list of types, as determined by `<:<`. */ def glb(ts: List[Type]): Type // Creators --------------------------------------------------------------- @@ -515,15 +515,17 @@ trait Types { self: Universe => /** A creator for existential types. This generates: * - * tpe1 where { tparams } + * {{{ + * tpe1 where { tparams } + * }}} * - * where `tpe1` is the result of extrapolating `tpe` wrt to `tparams`. + * where `tpe1` is the result of extrapolating `tpe` with regard to `tparams`. * Extrapolating means that type variables in `tparams` occurring * in covariant positions are replaced by upper bounds, (minus any * SingletonClass markers), type variables in `tparams` occurring in * contravariant positions are replaced by upper bounds, provided the - * resulting type is legal wrt to stability, and does not contain any type - * variable in `tparams`. + * resulting type is legal with regard to stability, and does not contain + * any type variable in `tparams`. * * The abstraction drops all type parameters that are not directly or * indirectly referenced by type `tpe1`. If there are no remaining type -- cgit v1.2.3 From b6e989fbf63c9f47acfb54175241b42fdfbfe51b Mon Sep 17 00:00:00 2001 From: Vlad Ureche Date: Thu, 3 May 2012 02:54:27 +0200 Subject: Fixes the backticks in use case signature crash Suggested by Simon in https://groups.google.com/forum/?hl=en&fromgroups#!topic/scala-internals/z7s1CCRCz74 Now it eliminates backticks and gracefully bails out with an error message when it can't remove the wiki syntax. --- src/compiler/scala/tools/nsc/ast/DocComments.scala | 25 ++++++++++++++++----- test/scaladoc/run/usecase-var-expansion.check | 4 ++++ test/scaladoc/run/usecase-var-expansion.scala | 26 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 test/scaladoc/run/usecase-var-expansion.check create mode 100644 test/scaladoc/run/usecase-var-expansion.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/ast/DocComments.scala b/src/compiler/scala/tools/nsc/ast/DocComments.scala index b3ed446563..028c5741c9 100755 --- a/src/compiler/scala/tools/nsc/ast/DocComments.scala +++ b/src/compiler/scala/tools/nsc/ast/DocComments.scala @@ -383,7 +383,7 @@ trait DocComments { self: Global => } // !!! todo: inherit from Comment? - case class DocComment(raw: String, pos: Position = NoPosition) { + case class DocComment(raw: String, pos: Position = NoPosition, codePos: Position = NoPosition) { /** Returns: * template: the doc comment minus all @define and @usecase sections @@ -412,7 +412,7 @@ trait DocComments { self: Global => val comment = "/** " + raw.substring(commentStart, end) + "*/" val commentPos = subPos(commentStart, end) - UseCase(DocComment(comment, commentPos), code, codePos) + UseCase(DocComment(comment, commentPos, codePos), code, codePos) } private def subPos(start: Int, end: Int) = @@ -461,7 +461,18 @@ trait DocComments { self: Global => findIn(classes ::: List(pkgs.head, definitions.RootClass)) } - def getType(str: String): Type = { + def getType(_str: String, variable: String): Type = { + /* + * work around the backticks issue suggested by Simon in + * https://groups.google.com/forum/?hl=en&fromgroups#!topic/scala-internals/z7s1CCRCz74 + * ideally, we'd have a removeWikiSyntax method in the CommentFactory to completely eliminate the wiki markup + */ + val str = + if (_str.length >= 2 && _str.startsWith("`") && _str.endsWith("`")) + _str.substring(1, _str.length - 2) + else + _str + def getParts(start: Int): List[String] = { val end = skipIdent(str, start) if (end == start) List() @@ -471,7 +482,11 @@ trait DocComments { self: Global => } } val parts = getParts(0) - assert(parts.nonEmpty, "parts is empty '" + str + "' in site " + site) + if (parts.isEmpty) { + reporter.error(comment.codePos, "Incorrect variable expansion for " + variable + " in use case. Does the " + + "variable expand to wiki syntax when documenting " + site + "?") + return ErrorType + } val partnames = (parts.init map newTermName) :+ newTypeName(parts.last) val (start, rest) = parts match { case "this" :: _ => (site.thisType, partnames.tail) @@ -490,7 +505,7 @@ trait DocComments { self: Global => for (alias <- aliases) yield lookupVariable(alias.name.toString.substring(1), site) match { case Some(repl) => - val tpe = getType(repl.trim) + val tpe = getType(repl.trim, alias.name.toString) if (tpe != NoType) tpe else { val alias1 = alias.cloneSymbol(definitions.RootClass, alias.rawflags, newTypeName(repl)) diff --git a/test/scaladoc/run/usecase-var-expansion.check b/test/scaladoc/run/usecase-var-expansion.check new file mode 100644 index 0000000000..3faa4735c0 --- /dev/null +++ b/test/scaladoc/run/usecase-var-expansion.check @@ -0,0 +1,4 @@ +newSource:8: error: Incorrect variable expansion for $Coll in use case. Does the variable expand to wiki syntax when documenting class Test2? + * @usecase def foo: $Coll[T] + ^ +Done. diff --git a/test/scaladoc/run/usecase-var-expansion.scala b/test/scaladoc/run/usecase-var-expansion.scala new file mode 100644 index 0000000000..e86ea4a835 --- /dev/null +++ b/test/scaladoc/run/usecase-var-expansion.scala @@ -0,0 +1,26 @@ +import scala.tools.nsc.doc.model._ +import scala.tools.partest.ScaladocModelTest +import language._ + +object Test extends ScaladocModelTest { + + override def code = """ + /** + * @define Coll `Test` + */ + class Test[T] { + /** + * member $Coll + * @usecase def foo: $Coll[T] + * usecase $Coll + */ + def foo(implicit err: String): Test[T] = sys.error(err) + } + + /** @define Coll {{{some `really` < !! >> invalid $$$ thing}}} */ + class Test2[T] extends Test[Int] + """ + + def scaladocSettings = "" + def testModel(root: Package) = () +} -- cgit v1.2.3 From 6300c3033e7b852c6cbef332af6085aac6150a70 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Wed, 2 May 2012 14:39:13 -0700 Subject: Eliminating reflective calls. Frobbed knobs and made little traits until all relevant looking reflective calls were gone. --- src/compiler/scala/reflect/internal/Required.scala | 5 +--- .../scala/reflect/internal/SymbolTable.scala | 27 ++++++++++------------ src/compiler/scala/reflect/internal/Types.scala | 7 +++--- .../scala/reflect/runtime/AbstractFile.scala | 11 +++++---- src/compiler/scala/tools/nsc/io/AbstractFile.scala | 3 ++- .../scala/tools/nsc/util/WeakHashSet.scala | 3 ++- .../scala/collection/generic/Clearable.scala | 26 +++++++++++++++++++++ .../scala/collection/generic/Growable.scala | 4 ++-- src/library/scala/reflect/api/RequiredFile.scala | 7 ++++++ 9 files changed, 62 insertions(+), 31 deletions(-) create mode 100644 src/library/scala/collection/generic/Clearable.scala create mode 100644 src/library/scala/reflect/api/RequiredFile.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/Required.scala b/src/compiler/scala/reflect/internal/Required.scala index ba6d65a306..6d146354a3 100644 --- a/src/compiler/scala/reflect/internal/Required.scala +++ b/src/compiler/scala/reflect/internal/Required.scala @@ -5,10 +5,7 @@ import settings.MutableSettings trait Required { self: SymbolTable => - type AbstractFileType >: Null <: { - def path: String - def canonicalPath: String - } + type AbstractFileType >: Null <: api.RequiredFile def picklerPhase: Phase diff --git a/src/compiler/scala/reflect/internal/SymbolTable.scala b/src/compiler/scala/reflect/internal/SymbolTable.scala index 9158c2a4d4..aa60fb4aba 100644 --- a/src/compiler/scala/reflect/internal/SymbolTable.scala +++ b/src/compiler/scala/reflect/internal/SymbolTable.scala @@ -280,16 +280,8 @@ abstract class SymbolTable extends api.Universe object perRunCaches { import java.lang.ref.WeakReference import scala.runtime.ScalaRunTime.stringOf + import scala.collection.generic.Clearable - import language.reflectiveCalls - - // We can allow ourselves a structural type, these methods - // amount to a few calls per run at most. This does suggest - // a "Clearable" trait may be useful. - private type Clearable = { - def size: Int - def clear(): Unit - } // Weak references so the garbage collector will take care of // letting us know when a cache is really out of commission. private val caches = mutable.HashSet[WeakReference[Clearable]]() @@ -298,10 +290,14 @@ abstract class SymbolTable extends api.Universe println(caches.size + " structures are in perRunCaches.") caches.zipWithIndex foreach { case (ref, index) => val cache = ref.get() - println("(" + index + ")" + ( - if (cache == null) " has been collected." - else " has " + cache.size + " entries:\n" + stringOf(cache) - )) + cache match { + case xs: Traversable[_] => + println("(" + index + ")" + ( + if (cache == null) " has been collected." + else " has " + xs.size + " entries:\n" + stringOf(xs) + )) + case _ => + } } } // if (settings.debug.value) { @@ -315,8 +311,9 @@ abstract class SymbolTable extends api.Universe def clearAll() = { if (settings.debug.value) { - val size = caches flatMap (ref => Option(ref.get)) map (_.size) sum; - log("Clearing " + caches.size + " caches totalling " + size + " entries.") + // val size = caches flatMap (ref => Option(ref.get)) map (_.size) sum; + log("Clearing " + caches.size + " caches.") + // totalling " + size + " entries.") } caches foreach { ref => val cache = ref.get() diff --git a/src/compiler/scala/reflect/internal/Types.scala b/src/compiler/scala/reflect/internal/Types.scala index b8346a663d..165f8119ce 100644 --- a/src/compiler/scala/reflect/internal/Types.scala +++ b/src/compiler/scala/reflect/internal/Types.scala @@ -6,7 +6,8 @@ package scala.reflect package internal -import scala.collection.{ mutable, immutable } +import scala.collection.{ mutable, immutable, generic } +import generic.Clearable import scala.ref.WeakReference import mutable.ListBuffer import Flags._ @@ -115,7 +116,7 @@ trait Types extends api.Types { self: SymbolTable => protected def newUndoLog = new UndoLog - class UndoLog { + class UndoLog extends Clearable { private type UndoPairs = List[(TypeVar, TypeConstraint)] private var log: UndoPairs = List() @@ -139,7 +140,7 @@ trait Types extends api.Types { self: SymbolTable => log ::= ((tv, tv.constr.cloneInternal)) } - private[scala] def clear() { + def clear() { if (settings.debug.value) self.log("Clearing " + log.size + " entries from the undoLog.") diff --git a/src/compiler/scala/reflect/runtime/AbstractFile.scala b/src/compiler/scala/reflect/runtime/AbstractFile.scala index bf3b47298b..414bba020b 100644 --- a/src/compiler/scala/reflect/runtime/AbstractFile.scala +++ b/src/compiler/scala/reflect/runtime/AbstractFile.scala @@ -1,6 +1,7 @@ -package scala.reflect.runtime +package scala.reflect +package runtime -class AbstractFile(val jfile: java.io.File) { - def path: String = jfile.getPath() - def canonicalPath: String = jfile.getCanonicalPath() -} \ No newline at end of file +class AbstractFile(val jfile: java.io.File) extends api.RequiredFile { + def path: String = jfile.getPath() + def canonicalPath: String = jfile.getCanonicalPath() +} diff --git a/src/compiler/scala/tools/nsc/io/AbstractFile.scala b/src/compiler/scala/tools/nsc/io/AbstractFile.scala index b51cf1228c..deb914f806 100644 --- a/src/compiler/scala/tools/nsc/io/AbstractFile.scala +++ b/src/compiler/scala/tools/nsc/io/AbstractFile.scala @@ -10,6 +10,7 @@ package io import java.io.{ FileOutputStream, IOException, InputStream, OutputStream, BufferedOutputStream } import java.net.URL import scala.collection.mutable.ArrayBuffer +import scala.reflect.api.RequiredFile /** * @author Philippe Altherr @@ -81,7 +82,7 @@ object AbstractFile { * global.settings.encoding.value. *

*/ -abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] { +abstract class AbstractFile extends AnyRef with RequiredFile with Iterable[AbstractFile] { /** Returns the name of this abstract file. */ def name: String diff --git a/src/compiler/scala/tools/nsc/util/WeakHashSet.scala b/src/compiler/scala/tools/nsc/util/WeakHashSet.scala index 6a10422b00..5bbb766e21 100644 --- a/src/compiler/scala/tools/nsc/util/WeakHashSet.scala +++ b/src/compiler/scala/tools/nsc/util/WeakHashSet.scala @@ -4,6 +4,7 @@ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.collection.mutable.Builder import scala.collection.mutable.SetBuilder +import scala.collection.generic.Clearable import scala.runtime.AbstractFunction1 /** A bare-bones implementation of a mutable `Set` that uses weak references @@ -12,7 +13,7 @@ import scala.runtime.AbstractFunction1 * This implementation offers only add/remove/test operations, * therefore it does not fulfill the contract of Scala collection sets. */ -class WeakHashSet[T <: AnyRef] extends AbstractFunction1[T, Boolean] { +class WeakHashSet[T <: AnyRef] extends AbstractFunction1[T, Boolean] with Clearable { private val underlying = mutable.HashSet[WeakReferenceWithEquals[T]]() /** Add the given element to this set. */ diff --git a/src/library/scala/collection/generic/Clearable.scala b/src/library/scala/collection/generic/Clearable.scala new file mode 100644 index 0000000000..6c8d9558b0 --- /dev/null +++ b/src/library/scala/collection/generic/Clearable.scala @@ -0,0 +1,26 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.collection +package generic + +/** This trait forms part of collections that can be cleared + * with a clear() call. + * + * @author Paul Phillips + * @version 2.10 + * @since 2.10 + * @define coll clearable collection + * @define Coll `Clearable` + */ +trait Clearable { + /** Clears the $coll's contents. After this operation, the + * $coll is empty. + */ + def clear(): Unit +} diff --git a/src/library/scala/collection/generic/Growable.scala b/src/library/scala/collection/generic/Growable.scala index baf332fcd8..d6a263af2f 100644 --- a/src/library/scala/collection/generic/Growable.scala +++ b/src/library/scala/collection/generic/Growable.scala @@ -22,7 +22,7 @@ package generic * @define add add * @define Add add */ -trait Growable[-A] { +trait Growable[-A] extends Clearable { /** ${Add}s a single element to this $coll. * @@ -50,5 +50,5 @@ trait Growable[-A] { /** Clears the $coll's contents. After this operation, the * $coll is empty. */ - def clear() + def clear(): Unit } diff --git a/src/library/scala/reflect/api/RequiredFile.scala b/src/library/scala/reflect/api/RequiredFile.scala new file mode 100644 index 0000000000..4a54595940 --- /dev/null +++ b/src/library/scala/reflect/api/RequiredFile.scala @@ -0,0 +1,7 @@ +package scala.reflect +package api + +trait RequiredFile { + def path: String + def canonicalPath: String +} -- cgit v1.2.3 From aabe71f989f023d64b6c52680485e4cacb4e88b9 Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Wed, 2 May 2012 10:19:05 -0700 Subject: SI-5720: Qual block doesn't update sym owner A one-line change to blockWithQualifier. The symptom is undefined tmp var symbols in the backend; lamba lift thinks the tmp var is free and adds it to anonfun ctors. --- .../tools/nsc/typechecker/NamesDefaults.scala | 2 + test/files/pos/t5720-ownerous.scala | 56 ++++++++++++++++++++++ test/files/pos/t5727.scala | 31 ++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 test/files/pos/t5720-ownerous.scala create mode 100644 test/files/pos/t5727.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala index 898a9fee9f..90e388c30a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala +++ b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala @@ -155,6 +155,8 @@ trait NamesDefaults { self: Analyzer => val sym = blockTyper.context.owner.newValue(unit.freshTermName("qual$"), qual.pos) setInfo qual.tpe blockTyper.context.scope enter sym val vd = atPos(sym.pos)(ValDef(sym, qual) setType NoType) + // it stays in Vegas: SI-5720, SI-5727 + qual changeOwner (blockTyper.context.owner -> sym) var baseFunTransformed = atPos(baseFun.pos.makeTransparent) { // don't use treeCopy: it would assign opaque position. diff --git a/test/files/pos/t5720-ownerous.scala b/test/files/pos/t5720-ownerous.scala new file mode 100644 index 0000000000..3a12499612 --- /dev/null +++ b/test/files/pos/t5720-ownerous.scala @@ -0,0 +1,56 @@ + +/* + * The block under qual$1 must be owned by it. + * In the sample bug, the first default arg generates x$4, + * the second default arg generates qual$1, hence the maximal + * minimization. + * + def model: C.this.M = { + val qual$1: C.this.M = scala.Option.apply[C.this.M]({ + val x$1: lang.this.String("foo") = "foo"; + val x$2: String = C.this.M.apply$default$2("foo"); + C.this.M.apply("foo")(x$2) +}).getOrElse[C.this.M]({ + val x$3: lang.this.String("bar") = "bar"; + val x$4: String = C.this.M.apply$default$2("bar"); + C.this.M.apply("bar")(x$4) + }); + val x$5: lang.this.String("baz") = "baz"; + val x$6: String = qual$1.copy$default$2("baz"); + qual$1.copy("baz")(x$6) + } + */ +class C { + case class M(currentUser: String = "anon")(val message: String = "empty") + val m = M("foo")() + + // reported + //def model = Option(M("foo")()).getOrElse(M("bar")()).copy(currentUser = "")() + + // the bug + def model = Option(m).getOrElse(M("bar")()).copy("baz")() + + // style points for this version + def modish = ((null: Option[M]) getOrElse new M()()).copy()() + + // various simplifications are too simple + case class N(currentUser: String = "anon") + val n = N("fun") + def nudel = Option(n).getOrElse(N()).copy() +} + +object Test { + def main(args: Array[String]) { + val c = new C + println(c.model.currentUser) + println(c.model.message) + } +} +/* +symbol value x$4$1 does not exist in badcopy.C.model +at scala.reflect.internal.SymbolTable.abort(SymbolTable.scala:45) +at scala.tools.nsc.Global.abort(Global.scala:202) +at scala.tools.nsc.backend.icode.GenICode$ICodePhase.liftedTree2$1(GenICode.scala:998) +at scala.tools.nsc.backend.icode.GenICode$ICodePhase.scala$tools$nsc$backend$icode$GenICode$ICodePhase$$genLoad(GenICode.scala:992) +*/ + diff --git a/test/files/pos/t5727.scala b/test/files/pos/t5727.scala new file mode 100644 index 0000000000..e091d827b4 --- /dev/null +++ b/test/files/pos/t5727.scala @@ -0,0 +1,31 @@ + +/* + * We like operators, bar none. + */ +object Test { + + trait SomeInfo + case object NoInfo extends SomeInfo + + sealed abstract class Res[+T] + case object NotRes extends Res[Nothing] + + + abstract class Base[+T] { + def apply(f: String): Res[T] + // 'i' crashes the compiler, similarly if we use currying + //def |[U >: T](a: => Base[U], i: SomeInfo = NoInfo): Base[U] = null + def bar[U >: T](a: => Base[U], i: SomeInfo = NoInfo): Base[U] = null + } + + implicit def fromStringToBase(a: String): Base[String] = new Base[String] { def apply(in: String) = NotRes } + + // bug + //def Sample: Base[Any] = ( rep("foo" | "bar") | "sth") + def Sample: Base[Any] = ( rep("foo" bar "bar") bar "sth") + + def rep[T](p: => Base[T]): Base[T] = null // whatever + + def main(args: Array[String]) { + } +} -- cgit v1.2.3 From 7a5aaa9e23a98d60343cc0c4411b3fc395faa3ab Mon Sep 17 00:00:00 2001 From: Adriaan Moors Date: Thu, 3 May 2012 11:09:13 +0200 Subject: SI-5703: normalize refined types more to improve Array[T] java-interop with T[], normalize Object with Object{} to Object fix #SI-5688 by flattening refined types in parents updated check files to reflect flattening of refined types and updated position for refined types --- src/compiler/scala/reflect/internal/Types.scala | 31 ++++++++++----- .../nsc/symtab/classfile/ClassfileParser.scala | 6 ++- .../scala/tools/nsc/typechecker/Namers.scala | 5 +++ .../tools/nsc/typechecker/PatternMatching.scala | 2 +- test/files/neg/override.check | 2 +- test/files/pos/t5703/Base.java | 3 ++ test/files/pos/t5703/Impl.scala | 3 ++ test/files/run/existentials3-old.check | 44 +++++++++++----------- test/files/run/t5688.check | 1 + test/files/run/t5688.scala | 23 +++++++++++ 10 files changed, 86 insertions(+), 34 deletions(-) create mode 100644 test/files/pos/t5703/Base.java create mode 100644 test/files/pos/t5703/Impl.scala create mode 100644 test/files/run/t5688.check create mode 100644 test/files/run/t5688.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/reflect/internal/Types.scala b/src/compiler/scala/reflect/internal/Types.scala index 165f8119ce..799671f9e3 100644 --- a/src/compiler/scala/reflect/internal/Types.scala +++ b/src/compiler/scala/reflect/internal/Types.scala @@ -1610,12 +1610,26 @@ trait Types extends api.Types { self: SymbolTable => override def typeConstructor = copyRefinedType(this, parents map (_.typeConstructor), decls) - /* MO to AM: This is probably not correct - * If they are several higher-kinded parents with different bounds we need - * to take the intersection of their bounds - */ - override def normalize = { - if (isHigherKinded) { + final override def normalize: Type = + if (phase.erasedTypes) normalizeImpl + else { + if (normalized eq null) normalized = normalizeImpl + normalized + } + + private var normalized: Type = _ + private def normalizeImpl = { + // TODO see comments around def intersectionType and def merge + def flatten(tps: List[Type]): List[Type] = tps flatMap { case RefinedType(parents, ds) if ds.isEmpty => flatten(parents) case tp => List(tp) } + val flattened = flatten(parents).distinct + if (decls.isEmpty && flattened.tail.isEmpty) { + flattened.head + } else if (flattened != parents) { + refinedType(flattened, if (typeSymbol eq NoSymbol) NoSymbol else typeSymbol.owner, decls, NoPosition) + } else if (isHigherKinded) { + // MO to AM: This is probably not correct + // If they are several higher-kinded parents with different bounds we need + // to take the intersection of their bounds typeFun( typeParams, RefinedType( @@ -1625,8 +1639,7 @@ trait Types extends api.Types { self: SymbolTable => }, decls, typeSymbol)) - } - else super.normalize + } else super.normalize } /** A refined type P1 with ... with Pn { decls } is volatile if @@ -3322,7 +3335,7 @@ trait Types extends api.Types { self: SymbolTable => if (phase.erasedTypes) if (parents.isEmpty) ObjectClass.tpe else parents.head else { - val clazz = owner.newRefinementClass(NoPosition) + val clazz = owner.newRefinementClass(pos) // TODO: why were we passing in NoPosition instead of pos? val result = RefinedType(parents, decls, clazz) clazz.setInfo(result) result diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index b51c8baa31..739060d02e 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -774,8 +774,12 @@ abstract class ClassfileParser { // make unbounded Array[T] where T is a type variable into Array[T with Object] // (this is necessary because such arrays have a representation which is incompatible // with arrays of primitive types. - if (elemtp.typeSymbol.isAbstractType && !(elemtp <:< definitions.ObjectClass.tpe)) + // NOTE that the comparison to Object only works for abstract types bounded by classes that are strict subclasses of Object + // if the bound is exactly Object, it will have been converted to Any, and the comparison will fail + // see also RestrictJavaArraysMap (when compiling java sources directly) + if (elemtp.typeSymbol.isAbstractType && !(elemtp <:< definitions.ObjectClass.tpe)) { elemtp = intersectionType(List(elemtp, definitions.ObjectClass.tpe)) + } definitions.arrayType(elemtp) case '(' => diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index 45f7d7e618..4e7dac890b 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -1347,6 +1347,11 @@ trait Namers extends MethodSynthesis { /** Convert Java generic array type T[] to (T with Object)[] * (this is necessary because such arrays have a representation which is incompatible * with arrays of primitive types.) + * + * @note the comparison to Object only works for abstract types bounded by classes that are strict subclasses of Object + * if the bound is exactly Object, it will have been converted to Any, and the comparison will fail + * + * see also sigToType */ private object RestrictJavaArraysMap extends TypeMap { def apply(tp: Type): Type = tp match { diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index c3a7f2bbc5..61e02edaff 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -931,7 +931,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL // implements the run-time aspects of (§8.2) (typedPattern has already done the necessary type transformations) // TODO: normalize construction, which yields a combination of a EqualityTestTreeMaker (when necessary) and a TypeTestTreeMaker case class TypeAndEqualityTestTreeMaker(prevBinder: Symbol, patBinder: Symbol, pt: Type, pos: Position) extends CondTreeMaker { - val nextBinderTp = glb(List(patBinder.info.widen, pt)) + val nextBinderTp = glb(List(patBinder.info.widen, pt)).normalize /** Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms: - A reference to a class C, p.C, or T#C. diff --git a/test/files/neg/override.check b/test/files/neg/override.check index 0336fb2b11..fc152cb3b1 100644 --- a/test/files/neg/override.check +++ b/test/files/neg/override.check @@ -1,5 +1,5 @@ override.scala:9: error: overriding type T in trait A with bounds >: Int <: Int; type T in trait B with bounds >: String <: String has incompatible type lazy val x : A with B = x - ^ + ^ one error found diff --git a/test/files/pos/t5703/Base.java b/test/files/pos/t5703/Base.java new file mode 100644 index 0000000000..fa75cc3bdd --- /dev/null +++ b/test/files/pos/t5703/Base.java @@ -0,0 +1,3 @@ +public abstract class Base { + public abstract void func(Params[] params); +} \ No newline at end of file diff --git a/test/files/pos/t5703/Impl.scala b/test/files/pos/t5703/Impl.scala new file mode 100644 index 0000000000..ee22d8fb4b --- /dev/null +++ b/test/files/pos/t5703/Impl.scala @@ -0,0 +1,3 @@ +class Implementation extends Base[Object] { + def func(params: Array[Object]): Unit = {} +} \ No newline at end of file diff --git a/test/files/run/existentials3-old.check b/test/files/run/existentials3-old.check index e166e53ba8..72abfac637 100644 --- a/test/files/run/existentials3-old.check +++ b/test/files/run/existentials3-old.check @@ -1,22 +1,22 @@ -_ <: scala.runtime.AbstractFunction0[_ <: Object with Test$ToS with scala.Product with scala.Serializable] with scala.Serializable with java.lang.Object -_ <: Object with Test$ToS with scala.Product with scala.Serializable -Object with Test$ToS -Object with Test$ToS -Object with Test$ToS -scala.Function0[Object with Test$ToS] -scala.Function0[Object with Test$ToS] -_ <: Object with _ <: Object with Object with Test$ToS -_ <: Object with _ <: Object with _ <: Object with Test$ToS -scala.collection.immutable.List[Object with scala.collection.Seq[Int]] -scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] -_ <: scala.runtime.AbstractFunction0[_ <: Object with Test$ToS with scala.Product with scala.Serializable] with scala.Serializable with java.lang.Object -_ <: Object with Test$ToS with scala.Product with scala.Serializable -Object with Test$ToS -Object with Test$ToS -Object with Test$ToS -scala.Function0[Object with Test$ToS] -scala.Function0[Object with Test$ToS] -_ <: Object with _ <: Object with Object with Test$ToS -_ <: Object with _ <: Object with _ <: Object with Test$ToS -scala.collection.immutable.List[Object with scala.collection.Seq[Int]] -scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] +_ <: scala.runtime.AbstractFunction0[_ <: Object with Test$ToS with scala.Product with scala.Serializable] with scala.Serializable with java.lang.Object +_ <: Object with Test$ToS with scala.Product with scala.Serializable +Object with Test$ToS +Object with Test$ToS +Object with Test$ToS +scala.Function0[Object with Test$ToS] +scala.Function0[Object with Test$ToS] +_ <: Object with _ <: Object with Test$ToS +_ <: Object with _ <: Object with _ <: Object with Test$ToS +scala.collection.immutable.List[Object with scala.collection.Seq[Int]] +scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] +_ <: scala.runtime.AbstractFunction0[_ <: Object with Test$ToS with scala.Product with scala.Serializable] with scala.Serializable with java.lang.Object +_ <: Object with Test$ToS with scala.Product with scala.Serializable +Object with Test$ToS +Object with Test$ToS +Object with Test$ToS +scala.Function0[Object with Test$ToS] +scala.Function0[Object with Test$ToS] +_ <: Object with _ <: Object with Test$ToS +_ <: Object with _ <: Object with _ <: Object with Test$ToS +scala.collection.immutable.List[Object with scala.collection.Seq[Int]] +scala.collection.immutable.List[Object with scala.collection.Seq[_ <: Int]] diff --git a/test/files/run/t5688.check b/test/files/run/t5688.check new file mode 100644 index 0000000000..2c84f9e2ef --- /dev/null +++ b/test/files/run/t5688.check @@ -0,0 +1 @@ +Vector(ta, tb, tab) diff --git a/test/files/run/t5688.scala b/test/files/run/t5688.scala new file mode 100644 index 0000000000..f99bfb47d3 --- /dev/null +++ b/test/files/run/t5688.scala @@ -0,0 +1,23 @@ +object Test extends App { + trait T + + trait TA + trait TB + + class A extends T with TA + class B extends T with TB + class AB extends T with TA with TB + // Matching on _: TA with TB + + val li: Vector[T] = Vector(new A, new B, new AB) + + val matched = (for (l <- li) yield { + l match { + case _: TA with TB => "tab" + case _: TA => "ta" + case _: TB => "tb" + } + }) + + println(matched) +} \ No newline at end of file -- cgit v1.2.3 From 44797916bd4437729e1f13333eee7a2a2cb8ca58 Mon Sep 17 00:00:00 2001 From: Kato Kazuyoshi Date: Thu, 3 May 2012 23:44:48 +0900 Subject: Fix SI-4976 partially If a package have a package object, generate the package's "linearization" from the object. --- src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala | 14 +++++++++++--- test/scaladoc/resources/package-object-res.scala | 14 ++++++++++++++ test/scaladoc/run/package-object.check | 2 ++ test/scaladoc/run/package-object.scala | 15 +++++++++++++++ 4 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 test/scaladoc/resources/package-object-res.scala create mode 100644 test/scaladoc/run/package-object.check create mode 100644 test/scaladoc/run/package-object.scala (limited to 'src/compiler') diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala index a6728654cd..9062203dcd 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala @@ -231,9 +231,10 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { Some(makeType(RefinedType(tps, EmptyScope), inTpl)) } } - val linearization: List[(TemplateEntity, TypeEntity)] = { - sym.ancestors map { ancestor => - val typeEntity = makeType(sym.info.baseType(ancestor), this) + + protected def linearizationFromSymbol(symbol: Symbol) = { + symbol.ancestors map { ancestor => + val typeEntity = makeType(symbol.info.baseType(ancestor), this) val tmplEntity = makeTemplate(ancestor) match { case tmpl: DocTemplateImpl => tmpl registerSubClass this ; tmpl case tmpl => tmpl @@ -242,6 +243,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { } } + val linearization = linearizationFromSymbol(sym) def linearizationTemplates = linearization map { _._1 } def linearizationTypes = linearization map { _._2 } @@ -282,6 +284,12 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { abstract class PackageImpl(sym: Symbol, inTpl: => PackageImpl) extends DocTemplateImpl(sym, inTpl) with Package { override def inTemplate = inTpl override def toRoot: List[PackageImpl] = this :: inTpl.toRoot + override val linearization = { + val symbol = sym.info.members.find { + s => s.isPackageObject + } getOrElse sym + linearizationFromSymbol(symbol) + } val packages = members collect { case p: Package => p } } diff --git a/test/scaladoc/resources/package-object-res.scala b/test/scaladoc/resources/package-object-res.scala new file mode 100644 index 0000000000..17d5c0a499 --- /dev/null +++ b/test/scaladoc/resources/package-object-res.scala @@ -0,0 +1,14 @@ +/** This package have A and B. + */ +package test { + trait A { def hi = "hello" } + trait B { def bye = "bye!" } +} + +/** This package object extends A and B. + */ +package object test extends A with B { + override def hi = "good morning!" + override def bye = "good bye!" + protected def thank = "thank you!" +} diff --git a/test/scaladoc/run/package-object.check b/test/scaladoc/run/package-object.check new file mode 100644 index 0000000000..4297847e73 --- /dev/null +++ b/test/scaladoc/run/package-object.check @@ -0,0 +1,2 @@ +List((test.B,B), (test.A,A), (scala.AnyRef,AnyRef), (scala.Any,Any)) +Done. diff --git a/test/scaladoc/run/package-object.scala b/test/scaladoc/run/package-object.scala new file mode 100644 index 0000000000..fd36a8df7b --- /dev/null +++ b/test/scaladoc/run/package-object.scala @@ -0,0 +1,15 @@ +import scala.tools.nsc.doc.model._ +import scala.tools.partest.ScaladocModelTest +import language._ + +object Test extends ScaladocModelTest { + override def resourceFile = "package-object-res.scala" + override def scaladocSettings = "" + def testModel(root: Package) = { + import access._ + + val p = root._package("test") + println(p.linearization) + } +} + -- cgit v1.2.3