diff options
45 files changed, 2837 insertions, 1478 deletions
@@ -64,7 +64,6 @@ val scalaParserCombinatorsDep = withoutScalaLang("org.scala-lang.modules" %% "sc val scalaSwingDep = withoutScalaLang("org.scala-lang.modules" %% "scala-swing" % versionNumber("scala-swing")) val scalaXmlDep = withoutScalaLang("org.scala-lang.modules" %% "scala-xml" % versionNumber("scala-xml")) val partestDep = withoutScalaLang("org.scala-lang.modules" %% "scala-partest" % versionNumber("partest")) -val partestInterfaceDep = withoutScalaLang("org.scala-lang.modules" %% "scala-partest-interface" % "0.7.0") val junitDep = "junit" % "junit" % "4.11" val junitIntefaceDep = "com.novocode" % "junit-interface" % "0.11" % "test" val asmDep = "org.scala-lang.modules" % "scala-asm" % versionProps("scala-asm.version") @@ -548,7 +547,7 @@ lazy val test = project .settings(Defaults.itSettings: _*) .settings( publishArtifact := false, - libraryDependencies ++= Seq(asmDep, partestDep, scalaXmlDep, partestInterfaceDep, scalacheckDep), + libraryDependencies ++= Seq(asmDep, partestDep, scalaXmlDep, scalacheckDep), unmanagedBase in IntegrationTest := baseDirectory.value / "files" / "lib", unmanagedJars in IntegrationTest <+= (unmanagedBase) (j => Attributed.blank(j)) map(identity), // no main sources @@ -557,7 +556,7 @@ lazy val test = project sources in IntegrationTest := Seq.empty, fork in IntegrationTest := true, javaOptions in IntegrationTest += "-Xmx1G", - testFrameworks += new TestFramework("scala.tools.partest.Framework"), + testFrameworks += new TestFramework("scala.tools.partest.sbt.Framework"), testOptions in IntegrationTest += Tests.Setup( () => root.base.getAbsolutePath + "/pull-binary-libs.sh" ! ), testOptions in IntegrationTest += Tests.Argument("-Dpartest.java_opts=-Xmx1024M -Xms64M -XX:MaxPermSize=128M"), definedTests in IntegrationTest += ( diff --git a/scripts/jobs/integrate/bootstrap b/scripts/jobs/integrate/bootstrap index 410fe573f8..11cf659229 100755 --- a/scripts/jobs/integrate/bootstrap +++ b/scripts/jobs/integrate/bootstrap @@ -87,6 +87,7 @@ moduleVersioning=${moduleVersioning-"versions.properties"} publishPrivateTask=${publishPrivateTask-"publish"} publishSonatypeTaskCore=${publishSonatypeTaskCore-"publish-signed"} publishSonatypeTaskModules=${publishSonatypeTaskModules-"publish-signed"} +publishStarrPrivateTask=${publishStarrPrivateTask-$publishPrivateTask} # set to "init" to speed up testing of the script (if you already built STARR before) publishLockerPrivateTask=${publishLockerPrivateTask-$publishPrivateTask} # set to "init" to speed up testing of the script (if you already built locker before) forceRebuild=${forceRebuild-no} @@ -208,12 +209,17 @@ sbtResolve() { # scala-xml depends on scala-library, so sbt tries to find the scala-library of the version that we are currently building, # which exists only in private-repo. +docTask() { + if [ "$1" == "yes" ]; then echo doc; else echo set publishArtifact in packageDoc in Compile := false; fi +} + buildXML() { if [ "$XML_BUILT" != "yes" ] && [ "$forceRebuild" != "yes" ] && ( sbtResolve "org.scala-lang.modules" "scala-xml" $XML_VER ) then echo "Found scala-xml $XML_VER; not building." else update scala scala-xml "$XML_REF" && gfxd - sbtBuild 'set version := "'$XML_VER'-DOC"' $clean doc 'set version := "'$XML_VER'"' test "${buildTasks[@]}" + doc="$(docTask $XML_BUILT)" + sbtBuild 'set version := "'$XML_VER'-DOC"' $clean "$doc" 'set version := "'$XML_VER'"' test "${buildTasks[@]}" XML_BUILT="yes" # ensure the module is built and published when buildXML is invoked for the second time, see comment above fi } @@ -223,7 +229,8 @@ buildParsers() { then echo "Found scala-parser-combinators $PARSERS_VER; not building." else update scala scala-parser-combinators "$PARSERS_REF" && gfxd - sbtBuild 'set version := "'$PARSERS_VER'-DOC"' $clean doc 'set version := "'$PARSERS_VER'"' test "${buildTasks[@]}" + doc="$(docTask $PARSERS_BUILT)" + sbtBuild 'set version := "'$PARSERS_VER'-DOC"' $clean "$doc" 'set version := "'$PARSERS_VER'"' test "${buildTasks[@]}" PARSERS_BUILT="yes" fi } @@ -233,26 +240,19 @@ buildPartest() { then echo "Found scala-partest $PARTEST_VER; not building." else update scala scala-partest "$PARTEST_REF" && gfxd - sbtBuild 'set version :="'$PARTEST_VER'"' 'set VersionKeys.scalaXmlVersion := "'$XML_VER'"' 'set VersionKeys.scalaCheckVersion := "'$SCALACHECK_VER'"' $clean test "${buildTasks[@]}" + doc="$(docTask $PARTEST_BUILT)" + sbtBuild 'set version :="'$PARTEST_VER'"' 'set VersionKeys.scalaXmlVersion := "'$XML_VER'"' 'set VersionKeys.scalaCheckVersion := "'$SCALACHECK_VER'"' $clean "$doc" test "${buildTasks[@]}" PARTEST_BUILT="yes" fi } -# buildPartestIface() { -# if [ "$forceRebuild" != "yes" ] && ( sbtResolve "org.scala-lang.modules" "scala-partest-interface" $PARTEST_IFACE_VER ) -# then echo "Found scala-partest-interface $PARTEST_IFACE_VER; not building." -# else -# update scala scala-partest-interface "$PARTEST_IFACE_REF" && gfxd -# sbtBuild 'set version :="'$PARTEST_IFACE_VER'"' $clean "${buildTasks[@]}" -# fi -# } - buildSwing() { if [ "$SWING_BUILT" != "yes" ] && [ "$forceRebuild" != "yes" ] && ( sbtResolve "org.scala-lang.modules" "scala-swing" $SWING_VER ) then echo "Found scala-swing $SWING_VER; not building." else update scala scala-swing "$SWING_REF" && gfxd - sbtBuild 'set version := "'$SWING_VER'"' $clean test "${buildTasks[@]}" + doc="$(docTask $SWING_BUILT)" + sbtBuild 'set version := "'$SWING_VER'"' $clean "$doc" test "${buildTasks[@]}" SWING_BUILT="yes" fi } @@ -263,7 +263,8 @@ buildScalacheck(){ then echo "Found scalacheck $SCALACHECK_VER; not building." else update rickynils scalacheck $SCALACHECK_REF && gfxd - sbtBuild 'set version := "'$SCALACHECK_VER'"' 'set VersionKeys.scalaParserCombinatorsVersion := "'$PARSERS_VER'"' $clean publish # test times out NOTE: never published to sonatype + doc="$(docTask $SCALACHECK_BUILT)" + sbtBuild 'set version := "'$SCALACHECK_VER'"' 'set VersionKeys.scalaParserCombinatorsVersion := "'$PARSERS_VER'"' $clean "$doc" publish # test times out NOTE: never published to sonatype SCALACHECK_BUILT="yes" fi } @@ -277,7 +278,6 @@ buildModules() { buildSwing buildScalacheck buildPartest - # buildPartestIface } buildPublishedModules() { @@ -287,7 +287,6 @@ buildPublishedModules() { buildParsers buildSwing buildPartest - # buildPartestIface } @@ -400,7 +399,6 @@ deriveModuleVersions() { PARSERS_REF="v$PARSERS_VER" SWING_REF="v$SWING_VER" PARTEST_REF="v$PARTEST_VER" - # PARTEST_IFACE_REF="v$PARTEST_IFACE_VER" SCALACHECK_REF="$SCALACHECK_VER" # no `v` in their tags else # use HEAD as default when no revision is specified on the command line @@ -408,7 +406,6 @@ deriveModuleVersions() { PARSERS_REF=${PARSERS_REF-"HEAD"} SWING_REF=${SWING_REF-"HEAD"} PARTEST_REF=${PARTEST_REF-"HEAD"} - # PARTEST_IFACE_REF=${PARTEST_IFACE_REF-"HEAD"} SCALACHECK_REF=${SCALACHECK_REF-"HEAD"} XML_VER=$(deriveVersion scala scala-xml "$XML_REF") @@ -425,7 +422,6 @@ deriveModuleVersions() { echo "SWING = $SWING_VER at $SWING_REF" echo "XML = $XML_VER at $XML_REF" - # PARTEST_IFACE_VER=${PARTEST_IFACE_VER-$(deriveVersion scala scala-partest-interface "$PARTEST_IFACE_REF")} } createNetrcFile() { @@ -440,7 +436,7 @@ removeExistingBuilds() { local netrcFile="$HOME/.credentials-private-repo-netrc" local storageApiUrl=`echo $releaseTempRepoUrl | sed 's/\(scala-release-temp\)/api\/storage\/\1/'` - local scalaLangModules=`curl -s $storageApiUrl/org/scala-lang | jq -r '.children | .[] | "org/scala-lang" + .uri'` + local scalaLangModules=`curl -s $storageApiUrl/org/scala-lang | jq -r '.children | .[] | "org/scala-lang" + .uri' | grep -v actors-migration` for module in "org/scalacheck" $scalaLangModules; do local artifacts=`curl -s $storageApiUrl/$module | jq -r ".children | .[] | select(.uri | contains(\"$SCALA_VER\")) | .uri"` @@ -476,6 +472,29 @@ bootstrap() { cd $WORKSPACE + #### (Optional) STARR. + if [ ! -z "$STARR_REF" ]; then + echo "### Building STARR" + + STARR_DIR=./scala-starr + STARR_VER_SUFFIX="-$(git rev-parse --short $STARR_REF)-nightly" + STARR_VER=$SCALA_VER_BASE$STARR_VER_SUFFIX + rm -rf "$STARR_DIR" + ( + git clone --reference $WORKSPACE/.git $WORKSPACE/.git $STARR_DIR + cd $STARR_DIR + git co $STARR_REF + ant -Dmaven.version.number=$STARR_VER\ + -Dremote.snapshot.repository=NOPE\ + -Dremote.release.repository=$releaseTempRepoUrl\ + -Drepository.credentials.id=$releaseTempRepoCred\ + -Dscalac.args.optimise=-Yopt:l:classpath\ + -Ddocs.skip=1\ + -Dlocker.skip=1\ + $publishStarrPrivateTask >> $baseDir/logs/builds 2>&1 + ) + fi + #### LOCKER echo "### Building locker" @@ -485,8 +504,10 @@ bootstrap() { # must publish under $SCALA_VER so that the modules will depend on this (binary) version of Scala # publish more than just core: partest needs scalap # in sabbus lingo, the resulting Scala build will be used as starr to build the released Scala compiler + if [ ! -z "$STARR_VER" ]; then SET_STARR=-Dstarr.version=$STARR_VER; fi ant -Dmaven.version.number=$SCALA_VER\ -Dremote.snapshot.repository=NOPE\ + $SET_STARR\ -Dremote.release.repository=$releaseTempRepoUrl\ -Drepository.credentials.id=$releaseTempRepoCred\ -Dscalac.args.optimise=-Yopt:l:classpath\ @@ -494,7 +515,6 @@ bootstrap() { -Dlocker.skip=1\ $publishLockerPrivateTask >> $baseDir/logs/builds 2>&1 - echo "### Building modules using locker" # build, test and publish modules with this core diff --git a/src/compiler/scala/tools/nsc/transform/Delambdafy.scala b/src/compiler/scala/tools/nsc/transform/Delambdafy.scala index 9825efdc67..5d93f9f20e 100644 --- a/src/compiler/scala/tools/nsc/transform/Delambdafy.scala +++ b/src/compiler/scala/tools/nsc/transform/Delambdafy.scala @@ -127,9 +127,8 @@ abstract class Delambdafy extends Transform with TypingTransformers with ast.Tre // turns a lambda into a new class def, a New expression instantiating that class private def transformFunction(originalFunction: Function): TransformedFunction = { - val functionTpe = originalFunction.tpe - val targs = functionTpe.typeArgs - val formals :+ restpe = targs + val formals = originalFunction.vparams.map(_.tpe) + val restpe = originalFunction.body.tpe.deconst val oldClass = originalFunction.symbol.enclClass // find which variables are free in the lambda because those are captures that need to be diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index 3a8edafd58..783db65b33 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -128,6 +128,13 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper def canTranslateEmptyListToNil = true def missingSelectErrorTree(tree: Tree, qual: Tree, name: Name): Tree = tree + // when type checking during erasure, generate erased types in spots that aren't transformed by erasure + // (it erases in TypeTrees, but not in, e.g., the type a Function node) + def phasedAppliedType(sym: Symbol, args: List[Type]) = { + val tp = appliedType(sym, args) + if (phase.erasedTypes) erasure.specialScalaErasure(tp) else tp + } + def typedDocDef(docDef: DocDef, mode: Mode, pt: Type): Tree = typed(docDef.definition, mode, pt) @@ -2983,7 +2990,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper val formals = vparamSyms map (_.tpe) val body1 = typed(fun.body, respt) val restpe = packedType(body1, fun.symbol).deconst.resultType - val funtpe = appliedType(FunctionSymbol, formals :+ restpe: _*) + val funtpe = phasedAppliedType(FunctionSymbol, formals :+ restpe) treeCopy.Function(fun, vparams, body1) setType funtpe } @@ -3215,7 +3222,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper // less expensive than including them in inferMethodAlternative (see below). def shapeType(arg: Tree): Type = arg match { case Function(vparams, body) => - functionType(vparams map (_ => AnyTpe), shapeType(body)) + functionType(vparams map (_ => AnyTpe), shapeType(body)) // TODO: should this be erased when retyping during erasure? case AssignOrNamedArg(Ident(name), rhs) => NamedType(name, shapeType(rhs)) case _ => diff --git a/src/partest-extras/scala/tools/partest/ASMConverters.scala b/src/partest-extras/scala/tools/partest/ASMConverters.scala index d990160ce8..a3d849a9c1 100644 --- a/src/partest-extras/scala/tools/partest/ASMConverters.scala +++ b/src/partest-extras/scala/tools/partest/ASMConverters.scala @@ -43,6 +43,23 @@ object ASMConverters { case i: Invoke => i.name case i => i.opcode } + + def summaryText: String = { + def comment(i: Instruction) = i match { + case j: Jump => s" /*${j.label.offset}*/" + case l: Label => s" /*${l.offset}*/" + case _ => "" + } + dropNonOp.map({ + case i: Invoke => s""""${i.name}"""" + case ins => opcodeToString(ins.opcode, ins.opcode) + comment(ins) + }).mkString("List(", ", ", ")") + } + } + + def opcodeToString(op: Int, default: Any = "?"): String = { + import scala.tools.asm.util.Printer.OPCODES + if (OPCODES.isDefinedAt(op)) OPCODES(op) else default.toString } sealed abstract class Instruction extends Product { @@ -50,12 +67,9 @@ object ASMConverters { // toString such that the first field, "opcode: Int", is printed textually. final override def toString() = { - import scala.tools.asm.util.Printer.OPCODES - def opString(op: Int) = if (OPCODES.isDefinedAt(op)) OPCODES(op) else "?" val printOpcode = opcode != -1 - productPrefix + ( - if (printOpcode) Iterator(opString(opcode)) ++ productIterator.drop(1) + if (printOpcode) Iterator(opcodeToString(opcode)) ++ productIterator.drop(1) else productIterator ).mkString("(", ", ", ")") } diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index e53b47e808..685c9f7476 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -462,7 +462,7 @@ trait Types * the empty list for all other types */ def boundSyms: immutable.Set[Symbol] = emptySymbolSet - /** Replace formal type parameter symbols with actual type arguments. + /** Replace formal type parameter symbols with actual type arguments. ErrorType on arity mismatch. * * Amounts to substitution except for higher-kinded types. (See overridden method in TypeRef) -- @M */ @@ -1867,53 +1867,13 @@ trait Types override def isHigherKinded = false override def typeParams = Nil - override def transform(tp: Type): Type = { - // This situation arises when a typevar is encountered for which - // too little information is known to determine its kind, and - // it later turns out not to have kind *. See SI-4070. Only - // logging it for now. - val tparams = sym.typeParams - if (tparams.size != args.size) - devWarning(s"$this.transform($tp), but tparams.isEmpty and args=$args") - def asSeenFromInstantiated(tp: Type) = - asSeenFromOwner(tp).instantiateTypeParams(tparams, args) - // If we're called with a poly type, and we were to run the `asSeenFrom`, over the entire - // type, we can end up with new symbols for the type parameters (clones from TypeMap). - // The subsequent substitution of type arguments would fail. This problem showed up during - // the fix for SI-8046, however the solution taken there wasn't quite right, and led to - // SI-8170. - // - // Now, we detect the PolyType before both the ASF *and* the substitution, and just operate - // on the result type. - // - // TODO: Revisit this and explore the questions raised: - // - // AM: I like this better than the old code, but is there any way the tparams would need the ASF treatment as well? - // JZ: I think its largely irrelevant, as they are no longer referred to in the result type. - // In fact, you can get away with returning a type of kind * here and the sky doesn't fall: - // `case PolyType(`tparams`, result) => asSeenFromInstantiated(result)` - // But I thought it was better to retain the kind. - // AM: I've been experimenting with apply-type-args-then-ASF, but running into cycles. - // In general, it seems iffy the tparams can never occur in the result - // then we might as well represent the type as a no-arg typeref. - // AM: I've also been trying to track down uses of transform (pretty generic name for something that - // does not seem that widely applicable). - // It's kind of a helper for computing baseType (since it tries to propagate our type args to some - // other type, which has to be related to this type for that to make sense). - // - tp match { - case PolyType(`tparams`, result) => PolyType(tparams, asSeenFromInstantiated(result)) - case _ => asSeenFromInstantiated(tp) - } - } - // note: does not go through typeRef. There's no need to because // neither `pre` nor `sym` changes. And there's a performance // advantage to call TypeRef directly. override def typeConstructor = TypeRef(pre, sym, Nil) } - class ModuleTypeRef(pre0: Type, sym0: Symbol) extends NoArgsTypeRef(pre0, sym0) with ClassTypeRef { + class ModuleTypeRef(pre0: Type, sym0: Symbol) extends NoArgsTypeRef(pre0, sym0) { require(sym.isModuleClass, sym) private[this] var narrowedCache: Type = _ override def narrow = { @@ -1922,7 +1882,8 @@ trait Types narrowedCache } - private[Types] def invalidateModuleTypeRefCaches(): Unit = { + override private[Types] def invalidateTypeRefCaches(): Unit = { + super.invalidateTypeRefCaches() narrowedCache = null } override protected def finishPrefix(rest: String) = objectPrefix + rest @@ -1935,12 +1896,12 @@ trait Types require(sym.isPackageClass, sym) override protected def finishPrefix(rest: String) = packagePrefix + rest } - class RefinementTypeRef(pre0: Type, sym0: Symbol) extends NoArgsTypeRef(pre0, sym0) with ClassTypeRef { + class RefinementTypeRef(pre0: Type, sym0: Symbol) extends NoArgsTypeRef(pre0, sym0) { require(sym.isRefinementClass, sym) // I think this is okay, but see #1241 (r12414), #2208, and typedTypeConstructor in Typers override protected def normalizeImpl: Type = sym.info.normalize - override protected def finishPrefix(rest: String) = "" + thisInfo + override protected def finishPrefix(rest: String) = "" + sym.info } class NoArgsTypeRef(pre0: Type, sym0: Symbol) extends TypeRef(pre0, sym0, Nil) { @@ -1951,7 +1912,6 @@ trait Types // represented as existential types. override def isHigherKinded = (typeParams ne Nil) override def typeParams = if (isDefinitionsInitialized) sym.typeParams else sym.unsafeTypeParams - private def isRaw = !phase.erasedTypes && isRawIfWithoutArgs(sym) override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type = if (isHigherKinded) { @@ -1964,17 +1924,6 @@ trait Types else super.instantiateTypeParams(formals, actuals) - override def transform(tp: Type): Type = { - val res = asSeenFromOwner(tp) - if (isHigherKinded && !isRaw) - res.instantiateTypeParams(typeParams, dummyArgs) - else - res - } - - override def transformInfo(tp: Type): Type = - appliedType(asSeenFromOwner(tp), dummyArgs) - override def narrow = if (sym.isModuleClass) singleType(pre, sym.sourceModule) else super.narrow @@ -1986,69 +1935,75 @@ trait Types if (isHigherKinded) etaExpand else super.normalizeImpl } - trait ClassTypeRef extends TypeRef { - // !!! There are scaladoc-created symbols arriving which violate this require. - // require(sym.isClass, sym) - - override def baseType(clazz: Symbol): Type = - if (sym == clazz) this - else transform(sym.info.baseType(clazz)) - } - trait NonClassTypeRef extends TypeRef { require(sym.isNonClassType, sym) - /* Syncnote: These are pure caches for performance; no problem to evaluate these - * several times. Hence, no need to protected with synchronized in a multi-threaded - * usage scenario. - */ + /** Syncnote: These are pure caches for performance; no problem to evaluate these + * several times. Hence, no need to protected with synchronized in a multi-threaded + * usage scenario. + */ private var relativeInfoCache: Type = _ - private var relativeInfoPeriod: Period = NoPeriod - private[Types] def invalidateNonClassTypeRefCaches(): Unit = { + private var relativeInfoCacheValidForPeriod: Period = NoPeriod + private var relativeInfoCacheValidForSymInfo: Type = _ + + override private[Types] def invalidateTypeRefCaches(): Unit = { + super.invalidateTypeRefCaches() relativeInfoCache = NoType - relativeInfoPeriod = NoPeriod + relativeInfoCacheValidForPeriod = NoPeriod + relativeInfoCacheValidForSymInfo = null } - private[Types] def relativeInfo = /*trace(s"relativeInfo(${safeToString}})")*/{ - if (relativeInfoPeriod != currentPeriod) { - val memberInfo = pre.memberInfo(sym) - relativeInfoCache = transformInfo(memberInfo) - relativeInfoPeriod = currentPeriod + final override protected def relativeInfo = { + val symInfo = sym.info + if ((relativeInfoCache eq null) || (relativeInfoCacheValidForSymInfo ne symInfo) || (relativeInfoCacheValidForPeriod != currentPeriod)) { + relativeInfoCache = super.relativeInfo + + if (this.isInstanceOf[AbstractTypeRef]) validateRelativeInfo() + + relativeInfoCacheValidForSymInfo = symInfo + relativeInfoCacheValidForPeriod = currentPeriod } relativeInfoCache } - override def baseType(clazz: Symbol): Type = - if (sym == clazz) this else baseTypeOfNonClassTypeRef(this, clazz) + private def validateRelativeInfo(): Unit = relativeInfoCache match { + // If a subtyping cycle is not detected here, we'll likely enter an infinite + // loop before a sensible error can be issued. SI-5093 is one example. + case x: SubType if x.supertype eq this => + relativeInfoCache = null + throw new RecoverableCyclicReference(sym) + case _ => + } } - protected def baseTypeOfNonClassTypeRef(tpe: NonClassTypeRef, clazz: Symbol) = try { - basetypeRecursions += 1 - if (basetypeRecursions < LogPendingBaseTypesThreshold) - tpe.relativeInfo.baseType(clazz) - else if (pendingBaseTypes contains tpe) - if (clazz == AnyClass) clazz.tpe else NoType - else - try { - pendingBaseTypes += tpe - tpe.relativeInfo.baseType(clazz) - } finally { - pendingBaseTypes -= tpe - } - } finally { - basetypeRecursions -= 1 - } trait AliasTypeRef extends NonClassTypeRef { require(sym.isAliasType, sym) override def dealias = if (typeParamsMatchArgs) betaReduce.dealias else super.dealias override def narrow = normalize.narrow - override def thisInfo = normalize override def prefix = if (this ne normalize) normalize.prefix else pre override def termSymbol = if (this ne normalize) normalize.termSymbol else super.termSymbol override def typeSymbol = if (this ne normalize) normalize.typeSymbol else sym + override protected[Types] def parentsImpl: List[Type] = normalize.parents map relativize + + // `baseClasses` is sensitive to type args when referencing type members + // consider `type foo[x] = x`, `typeOf[foo[String]].baseClasses` should be the same as `typeOf[String].baseClasses`, + // which would be lost by looking at `sym.info` without propagating args + // since classes cannot be overridden, the prefix can be ignored + // (in fact, taking the prefix into account by replacing `normalize` + // with `relativeInfo` breaks pos/t8177g.scala, which is probably a bug, but a tricky one... + override def baseClasses = normalize.baseClasses + + // similar reasoning holds here as for baseClasses + // as another example, consider the type alias `Foo` in `class O { o => type Foo = X { val bla: o.Bar }; type Bar }` + // o1.Foo and o2.Foo have different decls `val bla: o1.Bar` versus `val bla: o2.Bar` + // In principle, you should only call `sym.info.decls` when you know `sym.isClass`, + // and you should `relativize` the infos of the resulting members. + // The latter is certainly violated in multiple spots in the codebase (the members are usually transformed correctly, though). + override def decls: Scope = normalize.decls + // beta-reduce, but don't do partial application -- cycles have been checked in typeRef override protected def normalizeImpl = if (typeParamsMatchArgs) betaReduce.normalize @@ -2071,7 +2026,7 @@ trait Types // // this crashes pos/depmet_implicit_tpbetareduce.scala // appliedType(sym.info, typeArgs).asSeenFrom(pre, sym.owner) - override def betaReduce = transform(sym.info.resultType) + override def betaReduce = relativize(sym.info.resultType) /** SI-3731, SI-8177: when prefix is changed to `newPre`, maintain consistency of prefix and sym * (where the symbol refers to a declaration "embedded" in the prefix). @@ -2121,31 +2076,13 @@ trait Types trait AbstractTypeRef extends NonClassTypeRef { require(sym.isAbstractType, sym) - /** Syncnote: Pure performance caches; no need to synchronize in multi-threaded environment - */ - private var symInfoCache: Type = _ - private var thisInfoCache: Type = _ + override def baseClasses = relativeInfo.baseClasses + override def decls = relativeInfo.decls + override def bounds = relativeInfo.bounds + + override protected[Types] def baseTypeSeqImpl: BaseTypeSeq = bounds.hi.baseTypeSeq prepend this + override protected[Types] def parentsImpl: List[Type] = relativeInfo.parents - override def thisInfo = { - val symInfo = sym.info - if (thisInfoCache == null || (symInfo ne symInfoCache)) { - symInfoCache = symInfo - thisInfoCache = transformInfo(symInfo) match { - // If a subtyping cycle is not detected here, we'll likely enter an infinite - // loop before a sensible error can be issued. SI-5093 is one example. - case x: SubType if x.supertype eq this => - throw new RecoverableCyclicReference(sym) - case tp => tp - } - } - thisInfoCache - } - private[Types] def invalidateAbstractTypeRefCaches(): Unit = { - symInfoCache = null - thisInfoCache = null - } - override def bounds = thisInfo.bounds - override protected[Types] def baseTypeSeqImpl: BaseTypeSeq = transform(bounds.hi).baseTypeSeq prepend this override def kind = "AbstractTypeRef" } @@ -2189,11 +2126,91 @@ trait Types finalizeHash(h, 2) } + // interpret symbol's info in terms of the type's prefix and type args + protected def relativeInfo: Type = appliedType(sym.info.asSeenFrom(pre, sym.owner), argsOrDummies) + // @M: propagate actual type params (args) to `tp`, by replacing // formal type parameters with actual ones. If tp is higher kinded, // the "actual" type arguments are types that simply reference the // corresponding type parameters (unbound type variables) - def transform(tp: Type): Type + // + // NOTE: for performance, as well as correctness, we do not attempt + // to reframe trivial types in terms of our prefix and args. + // asSeenFrom, by construction, is the identity for trivial types, + // and substitution cannot change them either (abstract types are non-trivial, specifically because they may need to be replaced) + // For correctness, the result for `tp == NoType` must be `NoType`, + // if we don't shield against this, and apply instantiateTypeParams to it, + // this would result in an ErrorType, which behaves differently during subtyping + // (and thus on recursion, subtyping would go from false -- since a NoType is involved -- + // to true, as ErrorType is always a sub/super type....) + final def relativize(tp: Type): Type = + if (tp.isTrivial) tp + else if (args.isEmpty && (phase.erasedTypes || !isHigherKinded || isRawIfWithoutArgs(sym))) tp.asSeenFrom(pre, sym.owner) + else { + // The type params and type args should always match in length, + // though a mismatch can arise when a typevar is encountered for which + // too little information is known to determine its kind, and + // it later turns out not to have kind *. See SI-4070. + val formals = sym.typeParams + + // If we're called with a poly type, and we were to run the `asSeenFrom`, over the entire + // type, we can end up with new symbols for the type parameters (clones from TypeMap). + // The subsequent substitution of type arguments would fail. This problem showed up during + // the fix for SI-8046, however the solution taken there wasn't quite right, and led to + // SI-8170. + // + // Now, we detect the PolyType before both the ASF *and* the substitution, and just operate + // on the result type. + // + // TODO: Revisit this and explore the questions raised: + // + // AM: I like this better than the old code, but is there any way the tparams would need the ASF treatment as well? + // JZ: I think its largely irrelevant, as they are no longer referred to in the result type. + // In fact, you can get away with returning a type of kind * here and the sky doesn't fall: + // `case PolyType(`tparams`, result) => asSeenFromInstantiated(result)` + // But I thought it was better to retain the kind. + // AM: I've been experimenting with apply-type-args-then-ASF, but running into cycles. + // In general, it seems iffy the tparams can never occur in the result + // then we might as well represent the type as a no-arg typeref. + // AM: I've also been trying to track down uses of transform (pretty generic name for something that + // does not seem that widely applicable). + // It's kind of a helper for computing baseType (since it tries to propagate our type args to some + // other type, which has to be related to this type for that to make sense). + // + def seenFromOwnerInstantiated(tp: Type): Type = + tp.asSeenFrom(pre, sym.owner).instantiateTypeParams(formals, argsOrDummies) + + tp match { + case PolyType(`formals`, result) => PolyType(formals, seenFromOwnerInstantiated(result)) + case _ => seenFromOwnerInstantiated(tp) + } + } + + private def argsOrDummies = if (args.isEmpty) dummyArgs else args + + final override def baseType(clazz: Symbol): Type = + if (clazz eq sym) this + // NOTE: this first goes to requested base type, *then* does asSeenFrom prefix & instantiates args + else if (sym.isClass) relativize(sym.info.baseType(clazz)) + else baseTypeOfNonClassTypeRef(clazz) + + // two differences with class type basetype: + // (1) first relativize the type, then go to the requested base type + // (2) cache for cycle robustness + private def baseTypeOfNonClassTypeRef(clazz: Symbol) = + try { + basetypeRecursions += 1 + if (basetypeRecursions >= LogPendingBaseTypesThreshold) baseTypeOfNonClassTypeRefLogged(clazz) + else relativeInfo.baseType(clazz) + } finally basetypeRecursions -= 1 + + private def baseTypeOfNonClassTypeRefLogged(clazz: Symbol) = + if (pendingBaseTypes add this) try relativeInfo.baseType(clazz) finally { pendingBaseTypes remove this } + // TODO: is this optimization for AnyClass worth it? (or is it playing last-ditch cycle defense?) + // NOTE: for correctness, it only applies for non-class types + // (e.g., a package class should not get AnyTpe as its supertype, ever) + else if (clazz eq AnyClass) AnyTpe + else NoType // eta-expand, subtyping relies on eta-expansion of higher-kinded types protected def normalizeImpl: Type = if (isHigherKinded) etaExpand else super.normalize @@ -2226,21 +2243,16 @@ trait Types // (they are allowed to be rebound more liberally) def coevolveSym(pre1: Type): Symbol = sym - //@M! use appliedType on the polytype that represents the bounds (or if aliastype, the rhs) - def transformInfo(tp: Type): Type = appliedType(asSeenFromOwner(tp), args) - - def thisInfo = sym.info def initializedTypeParams = sym.info.typeParams def typeParamsMatchArgs = sameLength(initializedTypeParams, args) - def asSeenFromOwner(tp: Type) = tp.asSeenFrom(pre, sym.owner) - override def baseClasses = thisInfo.baseClasses + override def baseTypeSeqDepth = baseTypeSeq.maxDepth override def prefix = pre override def termSymbol = super.termSymbol override def termSymbolDirect = super.termSymbol override def typeArgs = args - override def typeOfThis = transform(sym.typeOfThis) + override def typeOfThis = relativize(sym.typeOfThis) override def typeSymbol = sym override def typeSymbolDirect = sym @@ -2253,22 +2265,26 @@ trait Types } } - override def decls: Scope = { - sym.info match { - case TypeRef(_, sym1, _) => - assert(sym1 != sym, this) // @MAT was != typeSymbol - case _ => - } - thisInfo.decls - } + protected[Types] def parentsImpl: List[Type] = sym.info.parents map relativize + + // Since type parameters cannot occur in super types, no need to relativize before looking at base *classes*. + // Similarly, our prefix can occur in super class types, but it cannot influence which classes those types resolve to. + // For example, `class Outer { outer => class Inner extends outer.Foo; class Foo }` + // `outer`'s value has no impact on which `Foo` is selected, since classes cannot be overridden. + // besides being faster, we can't use relativeInfo because it causes cycles + override def baseClasses = sym.info.baseClasses + + // in principle, we should use `relativeInfo.decls`, but I believe all uses of `decls` will correctly `relativize` the individual members + override def decls: Scope = sym.info.decls + protected[Types] def baseTypeSeqImpl: BaseTypeSeq = if (sym.info.baseTypeSeq exists (_.typeSymbolDirect.isAbstractType)) // SI-8046 base type sequence might have more elements in a subclass, we can't map it element wise. - transform(sym.info).baseTypeSeq + relativize(sym.info).baseTypeSeq else // Optimization: no abstract types, we can compute the BTS of this TypeRef as an element-wise map // of the BTS of the referenced symbol. - sym.info.baseTypeSeq map transform + sym.info.baseTypeSeq map relativize override def baseTypeSeq: BaseTypeSeq = { val cache = baseTypeSeqCache @@ -2299,9 +2315,10 @@ trait Types ) protected def finishPrefix(rest: String) = ( if (sym.isInitialized && sym.isAnonymousClass && !phase.erasedTypes) - parentsString(thisInfo.parents) + refinementString + parentsString(sym.info.parents) + refinementString else rest - ) + ) + private def noArgsString = finishPrefix(preString + sym.nameString) private def tupleTypeString: String = args match { case Nil => noArgsString @@ -2363,10 +2380,10 @@ trait Types // No longer defined as anonymous classes in `object TypeRef` to avoid an unnecessary outer pointer. private final class AliasArgsTypeRef(pre: Type, sym: Symbol, args: List[Type]) extends ArgsTypeRef(pre, sym, args) with AliasTypeRef private final class AbstractArgsTypeRef(pre: Type, sym: Symbol, args: List[Type]) extends ArgsTypeRef(pre, sym, args) with AbstractTypeRef - private final class ClassArgsTypeRef(pre: Type, sym: Symbol, args: List[Type]) extends ArgsTypeRef(pre, sym, args) with ClassTypeRef + private final class ClassArgsTypeRef(pre: Type, sym: Symbol, args: List[Type]) extends ArgsTypeRef(pre, sym, args) private final class AliasNoArgsTypeRef(pre: Type, sym: Symbol) extends NoArgsTypeRef(pre, sym) with AliasTypeRef private final class AbstractNoArgsTypeRef(pre: Type, sym: Symbol) extends NoArgsTypeRef(pre, sym) with AbstractTypeRef - private final class ClassNoArgsTypeRef(pre: Type, sym: Symbol) extends NoArgsTypeRef(pre, sym) with ClassTypeRef + private final class ClassNoArgsTypeRef(pre: Type, sym: Symbol) extends NoArgsTypeRef(pre, sym) object TypeRef extends TypeRefExtractor { def apply(pre: Type, sym: Symbol, args: List[Type]): Type = unique({ @@ -2391,7 +2408,7 @@ trait Types if (period != currentPeriod) { tpe.parentsPeriod = currentPeriod if (!isValidForBaseClasses(period)) { - tpe.parentsCache = tpe.thisInfo.parents map tpe.transform + tpe.parentsCache = tpe.parentsImpl } else if (tpe.parentsCache == null) { // seems this can happen if things are corrupted enough, see #2641 tpe.parentsCache = List(AnyTpe) } @@ -4603,32 +4620,14 @@ trait Types invalidateCaches(tp, updatedSyms) } - def invalidateCaches(t: Type, updatedSyms: List[Symbol]) = { - t match { - case st: SingleType if updatedSyms.contains(st.sym) => st.invalidateSingleTypeCaches() - case _ => - } - t match { - case tr: NonClassTypeRef if updatedSyms.contains(tr.sym) => tr.invalidateNonClassTypeRefCaches() - case _ => - } - t match { - case tr: AbstractTypeRef if updatedSyms.contains(tr.sym) => tr.invalidateAbstractTypeRefCaches() - case _ => - } - t match { - case tr: TypeRef if updatedSyms.contains(tr.sym) => tr.invalidateTypeRefCaches() - case _ => - } - t match { - case tr: ModuleTypeRef if updatedSyms.contains(tr.sym) => tr.invalidateModuleTypeRefCaches() - case _ => - } + def invalidateCaches(t: Type, updatedSyms: List[Symbol]) = t match { + case st: SingleType if updatedSyms.contains(st.sym) => st.invalidateSingleTypeCaches() + case tr: TypeRef if updatedSyms.contains(tr.sym) => tr.invalidateTypeRefCaches() case ct: CompoundType if ct.baseClasses.exists(updatedSyms.contains) => ct.invalidatedCompoundTypeCaches() case _ => } - } + val shorthands = Set( "scala.collection.immutable.List", diff --git a/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala b/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala index e6d7b11cad..cf274f24bb 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeComparers.scala @@ -58,7 +58,7 @@ trait TypeComparers { false private def equalSymsAndPrefixes(sym1: Symbol, pre1: Type, sym2: Symbol, pre2: Type): Boolean = ( - if (sym1 == sym2) + if (sym1 eq sym2) sym1.hasPackageFlag || sym1.owner.hasPackageFlag || phase.erasedTypes || pre1 =:= pre2 else (sym1.name == sym2.name) && isUnifiable(pre1, pre2) @@ -79,7 +79,7 @@ trait TypeComparers { def isDifferentTypeConstructor(tp1: Type, tp2: Type) = !isSameTypeConstructor(tp1, tp2) private def isSameTypeConstructor(tr1: TypeRef, tr2: TypeRef): Boolean = ( - (tr1.sym == tr2.sym) + (tr1.sym eq tr2.sym) && !isDifferentType(tr1.pre, tr2.pre) ) private def isSameTypeConstructor(tp1: Type, tp2: Type): Boolean = ( @@ -222,7 +222,7 @@ trait TypeComparers { case SingleType(pre1, sym1) => tp2 match { case SingleType(pre2, sym2) => equalSymsAndPrefixes(sym1, pre1, sym2, pre2) ; case _ => false } case PolyType(ps1, res1) => tp2 match { case PolyType(ps2, res2) => equalTypeParamsAndResult(ps1, res1, ps2, res2) ; case _ => false } case ExistentialType(qs1, res1) => tp2 match { case ExistentialType(qs2, res2) => equalTypeParamsAndResult(qs1, res1, qs2, res2) ; case _ => false } - case ThisType(sym1) => tp2 match { case ThisType(sym2) => sym1 == sym2 ; case _ => false } + case ThisType(sym1) => tp2 match { case ThisType(sym2) => sym1 eq sym2 ; case _ => false } case ConstantType(c1) => tp2 match { case ConstantType(c2) => c1 == c2 ; case _ => false } case NullaryMethodType(res1) => tp2 match { case NullaryMethodType(res2) => res1 =:= res2 ; case _ => false } case TypeBounds(lo1, hi1) => tp2 match { case TypeBounds(lo2, hi2) => lo1 =:= lo2 && hi1 =:= hi2 ; case _ => false } @@ -344,7 +344,7 @@ trait TypeComparers { // in the same class, and the 'x' in the ThisType has in its override chain // the 'x' in the SuperType, then the types conform. private def isThisAndSuperSubtype(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match { - case (SingleType(ThisType(lpre), v1), SingleType(SuperType(ThisType(rpre), _), v2)) => (lpre == rpre) && (v1.overrideChain contains v2) + case (SingleType(ThisType(lpre), v1), SingleType(SuperType(ThisType(rpre), _), v2)) => (lpre eq rpre) && (v1.overrideChain contains v2) case _ => false } @@ -361,8 +361,8 @@ trait TypeComparers { false } - ( tp1.typeSymbol == NothingClass // @M Nothing is subtype of every well-kinded type - || tp2.typeSymbol == AnyClass // @M Any is supertype of every well-kinded type (@PP: is it? What about continuations plugin?) + ( (tp1.typeSymbol eq NothingClass) // @M Nothing is subtype of every well-kinded type + || (tp2.typeSymbol eq AnyClass) // @M Any is supertype of every well-kinded type (@PP: is it? What about continuations plugin?) || isSub(tp1.normalize, tp2.normalize) && annotationsConform(tp1, tp2) // @M! normalize reduces higher-kinded case to PolyType's ) } @@ -394,7 +394,7 @@ trait TypeComparers { val sym2 = tr2.sym val pre1 = tr1.pre val pre2 = tr2.pre - (((if (sym1 == sym2) phase.erasedTypes || sym1.owner.hasPackageFlag || isSubType(pre1, pre2, depth) + (((if (sym1 eq sym2) phase.erasedTypes || sym1.owner.hasPackageFlag || isSubType(pre1, pre2, depth) else (sym1.name == sym2.name && !sym1.isModuleClass && !sym2.isModuleClass && (isUnifiable(pre1, pre2) || isSameSpecializedSkolem(sym1, sym2, pre1, pre2) || @@ -403,7 +403,9 @@ trait TypeComparers { || sym2.isClass && { val base = tr1 baseType sym2 - (base ne tr1) && isSubType(base, tr2, depth) + // During bootstrap, `base eq NoType` occurs about 2.5 times as often as `base ne NoType`. + // The extra check seems like a worthwhile optimization (about 2.5M useless calls to isSubtype saved during that run). + (base ne tr1) && (base ne NoType) && isSubType(base, tr2, depth) } || thirdTryRef(tr1, tr2)) diff --git a/src/scaladoc/scala/tools/nsc/doc/base/CommentFactoryBase.scala b/src/scaladoc/scala/tools/nsc/doc/base/CommentFactoryBase.scala index 707d0c469f..8cd8a7ee09 100644 --- a/src/scaladoc/scala/tools/nsc/doc/base/CommentFactoryBase.scala +++ b/src/scaladoc/scala/tools/nsc/doc/base/CommentFactoryBase.scala @@ -47,7 +47,8 @@ trait CommentFactoryBase { this: MemberLookupBase => groupDesc0: Map[String,Body] = Map.empty, groupNames0: Map[String,Body] = Map.empty, groupPrio0: Map[String,Body] = Map.empty, - hideImplicitConversions0: List[Body] = List.empty + hideImplicitConversions0: List[Body] = List.empty, + shortDescription0: List[Body] = List.empty ): Comment = new Comment { val body = body0 getOrElse Body(Seq.empty) val authors = authors0 @@ -90,9 +91,13 @@ trait CommentFactoryBase { this: MemberLookupBase => } } + override val shortDescription: Option[Text] = shortDescription0.lastOption collect { + case Body(List(Paragraph(Chain(List(Summary(Text(e))))))) if !e.trim.contains("\n") => Text(e) + } + override val hideImplicitConversions: List[String] = hideImplicitConversions0 flatMap { - case Body(List(Paragraph(Chain(List(Summary(Text(e))))))) if (!e.trim.contains("\n")) => List(e) + case Body(List(Paragraph(Chain(List(Summary(Text(e))))))) if !e.trim.contains("\n") => List(e) case _ => List() } } @@ -397,7 +402,8 @@ trait CommentFactoryBase { this: MemberLookupBase => groupDesc0 = allSymsOneTag(SimpleTagKey("groupdesc")), groupNames0 = allSymsOneTag(SimpleTagKey("groupname")), groupPrio0 = allSymsOneTag(SimpleTagKey("groupprio")), - hideImplicitConversions0 = allTags(SimpleTagKey("hideImplicitConversion")) + hideImplicitConversions0 = allTags(SimpleTagKey("hideImplicitConversion")), + shortDescription0 = allTags(SimpleTagKey("shortDescription")) ) for ((key, _) <- bodyTags) diff --git a/src/scaladoc/scala/tools/nsc/doc/base/comment/Comment.scala b/src/scaladoc/scala/tools/nsc/doc/base/comment/Comment.scala index 183297f2c3..eeb861e246 100644 --- a/src/scaladoc/scala/tools/nsc/doc/base/comment/Comment.scala +++ b/src/scaladoc/scala/tools/nsc/doc/base/comment/Comment.scala @@ -21,7 +21,7 @@ abstract class Comment { /** The main body of the comment that describes what the entity does and is. */ def body: Body - private def closeHtmlTags(inline: Inline) = { + private def closeHtmlTags(inline: Inline): Inline = { val stack = mutable.ListBuffer.empty[HtmlTag] def scan(i: Inline) { i match { @@ -47,9 +47,10 @@ abstract class Comment { Chain(List(inline) ++ stack.reverse) } - /** A shorter version of the body. Usually, this is the first sentence of the body. */ + /** A shorter version of the body. Either from `@shortDescription` or the + * first sentence of the body. */ def short: Inline = { - body.summary match { + shortDescription orElse body.summary match { case Some(s) => closeHtmlTags(s) case _ => @@ -126,6 +127,9 @@ abstract class Comment { /** A list of implicit conversions to hide */ def hideImplicitConversions: List[String] + /** A short description used in the entity-view and search results */ + def shortDescription: Option[Text] + override def toString = body.toString + "\n" + (authors map ("@author " + _.toString)).mkString("\n") + diff --git a/src/scaladoc/scala/tools/nsc/doc/doclet/Indexer.scala b/src/scaladoc/scala/tools/nsc/doc/doclet/Indexer.scala index 0cdd47182f..12fee69cca 100644 --- a/src/scaladoc/scala/tools/nsc/doc/doclet/Indexer.scala +++ b/src/scaladoc/scala/tools/nsc/doc/doclet/Indexer.scala @@ -18,4 +18,4 @@ trait Indexer extends Generator with Universer { indexField != null } -}
\ No newline at end of file +} diff --git a/src/scaladoc/scala/tools/nsc/doc/html/Doclet.scala b/src/scaladoc/scala/tools/nsc/doc/html/Doclet.scala index 21c5f6bb67..cad7cf3298 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/Doclet.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/Doclet.scala @@ -3,7 +3,8 @@ * @author David Bernard, Manohar Jonnalagedda */ -package scala.tools.nsc.doc +package scala.tools.nsc +package doc package html import doclet._ @@ -13,7 +14,7 @@ import doclet._ class Doclet extends Generator with Universer with Indexer { def generateImpl() { - new html.HtmlFactory(universe, index).generate() + new html.HtmlFactory(universe, index, new ScalaDocReporter(universe.settings)).generate() } } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/HtmlFactory.scala b/src/scaladoc/scala/tools/nsc/doc/html/HtmlFactory.scala index 6076b1708c..65c540d4c5 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/HtmlFactory.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/HtmlFactory.scala @@ -16,7 +16,8 @@ import page.diagram._ /** A class that can generate Scaladoc sites to some fixed root folder. * @author David Bernard * @author Gilles Dubochet */ -class HtmlFactory(val universe: doc.Universe, index: doc.Index) { +class HtmlFactory(val universe: doc.Universe, index: doc.Index, val reporter: ScalaDocReporter) { + import page.{IndexScript, EntityPage} /** The character encoding to be used for generated Scaladoc sites. * This value is currently always UTF-8. */ @@ -34,6 +35,9 @@ class HtmlFactory(val universe: doc.Universe, index: doc.Index) { "trait_comp.svg", "permalink.svg", "abstract_type.svg", + "lato-v11-latin-100.eot", + "lato-v11-latin-100.ttf", + "lato-v11-latin-100.woff", "lato-v11-latin-regular.eot", "lato-v11-latin-regular.ttf", "lato-v11-latin-regular.woff", @@ -96,14 +100,15 @@ class HtmlFactory(val universe: doc.Universe, index: doc.Index) { libResources foreach (s => copyResource("lib/" + s)) - new page.Index(universe, index) writeFor this - new page.IndexScript(universe, index) writeFor this + IndexScript(universe, index) writeFor this + if (index.hasDeprecatedMembers) - new page.DeprecatedIndex(universe, index) writeFor this + new page.DeprecatedIndex(universe, index, reporter) writeFor this try { writeTemplates(_ writeFor this) + for (letter <- index.firstLetterIndex) { - new html.page.ReferenceIndex(letter._1, index, universe) writeFor this + new html.page.ReferenceIndex(letter._1, index, universe, reporter) writeFor this } } finally { DiagramStats.printStats(universe.settings) @@ -117,7 +122,7 @@ class HtmlFactory(val universe: doc.Universe, index: doc.Index) { def writeTemplate(tpl: DocTemplateEntity) { if (!(written contains tpl)) { val diagramGenerator: DiagramGenerator = new DotDiagramGenerator(universe.settings, universe.dotRunner) - writeForThis(new page.Template(universe, diagramGenerator, tpl)) + writeForThis(page.EntityPage(universe, diagramGenerator, tpl, reporter)) written += tpl tpl.templates collect { case d: DocTemplateEntity => d } map writeTemplate } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala b/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala index 16a2fc59d4..0eb90d8942 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/HtmlPage.scala @@ -26,6 +26,9 @@ abstract class HtmlPage extends Page { thisPage => /** The title of this page. */ protected def title: String + /** ScalaDoc reporter for error handling */ + protected def reporter: ScalaDocReporter + /** The page description */ protected def description: String = // unless overwritten, will display the title in a spaced format, keeping - and . @@ -48,7 +51,7 @@ abstract class HtmlPage extends Page { thisPage => <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> - <meta name="viewport" content="width=device-width, initial-scale=1"/> + <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>{ title }</title> <meta name="description" content={ description }/> <meta name="keywords" content={ keywords }/> @@ -281,7 +284,7 @@ abstract class HtmlPage extends Page { thisPage => } }</span> - def memberToUrl(template: Entity, isSelf: Boolean = true): String = { + private def memberToUrl(template: Entity, isSelf: Boolean = true): String = { val (signature: Option[String], containingTemplate: TemplateEntity) = template match { case dte: DocTemplateEntity if (!isSelf) => (Some(dte.signature), dte.inTemplate) case dte: DocTemplateEntity => (None, dte) @@ -289,12 +292,8 @@ abstract class HtmlPage extends Page { thisPage => case tpl => (None, tpl) } - def hashFromPath(templatePath: List[String]): String = - ((templatePath.head.replace(".html", "") :: templatePath.tail).reverse).mkString(".") - - val containingTemplatePath = templateToPath(containingTemplate) - val url = "../" * (containingTemplatePath.size - 1) + "index.html" - val hash = hashFromPath(containingTemplatePath) - s"$url#$hash" + signature.map("@" + _).getOrElse("") + val templatePath = templateToPath(containingTemplate) + val url = "../" * (templatePath.size - 1) + templatePath.reverse.mkString("/") + url + signature.map("#" + _).getOrElse("") } } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/Page.scala b/src/scaladoc/scala/tools/nsc/doc/html/Page.scala index 93950fd0a7..875d7919c2 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/Page.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/Page.scala @@ -7,6 +7,7 @@ package scala package tools.nsc.doc.html import scala.tools.nsc.doc.model._ +import scala.tools.nsc.doc.base.comment import java.io.{FileOutputStream, File} import scala.reflect.NameTransformer import java.nio.channels.Channels @@ -78,7 +79,7 @@ abstract class Page { } val (file, pack) = tpl match { - case p: Package => ("package.html", p) + case p: Package => ("index.html", p) case _ => downInner(doName(tpl), tpl) } file :: downPacks(pack) @@ -100,4 +101,16 @@ abstract class Page { } relativize(thisPage.path.reverse, destPath.reverse).mkString("/") } + + protected def inlineToStr(inl: comment.Inline): String = inl match { + case comment.Chain(items) => items flatMap (inlineToStr(_)) mkString "" + case comment.Italic(in) => inlineToStr(in) + case comment.Bold(in) => inlineToStr(in) + case comment.Underline(in) => inlineToStr(in) + case comment.Monospace(in) => inlineToStr(in) + case comment.Text(text) => text + case comment.Summary(in) => inlineToStr(in) + case comment.EntityLink(comment.Text(text), _) => text + case _ => inl.toString + } } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/DeprecatedIndex.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/DeprecatedIndex.scala index f257153bd7..e8cb58c732 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/DeprecatedIndex.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/DeprecatedIndex.scala @@ -11,7 +11,9 @@ package page import doc.model._ -class DeprecatedIndex(universe: Universe, index: doc.Index) extends HtmlPage { +class DeprecatedIndex(universe: Universe, index: doc.Index, rep: ScalaDocReporter) extends HtmlPage { + + def reporter = rep def path = List("deprecated-list.html") diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/Entity.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/Entity.scala new file mode 100644 index 0000000000..969e19c770 --- /dev/null +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/Entity.scala @@ -0,0 +1,1053 @@ +/* NSC -- new Scala compiler + * Copyright 2007-2016 LAMP/EPFL + * @author David Bernard, Manohar Jonnalagedda, Felix Mulder + */ + +package scala +package tools +package nsc +package doc +package html +package page + +import base._ +import base.comment._ + +import scala.collection.mutable +import scala.xml.{NodeSeq, Text, UnprefixedAttribute} +import scala.language.postfixOps + +import model._ +import model.diagram._ +import diagram._ + +trait EntityPage extends HtmlPage { + def universe: doc.Universe + def generator: DiagramGenerator + def tpl: DocTemplateEntity + def reporter: ScalaDocReporter + + override val path = templateToPath(tpl) + + def title = { + val s = universe.settings + ( if (!s.doctitle.isDefault) s.doctitle.value + " " else "" ) + + ( if (!s.docversion.isDefault) s.docversion.value else "" ) + + ( if ((!s.doctitle.isDefault || !s.docversion.isDefault) && tpl.qualifiedName != "_root_") " - " + tpl.qualifiedName else "" ) + } + + def headers = + <xml:group> + <link href={ relativeLinkTo{List("index.css", "lib")} } media="screen" type="text/css" rel="stylesheet"/> + <link href={ relativeLinkTo{List("template.css", "lib")} } media="screen" type="text/css" rel="stylesheet"/> + <link href={ relativeLinkTo{List("diagrams.css", "lib")} } media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> + <script type="text/javascript" src={ relativeLinkTo{List("jquery.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("jquery.panzoom.min.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("jquery.mousewheel.min.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("index.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("index.js")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("scheduler.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("template.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("tools.tooltip.js", "lib")} }></script> + { if (universe.settings.docDiagrams.value) { + <script type="text/javascript" src={ relativeLinkTo{List("modernizr.custom.js", "lib")} }></script> + <script type="text/javascript" src={ relativeLinkTo{List("diagrams.js", "lib")} } id="diagrams-js"></script> + } else NodeSeq.Empty } + <script type="text/javascript"> + /* this variable can be used by the JS to determine the path to the root document */ + var toRoot = '{ val p = templateToPath(tpl); "../" * (p.size - 1) }'; + </script> + </xml:group> + + def body = + <body> + { search } + <div id="search-results"> + <div id="search-progress"> + <div id="progress-fill"></div> + </div> + <div id="results-content"> + <div id="entity-results"></div> + <div id="member-results"></div> + </div> + </div> + <div id="content-container" style="-webkit-overflow-scrolling: touch;"> + <div id="content"> + { content } + </div> + </div> + </body> + + def search = + <div id="search"> + <span id="doc-title"> + {universe.settings.doctitle.value} + <span id="doc-version"> + { + val version = universe.settings.docversion.value + + if (version.length > "XX.XX.XX-XXX".length) { + reporter.warning(null, + s"doc-version ($version) is too long to be displayed in the webview") + "" + } else version + } + </span> + </span> + <span class="close-results"><span class="left"><</span> Back</span> + <div id="textfilter"> + <span class="input"> + <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/"/> + <i class="clear material-icons"></i> + <i id="search-icon" class="material-icons"></i> + </span> + </div> + </div> + + val valueMembers = + tpl.methods ++ tpl.values ++ tpl.templates.filter(x => x.isObject || x.isPackage) sorted + + val (absValueMembers, nonAbsValueMembers) = + valueMembers partition (_.isAbstract) + + val (deprValueMembers, nonDeprValueMembers) = + nonAbsValueMembers partition (_.deprecation.isDefined) + + val (concValueMembers, shadowedImplicitMembers) = + nonDeprValueMembers partition (!_.isShadowedOrAmbiguousImplicit) + + val typeMembers = + tpl.abstractTypes ++ tpl.aliasTypes ++ tpl.templates.filter(x => x.isTrait || x.isClass) sorted (implicitly[Ordering[MemberEntity]]) + + val constructors = (tpl match { + case cls: Class => (cls.constructors: List[MemberEntity]).sorted + case _ => Nil + }) + + /* for body, there is a special case for AnyRef, otherwise AnyRef appears + * like a package/object this problem should be fixed, this implementation + * is just a patch. */ + val content = { + val templateName = if (tpl.isRootPackage) "root package" else tpl.name + val displayName = tpl.companion match { + case Some(companion) if (companion.visibility.isPublic && companion.inSource != None) => + <a href={relativeLinkTo(companion)} title={docEntityKindToCompanionTitle(tpl)}>{ templateName }</a> + case _ => + templateName + } + val owner = { + if (tpl.isRootPackage || tpl.inTemplate.isRootPackage) + NodeSeq.Empty + else + <p id="owner">{ templatesToHtml(tpl.inTemplate.toRoot.reverse.tail, scala.xml.Text(".")) }</p> + } + + <body class={ tpl.kind + (if (tpl.isType) " type" else " value") }> + <div id="definition"> + { + val (src, alt) = docEntityKindToBigImage(tpl) + + val identifier = alt.toString.substring(0,2).toLowerCase + + tpl.companion match { + case Some(companion) if (companion.visibility.isPublic && companion.inSource != None) => + <a href={relativeLinkTo(companion)} title={docEntityKindToCompanionTitle(tpl)}><div class={s"big-circle companion $identifier"}>{ identifier.substring(0,1) }</div></a> + case _ => + <div class={ "big-circle " + alt.toString.toLowerCase }>{ identifier.substring(0,1) }</div> + }} + { owner } + <h1>{ displayName }</h1>{ + if (tpl.isPackage) NodeSeq.Empty else <h3>{companionAndPackage(tpl)}</h3> + }{ permalink(tpl) } + { signature(tpl, isSelf = true) } + </div> + + { memberToCommentHtml(tpl, tpl.inTemplate, isSelf = true) } + + <div id="mbrsel"> + <div class='toggle'></div> + <div id='memberfilter'> + <i class="material-icons arrow"></i> + <span class='input'> + <input id='mbrsel-input' placeholder='Filter members' type='text' accesskey='/'/> + </span> + <i class="clear material-icons"></i> + </div> + <div id='filterby'> + <div id="order"> + <span class="filtertype">Ordering</span> + <ol> + { + if (!universe.settings.docGroups.value || (tpl.members.map(_.group).distinct.length == 1)) + NodeSeq.Empty + else + <li class="group out"><span>Grouped</span></li> + } + <li class="alpha in"><span>Alphabetic</span></li> + { + if (tpl.linearizationTemplates.isEmpty && tpl.conversions.isEmpty) + NodeSeq.Empty + else + <li class="inherit out"><span>By Inheritance</span></li> + } + </ol> + </div> + { if (tpl.linearizationTemplates.isEmpty && tpl.conversions.isEmpty) NodeSeq.Empty else + { + if (!tpl.linearizationTemplates.isEmpty) + <div class="ancestors"> + <span class="filtertype">Inherited<br/> + </span> + <ol id="linearization"> + { (tpl :: tpl.linearizationTemplates).map(wte => <li class="in" name={ wte.qualifiedName }><span>{ wte.name }</span></li>) } + </ol> + </div> + else NodeSeq.Empty + } ++ { + if (!tpl.conversions.isEmpty) + <div class="ancestors"> + <span class="filtertype">Implicitly<br/> + </span> + <ol id="implicits"> { + tpl.conversions.map { conv => + val name = conv.conversionQualifiedName + val hide = universe.settings.hiddenImplicits(name) + <li class="in" name={ name } data-hidden={ hide.toString }><span>{ "by " + conv.conversionShortName }</span></li> + } + } + </ol> + </div> + else NodeSeq.Empty + } ++ + <div class="ancestors"> + <span class="filtertype"></span> + <ol> + <li class="hideall out"><span>Hide All</span></li> + <li class="showall in"><span>Show All</span></li> + </ol> + </div> + } + { + <div id="visbl"> + <span class="filtertype">Visibility</span> + <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> + </div> + } + </div> + </div> + + <div id="template"> + <div id="allMembers"> + { if (constructors.isEmpty) NodeSeq.Empty else + <div id="constructors" class="members"> + <h3>Instance Constructors</h3> + <ol>{ constructors map (memberToHtml(_, tpl)) }</ol> + </div> + } + + { if (typeMembers.isEmpty) NodeSeq.Empty else + <div id="types" class="types members"> + <h3>Type Members</h3> + <ol>{ typeMembers map (memberToHtml(_, tpl)) }</ol> + </div> + } + + { if (absValueMembers.isEmpty) NodeSeq.Empty else + <div class="values members"> + <h3>Abstract Value Members</h3> + <ol>{ absValueMembers map (memberToHtml(_, tpl)) }</ol> + </div> + } + + { if (concValueMembers.isEmpty) NodeSeq.Empty else + <div class="values members"> + <h3>{ if (absValueMembers.isEmpty) "Value Members" else "Concrete Value Members" }</h3> + <ol>{ concValueMembers map (memberToHtml(_, tpl)) }</ol> + </div> + } + + { if (shadowedImplicitMembers.isEmpty) NodeSeq.Empty else + <div class="values members"> + <h3>Shadowed Implicit Value Members</h3> + <ol>{ shadowedImplicitMembers map (memberToHtml(_, tpl)) }</ol> + </div> + } + + { if (deprValueMembers.isEmpty) NodeSeq.Empty else + <div class="values members"> + <h3>Deprecated Value Members</h3> + <ol>{ deprValueMembers map (memberToHtml(_, tpl)) }</ol> + </div> + } + </div> + + <div id="inheritedMembers"> + { + // linearization + NodeSeq fromSeq (for ((superTpl, superType) <- (tpl.linearizationTemplates zip tpl.linearizationTypes)) yield + <div class="parent" name={ superTpl.qualifiedName }> + <h3>Inherited from { + typeToHtmlWithStupidTypes(tpl, superTpl, superType) + }</h3> + </div> + ) + } + { + // implicitly inherited + NodeSeq fromSeq (for (conversion <- (tpl.conversions)) yield + <div class="conversion" name={ conversion.conversionQualifiedName }> + <h3>Inherited by implicit conversion { conversion.conversionShortName } from + { typeToHtml(tpl.resultType, hasLinks = true) } to { typeToHtml(conversion.targetType, hasLinks = true) } + </h3> + </div> + ) + } + </div> + + <div id="groupedMembers"> + { + val allGroups = tpl.members.map(_.group).distinct + val orderedGroups = allGroups.map(group => (tpl.groupPriority(group), group)).sorted.map(_._2) + // linearization + NodeSeq fromSeq (for (group <- orderedGroups) yield + <div class="group" name={ group }> + <h3>{ tpl.groupName(group) }</h3> + { + tpl.groupDescription(group) match { + case Some(body) => <div class="comment cmt">{ bodyToHtml(body) }</div> + case _ => NodeSeq.Empty + } + } + </div> + ) + } + </div> + + </div> + + <div id="tooltip" ></div> + + { + if (Set("epfl", "EPFL").contains(tpl.universe.settings.docfooter.value)) + <div id="footer">Scala programming documentation. Copyright (c) 2003-2016 <a href="http://www.epfl.ch" target="_top">EPFL</a>, with contributions from <a href="http://typesafe.com" target="_top">Typesafe</a>.</div> + else + <div id="footer"> { tpl.universe.settings.docfooter.value } </div> + } + </body> + } + + def memberToHtml(mbr: MemberEntity, inTpl: DocTemplateEntity): NodeSeq = { + // Sometimes it's same, do we need signatureCompat still? + val sig = if (mbr.signature == mbr.signatureCompat) { + <a id={ mbr.signature }/> + } else { + <a id={ mbr.signature }/><a id={ mbr.signatureCompat }/> + } + + val memberComment = memberToCommentHtml(mbr, inTpl, isSelf = false) + <li name={ mbr.definitionName } visbl={ if (mbr.visibility.isProtected) "prt" else "pub" } + data-isabs={ mbr.isAbstract.toString } + fullComment={ if(memberComment.filter(_.label=="div").isEmpty) "no" else "yes" } + group={ mbr.group }> + { sig } + { signature(mbr, isSelf = false) } + { memberComment } + </li> + } + + def memberToCommentHtml(mbr: MemberEntity, inTpl: DocTemplateEntity, isSelf: Boolean): NodeSeq = { + mbr match { + case dte: DocTemplateEntity if isSelf => + // comment of class itself + <xml:group> + <div id="comment" class="fullcommenttop">{ memberToCommentBodyHtml(mbr, inTpl, isSelf = true) }</div> + </xml:group> + case _ => + // comment of non-class member or non-documentented inner class + val commentBody = memberToCommentBodyHtml(mbr, inTpl, isSelf = false) + if (commentBody.isEmpty) + NodeSeq.Empty + else { + val shortComment = memberToShortCommentHtml(mbr, isSelf) + val longComment = memberToUseCaseCommentHtml(mbr, isSelf) ++ memberToCommentBodyHtml(mbr, inTpl, isSelf) + + val includedLongComment = if (shortComment.text.trim == longComment.text.trim) + NodeSeq.Empty + else + <div class="fullcomment">{ longComment }</div> + + shortComment ++ includedLongComment + } + } + } + + def memberToUseCaseCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq = { + mbr match { + case nte: NonTemplateMemberEntity if nte.isUseCase => + inlineToHtml(comment.Text("[use case] ")) + case _ => NodeSeq.Empty + } + } + + def memberToShortCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq = + mbr.comment.fold(NodeSeq.Empty) { comment => + <p class="shortcomment cmt">{ memberToUseCaseCommentHtml(mbr, isSelf) }{ inlineToHtml(comment.short) }</p> + } + + def memberToInlineCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq = + <p class="comment cmt">{ inlineToHtml(mbr.comment.get.short) }</p> + + def memberToCommentBodyHtml(mbr: MemberEntity, inTpl: DocTemplateEntity, isSelf: Boolean, isReduced: Boolean = false): NodeSeq = { + val s = universe.settings + + val memberComment = + if (mbr.comment.isEmpty) NodeSeq.Empty + else <div class="comment cmt">{ commentToHtml(mbr.comment) }</div> + + val authorComment = + if (! s.docAuthor || mbr.comment.isEmpty || + mbr.comment.isDefined && mbr.comment.get.authors.isEmpty) NodeSeq.Empty + else <div class="comment cmt"> + {if (mbr.comment.get.authors.size > 1) <h6>Authors:</h6> else <h6>Author:</h6>} + { mbr.comment.get.authors map bodyToHtml} + </div> + + val paramComments = { + val prs: List[ParameterEntity] = mbr match { + case cls: Class => cls.typeParams ::: cls.valueParams.flatten + case trt: Trait => trt.typeParams + case dfe: Def => dfe.typeParams ::: dfe.valueParams.flatten + case ctr: Constructor => ctr.valueParams.flatten + case _ => Nil + } + + def paramCommentToHtml(prs: List[ParameterEntity], comment: Comment): NodeSeq = prs match { + + case (tp: TypeParam) :: rest => + val paramEntry: NodeSeq = { + <dt class="tparam">{ tp.name }</dt><dd class="cmt">{ bodyToHtml(comment.typeParams(tp.name)) }</dd> + } + paramEntry ++ paramCommentToHtml(rest, comment) + + case (vp: ValueParam) :: rest => + val paramEntry: NodeSeq = { + <dt class="param">{ vp.name }</dt><dd class="cmt">{ bodyToHtml(comment.valueParams(vp.name)) }</dd> + } + paramEntry ++ paramCommentToHtml(rest, comment) + + case _ => + NodeSeq.Empty + } + + mbr.comment.fold(NodeSeq.Empty) { comment => + val cmtedPrs = prs filter { + case tp: TypeParam => comment.typeParams isDefinedAt tp.name + case vp: ValueParam => comment.valueParams isDefinedAt vp.name + } + if (cmtedPrs.isEmpty && comment.result.isEmpty) NodeSeq.Empty + else { + <dl class="paramcmts block">{ + paramCommentToHtml(cmtedPrs, comment) ++ ( + comment.result match { + case None => NodeSeq.Empty + case Some(cmt) => + <dt>returns</dt><dd class="cmt">{ bodyToHtml(cmt) }</dd> + }) + }</dl> + } + } + } + + val implicitInformation = mbr.byConversion match { + case Some(conv) => + <dt class="implicit">Implicit</dt> ++ + { + val targetType = typeToHtml(conv.targetType, hasLinks = true) + val conversionMethod = conv.convertorMethod match { + case Left(member) => Text(member.name) + case Right(name) => Text(name) + } + + // strip off the package object endings, they make things harder to follow + val conversionOwnerQualifiedNane = conv.convertorOwner.qualifiedName.stripSuffix(".package") + val conversionOwner = templateToHtml(conv.convertorOwner, conversionOwnerQualifiedNane) + + val constraintText = conv.constraints match { + case Nil => + NodeSeq.Empty + case List(constraint) => + scala.xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint) ++ scala.xml.Text(".") + case List(constraint1, constraint2) => + scala.xml.Text("This conversion will take place only if ") ++ constraintToHtml(constraint1) ++ + scala.xml.Text(" and at the same time ") ++ constraintToHtml(constraint2) ++ scala.xml.Text(".") + case constraints => + <br/> ++ "This conversion will take place only if all of the following constraints are met:" ++ <br/> ++ { + var index = 0 + constraints map { constraint => scala.xml.Text({ index += 1; index } + ". ") ++ constraintToHtml(constraint) ++ <br/> } + } + } + + <dd> + This member is added by an implicit conversion from { typeToHtml(inTpl.resultType, hasLinks = true) } to + { targetType } performed by method { conversionMethod } in { conversionOwner }. + { constraintText } + </dd> + } ++ { + if (mbr.isShadowedOrAmbiguousImplicit) { + // These are the members that are shadowing or ambiguating the current implicit + // see ImplicitMemberShadowing trait for more information + val shadowingSuggestion = { + val params = mbr match { + case d: Def => d.valueParams map (_ map (_ name) mkString("(", ", ", ")")) mkString + case _ => "" // no parameters + } + <br/> ++ scala.xml.Text("To access this member you can use a ") ++ + <a href="http://stackoverflow.com/questions/2087250/what-is-the-purpose-of-type-ascription-in-scala" + target="_blank">type ascription</a> ++ scala.xml.Text(":") ++ + <br/> ++ <div class="cmt"><pre>{"(" + Template.lowerFirstLetter(tpl.name) + ": " + conv.targetType.name + ")." + mbr.name + params }</pre></div> + } + + val shadowingWarning: NodeSeq = + if (mbr.isShadowedImplicit) + scala.xml.Text("This implicitly inherited member is shadowed by one or more members in this " + + "class.") ++ shadowingSuggestion + else if (mbr.isAmbiguousImplicit) + scala.xml.Text("This implicitly inherited member is ambiguous. One or more implicitly " + + "inherited members have similar signatures, so calling this member may produce an ambiguous " + + "implicit conversion compiler error.") ++ shadowingSuggestion + else NodeSeq.Empty + + <dt class="implicit">Shadowing</dt> ++ + <dd>{ shadowingWarning }</dd> + + } else NodeSeq.Empty + } + case _ => + NodeSeq.Empty + } + + // --- start attributes block vals + val attributes: NodeSeq = { + val fvs: List[comment.Paragraph] = visibility(mbr).toList + if (fvs.isEmpty || isReduced) NodeSeq.Empty + else { + <dt>Attributes</dt> + <dd>{ fvs map { fv => { inlineToHtml(fv.text) ++ scala.xml.Text(" ") } } }</dd> + } + } + + val definitionClasses: NodeSeq = { + val inDefTpls = mbr.inDefinitionTemplates + if ((inDefTpls.tail.isEmpty && (inDefTpls.head == inTpl)) || isReduced) NodeSeq.Empty + else { + <dt>Definition Classes</dt> + <dd>{ templatesToHtml(inDefTpls, scala.xml.Text(" → ")) }</dd> + } + } + + val fullSignature: NodeSeq = { + mbr match { + case nte: NonTemplateMemberEntity if nte.isUseCase => + <div class="full-signature-block toggleContainer"> + <span class="toggle"> + <i class="material-icons"></i> + Full Signature + </span> + <div class="hiddenContent full-signature-usecase">{ signature(nte.useCaseOf.get,isSelf = true) }</div> + </div> + case _ => NodeSeq.Empty + } + } + + val selfType: NodeSeq = mbr match { + case dtpl: DocTemplateEntity if (isSelf && !dtpl.selfType.isEmpty && !isReduced) => + <dt>Self Type</dt> + <dd>{ typeToHtml(dtpl.selfType.get, hasLinks = true) }</dd> + case _ => NodeSeq.Empty + } + + val annotations: NodeSeq = { + // A list of annotations which don't show their arguments, e. g. because they are shown separately. + val annotationsWithHiddenArguments = List("deprecated", "Deprecated", "migration") + + def showArguments(annotation: Annotation) = + !(annotationsWithHiddenArguments.contains(annotation.qualifiedName)) + + if (!mbr.annotations.isEmpty) { + <dt>Annotations</dt> + <dd>{ + mbr.annotations.map { annot => + <xml:group> + <span class="name">@{ templateToHtml(annot.annotationClass) }</span>{ + if (showArguments(annot)) argumentsToHtml(annot.arguments) else NodeSeq.Empty + } + </xml:group> + } + } + </dd> + } else NodeSeq.Empty + } + + val sourceLink: NodeSeq = mbr match { + case dtpl: DocTemplateEntity if (isSelf && dtpl.sourceUrl.isDefined && dtpl.inSource.isDefined && !isReduced) => + val (absFile, _) = dtpl.inSource.get + <dt>Source</dt> + <dd>{ <a href={ dtpl.sourceUrl.get.toString } target="_blank">{ Text(absFile.file.getName) }</a> }</dd> + case _ => NodeSeq.Empty + } + + val deprecation: NodeSeq = + mbr.deprecation match { + case Some(deprecation) if !isReduced => + <dt>Deprecated</dt> + <dd class="cmt">{ bodyToHtml(deprecation) }</dd> + case _ => NodeSeq.Empty + } + + val migration: NodeSeq = + mbr.migration match { + case Some(migration) if !isReduced => + <dt>Migration</dt> + <dd class="cmt">{ bodyToHtml(migration) }</dd> + case _ => NodeSeq.Empty + } + + val mainComment: NodeSeq = mbr.comment match { + case Some(comment) if (! isReduced) => + def orEmpty[T](it: Iterable[T])(gen: =>NodeSeq): NodeSeq = + if (it.isEmpty) NodeSeq.Empty else gen + + val example = + orEmpty(comment.example) { + <div class="block">Example{ if (comment.example.length > 1) "s" else ""}: + <ol>{ + val exampleXml: List[NodeSeq] = for (ex <- comment.example) yield + <li class="cmt">{ bodyToHtml(ex) }</li> + exampleXml.reduceLeft(_ ++ Text(", ") ++ _) + }</ol> + </div> + } + + val version: NodeSeq = + orEmpty(comment.version) { + <dt>Version</dt> + <dd>{ for(body <- comment.version.toList) yield bodyToHtml(body) }</dd> + } + + val sinceVersion: NodeSeq = + orEmpty(comment.since) { + <dt>Since</dt> + <dd>{ for(body <- comment.since.toList) yield bodyToHtml(body) }</dd> + } + + val note: NodeSeq = + orEmpty(comment.note) { + <dt>Note</dt> + <dd>{ + val noteXml: List[NodeSeq] = for(note <- comment.note ) yield <span class="cmt">{bodyToHtml(note)}</span> + noteXml.reduceLeft(_ ++ Text(", ") ++ _) + }</dd> + } + + val seeAlso: NodeSeq = + orEmpty(comment.see) { + <dt>See also</dt> + <dd>{ + val seeXml: List[NodeSeq] = for(see <- comment.see ) yield <span class="cmt">{bodyToHtml(see)}</span> + seeXml.reduceLeft(_ ++ _) + }</dd> + } + + val exceptions: NodeSeq = + orEmpty(comment.throws) { + <dt>Exceptions thrown</dt> + <dd>{ + val exceptionsXml: List[NodeSeq] = + for((name, body) <- comment.throws.toList.sortBy(_._1) ) yield + <span class="cmt">{bodyToHtml(body)}</span> + exceptionsXml.reduceLeft(_ ++ Text("") ++ _) + }</dd> + } + + val todo: NodeSeq = + orEmpty(comment.todo) { + <dt>To do</dt> + <dd>{ + val todoXml: List[NodeSeq] = (for(todo <- comment.todo ) yield <span class="cmt">{bodyToHtml(todo)}</span> ) + todoXml.reduceLeft(_ ++ _) + }</dd> + } + + example ++ version ++ sinceVersion ++ exceptions ++ todo ++ note ++ seeAlso + + case _ => NodeSeq.Empty + } + // end attributes block vals --- + + val attributesInfo = implicitInformation ++ attributes ++ definitionClasses ++ fullSignature ++ selfType ++ annotations ++ deprecation ++ migration ++ sourceLink ++ mainComment + val attributesBlock = + if (attributesInfo.isEmpty) + NodeSeq.Empty + else + <dl class="attributes block"> { attributesInfo }</dl> + + val linearization = mbr match { + case dtpl: DocTemplateEntity if isSelf && !isReduced && dtpl.linearizationTemplates.nonEmpty => + <div class="toggleContainer block"> + <span class="toggle"> + <i class="material-icons"></i> + Linear Supertypes + </span> + <div class="superTypes hiddenContent">{ + typesToHtml(dtpl.linearizationTypes, hasLinks = true, sep = scala.xml.Text(", ")) + }</div> + </div> + case _ => NodeSeq.Empty + } + + val subclasses = mbr match { + case dtpl: DocTemplateEntity if isSelf && !isReduced => + val subs = mutable.HashSet.empty[DocTemplateEntity] + def transitive(dtpl: DocTemplateEntity) { + for (sub <- dtpl.directSubClasses if !(subs contains sub)) { + subs add sub + transitive(sub) + } + } + transitive(dtpl) + if (subs.nonEmpty) + <div class="toggleContainer block"> + <span class="toggle"> + <i class="material-icons"></i> + Known Subclasses + </span> + <div class="subClasses hiddenContent">{ + templatesToHtml(subs.toList.sorted(Entity.EntityOrdering), scala.xml.Text(", ")) + }</div> + </div> + else NodeSeq.Empty + case _ => NodeSeq.Empty + } + + def createDiagram(f: DocTemplateEntity => Option[Diagram], description: String, id: String): NodeSeq = + if (s.docDiagrams.value) mbr match { + case dtpl: DocTemplateEntity if isSelf && !isReduced => + val diagram = f(dtpl) + if (diagram.isDefined) { + val diagramSvg = generator.generate(diagram.get, tpl, this) + if (diagramSvg != NodeSeq.Empty) { + <div class="toggleContainer block diagram-container" id={ id + "-container"}> + <span class="toggle diagram-link"> + <i class="material-icons"></i> + { description } + </span> + <div class="diagram" id={ id }>{ diagramSvg }</div> + <div id="diagram-controls" class="hiddenContent"> + <button id="diagram-zoom-out" class="diagram-btn"><i class="material-icons"></i></button> + <button id="diagram-zoom-in" class="diagram-btn"><i class="material-icons"></i></button> + <button title="Toggle full-screen" id="diagram-fs" class="diagram-btn to-full"><i class="material-icons"></i></button> + </div> + </div> + } else NodeSeq.Empty + } else NodeSeq.Empty + case _ => NodeSeq.Empty + } else NodeSeq.Empty // diagrams not generated + + val typeHierarchy = createDiagram(_.inheritanceDiagram, "Type Hierarchy", "inheritance-diagram") + val contentHierarchy = createDiagram(_.contentDiagram, "Content Hierarchy", "content-diagram") + + memberComment ++ authorComment ++ paramComments ++ attributesBlock ++ linearization ++ subclasses ++ typeHierarchy ++ contentHierarchy + } + + def boundsToHtml(hi: Option[TypeEntity], lo: Option[TypeEntity], hasLinks: Boolean): NodeSeq = { + def bound0(bnd: Option[TypeEntity], pre: String): NodeSeq = bnd match { + case None => NodeSeq.Empty + case Some(tpe) => scala.xml.Text(pre) ++ typeToHtml(tpe, hasLinks) + } + bound0(lo, " >: ") ++ bound0(hi, " <: ") + } + + def visibility(mbr: MemberEntity): Option[comment.Paragraph] = { + import comment._ + import comment.{ Text => CText } + mbr.visibility match { + case PrivateInInstance() => + Some(Paragraph(CText("private[this]"))) + case PrivateInTemplate(owner) if (owner == mbr.inTemplate) => + Some(Paragraph(CText("private"))) + case PrivateInTemplate(owner) => + Some(Paragraph(Chain(List(CText("private["), EntityLink(comment.Text(owner.qualifiedName), LinkToTpl(owner)), CText("]"))))) + case ProtectedInInstance() => + Some(Paragraph(CText("protected[this]"))) + case ProtectedInTemplate(owner) if (owner == mbr.inTemplate) => + Some(Paragraph(CText("protected"))) + case ProtectedInTemplate(owner) => + Some(Paragraph(Chain(List(CText("protected["), EntityLink(comment.Text(owner.qualifiedName), LinkToTpl(owner)), CText("]"))))) + case Public() => + None + } + } + + /** name, tparams, params, result */ + def signature(mbr: MemberEntity, isSelf: Boolean, isReduced: Boolean = false): NodeSeq = { + + def inside(hasLinks: Boolean, nameLink: String = ""): NodeSeq = + <xml:group> + <span class="modifier_kind"> + <i class="material-icons unfold-arrow"></i> + <span class="modifier">{ mbr.flags.map(flag => inlineToHtml(flag.text) ++ scala.xml.Text(" ")) }</span> + <span class="kind">{ kindToString(mbr) }</span> + </span> + <span class="symbol"> + { + val nameClass = + if (mbr.isImplicitlyInherited) + if (mbr.isShadowedOrAmbiguousImplicit) + "implicit shadowed" + else + "implicit" + else + "name" + + val nameHtml = { + val value = if (mbr.isConstructor) tpl.name else mbr.name + val span = if (mbr.deprecation.isDefined) + <span class={ nameClass + " deprecated"} title={"Deprecated: "+bodyToStr(mbr.deprecation.get)}>{ value }</span> + else + <span class={ nameClass }>{ value }</span> + val encoded = scala.reflect.NameTransformer.encode(value) + if (encoded != value) { + span % new UnprefixedAttribute("title", + "gt4s: " + encoded + + span.attribute("title").map( + node => ". " + node + ).getOrElse(""), + scala.xml.Null) + } else { + span + } + } + if (!nameLink.isEmpty) + <a href={nameLink}>{nameHtml}</a> + else nameHtml + }{ + def tparamsToHtml(mbr: Any): NodeSeq = mbr match { + case hk: HigherKinded => + val tpss = hk.typeParams + if (tpss.isEmpty) NodeSeq.Empty else { + def tparam0(tp: TypeParam): NodeSeq = + <span name={ tp.name }>{ tp.variance + tp.name }{ tparamsToHtml(tp) }{ boundsToHtml(tp.hi, tp.lo, hasLinks)}</span> + def tparams0(tpss: List[TypeParam]): NodeSeq = (tpss: @unchecked) match { + case tp :: Nil => tparam0(tp) + case tp :: tps => tparam0(tp) ++ Text(", ") ++ tparams0(tps) + } + <span class="tparams">[{ tparams0(tpss) }]</span> + } + case _ => NodeSeq.Empty + } + tparamsToHtml(mbr) + }{ + if (isReduced) NodeSeq.Empty else { + def paramsToHtml(vlsss: List[List[ValueParam]]): NodeSeq = { + def param0(vl: ValueParam): NodeSeq = + // notice the }{ in the next lines, they are necessary to avoid an undesired whitespace in output + <span name={ vl.name }>{ + Text(vl.name) + }{ Text(": ") ++ typeToHtml(vl.resultType, hasLinks) }{ + vl.defaultValue match { + case Some(v) => Text(" = ") ++ treeToHtml(v) + case None => NodeSeq.Empty + } + }</span> + + def params0(vlss: List[ValueParam]): NodeSeq = vlss match { + case Nil => NodeSeq.Empty + case vl :: Nil => param0(vl) + case vl :: vls => param0(vl) ++ Text(", ") ++ params0(vls) + } + def implicitCheck(vlss: List[ValueParam]): NodeSeq = vlss match { + case vl :: vls => if(vl.isImplicit) { <span class="implicit">implicit </span> } else Text("") + case _ => Text("") + } + vlsss map { vlss => <span class="params">({implicitCheck(vlss) ++ params0(vlss) })</span> } + } + mbr match { + case cls: Class => paramsToHtml(cls.valueParams) + case ctr: Constructor => paramsToHtml(ctr.valueParams) + case dfe: Def => paramsToHtml(dfe.valueParams) + case _ => NodeSeq.Empty + } + } + }{ if (isReduced) NodeSeq.Empty else { + mbr match { + case tme: MemberEntity if (tme.isDef || tme.isVal || tme.isLazyVal || tme.isVar) => + <span class="result">: { typeToHtml(tme.resultType, hasLinks) }</span> + + case abt: MemberEntity with AbstractType => + val b2s = boundsToHtml(abt.hi, abt.lo, hasLinks) + if (b2s != NodeSeq.Empty) + <span class="result">{ b2s }</span> + else NodeSeq.Empty + + case alt: MemberEntity with AliasType => + <span class="result"> = { typeToHtml(alt.alias, hasLinks) }</span> + + case tpl: MemberTemplateEntity if !tpl.parentTypes.isEmpty => + <span class="result"> extends { typeToHtml(tpl.parentTypes.map(_._2), hasLinks) }</span> + + case _ => NodeSeq.Empty + } + }} + </span> + </xml:group> + mbr match { + case dte: DocTemplateEntity if !isSelf => + permalink(dte, isSelf) ++ { inside(hasLinks = true, nameLink = relativeLinkTo(dte)) } + case _ if isSelf => + <h4 id="signature" class="signature">{ inside(hasLinks = true) }</h4> + case _ => + permalink(mbr) ++ { inside(hasLinks = true) } + } + + } + + /** */ + def treeToHtml(tree: TreeEntity): NodeSeq = { + + /** Makes text good looking in the html page : newlines and basic indentation, + * You must change this function if you want to improve pretty printing of default Values + */ + def codeStringToXml(text: String): NodeSeq = { + var goodLookingXml: NodeSeq = NodeSeq.Empty + var indent = 0 + for (c <- text) c match { + case '{' => indent+=1 + goodLookingXml ++= Text("{") + case '}' => indent-=1 + goodLookingXml ++= Text("}") + case '\n' => + goodLookingXml++= <br/> ++ indentation + case _ => goodLookingXml ++= Text(c.toString) + } + def indentation:NodeSeq = { + var indentXml = NodeSeq.Empty + for (x <- 1 to indent) indentXml ++= Text(" ") + indentXml + } + goodLookingXml + } + + var index = 0 + val str = tree.expression + val length = str.length + var myXml: NodeSeq = NodeSeq.Empty + for ((from, (member, to)) <- tree.refEntity.toSeq) { + if (index < from) { + myXml ++= codeStringToXml(str.substring(index,from)) + index = from + } + if (index == from) { + member match { + case mbr: DocTemplateEntity => + val link = relativeLinkTo(mbr) + myXml ++= <span class="name"><a href={link}>{str.substring(from, to)}</a></span> + case mbr: MemberEntity => + val anchor = "#" + mbr.signature + val link = relativeLinkTo(mbr.inTemplate) + myXml ++= <span class="name"><a href={link ++ anchor}>{str.substring(from, to)}</a></span> + } + index = to + } + } + + if (index <= length-1) + myXml ++= codeStringToXml(str.substring(index, length )) + + if (length < 36) + <span class="symbol">{ myXml }</span> + else + <span class="defval" name={ myXml }>{ "..." }</span> + } + + private def argumentsToHtml(argss: List[ValueArgument]): NodeSeq = { + def argumentsToHtml0(argss: List[ValueArgument]): NodeSeq = argss match { + case Nil => NodeSeq.Empty + case arg :: Nil => argumentToHtml(arg) + case arg :: args => argumentToHtml(arg) ++ scala.xml.Text(", ") ++ argumentsToHtml0(args) + } + <span class="args">({ argumentsToHtml0(argss) })</span> + } + + private def argumentToHtml(arg: ValueArgument): NodeSeq = { + <span> + { + arg.parameter match { + case Some(param) => Text(param.name + " = ") + case None => NodeSeq.Empty + } + } + { treeToHtml(arg.value) } + </span> + } + + private def bodyToStr(body: comment.Body): String = + body.blocks flatMap (blockToStr(_)) mkString "" + + private def blockToStr(block: comment.Block): String = block match { + case comment.Paragraph(in) => inlineToStr(in) + case _ => block.toString + } + + private def typeToHtmlWithStupidTypes(tpl: TemplateEntity, superTpl: TemplateEntity, superType: TypeEntity): NodeSeq = + if (tpl.universe.settings.useStupidTypes.value) + superTpl match { + case dtpl: DocTemplateEntity => + val sig = signature(dtpl, isSelf = false, isReduced = true) \ "_" + sig + case tpl: TemplateEntity => + Text(tpl.name) + } + else + typeToHtml(superType, hasLinks = true) + + private def constraintToHtml(constraint: Constraint): NodeSeq = constraint match { + case ktcc: KnownTypeClassConstraint => + scala.xml.Text(ktcc.typeExplanation(ktcc.typeParamName) + " (" + ktcc.typeParamName + ": ") ++ + templateToHtml(ktcc.typeClassEntity) ++ scala.xml.Text(")") + case tcc: TypeClassConstraint => + scala.xml.Text(tcc.typeParamName + " is ") ++ + <a href="http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala" target="_blank"> + context-bounded</a> ++ scala.xml.Text(" by " + tcc.typeClassEntity.qualifiedName + " (" + tcc.typeParamName + ": ") ++ + templateToHtml(tcc.typeClassEntity) ++ scala.xml.Text(")") + case impl: ImplicitInScopeConstraint => + scala.xml.Text("an implicit value of type ") ++ typeToHtml(impl.implicitType, hasLinks = true) ++ scala.xml.Text(" is in scope") + case eq: EqualTypeParamConstraint => + scala.xml.Text(eq.typeParamName + " is " + eq.rhs.name + " (" + eq.typeParamName + " =:= ") ++ + typeToHtml(eq.rhs, hasLinks = true) ++ scala.xml.Text(")") + case bt: BoundedTypeParamConstraint => + scala.xml.Text(bt.typeParamName + " is a superclass of " + bt.lowerBound.name + " and a subclass of " + + bt.upperBound.name + " (" + bt.typeParamName + " >: ") ++ + typeToHtml(bt.lowerBound, hasLinks = true) ++ scala.xml.Text(" <: ") ++ + typeToHtml(bt.upperBound, hasLinks = true) ++ scala.xml.Text(")") + case lb: LowerBoundedTypeParamConstraint => + scala.xml.Text(lb.typeParamName + " is a superclass of " + lb.lowerBound.name + " (" + lb.typeParamName + " >: ") ++ + typeToHtml(lb.lowerBound, hasLinks = true) ++ scala.xml.Text(")") + case ub: UpperBoundedTypeParamConstraint => + scala.xml.Text(ub.typeParamName + " is a subclass of " + ub.upperBound.name + " (" + ub.typeParamName + " <: ") ++ + typeToHtml(ub.upperBound, hasLinks = true) ++ scala.xml.Text(")") + } +} + +object EntityPage { + def apply( + uni: doc.Universe, + gen: DiagramGenerator, + docTpl: DocTemplateEntity, + rep: ScalaDocReporter + ): EntityPage = new EntityPage { + def universe = uni + def generator = gen + def tpl = docTpl + def reporter = rep + } +} diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/Index.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/Index.scala index 1aa1241847..8204f413fd 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/Index.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/Index.scala @@ -1,6 +1,6 @@ /* NSC -- new Scala compiler * Copyright 2007-2013 LAMP/EPFL - * @author David Bernard, Manohar Jonnalagedda + * @author David Bernard, Manohar Jonnalagedda, Felix Mulder */ package scala.tools.nsc @@ -12,115 +12,60 @@ import model._ import scala.collection._ import scala.xml._ -class Index(universe: doc.Universe, val index: doc.Index) extends HtmlPage { +class Index(universe: doc.Universe, val index: doc.Index, rep: ScalaDocReporter) extends HtmlPage { + + def reporter = rep def path = List("index.html") - def title = { - val s = universe.settings - ( if (!s.doctitle.isDefault) s.doctitle.value else "" ) + - ( if (!s.docversion.isDefault) (" " + s.docversion.value) else "" ) - } + def title = "" val headers = <xml:group> <link href={ relativeLinkTo{List("index.css", "lib")} } media="screen" type="text/css" rel="stylesheet"/> <script type="text/javascript" src={ relativeLinkTo{List("jquery.js", "lib")} }></script> <script type="text/javascript" src={ relativeLinkTo{List("index.js", "lib")} }></script> + <script type="text/javascript" src="index.js"></script> <script type="text/javascript" src={ relativeLinkTo{List("scheduler.js", "lib")} }></script> </xml:group> val body = <body> - { browser } - <div id="content" class="ui-layout-center"> + { search } + <div id="search-results"> + <div id="results-content"> + <div id="entity-results"></div> + <div id="member-results"></div> + </div> + </div> + <div id="content" style="-webkit-overflow-scrolling: touch;"> <iframe id="template" name="template" src={ relativeLinkTo{List("package.html")} }/> </div> </body> - def letters: NodeSeq = - '_' +: ('a' to 'z') map { - char => { - val label = if (char == '_') '#' else char.toUpper - - index.firstLetterIndex.get(char) match { - case Some(_) => - <a target="template" href={ "index/index-" + char + ".html" }>{ - label - }</a> - case None => <span>{ label }</span> - } - } - } - - def deprecated: NodeSeq = if (index.hasDeprecatedMembers) - <a target="template" href="deprecated-list.html">deprecated</a> - else - <span>deprecated</span> - - def browser = - <div id="browser" class="ui-layout-west"> - <div class="ui-west-center"> - <div id="filter"> - <div id="textfilter"></div> - <div id="letters">{ letters } – { deprecated }</div> - </div> - <div class="pack" id="tpl">{ - def packageElem(pack: model.Package): NodeSeq = { - <xml:group> - { if (!pack.isRootPackage) - <a class="tplshow" href={ relativeLinkTo(pack) } target="template">{ pack.qualifiedName }</a> - else NodeSeq.Empty - } - <ol class="templates">{ - val tpls: Map[String, Seq[DocTemplateEntity]] = - (pack.templates collect { - case t: DocTemplateEntity if !t.isPackage && !universe.settings.hardcoded.isExcluded(t.qualifiedName) => t - }) groupBy (_.name) - - val placeholderSeq: NodeSeq = <div class="placeholder"></div> - - def createLink(entity: DocTemplateEntity, includePlaceholder: Boolean, includeText: Boolean) = { - val entityType = kindToString(entity) - val linkContent = ( - { if (includePlaceholder) placeholderSeq else NodeSeq.Empty } - ++ - { if (includeText) <span class="tplLink">{ Text(packageQualifiedName(entity)) }</span> else NodeSeq.Empty } - ) - <a class="tplshow" href={ relativeLinkTo(entity) } target="template"><span class={ entityType }>({ Text(entityType) })</span>{ linkContent }</a> - } - - for (tn <- tpls.keySet.toSeq sortBy (_.toLowerCase)) yield { - val entities = tpls(tn) - val row = (entities find (e => e.isPackage || e.isObject), entities find (e => e.isTrait || e.isClass)) - - val itemContents = row match { - case (Some(obj), None) => createLink(obj, includePlaceholder = true, includeText = true) - - case (maybeObj, Some(template)) => - val firstLink = maybeObj match { - case Some(obj) => createLink(obj, includePlaceholder = false, includeText = false) - case None => placeholderSeq - } - - firstLink ++ createLink(template, includePlaceholder = false, includeText = true) - - case _ => // FIXME: this default case should not be necessary. For some reason AnyRef is not a package, object, trait, or class - val entry = entities.head - placeholderSeq ++ createLink(entry, includePlaceholder = false, includeText = true) - } - - <li title={ entities.head.qualifiedName }>{ itemContents }</li> - } - }</ol> - <ol class="packages"> { - for (sp <- pack.packages sortBy (_.name.toLowerCase)) yield - <li class="pack" title={ sp.qualifiedName }>{ packageElem(sp) }</li> - }</ol> - </xml:group> - } - packageElem(universe.rootPackage) - }</div></div><script src="index.js"></script> + def search = + <div id="search"> + <span id="doc-title"> + {universe.settings.doctitle.value} + <span id="doc-version"> + { + val version = universe.settings.docversion.value + + if (version.length > "XX.XX.XX-XXX".length) { + reporter.warning(null, + s"doc-version ($version) is too long to be displayed in the webview") + "" + } else version + } + </span> + </span> + <span class="close-results"><span class="left"><</span> Back</span> + <div id="textfilter"> + <span class="input"> + <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/"/> + <span class="clear">✖</span> + </span> + </div> </div> def packageQualifiedName(ety: DocTemplateEntity): String = diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/IndexScript.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/IndexScript.scala index e3c94505ab..2c38036bb6 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/IndexScript.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/IndexScript.scala @@ -1,16 +1,22 @@ /* NSC -- new Scala compiler - * Copyright 2007-2013 LAMP/EPFL - * @author David Bernard, Manohar Jonnalagedda + * Copyright 2007-2016 LAMP/EPFL + * @author David Bernard, Manohar Jonnalagedda, Felix Mulder */ -package scala.tools.nsc.doc.html.page +package scala.tools.nsc.doc +package html +package page import scala.tools.nsc.doc import scala.tools.nsc.doc.model.{Package, DocTemplateEntity} import scala.tools.nsc.doc.html.{Page, HtmlFactory} -import scala.util.parsing.json.{JSONObject, JSONArray} +import scala.util.parsing.json.{JSONObject, JSONArray, JSONType} class IndexScript(universe: doc.Universe, index: doc.Index) extends Page { + import model._ + import scala.tools.nsc.doc.base.comment.Text + import scala.collection.immutable.Map + def path = List("index.js") override def writeFor(site: HtmlFactory) { @@ -25,18 +31,22 @@ class IndexScript(universe: doc.Universe, index: doc.Index) extends Page { val merged = mergeByQualifiedName(templates) val ary = merged.keys.toList.sortBy(_.toLowerCase).map(key => { - val pairs = merged(key).map( - t => kindToString(t) -> relativeLinkTo(t) - ) :+ ("name" -> key) + val pairs = merged(key).flatMap { t: DocTemplateEntity => + Seq( + kindToString(t) -> relativeLinkTo(t), + "kind" -> kindToString(t), + "members" -> membersToJSON(t.members.filter(!_.isShadowedOrAmbiguousImplicit)), + "shortDescription" -> shortDesc(t)) + } - JSONObject(scala.collection.immutable.Map(pairs : _*)) + JSONObject(Map(pairs : _*) + ("name" -> key)) }) pack.qualifiedName -> JSONArray(ary) } }).toSeq - JSONObject(scala.collection.immutable.Map(pairs : _*)) + JSONObject(Map(pairs : _*)) } def mergeByQualifiedName(source: List[DocTemplateEntity]) = { @@ -66,4 +76,70 @@ class IndexScript(universe: doc.Universe, index: doc.Index) extends Page { } }) : _*) } + + /** Gets the short description i.e. the first sentence of the docstring */ + def shortDesc(mbr: MemberEntity): String = mbr.comment.fold("") { c => + inlineToStr(c.short).replaceAll("\n", "") + } + + /** Returns the json representation of the supplied members */ + def membersToJSON(entities: List[MemberEntity]): JSONType = + JSONArray(entities map memberToJSON) + + private def memberToJSON(mbr: MemberEntity): JSONObject = { + /** This function takes a member and gets eventual parameters and the + * return type. For example, the definition: + * {{{ def get(key: A): Option[B] }}} + * Gets turned into: "(key: A): Option[B]" + */ + def memberTail: MemberEntity => String = { + case d: Def => d + .valueParams //List[List[ValueParam]] + .map { params => + params.map(p => p.name + ": " + p.resultType.name).mkString(", ") + } + .mkString("(", ")(", "): " + d.resultType.name) + case v: Val => ": " + v.resultType.name + } + + /** This function takes a member entity and return all modifiers in a + * string, example: + * {{{ lazy val scalaProps: java.util.Properties }}} + * Gets turned into: "lazy val" + */ + def memberKindToString(mbr: MemberEntity): String = { + val kind = mbr.flags.map(_.text.asInstanceOf[Text].text).mkString(" ") + val space = if (kind == "") "" else " " + + kind + space + kindToString(mbr) + } + + /** This function turns a member entity into a JSON object that the index.js + * script can use to render search results + */ + def jsonObject(m: MemberEntity): JSONObject = + JSONObject(Map( + "label" -> m.definitionName.replaceAll(".*#", ""), // member name + "member" -> m.definitionName.replaceFirst("#", "."), // full member name + "tail" -> memberTail(m), + "kind" -> memberKindToString(m), // modifiers i.e. "abstract def" + "link" -> memberToUrl(m))) // permalink to the member + + mbr match { + case d: Def => jsonObject(d) + case v: Val => jsonObject(v) + case m: MemberEntity => + JSONObject(Map("member" -> m.definitionName, "error" -> "unsupported entity")) + } + } + + def memberToUrl(mbr: MemberEntity): String = { + val path = templateToPath(mbr.inTemplate).reverse.mkString("/") + s"$path#${mbr.signature}" + } +} + +object IndexScript { + def apply(universe: doc.Universe, index: doc.Index) = + new IndexScript(universe, index) } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala index 84ee82f994..6780f17a8c 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/ReferenceIndex.scala @@ -12,7 +12,9 @@ package page import doc.model._ -class ReferenceIndex(letter: Char, index: doc.Index, universe: Universe) extends HtmlPage { +class ReferenceIndex(letter: Char, index: doc.Index, universe: Universe, rep: ScalaDocReporter) extends HtmlPage { + + def reporter = rep def path = List("index-"+letter+".html", "index") diff --git a/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala b/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala index 6e87f2b0a9..f5e909cf90 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala +++ b/src/scaladoc/scala/tools/nsc/doc/html/page/Template.scala @@ -21,18 +21,17 @@ import model._ import model.diagram._ import diagram._ -class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemplateEntity) extends HtmlPage { +class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemplateEntity, rep: ScalaDocReporter) extends HtmlPage { - val path = - templateToPath(tpl) + def reporter = rep + + val path = templateToPath(tpl) def title = { val s = universe.settings - - tpl.name + - ( if (!s.doctitle.isDefault) " - " + s.doctitle.value else "" ) + - ( if (!s.docversion.isDefault) (" " + s.docversion.value) else "" ) + - " - " + tpl.qualifiedName + ( if (!s.doctitle.isDefault) s.doctitle.value + " " else "" ) + + ( if (!s.docversion.isDefault) s.docversion.value else "" ) + + ( if ((!s.doctitle.isDefault || !s.docversion.isDefault) && tpl.qualifiedName != "_root_") " - " + tpl.qualifiedName else "" ) } val headers = @@ -116,9 +115,9 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp <h1>{ displayName }</h1>{ if (tpl.isPackage) NodeSeq.Empty else <h3>{companionAndPackage(tpl)}</h3> }{ permalink(tpl) } + { signature(tpl, isSelf = true) } </div> - { signature(tpl, isSelf = true) } { memberToCommentHtml(tpl, tpl.inTemplate, isSelf = true) } <div id="mbrsel"> @@ -940,17 +939,6 @@ class Template(universe: doc.Universe, generator: DiagramGenerator, tpl: DocTemp case _ => block.toString } - private def inlineToStr(inl: comment.Inline): String = inl match { - case comment.Chain(items) => items flatMap (inlineToStr(_)) mkString "" - case comment.Italic(in) => inlineToStr(in) - case comment.Bold(in) => inlineToStr(in) - case comment.Underline(in) => inlineToStr(in) - case comment.Monospace(in) => inlineToStr(in) - case comment.Text(text) => text - case comment.Summary(in) => inlineToStr(in) - case _ => inl.toString - } - private def typeToHtmlWithStupidTypes(tpl: TemplateEntity, superTpl: TemplateEntity, superType: TypeEntity): NodeSeq = if (tpl.universe.settings.useStupidTypes.value) superTpl match { diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.css b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.css index 1260d860d0..ea1c358149 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.css +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.css @@ -2,6 +2,17 @@ @font-face { font-family: 'Lato'; font-style: normal; + font-weight: 100; + src: url('lato-v11-latin-regular.eot'); + src: local('Lato'), local('Lato'), + url('lato-v11-latin-100.eot?#iefix') format('embedded-opentype'), + url('lato-v11-latin-100.woff') format('woff'), + url('lato-v11-latin-100.ttf') format('truetype'); +} + +@font-face { + font-family: 'Lato'; + font-style: normal; font-weight: 400; src: url('lato-v11-latin-regular.eot'); src: local('Lato'), local('Lato'), @@ -21,6 +32,27 @@ url('open-sans-v13-latin-regular.ttf') format('truetype'); } +@font-face { + font-family: 'Source Code Pro'; + font-style: normal; + font-weight: 400; + src: url('source-code-pro-v6-latin-regular.eot'); + src: local('Source Code Pro'), local('SourceCodePro-Regular'), + url('source-code-pro-v6-latin-regular.eot?#iefix') format('embedded-opentype'), + url('source-code-pro-v6-latin-regular.woff') format('woff'), + url('source-code-pro-v6-latin-regular.ttf') format('truetype'); +} +@font-face { + font-family: 'Source Code Pro'; + font-style: normal; + font-weight: 700; + src: url('source-code-pro-v6-latin-700.eot'); + src: local('Source Code Pro Bold'), local('SourceCodePro-Bold'), + url('source-code-pro-v6-latin-700.eot?#iefix') format('embedded-opentype'), + url('source-code-pro-v6-latin-700.woff') format('woff'), + url('source-code-pro-v6-latin-700.ttf') format('truetype'); +} + * { color: inherit; text-decoration: none; @@ -31,18 +63,25 @@ a { cursor: pointer; + text-decoration: none; } a:hover { text-decoration: underline; } -.selected { - background-color: #2E6D82; +span.entity > a { + padding: 0.1em 0.5em; + margin-left: 0.2em; +} + +span.entity > a.selected { + background-color: #C2D2DC; + border-radius: 0.2em; } html { - background-color: #364550; + background-color: #f0f3f6; box-sizing: border-box; } *, *:before, *:after { @@ -56,51 +95,46 @@ textarea, input { outline: none; } } #browser { - width: 16.75em; + width: 17.5em; top: 0px; left: 0; bottom: 0px; display: block; position: fixed; - background-color: #364550; + background-color: #f0f3f6; } #browser.full-screen { - left: -15em; + left: -17.5em; } -#filter { - position: absolute; - display: block; - right: 0; - left: 0; - top: 0; - background-color: #364550; /* light gray */ - border-top:0; - border-left:0; - border-right:0; - z-index: 99; +#search { + background-color: #103a51; /* typesafe blue */ min-height: 5.5em; + position: fixed; + top: 0; + left: 0; + right: 0; + height: 3em; + min-height: initial; + z-index: 103; + box-shadow: 0 0 4px rgba(0, 0, 0, 0.18), 0 4px 8px rgba(0, 0, 0, 0.28); } -#filter.scrolled { - box-shadow: 0 0 8px rgba(0,0,0,0.5); -} - -#filter > h1 { +#search > h1 { font-size: 2em; position: absolute; left: 0.25em; top: 0.5em; } -#filter > h2 { +#search > h2 { position: absolute; left: 3.8em; top: 3em; } -#filter > img.scala-logo { +#search > img.scala-logo { width: 3em; height: auto; position: absolute; @@ -108,22 +142,39 @@ textarea, input { outline: none; } top: 0.43em; } -#filter > span.toggle-sidebar { +#search > span.toggle-sidebar { position: absolute; top: 0.8em; - right: 0.2em; + left: 0.2em; color: #fff; z-index: 99; width: 1.5em; height: 1.5em; } -#filter > span.toggle-sidebar:hover { +#search > span#doc-title { + color: #fff; + position: absolute; + top: 0.8em; + left: 0; + width: 18em; + text-align: center; + cursor: pointer; + z-index: 2; +} + +#search > span#doc-title > span#doc-version { + color: #c2c2c2; + font-weight: 100; + font-size: 0.72em; +} + +#search > span.toggle-sidebar:hover { cursor: pointer; } /* Pseudo element replacing UTF8-symbol "Trigram From Heaven" */ -#filter > span.toggle-sidebar:before { +#search > span.toggle-sidebar:before { position: absolute; top: -0.45em; left: 0.45em; @@ -134,7 +185,7 @@ textarea, input { outline: none; } box-shadow: 0 0.8em 0 1px #fff, 0 1.1em 0 1px #fff, 0 1.4em 0 1px #fff; } -#filter > span.toggle-sidebar:hover:before { +#search > span.toggle-sidebar:hover:before { -webkit-box-shadow: 0 0.8em 0 1px #c2c2c2, 0 1.1em 0 1px #c2c2c2, 0 1.4em 0 1px #c2c2c2; box-shadow: 0 0.8em 0 1px #c2c2c2, 0 1.1em 0 1px #c2c2c2, 0 1.4em 0 1px #c2c2c2; } @@ -149,20 +200,29 @@ textarea, input { outline: none; } } #textfilter { - position: relative; + position: absolute; + top: 0.5em; + bottom: 0.8em; + left: 0; + right: 0; display: block; - height: 20px; - margin-top: 0.5em; - margin-bottom: 0.8em; + height: 2em; } #textfilter > .input { + position: relative; display: block; + padding: 0.2em; + max-width: 48.5em; + margin: 0 auto; +} + +#textfilter > .input > i#search-icon { + color: rgba(255,255,255, 0.4); position: absolute; - top: 0; - left: 0; - padding: 0.2em 1.8em 0.2em 0.5em; - width: 100%; + left: 0.34em; + top: 0.3em; + font-size: 1.3rem; } #textfilter > span.toggle { @@ -199,29 +259,46 @@ textarea, input { outline: none; } font-family: "Open Sans"; font-size: 0.85em; height: 2em; - padding: 0 0.5em; + padding: 0 0 0 2.1em; color: #fff; width: 100%; border-radius: 0.2em; background: rgba(255, 255, 255, 0.2); } + +#textfilter > .input > input::-webkit-input-placeholder { + color: rgba(255, 255, 255, 0.4); +} + +#textfilter > .input > input::-moz-placeholder { + color: rgba(255, 255, 255, 0.4); +} + +#textfilter > .input > input:-ms-input-placeholder { + color: rgba(255, 255, 255, 0.4); +} + +#textfilter > .input > input:-moz-placeholder { + color: rgba(255, 255, 255, 0.4); +} + #focusfilter > .focusremove:hover { text-decoration: none; } -#textfilter > .clear { +#textfilter > .input > .clear { display: none; position: absolute; font-size: 0.9em; - top: 0.53em; - right: 1.8em; + top: 0.7em; + right: 0.1em; height: 23px; width: 21px; color: rgba(255, 255, 255, 0.4); } -#textfilter > .clear:hover { +#textfilter > .input > .clear:hover { cursor: pointer; color: #fff; } @@ -230,11 +307,27 @@ textarea, input { outline: none; } font-size: 0.9em; position: relative; text-align: center; - display: block; + display: none; padding: 0.6em; background-color: #f16665; color: #fff; - margin-top: 0.65em; + margin: 3.9em 0.55em 0 0.35em; + border-radius: 0.2em; + z-index: 1; +} + +div#search-progress { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 0.25em; +} + +div#search-progress > div#progress-fill { + width: 0%; + background-color: #f16665; + transition: 0.1s; } #focusfilter .focuscoll { @@ -252,7 +345,7 @@ textarea, input { outline: none; } z-index: 99; bottom: 0.5em; left: 0; - width: 16.75em; + width: 17.25em; } #kindfilter { @@ -300,177 +393,344 @@ textarea, input { outline: none; } color: #bbb; } -#tpl { - font-size: 0.8em; - overflow: auto; +div#content-container { + position: absolute; + top: 0; right: 0; - left: 0; bottom: 0; - top: 6.9em !important; - position: absolute; + left: 0; + z-index: 100; + overflow-x: hidden; + overflow-y: auto; +} + +div#content-container > div#content { + -webkit-overflow-scrolling: touch; display: block; - background-color: #364550; - padding-top: 0.3em; + overflow-y: auto; + max-width: 1140px; + margin: 5em auto 0; } -#tpl.packfocused { - top: 9.5em !important; +div#search-results { + color: #103a51; + position: absolute; + left: 0; + top: 3em; + right: 0; + bottom: 0; + background-color: rgb(240, 243, 246); + z-index: 101; + overflow-x: hidden; + display: none; + padding: 1em; + -webkit-overflow-scrolling: touch; } -#tpl .packfocus, -#tpl .packhide { - display: block; - float: right; - font-weight: normal; - color: #f16665; +div#search > span.close-results { + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + position: fixed; + top: 0.8em; + left: 1em; + color: #fff; + display: none; + z-index: 1; } -#tpl .packfocus:hover, -#tpl .packhide:hover { - text-decoration: none; - color: #53cdec; +div#search > span.close-results:hover { + cursor: pointer; +} + +div#results-content { + max-width: 1140px; + margin: 0 auto; } -#tpl .packages { +div#results-content > span.search-text { + margin-left: 1em; + font-size: 1.2em; + float: left; width: 100%; - padding-left: 0; - overflow-x: hidden; } -#tpl .packages > ol { - color: #fff; - background-color: #364550; - padding-left: 0; +div#results-content > span.search-text > span.query-str { + font-weight: 900; } -#tpl .packages > li > a { - padding: 0px 5px; +div#results-content > div > h1.result-type { + font-size: 1.5em; + margin: 1em 0 0.3em; + font-family: "Open Sans"; + font-weight: 300; + border-bottom: 1px solid #103a51; } -#tpl .packages > li > a.tplshow { - display: block; +div#results-content > div#entity-results { + float: left; + width: 50%; + padding: 1em; + display: inline; +} + +div#results-content > div#member-results { + float: left; + width: 50%; + padding: 1em; + display: inline; +} + +div#results-content > div#member-results > a.package, +div#results-content > div#entity-results > a.package { + font-size: 1em; + margin: 0 0 1em 0; color: #f16665; - font-weight: bold; - display: block; + cursor: pointer; } -#tpl .packages > li > a.tplshow:hover { - color: #53cdec; - text-decoration: none; +div#results-content > div#member-results > ul.entities, +div#results-content > div#entity-results > ul.entities { + list-style-type: none; + padding-left: 0; } -#tpl .packages a.tplshow > .type-circle { +div#results-content > div#member-results > ul.entities > li, +div#results-content > div#entity-results > ul.entities > li { + margin: 0.5em 0; +} + +div#results-content > div#member-results > ul.entities > li > .icon, +div#results-content > div#entity-results > ul.entities > li > .icon { float: left; - border: 1px solid rgba(255, 255, 255, 0.4); - height: 0.8rem; - width: 0.8rem; - border-radius: 0.8rem; - color: #efefef; - margin-top: 0.16em; - margin-right: 0.1em; - position: relative; - font-size: 0.8em; - line-height: 0.9; - font-family: Arial, sans-serif; - text-align: center; - display: table-cell; - vertical-align: middle; + display: inline; + height: 1em; + width: 1em; + margin: 0.23em 0 0; + cursor: pointer; } +div#results-content > div#member-results > ul.entities > li > .icon.class, +div#results-content > div#entity-results > ul.entities > li > .icon.class { + background: url("class.svg") no-repeat center; + background-size: 1em 1em; +} -#tpl .packages a.tplshow > .type-circle > span { - font-size: 0.9em; +div#results-content > div#member-results > ul.entities > li > .icon.trait, +div#results-content > div#entity-results > ul.entities > li > .icon.trait { + background: url("trait.svg") no-repeat center; + background-size: 1em 1em; } -#tpl .packages a.tplshow > .type-circle.class { - background-color: #316555; +div#results-content > div#member-results > ul.entities > li > .icon.object, +div#results-content > div#entity-results > ul.entities > li > .icon.object { + background: url("object.svg") no-repeat center; + background-size: 1em 1em; } -#tpl .packages a.tplshow > .type-circle.object { - background-color: #103A51; +div#results-content > div#member-results > ul.entities > li > span.entity, +div#results-content > div#entity-results > ul.entities > li > span.entity { + font-size: 1.1em; + font-weight: 900; } -#tpl .packages a.tplshow > .type-circle.trait { - background-color: #19AACF; +div#results-content > div#member-results > ul.entities > li > ul.members, +div#results-content > div#entity-results > ul.entities > li > ul.members { + margin-top: 0.5em; + list-style-type: none; + font-size: 0.85em; + margin-left: 0.2em; } -#tpl ol > li.pack { - padding: 3px 5px; - min-height: 14px; - background-color: #364550; +div#results-content > div#member-results > ul.entities > li > ul.members > li, +div#results-content > div#entity-results > ul.entities > li > ul.members > li { + margin: 0.5em 0; } -#tpl > ol > ol > li > a:hover { - text-decoration: none; - color: #53cdec; +div#results-content > div#member-results > ul.entities > li > ul.members > li > span.kind, +div#results-content > div#member-results > ul.entities > li > ul.members > li > span.tail, +div#results-content > div#entity-results > ul.entities > li > ul.members > li > span.kind, +div#results-content > div#entity-results > ul.entities > li > ul.members > li > span.tail { + margin-right: 0.6em; + font-family: "Source Code Pro"; } -#tpl ol > li { - display: block; +div#results-content > div#member-results > ul.entities > li > ul.members > li > span.kind { + font-weight: 600; } -#tpl .templates > li { - padding-left: 5px; - min-height: 1.4em; - width: 21em; /* tpl width == 20em */ +div#results-content > div#member-results > ul.entities > li > ul.members > li > a.label, +div#results-content > div#entity-results > ul.entities > li > ul.members > li > a.label { + color: #2C3D9B; + font-family: "Source Code Pro"; } -#tpl ol > li .icon { - padding-right: 5px; - bottom: -2px; +/** Scrollpane settings needed for jquery.scrollpane.min.js */ +.jspContainer { + overflow: hidden; position: relative; } -#tpl .templates div.placeholder { - padding-right: 14px; - width: 11px; - display: inline-block; +.jspPane { + position: absolute; } -#tpl .templates span.tplLink { - padding-left: 7px; +.jspVerticalBar { + position: absolute; + top: 0; + right: 0; + width: 0.6em; + height: 100%; + background: transparent; } -#content { - right: 0px; - left: 16.75em; - bottom: 0px; - top: 0px; - position: fixed; - display: block; - overflow-y: auto; - -webkit-overflow-scrolling: touch; - background-color: #fff; - z-index: 100; +.jspHorizontalBar { + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 16px; + background: red; +} + +.jspCap { + display: none; } -#content.full-screen { - left: 1.7em; +.jspHorizontalBar .jspCap { + float: left; } -#content.hide-filter { - left: 1.5em; +.jspTrack { + background: #f0f3f6; + position: relative; } -#content > iframe { +.jspDrag { + display: none; + background: rgba(0, 0, 0, 0.35); + position: relative; + top: 0; + left: 0; + cursor: pointer; +} + +#tpl:hover .jspDrag { display: block; +} + +.jspHorizontalBar .jspTrack, +.jspHorizontalBar .jspDrag { + float: left; height: 100%; - width: 100%; } -.ui-layout-pane { - background: #FFF; - overflow: auto; +.jspArrow { + background: #50506d; + text-indent: -20000px; + display: block; + cursor: pointer; + padding: 0; + margin: 0; +} + +.jspArrow.jspDisabled { + cursor: default; + background: #80808d; } -.ui-layout-resizer { - background-color: #ededee; /* light gray */ - border:1px solid #bbbbbb; - border-top:0; - border-bottom:0; - border-left: 0; +.jspVerticalBar .jspArrow { + height: 16px; } -.ui-layout-toggler { - background: #AAA; +.jspHorizontalBar .jspArrow { + width: 16px; + float: left; + height: 100%; +} + +.jspVerticalBar .jspArrow:focus { + outline: none; +} + +.jspCorner { + background: #eeeef4; + float: left; + height: 100%; +} + +/* CSS Hack for IE6 3 pixel bug */ +* html .jspCorner { + margin: 0 -3px 0 0; +} + +/* Media query rules for smaller viewport */ +@media only screen /* Large screen with a small window */ +and (max-width: 1300px) +{ + #textfilter { + left: 17.8em; + right: 0.35em; + } + + #textfilter .input { + max-width: none; + margin: 0; + } +} + +@media only screen /* Large screen with a smaller window */ +and (max-width: 800px) +{ + div#results-content > div#entity-results { + width: 100%; + padding: 0em; + } + + div#results-content > div#member-results { + width: 100%; + padding: 0em; + } +} + +/* Media query rules specifically for mobile devices */ +@media +screen /* HiDPI device like Nexus 5 */ +and (max-device-width: 360px) +and (max-device-height: 640px) +and (-webkit-device-pixel-ratio: 3) +, +screen /* Most mobile devices */ +and (max-device-width: 480px) +and (orientation: portrait) +, +only screen /* iPhone 6 */ +and (max-device-width: 667px) +and (-webkit-device-pixel-ratio: 2) +{ + div#content-container > div#content { + margin: 3.3em auto 0; + } + + #search > span#doc-title { + width: 100%; + text-align: left; + padding-left: 0.7em; + top: 0.95em; + z-index: 1; + } + + #search > div#textfilter { + z-index: 2; + } + + #search > span#doc-title > span#doc-version { + display: none; + } + + #textfilter { + left: 12.2em; + } } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.js b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.js index cad4072912..caa6406bc5 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.js +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/index.js @@ -1,363 +1,198 @@ // © 2009–2010 EPFL/LAMP // code by Gilles Dubochet with contributions by Johannes Rudolph, "spiros", Marcin Kubala and Felix Mulder -var topLevelTemplates = undefined; -var topLevelPackages = undefined; - var scheduler = undefined; -var kindFilterState = undefined; -var focusFilterState = undefined; - var title = $(document).attr('title'); var lastFragment = ""; -$(document).ready(function() { - /* check if browser is mobile, if so hide class nav */ - if( /Android|webOS|Mobi|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { - $("#browser").toggleClass("full-screen"); - $("#content").toggleClass("full-screen"); - $("#letters").toggle(); - setTimeout(function() { - $(".packages").hide(); - $("#kindfilter").hide(); - }, 4000); - } - - $('iframe').bind("load", function(){ - try { - var subtitle = $(this).contents().find('title').text(); - $(document).attr('title', (title ? title + " - " : "") + subtitle); - } catch (e) { - // Chrome doesn't allow reading the iframe's contents when - // used on the local file system. - } - setUrlFragmentFromFrameSrc(); - }); - - // workaround for IE's iframe sizing lack of smartness - if($.browser.msie) { - function fixIFrame() { - $('iframe').height($(window).height() ) - } - $('iframe').bind("load",fixIFrame) - $('iframe').bind("resize",fixIFrame) - } - - scheduler = new Scheduler(); - scheduler.addLabel("init", 1); - scheduler.addLabel("focus", 2); - scheduler.addLabel("filter", 4); - - prepareEntityList(); - configureTextFilter(); - configureEntityList(); - - setFrameSrcFromUrlFragment(); - - // If the url fragment changes, adjust the src of iframe "template". - $(window).bind('hashchange', function() { - if(lastFragment != window.location.hash) { - lastFragment = window.location.hash; - setFrameSrcFromUrlFragment(); - } - }); - - // Wait until page has loaded until binding input fields, setting fold all - setTimeout(function() { - configureKindFilter(); - - $("#index-input").on("focus", function() { - $("#textfilter > .clear").show(); - }); - - $("#index-input").on("blur", function() { - $("#textfilter > .clear").hide(); - }); - }, 1500); -}); - -// Set the iframe's src according to the fragment of the current url. -// fragment = "#scala.Either" => iframe url = "scala/Either.html" -// fragment = "#scala.Either@isRight:Boolean" => iframe url = "scala/Either.html#isRight:Boolean" -// fragment = "#scalaz.iteratee.package@>@>[E,A]=scalaz.iteratee.package.Iteratee[E,A]" => iframe url = "scalaz/iteratee/package.html#>@>[E,A]=scalaz.iteratee.package.Iteratee[E,A]" -function setFrameSrcFromUrlFragment() { - - function extractLoc(fragment) { - var loc = fragment.split('@')[0].replace(/\./g, "/"); - if (loc.indexOf(".html") < 0) { - loc += ".html"; - } - return loc; - } - - function extractMemberSig(fragment) { - var splitIdx = fragment.indexOf('@'); - if (splitIdx < 0) { - return; - } - return fragment.substr(splitIdx + 1); - } - - var fragment = location.hash.slice(1); - if (fragment) { - var locWithMemeberSig = extractLoc(fragment); - var memberSig = extractMemberSig(fragment); - if (memberSig) { - locWithMemeberSig += "#" + memberSig; - } - frames["template"].location.replace(location.protocol + locWithMemeberSig); - } else { - console.log("empty fragment detected"); - frames["template"].location.replace("package.html"); - } -} - -// Set the url fragment according to the src of the iframe "template". -// iframe url = "scala/Either.html" => url fragment = "#scala.Either" -// iframe url = "scala/Either.html#isRight:Boolean" => url fragment = "#scala.Either@isRight:Boolean" -// iframe url = "scalaz/iteratee/package.html#>@>[E,A]=scalaz.iteratee.package.Iteratee[E,A]" => fragment = "#scalaz.iteratee.package@>@>[E,A]=scalaz.iteratee.package.Iteratee[E,A]" -function setUrlFragmentFromFrameSrc() { - try { - var commonLength = location.pathname.lastIndexOf("/"); - var frameLocation = frames["template"].location; - var relativePath = frameLocation.pathname.slice(commonLength + 1); - - if(!relativePath || frameLocation.pathname.indexOf("/") < 0) - return; - - // Add #, remove ".html" and replace "/" with "." - fragment = "#" + relativePath.replace(/\.html$/, "").replace(/\//g, "."); - - // Add the frame's hash after an @ - if(frameLocation.hash) fragment += ("@" + frameLocation.hash.slice(1)); - - // Use replace to not add history items - lastFragment = fragment; - location.replace(fragment); - } - catch(e) { - // Chrome doesn't allow reading the iframe's location when - // used on the local file system. - } -} - var Index = {}; - (function (ns) { - function openLink(t, type) { - var href; - if (type == 'object') { - href = t['object']; - } else { - href = t['class'] || t['trait'] || t['case class'] || t['type']; - } - return [ - '<a class="tplshow" target="template" href="', - href, - '"><div class="type-circle ', - type, - '"><span>', - type.charAt(0).toLowerCase(), - '</span></div>' - ].join(''); - } - - function createPackageHeader(pack) { - return [ - '<li class="pack">', - '<a class="packfocus">focus</a><a class="packhide">hide</a>', - '<a class="tplshow" target="template" href="', - pack.replace(/\./g, '/'), - '/package.html">', - pack, - '</a></li>' - ].join(''); - }; - - function createListItem(template) { - var inner = ''; - - - if (template.object) { - inner += openLink(template, 'object'); - } - - if (template['class'] || template['trait'] || template['case class'] || template['type']) { - inner += (inner == '') ? - '<div class="placeholder" />' : '</a>'; - inner += openLink(template, template['trait'] ? 'trait' : template['type'] ? 'type' : 'class'); - } else { - inner += '<div class="placeholder"/>'; - } - - return [ - '<li>', - inner, - '<span class="tplLink">', - template.name.replace(/^.*\./, ''), - '</span></a></li>' - ].join(''); - } - - - ns.createPackageTree = function (pack, matched, focused) { - var html = $.map(matched, function (child, i) { - return createListItem(child); - }).join(''); - - var header; - if (focused && pack == focused) { - header = ''; - } else { - header = createPackageHeader(pack); - } - - return [ - '<ol class="packages">', - header, - '<ol class="templates">', - html, - '</ol></ol>' - ].join(''); - } - + ns.keyLength = 0; ns.keys = function (obj) { var result = []; var key; for (key in obj) { result.push(key); + ns.keyLength++; } return result; } +})(Index); - var hiddenPackages = {}; +$(document).ready(function() { + // Clicking #doc-title returns the user to the root package + $("#doc-title").click(function() { document.location = toRoot + "index.html" }); - function subPackages(pack) { - return $.grep($('#tpl ol.packages'), function (element, index) { - var pack = $('li.pack > .tplshow', element).text(); - return pack.indexOf(pack + '.') == 0; - }); - } + scheduler = new Scheduler(); + scheduler.addLabel("init", 1); + scheduler.addLabel("focus", 2); + scheduler.addLabel("filter", 4); + scheduler.addLabel("search", 5); - ns.hidePackage = function (ol) { - var selected = $('li.pack > .tplshow', ol).text(); - hiddenPackages[selected] = true; + configureTextFilter(); - $('ol.templates', ol).hide(); + $("#index-input").on("focus", function(e) { + $("#textfilter > .input > .clear").show(); + }); - $.each(subPackages(selected), function (index, element) { - $(element).hide(); - }); - } + $("#index-input").on("blur", function() { + setTimeout(function() { + $("#textfilter > .input > .clear").hide(); + }, 10); + }); +}); - ns.showPackage = function (ol, state) { - var selected = $('li.pack > .tplshow', ol).text(); - hiddenPackages[selected] = false; +/* Handles all key presses while scrolling around with keyboard shortcuts in search results */ +function handleKeyNavigation() { + /** Iterates both back and forth among selected elements */ + var EntityIterator = function (litems, ritems) { + var it = this; + this.index = -1; + + this.items = litems; + this.litems = litems; + this.ritems = ritems; + + if (litems.length == 0) + this.items = ritems; + + /** Returns the next entry - if trying to select past last element, it + * returns the last element + */ + it.next = function() { + it.index = Math.min(it.items.length - 1, it.index + 1); + return $(it.items[it.index]); + }; - $('ol.templates', ol).show(); + /** Returns the previous entry - will return `undefined` instead if + * selecting up from first element + */ + it.prev = function() { + it.index = Math.max(-1, it.index - 1); + return it.index == -1 ? undefined : $(it.items[it.index]); + }; - $.each(subPackages(selected), function (index, element) { - $(element).show(); + it.right = function() { + if (it.ritems.length != 0) { + it.items = it.ritems; + it.index = Math.min(it.index, it.items.length - 1); + } + return $(it.items[it.index]); + }; - // When the filter is in "packs" state, - // we don't want to show the `.templates` - var key = $('li.pack > .tplshow', element).text(); - if (hiddenPackages[key] || state == 'packs') { - $('ol.templates', element).hide(); + it.left = function() { + if (it.litems.length != 0) { + it.items = it.litems; + it.index = Math.min(it.index, it.items.length - 1); } - }); - } + return $(it.items[it.index]); + }; + }; -})(Index); + /** Scroll helper, ensures that the selected elem is inside the viewport */ + var Scroller = function ($container) { + scroller = this; + scroller.container = $container; + + scroller.scrollDown = function($elem) { + var yPos = $elem.offset().top; // offset relative to viewport + if ($container.height() < yPos) { + $container.animate({ + scrollTop: $container.scrollTop() + yPos - $("#search").height() - 10 + }, 200); + } + }; -function configureEntityList() { - kindFilterSync(); - configureHideFilter(); - configureFocusFilter(); - textFilter(); -} + scroller.scrollUp = function ($elem) { + var yPos = $elem.offset().top; // offset relative to viewport + if (yPos < $("#search").height()) { + $container.animate({ + scrollTop: $container.scrollTop() + yPos - $("#search").height() - 10 + }, 200); + } + }; -/** - * Updates the list of entities (i.e. the content of the #tpl element) from the - * raw form generated by Scaladoc to a form suitable for display. It configures - * links to open in the right frame. Furthermore, it sets the two reference - * top-level entities lists (topLevelTemplates and topLevelPackages) to serve - * as reference for resetting the list when needed. - * - * Be advised: this function should only be called once, on page load. - */ -function prepareEntityList() { - $('#tpl li.pack > a.tplshow').attr("target", "template"); - $('#tpl li.pack') - .prepend("<a class='packhide'>hide</a>") - .prepend("<a class='packfocus'>focus</a>"); -} + scroller.scrollTop = function() { + $container.animate({ + scrollTop: 0 + }, 200); + } + }; -/* Handles all key presses while scrolling around with keyboard shortcuts in left panel */ -function keyboardScrolldownLeftPane() { scheduler.add("init", function() { $("#textfilter input").blur(); - var $items = $("#tpl li"); - $items.first().addClass('selected'); + var items = new EntityIterator( + $("div#results-content > div#entity-results > ul.entities span.entity > a").toArray(), + $("div#results-content > div#member-results > ul.entities span.entity > a").toArray() + ); - $(window).bind("keydown", function(e) { - var $old = $items.filter('.selected'), - $new; + var scroller = new Scroller($("#search-results")); - switch ( e.keyCode ) { + var $old = items.next(); + $old.addClass("selected"); + $(window).bind("keydown", function(e) { + switch ( e.keyCode ) { case 9: // tab - $old.removeClass('selected'); + $old.removeClass("selected"); break; case 13: // enter - $old.removeClass('selected'); - var $url = $old.children().filter('a:last').attr('href'); - $("#template").attr("src",$url); + var href = $old.attr("href"); + location.replace(href); + $old.click(); + $("#textfilter input").attr("value", ""); break; case 27: // escape - $old.removeClass('selected'); - $(window).unbind(e); - $("#textfilter input").focus(); + $("#textfilter input").attr("value", ""); + $("div#search-results").hide(); + $("#search > span.close-results").hide(); + $("#search > span#doc-title").show(); + break; + + case 37: // left + var oldTop = $old.offset().top; + $old.removeClass("selected"); + $old = items.left(); + $old.addClass("selected"); + (oldTop - $old.offset().top < 0 ? scroller.scrollDown : scroller.scrollUp)($old); break; case 38: // up - $new = $old.prev(); - - if (!$new.length) { - $new = $old.parent().prev(); + $old.removeClass('selected'); + $old = items.prev(); + + if ($old === undefined) { // scroll past top + $(window).unbind("keydown"); + $("#textfilter input").focus(); + scroller.scrollTop(); + return false; + } else { + $old.addClass("selected"); + scroller.scrollUp($old); } + break; - if ($new.is('ol') && $new.children(':last').is('ol')) { - $new = $new.children().children(':last'); - } else if ($new.is('ol')) { - $new = $new.children(':last'); - } + case 39: // right + var oldTop = $old.offset().top; + $old.removeClass("selected"); + $old = items.right(); + $old.addClass("selected"); + (oldTop - $old.offset().top < 0 ? scroller.scrollDown : scroller.scrollUp)($old); break; case 40: // down - $new = $old.next(); - if (!$new.length) { - $new = $old.parent().parent().next(); - } - if ($new.is('ol')) { - $new = $new.children(':first'); - } + $old.removeClass("selected"); + $old = items.next(); + $old.addClass("selected"); + scroller.scrollDown($old); break; } - - if ($new && $new.is('li')) { - $old.removeClass('selected'); - $new.addClass('selected'); - } else if (e.keyCode == 38) { - $(window).unbind(e); - $("#textfilter input").focus(); - } }); }); } @@ -365,49 +200,43 @@ function keyboardScrolldownLeftPane() { /* Configures the text filter */ function configureTextFilter() { scheduler.add("init", function() { - $("#filter").prepend("<span class='toggle-sidebar'></span>"); - $("#textfilter").append("<span class='input'><input placeholder='Filter' id='index-input' type='text' accesskey='/'/></span><span class='clear'>✖</span>"); var input = $("#textfilter input"); - resizeFilterBlock(); input.bind('keyup', function(event) { - if (event.keyCode == 27) { // escape - input.attr("value", ""); - } - if (event.keyCode == 40) { // down arrow - $(window).unbind("keydown"); - keyboardScrolldownLeftPane(); - return false; + switch ( event.keyCode ) { + case 27: // escape + input.attr("value", ""); + $("div#search-results").hide(); + $("#search > span.close-results").hide(); + $("#search > span#doc-title").show(); + break; + + case 38: // up arrow + return false; + + case 40: // down arrow + $(window).unbind("keydown"); + handleKeyNavigation(); + return false; } - textFilter(); - }); - input.bind('keydown', function(event) { - if (event.keyCode == 9) { // tab - $("#template").contents().find("#mbrsel-input").focus(); - input.attr("value", ""); - return false; - } - textFilter(); + + searchAll(); }); - input.focus(function(event) { input.select(); }); }); scheduler.add("init", function() { - $("#textfilter > .clear").click(function(){ + $("#textfilter > .input > .clear").click(function() { $("#textfilter input").attr("value", ""); - textFilter(); + $("div#search-results").hide(); + $("#search > span.close-results").hide(); + $("#search > span#doc-title").show(); }); - $("#filter > span.toggle-sidebar").click(function() { - $("#browser").toggleClass("full-screen"); - $("#content").toggleClass("full-screen"); - $(".packages").toggle(); - $("#letters").toggle(); - $("#kindfilter").toggle(); - }); - $(".pack").scroll(function() { - var scroll = $(".pack").scrollTop(); - if (scroll > 0) - $("#filter").addClass("scrolled"); - else - $("#filter").removeClass("scrolled"); + }); + + scheduler.add("init", function() { + $("div#search > span.close-results").click(function() { + $("div#search-results").hide(); + $("#search > span.close-results").hide(); + $("#search > span#doc-title").show(); + $("#textfilter input").attr("value", ""); }); }); } @@ -425,196 +254,322 @@ function compilePattern(query) { } } -// Filters all focused templates and packages. This function should be made less-blocking. -// @param query The string of the query -function textFilter() { - var query = $("#textfilter input").attr("value") || ''; - var queryRegExp = compilePattern(query); - - // if we are filtering on types, then we have to display types - // ("display packages only" is not possible when filtering) - if (query !== "") { - kindFilter("all"); - } +/** Searches packages for entites matching the search query using a regex + * + * @param {[Object]} pack: package being searched + * @param {RegExp} regExp: a regular expression for finding matching entities + */ +function searchPackage(pack, regExp) { + scheduler.add("search", function() { + var entities = Index.PACKAGES[pack]; + var matched = []; + var notMatching = []; + + scheduler.add("search", function() { + searchMembers(entities, regExp, pack); + }); - // Three things trigger a reload of the left pane list: - // typeof textFilter.lastQuery === "undefined" <-- first load, there is nothing yet in the left pane - // textFilter.lastQuery !== query <-- the filter text has changed - // focusFilterState != null <-- a package has been "focused" - if ((typeof textFilter.lastQuery === "undefined") || (textFilter.lastQuery !== query) || (focusFilterState != null)) { + entities.forEach(function (elem) { + regExp.test(elem.name) ? matched.push(elem) : notMatching.push(elem); + }); - textFilter.lastQuery = query; + var results = { + "matched": matched, + "package": pack + }; - scheduler.clear("filter"); + scheduler.add("search", function() { + handleSearchedPackage(results, regExp); + setProgress(); + }); + }); +} - $('#tpl').html(''); +function searchMembers(entities, regExp, pack) { + var memDiv = document.getElementById("member-results"); + var packLink = document.createElement("a"); + packLink.className = "package"; + packLink.appendChild(document.createTextNode(pack)); + packLink.style.display = "none"; + packLink.title = pack; + packLink.href = toRoot + urlFriendlyEntity(pack).replace(new RegExp("\\.", "g"), "/") + "/index.html"; + memDiv.appendChild(packLink); + + var entityUl = document.createElement("ul"); + entityUl.className = "entities"; + memDiv.appendChild(entityUl); + + entities.forEach(function(entity) { + var entityLi = document.createElement("li"); + var name = entity.name.split('.').pop() + + var iconElem = document.createElement("a"); + iconElem.className = "icon " + entity.kind; + iconElem.title = name + " " + entity.kind; + iconElem.href = toRoot + entity[entity.kind]; + entityLi.appendChild(iconElem); + + if (entity.kind != "object" && entity.object) { + var companion = document.createElement("a"); + companion.className = "icon object"; + companion.title = name + " companion object"; + companion.href = toRoot + entity.object; + entityLi.insertBefore(companion, iconElem); + } else { + var spacer = document.createElement("div"); + spacer.className = "icon spacer"; + entityLi.insertBefore(spacer, iconElem); + } - var index = 0; + var nameElem = document.createElement("span"); + nameElem.className = "entity"; - var searchLoop = function () { - var packages = Index.keys(Index.PACKAGES).sort(); + var entityUrl = document.createElement("a"); + entityUrl.title = entity.shortDescription ? entity.shortDescription : name; + entityUrl.href = toRoot + entity[entity.kind]; + entityUrl.appendChild(document.createTextNode(name)); - while (packages[index]) { - var pack = packages[index]; - var children = Index.PACKAGES[pack]; - index++; + nameElem.appendChild(entityUrl); + entityLi.appendChild(nameElem); - if (focusFilterState) { - if (pack == focusFilterState || - pack.indexOf(focusFilterState + '.') == 0) { - ; - } else { - continue; - } - } + var membersUl = document.createElement("ul"); + membersUl.className = "members"; + entityLi.appendChild(membersUl); - var matched = $.grep(children, function (child, i) { - return queryRegExp.test(child.name); - }); - if (matched.length > 0) { - $('#tpl').append(Index.createPackageTree(pack, matched, - focusFilterState)); - scheduler.add('filter', searchLoop); - return; + searchEntity(entity, membersUl, regExp) + .then(function(res) { + if (res.length > 0) { + packLink.style.display = "block"; + entityUl.appendChild(entityLi); } - } - - $('#tpl a.packfocus').click(function () { - focusFilter($(this).parent().parent()); - $("#tpl").addClass("packfocused"); }); - configureHideFilter(); - }; + }); +} - scheduler.add('filter', searchLoop); +/** This function inserts `li` into the `ul` ordered by the li's id + * + * @param {Node} ul: the list in which to insert `li` + * @param {Node} li: item to insert + */ +function insertSorted(ul, li) { + var lis = ul.childNodes; + var beforeLi = null; + + for (var i = 0; i < lis.length; i++) { + if (lis[i].id > li.id) + beforeLi = lis[i]; } + + // if beforeLi == null, it will be inserted last + ul.insertBefore(li, beforeLi); } -/* Configures the hide tool by adding the hide link to all packages. */ -function configureHideFilter() { - $('#tpl li.pack a.packhide').click(function () { - var packhide = $(this) - var action = packhide.text(); +/** Defines the callback when a package has been searched and searches its + * members + * + * It will search all entities which matched the regExp. + * + * @param {Object} res: this is the searched package. It will contain the map + * from the `searchPackage`function. + * @param {RegExp} regExp + */ +function handleSearchedPackage(res, regExp) { + $("div#search-results").show(); + $("#search > span.close-results").show(); + $("#search > span#doc-title").hide(); - var ol = $(this).parent().parent(); + var searchRes = document.getElementById("results-content"); + var entityDiv = document.getElementById("entity-results"); - if (action == "hide") { - Index.hidePackage(ol); - packhide.text("show"); - } - else { - Index.showPackage(ol, kindFilterState); - packhide.text("hide"); - } - return false; - }); -} + var packLink = document.createElement("a"); + packLink.className = "package"; + packLink.title = res.package; + packLink.href = toRoot + urlFriendlyEntity(res.package).replace(new RegExp("\\.", "g"), "/") + "/index.html"; + packLink.appendChild(document.createTextNode(res.package)); -/* Configures the focus tool by adding the focus bar in the filter box (initially hidden), and by adding the focus - link to all packages. */ -function configureFocusFilter() { - scheduler.add("init", function() { - focusFilterState = null; - if ($("#focusfilter").length == 0) { - $("#filter").append("<div id='focusfilter'>focused on <span class='focuscoll'></span> <a class='focusremove'>✖</a></div>"); - $("#focusfilter > .focusremove").click(function(event) { - textFilter(); - - $("#focusfilter").hide(); - $("#kindfilter").show(); - $("#tpl").removeClass("packfocused"); - resizeFilterBlock(); - focusFilterState = null; - }); - $("#focusfilter").hide(); - resizeFilterBlock(); - } - }); - scheduler.add("init", function() { - $('#tpl li.pack a.packfocus').click(function () { - focusFilter($(this).parent()); - return false; - }); - }); -} + if (res.matched.length == 0) + packLink.style.display = "none"; -/* Focuses the entity index on a specific package. To do so, it will copy the sub-templates and sub-packages of the - focuses package into the top-level templates and packages position of the index. The original top-level - @param package The <li> element that corresponds to the package in the entity index */ -function focusFilter(package) { - scheduler.clear("filter"); + entityDiv.appendChild(packLink); - var currentFocus = $('li.pack > .tplshow', package).text(); - $("#focusfilter > .focuscoll").empty(); - $("#focusfilter > .focuscoll").append(currentFocus); + var ul = document.createElement("ul") + ul.className = "entities"; - $("#focusfilter").show(); - $("#kindfilter").hide(); - resizeFilterBlock(); - focusFilterState = currentFocus; - kindFilterSync(); + // Generate html list items from results + res.matched + .map(function(entity) { return listItem(entity, regExp); }) + .forEach(function(li) { ul.appendChild(li); }); - textFilter(); + entityDiv.appendChild(ul); } -function configureKindFilter() { - scheduler.add("init", function() { - kindFilterState = "all"; - $("#filter").append("<div id='kindfilter-container'><div id='kindfilter'><span>Fold All</span></div></div>"); - - while(isNaN(scrollbarWidth())) { - // wait until the width is available - } +/** Searches an entity asynchronously for regExp matches in an entity's members + * + * @param {Object} entity: the entity to be searched + * @param {Node} ul: the list in which to insert the list item created + * @param {RegExp} regExp + */ +function searchEntity(entity, ul, regExp) { + return new Promise(function(resolve, reject) { + var matchingMembers = $.grep(entity.members, function(member, i) { + return regExp.test(member.label); + }); - $("#kindfilter").css({"margin-right": (scrollbarWidth() + 7) + "px"}); - $("#kindfilter").unbind("click"); - $("#kindfilter").click(function(event) { - $("#kindfilter").toggleClass("open"); - kindFilter("packs"); + resolve(matchingMembers); + }) + .then(function(res) { + res.forEach(function(elem) { + var kind = document.createElement("span"); + kind.className = "kind"; + kind.appendChild(document.createTextNode(elem.kind)); + + var label = document.createElement("a"); + label.title = elem.label; + label.href = toRoot + elem.link; + label.className = "label"; + label.appendChild(document.createTextNode(elem.label)); + + var tail = document.createElement("span"); + tail.className = "tail"; + tail.appendChild(document.createTextNode(elem.tail)); + + var li = document.createElement("li"); + li.appendChild(kind); + li.appendChild(label); + li.appendChild(tail); + + ul.appendChild(li); }); - resizeFilterBlock(); + return res; }); } -function kindFilter(kind) { - if (kind == "packs") { - kindFilterState = "packs"; - kindFilterSync(); - $("#kindfilter > span").replaceWith("<span>Unfold All</span>"); - $("#kindfilter").unbind("click"); - $("#kindfilter").click(function(event) { - $("#kindfilter").toggleClass("open"); - kindFilter("all"); - }); - } - else { - kindFilterState = "all"; - kindFilterSync(); - $("#kindfilter > span").replaceWith("<span>Fold All</span>"); - $("#kindfilter").unbind("click"); - $("#kindfilter").click(function(event) { - $("#kindfilter").toggleClass("open"); - kindFilter("packs"); - }); +/** Creates a list item representing an entity + * + * @param {Object} entity, the searched entity to be displayed + * @param {RegExp} regExp + * @return {Node} list item containing entity + */ +function listItem(entity, regExp) { + var name = entity.name.split('.').pop() + var nameElem = document.createElement("span"); + nameElem.className = "entity"; + + var entityUrl = document.createElement("a"); + entityUrl.title = entity.shortDescription ? entity.shortDescription : name; + entityUrl.href = toRoot + entity[entity.kind]; + + entityUrl.appendChild(document.createTextNode(name)); + nameElem.appendChild(entityUrl); + + var iconElem = document.createElement("a"); + iconElem.className = "icon " + entity.kind; + iconElem.title = name + " " + entity.kind; + iconElem.href = toRoot + entity[entity.kind]; + + var li = document.createElement("li"); + li.id = entity.name.replace(new RegExp("\\.", "g"),"-"); + li.appendChild(iconElem); + li.appendChild(nameElem); + + if (entity.kind != "object" && entity.object) { + var companion = document.createElement("a"); + companion.title = name + " companion object"; + companion.href = toRoot + entity.object; + companion.className = "icon object"; + li.insertBefore(companion, iconElem); + } else { + var spacer = document.createElement("div"); + spacer.className = "icon spacer"; + li.appendChild(spacer); } + + var ul = document.createElement("ul"); + ul.className = "members"; + + li.appendChild(ul); + + return li; } -/* Applies the kind filter. */ -function kindFilterSync() { - if (kindFilterState == "all" || focusFilterState != null) { - $("#tpl a.packhide").text('hide'); - $("#tpl ol.templates").show(); - } else { - $("#tpl a.packhide").text('show'); - $("#tpl ol.templates").hide(); +/** Searches all packages and entities for the current search string in + * the input field "#textfilter" + * + * Then shows the results in div#search-results + */ +function searchAll() { + scheduler.clear("search"); // clear previous search + maxJobs = 1; // clear previous max + var searchStr = $("#textfilter input").attr("value").trim() || ''; + + if (searchStr === '') { + $("div#search-results").hide(); + $("#search > span.close-results").hide(); + $("#search > span#doc-title").show(); + return; } + + $("div#results-content > span.search-text").remove(); + + var memberResults = document.getElementById("member-results"); + memberResults.innerHTML = ""; + var memberH1 = document.createElement("h1"); + memberH1.className = "result-type"; + memberH1.innerHTML = "Member results"; + memberResults.appendChild(memberH1); + + var entityResults = document.getElementById("entity-results"); + entityResults.innerHTML = ""; + var entityH1 = document.createElement("h1"); + entityH1.className = "result-type"; + entityH1.innerHTML = "Entity results"; + entityResults.appendChild(entityH1); + + $("div#results-content") + .prepend("<span class='search-text'>" + +" Showing results for <span class='query-str'>\"" + searchStr + "\"</span>" + +"</span>"); + + var regExp = compilePattern(searchStr); + + // Search for all entities matching query + Index + .keys(Index.PACKAGES) + .sort() + .forEach(function(elem) { searchPackage(elem, regExp); }) } -function resizeFilterBlock() { - $("#tpl").css("top", $("#filter").outerHeight(true)); +/** Check if user agent is associated with a known mobile browser */ +function isMobile() { + return /Android|webOS|Mobi|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } -function scrollbarWidth() { - return $("#tpl").width() - $("#tpl")[0].clientWidth; +function urlFriendlyEntity(entity) { + var corr = { + '\\+': '$plus', + ':': '$colon' + }; + + for (k in corr) + entity = entity.replace(new RegExp(k, 'g'), corr[k]); + + return entity; +} + +var maxJobs = 1; +function setProgress() { + var running = scheduler.numberOfJobs("search"); + maxJobs = Math.max(maxJobs, running); + + var percent = 100 - (running / maxJobs * 100); + var bar = document.getElementById("progress-fill"); + bar.style.height = "100%"; + bar.style.width = percent + "%"; + + if (percent == 100) { + setTimeout(function() { + bar.style.height = 0; + }, 500); + } } diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.eot b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.eot Binary files differnew file mode 100644 index 0000000000..7437fd9805 --- /dev/null +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.eot diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.ttf b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.ttf Binary files differnew file mode 100644 index 0000000000..4e7128a481 --- /dev/null +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.ttf diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.woff b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.woff Binary files differnew file mode 100644 index 0000000000..48915bb476 --- /dev/null +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/lato-v11-latin-100.woff diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/scheduler.js b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/scheduler.js index 4417f5b438..750c9099fd 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/scheduler.js +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/scheduler.js @@ -1,5 +1,5 @@ // © 2010 EPFL/LAMP -// code by Gilles Dubochet +// code by Gilles Dubochet, Felix Mulder function Scheduler() { var scheduler = this; @@ -7,38 +7,44 @@ function Scheduler() { this.timeout = undefined; this.queues = new Array(0); // an array of work pacakges indexed by index in the labels table. this.labels = new Array(0); // an indexed array of labels indexed by priority. This should be short. + this.label = function(name, priority) { this.name = name; this.priority = priority; } + this.work = function(fn, self, args) { this.fn = fn; this.self = self; this.args = args; } + this.addLabel = function(name, priority) { var idx = 0; while (idx < scheduler.queues.length && scheduler.labels[idx].priority <= priority) { idx = idx + 1; } scheduler.labels.splice(idx, 0, new scheduler.label(name, priority)); scheduler.queues.splice(idx, 0, new Array(0)); } + this.clearLabel = function(name) { - var idx = 0; - while (idx < scheduler.queues.length && scheduler.labels[idx].name != name) { idx = idx + 1; } - if (idx < scheduler.queues.length && scheduler.labels[i].name == name) { + var idx = scheduler.indexOf(name); + if (idx != -1) { scheduler.labels.splice(idx, 1); scheduler.queues.splice(idx, 1); } } + this.nextWork = function() { var fn = undefined; var idx = 0; while (idx < scheduler.queues.length && scheduler.queues[idx].length == 0) { idx = idx + 1; } - if (idx < scheduler.queues.length && scheduler.queues[idx].length > 0) { + + if (idx < scheduler.queues.length && scheduler.queues[idx].length > 0) var fn = scheduler.queues[idx].shift(); - } + return fn; } + this.add = function(labelName, fn, self, args) { var doWork = function() { scheduler.timeout = setTimeout(function() { @@ -53,19 +59,50 @@ function Scheduler() { } }, resolution); } - var idx = 0; - while (idx < scheduler.labels.length && scheduler.labels[idx].name != labelName) { idx = idx + 1; } - if (idx < scheduler.queues.length && scheduler.labels[idx].name == labelName) { + + var idx = scheduler.indexOf(labelName) + if (idx != -1) { scheduler.queues[idx].push(new scheduler.work(fn, self, args)); if (scheduler.timeout == undefined) doWork(); + } else { + throw("queue for add is non existant"); } - else throw("queue for add is non existant"); } + this.clear = function(labelName) { + scheduler.queues[scheduler.indexOf(labelName)] = new Array(); + } + + this.indexOf = function(label) { var idx = 0; - while (idx < scheduler.labels.length && scheduler.labels[idx].name != labelName) { idx = idx + 1; } - if (idx < scheduler.queues.length && scheduler.labels[idx].name == labelName) { - scheduler.queues[idx] = new Array(); + while (idx < scheduler.labels.length && scheduler.labels[idx].name != label) + idx++; + + return idx < scheduler.queues.length && scheduler.labels[idx].name == label ? idx : -1; + } + + this.queueEmpty = function(label) { + var idx = scheduler.indexOf(label); + if (idx != -1) + return scheduler.queues[idx].length == 0; + else + throw("queue for label '" + label + "' is non existant"); + } + + this.scheduleLast = function(label, fn) { + if (scheduler.queueEmpty(label)) { + fn(); + } else { + scheduler.add(label, function() { + scheduler.scheduleLast(label, fn); + }); } } + + this.numberOfJobs = function(label) { + var index = scheduler.indexOf(label); + if (index == -1) throw("queue for label '" + label + "' non-existent"); + + return scheduler.queues[index].length; + } }; diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.css b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.css index 43e59076ca..2265f8f045 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.css +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.css @@ -29,39 +29,6 @@ a img { border: none; } input { border-width: 0px; } -/* Fonts */ -@font-face { - font-family: 'Source Code Pro'; - font-style: normal; - font-weight: 400; - src: url('source-code-pro-v6-latin-regular.eot'); - src: local('Source Code Pro'), local('SourceCodePro-Regular'), - url('source-code-pro-v6-latin-regular.eot?#iefix') format('embedded-opentype'), - url('source-code-pro-v6-latin-regular.woff') format('woff'), - url('source-code-pro-v6-latin-regular.ttf') format('truetype'); -} -@font-face { - font-family: 'Source Code Pro'; - font-style: normal; - font-weight: 700; - src: url('source-code-pro-v6-latin-700.eot'); - src: local('Source Code Pro Bold'), local('SourceCodePro-Bold'), - url('source-code-pro-v6-latin-700.eot?#iefix') format('embedded-opentype'), - url('source-code-pro-v6-latin-700.woff') format('woff'), - url('source-code-pro-v6-latin-700.ttf') format('truetype'); -} - -@font-face { - font-family: 'Open Sans'; - font-style: normal; - font-weight: 400; - src: url('open-sans-v13-latin-regular.eot'); - src: local('Open Sans'), local('OpenSans'), - url('open-sans-v13-latin-regular.eot?#iefix') format('embedded-opentype'), - url('open-sans-v13-latin-regular.woff') format('woff'), - url('open-sans-v13-latin-regular.ttf') format('truetype'); -} - /* Page */ body { overflow-x: hidden; @@ -69,32 +36,24 @@ body { background-color: #f0f3f6; } -html { - box-sizing: border-box; -} - -*, *:before, *:after { - box-sizing: inherit; -} - #footer { text-align: center; color: #858484; bottom: 0; - width: 100%; height: 20px; + margin: 0 1em 0.5em; } -a[href] { +#content-container a[href] { text-decoration: underline; color: #315479; } -a[href]:hover { +#content-container a[href]:hover { text-decoration: none; } -body.trait > div#definition { +body.trait div#definition { background-color: #2e6d82; } @@ -107,10 +66,13 @@ body.trait > div#definition { } #definition { + position: relative; display: block; - padding: 5px 0px; - height: 5.5em; + padding: 5px 0; padding: 0; + margin: 0.5em; + border-radius: 0.2em; + box-shadow: 0 0 10px rgba(0,0,0,0.2); } #definition > a > img { @@ -132,8 +94,8 @@ body.trait > div#definition { } #definition h1 > a { - color: #fff; - text-decoration: none; + color: #fff !important; + text-decoration: none !important; } #definition #owner { @@ -156,13 +118,10 @@ body.trait > div#definition { min-height: 18px; font-size: 0.9em; padding: 8px; - box-shadow: 0 0 0.35em 0.05em rgba(0,0,0,0.5); - position: fixed; - top: 6.1em; - left: 0; width: 100%; - z-index: 9998; color: #103a51; + border-bottom-left-radius: 0.2em; + border-bottom-right-radius: 0.2em; } #signature > span.modifier_kind { @@ -171,6 +130,7 @@ body.trait > div#definition { text-align: left; width: auto; position: static; + padding-left: 0; } #signature > span.symbol { @@ -197,43 +157,47 @@ body.trait > div#definition { user-select: none; } -.toggleContainer .toggle:before { - cursor: pointer; - padding-left: 15px; - content: "â–¶"; +.toggleContainer .toggle > i { position: absolute; - left: -2.7em; + left: -1.5em; top: 0em; + font-size: 1.3em; + transition: 0.1s; } -.toggleContainer .toggle.open:before { - content: "â–¼"; - position: absolute; - left: -2.7em; - top: 0em; +.toggleContainer .toggle.open > i { + transform: rotate(90deg); } .toggleContainer .hiddenContent { margin-top: 1.5em; } +#memberfilter > i.arrow { + position: absolute; + top: 0.45em; + left: -0.9em; + color: #fff; + font-size: 1.3em; + opacity: 0; + transition: 0.1s; + cursor: pointer; +} + +#memberfilter > i.arrow.rotate { + transform: rotate(90deg); +} + +#memberfilter:hover > i.arrow { + opacity: 1; +} + .value #definition { background-color: #103A51; /* blue */ - position: fixed; - top: 0; - left: 0; - width: 100%; - z-index: 9999; } .type #definition { background-color: rgba(49, 101, 85, 1); /* green */ - position: fixed; - top: 0; - left: 0; - min-height: 5.5em; - width: 100%; - z-index: 9999; } .abstract.type #definition { @@ -285,12 +249,13 @@ body.abstract.type div.big-circle { } #template { - margin: 0.9em 0.75em 2em 0.75em; + margin: 0.9em 0.75em 0.75em; border-radius: 0.2em; background-color: #fff; -webkit-box-shadow: 0 0 10px rgba(0,0,0,0.1); box-shadow: 0 0 10px rgba(0,0,0,0.1); padding-bottom: 0.5em; + overflow: hidden; } #order { @@ -369,19 +334,20 @@ dl.attributes > dd { /* Member cells */ div.members > ol { background-color: white; - list-style: none + list-style: none; + padding: 0 10px; } div.members > ol > li { - display: block; - padding: 5px 0 6px; - margin: 0 10px; + display: table; + width: 100%; position: relative; background-color: #e1e7ed; border-radius: 0.2em; color: #103a51; padding: 5px 0 5px; margin-bottom: 0.4em; + min-height: 2.8em; } div.members > ol >li.selected, @@ -413,17 +379,25 @@ div.members > ol > li:last-child { display: block; } -.signature .modifier_kind { - position: absolute; +.modifier_kind { + font-family: "Source Code Pro"; + font-size: 0.8rem; + padding-right: 0.5em; text-align: right; - width: 14em; + display: table-cell; + white-space: nowrap; + width: 16em; +} + +.symbol { + font-family: "Source Code Pro"; } -.signature > a > .symbol > .name { +a > .symbol > .name { text-decoration: underline; } -.signature > a:hover > .symbol > .name { +a:hover > .symbol > .name { text-decoration: none; } @@ -432,8 +406,7 @@ div.members > ol > li:last-child { } .signature > .symbol { - display: block; - padding-left: 14.7em; + display: inline; } .signature .name { @@ -441,62 +414,65 @@ div.members > ol > li:last-child { font-weight: bold; } -.signature .symbol > .implicit { +span.symbol > span.name { + font-weight: bold; +} + +.symbol > .implicit { display: inline-block; font-weight: bold; text-decoration: underline; color: darkgreen; } -.signature .symbol .shadowed { +.symbol .shadowed { color: darkseagreen; } -.signature .symbol .params > .implicit { +.symbol .params > .implicit { font-style: italic; } -.signature .symbol .deprecated { +.symbol .deprecated { text-decoration: line-through; } -.signature .symbol .params .default { +.symbol .params .default { font-style: italic; } -#template .signature.closed { +#template .closed { cursor: pointer; } -#template .signature.closed:before { - content: "â–¶"; - position: absolute; - left: 1em; - top: 0.5em; -} - -#template .signature.opened { +#template .opened { cursor: pointer; } -#template .signature.opened:before { - content: "â–¼"; +i.unfold-arrow { + font-size: 1em; position: absolute; - left: 1em; - top: 0.5em; - color: #2C475C; + top: 0.55em; + left: 0.7em; + transition: 0.1s; } -#template .values .signature .name { +#template .modifier_kind.opened > i.unfold-arrow { + transform: rotate(90deg); +} + +#template .values .name { + font-weight: 600; color: darkblue; } -#template .types .signature .name { +#template .types .name { + font-weight: 600; color: darkgreen; } .full-signature-usecase h4 span { - font-size: 0.9em; + font-size: 0.8rem; } .full-signature-usecase > #signature { @@ -505,19 +481,19 @@ div.members > ol > li:last-child { top: 0; } -.full-signature-usecase > .signature.closed:before { - content: "" !important; -} - -.full-signature-usecase > .signature.opened:before { - content: "" !important; +/* Hide unfold arrow where appropriate */ +#template li[fullComment=no] .modifier_kind > i.unfold-arrow, +div#definition > h4#signature > span.modifier_kind > i.unfold-arrow, +.full-signature-usecase > .signature > .closed > i.unfold-arrow, +.full-signature-usecase > .signature > .opened > i.unfold-arrow { + display: none; } -#template .full-signature-usecase > .signature.closed { +#template .full-signature-usecase > .signature > .closed { background: none; } -#template .full-signature-usecase > .signature.opened { +#template .full-signature-usecase > .signature > .opened { background: none; } @@ -531,8 +507,8 @@ div.members > ol > li:last-child { #definition .morelinks { text-align: right; position: absolute; - top: 40px; - right: 10px; + top: 2.95em; + right: 1em; width: 450px; font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif; } @@ -725,11 +701,11 @@ div.fullcomment { #template div.fullcommenttop, #template div.fullcomment { display:none; - margin: 5px 0 0 14.7em; + margin: 0.5em 1em 0 0; } #template .shortcomment { - margin: 5px 0 0 14.7em; + margin: 5px 0 0 0; padding: 0; font-family: "Open Sans"; } @@ -739,7 +715,6 @@ div.fullcomment .block { border-top: 2px solid #fff; margin-top: 5px; overflow: hidden; - margin-right: 0.5em; font-family: "Open Sans"; } @@ -818,7 +793,7 @@ div.fullcomment dl.paramcmts > dd { /* Members filter tool */ -#textfilter { +#memberfilter { position: relative; display: block; height: 2.7em; @@ -826,7 +801,7 @@ div.fullcomment dl.paramcmts > dd { margin-left: 1.5em; } -#textfilter > .input { +#memberfilter > .input { display: block; position: absolute; top: 0; @@ -835,7 +810,7 @@ div.fullcomment dl.paramcmts > dd { transition: 0.2s; } -#textfilter > .input > input { +#memberfilter > .input > input { color: #fff; width: 100%; border-radius: 0.2em; @@ -844,17 +819,16 @@ div.fullcomment dl.paramcmts > dd { font-family: "Open Sans"; } -#textfilter > .clear { +#memberfilter > .clear { display: none; position: absolute; - top: 0.6em; - right: -0.65em; - height: 23px; - width: 21px; + top: 0.55em; color: rgba(255, 255, 255, 0.4); + right: 0; + font-size: 1.2em; } -#textfilter > .clear:hover { +#memberfilter > .clear:hover { color: #fff; cursor: pointer; } @@ -893,21 +867,20 @@ div.fullcomment dl.paramcmts > dd { opacity: 1; } -#mbrsel:hover #textfilter > .input { +#mbrsel:hover #memberfilter > .input { left: 0.7em; } -#mbrsel > div.toggle:before { +#mbrsel > div.toggle > i { cursor: pointer; - content: "â–¶"; position: absolute; left: 0; top: 0; color: #fff; } -#mbrsel > div.toggle.open:before { - content: "â–¼"; +#mbrsel > div.toggle.open > i { + transform: rotate(90deg); } #mbrsel > div#filterby { @@ -1072,24 +1045,16 @@ and (-webkit-device-pixel-ratio: 2) min-width: 300px; } - .signature .modifier_kind { - width: 10em; - } - - .signature > .symbol { - padding-left: 10.7em; - } - - #template .shortcomment { - margin-left: 10.7em; + #template .modifier_kind { + width: 1px; + padding-left: 2.5em; } - #template div.fullcommenttop, #template div.fullcomment { - margin-left: 10.7em; + span.modifier_kind > span.modifier { + display: none; } #definition { - min-width: 300px; height: 6em; } @@ -1125,16 +1090,8 @@ only screen /* iPhone 6 */ and (max-device-width: 667px) and (-webkit-device-pixel-ratio: 2) { - #definition { - position: absolute !important; - min-height: 0 !important; - height: 4em !important; - } - #signature { - position: absolute !important; font-size: 0.7em; - top: 5.7em; } #definition > h1 { @@ -1149,12 +1106,8 @@ and (-webkit-device-pixel-ratio: 2) padding-top: 0.7em; } - div.fullcommenttop { - margin-top: 11.6em; - } - - #template .shortcomment { - margin-left: 1em; + #signature > span.modifier_kind { + width: auto; } div.fullcomment dl.attributes > dt { @@ -1167,10 +1120,6 @@ and (-webkit-device-pixel-ratio: 2) clear: both; } - #template div.fullcommenttop, #template div.fullcomment { - margin-left: 1em; - } - .big-circle { width: 3em; height: 3em; diff --git a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.js b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.js index 3baf0d9db7..b0719b1ed5 100644 --- a/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.js +++ b/src/scaladoc/scala/tools/nsc/doc/html/resource/lib/template.js @@ -17,38 +17,16 @@ $(document).ready(function() { }); $("#template > div > div > ol > li > span > a").click(function(e) { - $("#template > div > div > ol > li").removeClass("selected"); - $(this).parent().parent().addClass("selected"); - var defHeight = $("#definition").height() + $("#signature").height() + 50; - $('html,body').animate({scrollTop: $(this).offset().top - defHeight}, 500); - }); - - /* Handle dynamic size of signature and offset the fullcommenttop div - * appropriately - * - * Some mobile devices render quite slowly, delay the margin-top - * calculation if mobile - */ - if(/Android|webOS|Mobi|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { - setTimeout(function() { - $("div.fullcommenttop").css({ - "margin-top": $("#definition").height() + $("#signature").height() + 15 - }); - }, 1000); - } else { - $("div.fullcommenttop").css({ - "margin-top": $("#definition").height() + $("#signature").height() + 15 - }); - } - - /* When the window is resized, adjust the fullcommenttop div's offset */ - $(window).resize(function() { - $("div.fullcommenttop").css({ - "margin-top": $("#definition").height() + $("#signature").height() + 15 - }); + var href = $(this).attr("href"); + if (href.indexOf("#") != -1) { + e.preventDefault(); + location.hash = href.split("#").pop(); + $("#template > div > div > ol > li").removeClass("selected"); + var parent = $(this).parent().parent().addClass("selected"); + $("#content-container").animate({scrollTop: $("#content-container").scrollTop() + $(this).offset().top - $("#search").height() - 22}, 500); + } }); - var controls = { visibility: { publicOnly: $("#visbl").find("> ol > li.public"), @@ -93,10 +71,8 @@ $(document).ready(function() { } filter(); - window.scrollTo(0, 0); - var defHeight = $("#definition").height() + $("#signature").height() + 50; jqElemParent.addClass("selected"); - $('html,body').animate({scrollTop: jqElemParent.offset().top - defHeight}, 1000); + $("#content-container").animate({scrollTop: jqElemParent.offset().top - $("#search").height() - 5 }, 1000); } var isHiddenClass = function (name) { @@ -116,7 +92,8 @@ $(document).ready(function() { return isHidden(this); }).removeClass("in").addClass("out"); - $("#mbrsel > div.toggle").click(function() { + $("#memberfilter > i.arrow").click(function() { + $(this).toggleClass("rotate"); $("#filterby").toggle(); }); @@ -124,7 +101,7 @@ $(document).ready(function() { filter(); // Member filter box - var input = $("#textfilter input"); + var input = $("#memberfilter input"); input.bind("keyup", function(event) { switch ( event.keyCode ) { @@ -161,8 +138,8 @@ $(document).ready(function() { input.focus(function(event) { input.select(); }); - $("#textfilter > .clear").click(function() { - $("#textfilter input").attr("value", ""); + $("#memberfilter > .clear").click(function() { + $("#memberfilter input").attr("value", ""); filter(); }); $(document).keydown(function(event) { @@ -262,7 +239,7 @@ $(document).ready(function() { /* Add toggle arrows */ //var docAllSigs = $("#template li").has(".fullcomment").find(".signature"); // trying to speed things up a little bit - var docAllSigs = $("#template li[fullComment=yes] .signature"); + var docAllSigs = $("#template li[fullComment=yes] .modifier_kind"); function commentToggleFct(signature){ var parent = signature.parent(); @@ -271,12 +248,22 @@ $(document).ready(function() { var vis = $(":visible", fullComment); signature.toggleClass("closed").toggleClass("opened"); if (vis.length > 0) { - shortComment.slideDown(100); - fullComment.slideUp(100); + if (!isMobile()) { + shortComment.slideDown(100); + fullComment.slideUp(100); + } else { + fullComment.hide(); + shortComment.show(); + } } else { - shortComment.slideUp(100); - fullComment.slideDown(100); + if (!isMobile()) { + shortComment.slideUp(100); + fullComment.slideDown(100); + } else { + shortComment.hide(); + fullComment.show(); + } } }; docAllSigs.addClass("closed"); @@ -288,7 +275,13 @@ $(document).ready(function() { function toggleShowContentFct(e){ e.toggleClass("open"); var content = $(".hiddenContent", e.parent().get(0)); - (content.is(':visible') ? content.slideUp : content.slideDown)(100); + if(content.is(':visible')) { + if (!isMobile()) content.slideUp(100); + else content.hide(); + } else { + if (!isMobile()) content.slideDown(100); + else content.show(); + } }; $(".toggle:not(.diagram-link)").click(function() { @@ -315,11 +308,13 @@ $(document).ready(function() { } $("#mbrsel-input").on("focus", function() { - $("#textfilter > .clear").show(); + $("#memberfilter > .clear").show(); }); $("#mbrsel-input").on("blur", function() { - $("#textfilter > .clear").hide(); + setTimeout(function() { + $("#memberfilter > .clear").hide(); + }, 10); }); }); @@ -447,7 +442,7 @@ function initInherit() { /* filter used to take boolean scrollToMember */ function filter() { - var query = $.trim($("#textfilter input").val()).toLowerCase(); + var query = $.trim($("#memberfilter input").val()).toLowerCase(); query = query.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&").replace(/\s+/g, "|"); var queryRegExp = new RegExp(query, "i"); var privateMembersHidden = $("#visbl > ol > li.public").hasClass("in"); @@ -534,21 +529,24 @@ function filter() { }); if (membersVisible) - members.show(); + members.show(); else - members.hide(); + members.hide(); }; return false; }; -function windowTitle() -{ +function windowTitle() { try { parent.document.title=document.title; - } - catch(e) { + } catch(e) { // Chrome doesn't allow settings the parent's title when // used on the local file system. } }; + +/** Check if user agent is associated with a known mobile browser */ +function isMobile() { + return /Android|webOS|Mobi|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); +} diff --git a/test/files/run/delambdafy_t6028.check b/test/files/run/delambdafy_t6028.check index c8c4b1cb4c..b5a6e4b64e 100644 --- a/test/files/run/delambdafy_t6028.check +++ b/test/files/run/delambdafy_t6028.check @@ -11,7 +11,7 @@ package <empty> { def foo(methodParam: String): Function0 = { val methodLocal: String = ""; { - (() => T.this.$anonfun$1(methodParam, methodLocal)).$asInstanceOf[Function0]() + (() => T.this.$anonfun$1(methodParam, methodLocal)) } }; def bar(barParam: String): Object = { @@ -21,7 +21,7 @@ package <empty> { def tryy(tryyParam: String): Function0 = { var tryyLocal: runtime.ObjectRef = scala.runtime.ObjectRef.create(""); { - (() => T.this.$anonfun$2(tryyParam, tryyLocal)).$asInstanceOf[Function0]() + (() => T.this.$anonfun$2(tryyParam, tryyLocal)) } }; final <artifact> private[this] def $anonfun$1(methodParam$1: String, methodLocal$1: String): String = T.this.classParam.+(T.this.field()).+(methodParam$1).+(methodLocal$1); diff --git a/test/junit/scala/issues/BytecodeTest.scala b/test/junit/scala/issues/BytecodeTest.scala index ca1b33ed20..18f8b44391 100644 --- a/test/junit/scala/issues/BytecodeTest.scala +++ b/test/junit/scala/issues/BytecodeTest.scala @@ -150,21 +150,21 @@ class BytecodeTest extends ClearAfterClass { val List(c) = compileClasses(compiler)(code) // t1: no unnecessary GOTOs - assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List( + assertSameCode(getSingleMethod(c, "t1"), List( VarOp(ILOAD, 1), Jump(IFEQ, Label(6)), Op(ICONST_1), Jump(GOTO, Label(9)), Label(6), Op(ICONST_2), Label(9), Op(IRETURN))) // t2: no unnecessary GOTOs - assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List( + assertSameCode(getSingleMethod(c, "t2"), List( VarOp(ILOAD, 1), IntOp(SIPUSH, 393), Jump(IF_ICMPNE, Label(7)), Op(ICONST_1), Jump(GOTO, Label(10)), Label(7), Op(ICONST_2), Label(10), Op(IRETURN))) // t3: Array == is translated to reference equality, AnyRef == to null checks and equals - assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List( + assertSameCode(getSingleMethod(c, "t3"), List( // Array == VarOp(ALOAD, 1), VarOp(ALOAD, 2), Jump(IF_ACMPEQ, Label(23)), // AnyRef == @@ -183,13 +183,13 @@ class BytecodeTest extends ClearAfterClass { Label(13), Op(IRETURN)) // t4: one side is known null, so just a null check on the other - assertSameCode(getSingleMethod(c, "t4").instructions.dropNonOp, t4t5) + assertSameCode(getSingleMethod(c, "t4"), t4t5) // t5: one side known null, so just a null check on the other - assertSameCode(getSingleMethod(c, "t5").instructions.dropNonOp, t4t5) + assertSameCode(getSingleMethod(c, "t5"), t4t5) // t6: no unnecessary GOTOs - assertSameCode(getSingleMethod(c, "t6").instructions.dropNonOp, List( + assertSameCode(getSingleMethod(c, "t6"), List( VarOp(ILOAD, 1), IntOp(BIPUSH, 10), Jump(IF_ICMPNE, Label(7)), VarOp(ILOAD, 2), Jump(IFNE, Label(12)), Label(7), VarOp(ILOAD, 1), Op(ICONST_1), Jump(IF_ICMPEQ, Label(16)), @@ -201,7 +201,7 @@ class BytecodeTest extends ClearAfterClass { assertInvoke(getSingleMethod(c, "t7"), "scala/runtime/BoxesRunTime", "equals") // t8: no null checks invoking equals on modules and constants - assertSameCode(getSingleMethod(c, "t8").instructions.dropNonOp, List( + assertSameCode(getSingleMethod(c, "t8"), List( Field(GETSTATIC, "scala/collection/immutable/Nil$", "MODULE$", "Lscala/collection/immutable/Nil$;"), VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z", false), Jump(IFNE, Label(10)), Ldc(LDC, ""), VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z", false), Jump(IFNE, Label(14)), Label(10), Op(ICONST_1), Jump(GOTO, Label(17)), diff --git a/test/junit/scala/issues/OptimizedBytecodeTest.scala b/test/junit/scala/issues/OptimizedBytecodeTest.scala index 0e1a52b1c8..1555e8945a 100644 --- a/test/junit/scala/issues/OptimizedBytecodeTest.scala +++ b/test/junit/scala/issues/OptimizedBytecodeTest.scala @@ -36,7 +36,7 @@ class OptimizedBytecodeTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(compiler)(code) - assertSameCode(getSingleMethod(c, "t").instructions.dropNonOp, List(Label(0), Jump(GOTO, Label(0)))) + assertSameCode(getSingleMethod(c, "t"), List(Label(0), Jump(GOTO, Label(0)))) } @Test @@ -55,17 +55,10 @@ class OptimizedBytecodeTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(compiler)(code) - assertEquals( - getSingleMethod(c, "t").instructions.summary, - List(LDC, ASTORE, ALOAD /*0*/, ALOAD /*1*/, "C$$$anonfun$1", IRETURN)) - - assertEquals( - getSingleMethod(c, "C$$$anonfun$1").instructions.summary, - List(LDC, "C$$$anonfun$2", IRETURN)) - - assertEquals( - getSingleMethod(c, "C$$$anonfun$2").instructions.summary, - List(-1 /*A*/, GOTO /*A*/)) + assertSameSummary(getSingleMethod(c, "t"), List( + LDC, ASTORE, ALOAD /*0*/, ALOAD /*1*/, "C$$$anonfun$1", IRETURN)) + assertSameSummary(getSingleMethod(c, "C$$$anonfun$1"), List(LDC, "C$$$anonfun$2", IRETURN)) + assertSameSummary(getSingleMethod(c, "C$$$anonfun$2"), List(-1 /*A*/, GOTO /*A*/)) } @Test @@ -87,9 +80,7 @@ class OptimizedBytecodeTest extends ClearAfterClass { |} """.stripMargin val List(c, t, tMod) = compileClasses(compiler)(code, allowMessage = _.msg.contains("not be exhaustive")) - assertEquals( - getSingleMethod(c, "t").instructions.summary, - List(GETSTATIC, "$qmark$qmark$qmark", ATHROW)) + assertSameSummary(getSingleMethod(c, "t"), List(GETSTATIC, "$qmark$qmark$qmark", ATHROW)) } @Test @@ -235,9 +226,7 @@ class OptimizedBytecodeTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(compiler)(code) - assertEquals( - getSingleMethod(c, "t").instructions.summary, - List( + assertSameSummary(getSingleMethod(c, "t"), List( ALOAD /*1*/, INSTANCEOF /*Some*/, IFNE /*A*/, ALOAD /*0*/, "getInt", POP, -1 /*A*/, BIPUSH, IRETURN)) @@ -256,13 +245,11 @@ class OptimizedBytecodeTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(compiler)(code) - assertEquals( - getSingleMethod(c, "t").instructions.summary, - List( - -1 /*A*/, ILOAD /*1*/, TABLESWITCH, - -1, ALOAD, "pr", RETURN, - -1, ALOAD, "pr", RETURN, - -1, ILOAD, ICONST_2, ISUB, ISTORE, GOTO /*A*/)) + assertSameSummary(getSingleMethod(c, "t"), List( + -1 /*A*/, ILOAD /*1*/, TABLESWITCH, + -1, ALOAD, "pr", RETURN, + -1, ALOAD, "pr", RETURN, + -1, ILOAD, ICONST_2, ISUB, ISTORE, GOTO /*A*/)) } @Test @@ -283,12 +270,10 @@ class OptimizedBytecodeTest extends ClearAfterClass { val cls = compileClassesSeparately(List(c1, c2), extraArgs = OptimizedBytecodeTest.args) val c = cls.find(_.name == "C").get - assertEquals( - getSingleMethod(c, "t").instructions.summary, - List( - GETSTATIC, IFNONNULL, ACONST_NULL, ATHROW, // module load and null checks not yet eliminated - -1, ICONST_1, GETSTATIC, IFNONNULL, ACONST_NULL, ATHROW, - -1, ICONST_2, IADD, IRETURN)) + assertSameSummary(getSingleMethod(c, "t"), List( + GETSTATIC, IFNONNULL, ACONST_NULL, ATHROW, // module load and null checks not yet eliminated + -1, ICONST_1, GETSTATIC, IFNONNULL, ACONST_NULL, ATHROW, + -1, ICONST_2, IADD, IRETURN)) } @Test diff --git a/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala b/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala index 0d353e930e..fe43ed2f6a 100644 --- a/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala +++ b/test/junit/scala/tools/nsc/backend/jvm/CodeGenTools.scala @@ -164,8 +164,18 @@ object CodeGenTools { convertMethod(m) } + def assertSameCode(method: Method, expected: List[Instruction]): Unit = assertSameCode(method.instructions.dropNonOp, expected) def assertSameCode(actual: List[Instruction], expected: List[Instruction]): Unit = { - assertTrue(s"\nExpected: $expected\nActual : $actual", actual === expected) + assert(actual === expected, s"\nExpected: $expected\nActual : $actual") + } + + def assertSameSummary(method: Method, expected: List[Any]): Unit = assertSameSummary(method.instructions, expected) + def assertSameSummary(actual: List[Instruction], expected: List[Any]): Unit = { + def expectedString = expected.map({ + case s: String => s""""$s"""" + case i: Int => opcodeToString(i, i) + }).mkString("List(", ", ", ")") + assert(actual.summary == expected, s"\nFound : ${actual.summaryText}\nExpected: $expectedString") } def assertNoInvoke(m: Method): Unit = assertNoInvoke(m.instructions) @@ -181,6 +191,21 @@ object CodeGenTools { }, l.stringLines) } + def assertDoesNotInvoke(m: Method, method: String): Unit = assertDoesNotInvoke(m.instructions, method) + def assertDoesNotInvoke(l: List[Instruction], method: String): Unit = { + assert(!l.exists { + case i: Invoke => i.name == method + case _ => false + }, l.stringLines) + } + + def assertInvokedMethods(m: Method, expected: List[String]): Unit = assertInvokedMethods(m.instructions, expected) + def assertInvokedMethods(l: List[Instruction], expected: List[String]): Unit = { + def quote(l: List[String]) = l.map(s => s""""$s"""").mkString("List(", ", ", ")") + val actual = l collect { case i: Invoke => i.owner + "." + i.name } + assert(actual == expected, s"\nFound : ${quote(actual)}\nExpected: ${quote(expected)}") + } + def getSingleMethod(classNode: ClassNode, name: String): Method = convertMethod(classNode.methods.asScala.toList.find(_.name == name).get) diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala index b314643fb1..a0b9d6b4ed 100644 --- a/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala +++ b/test/junit/scala/tools/nsc/backend/jvm/opt/ClosureOptimizerTest.scala @@ -82,7 +82,7 @@ class ClosureOptimizerTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(compiler)(code) - assertSameCode(getSingleMethod(c, "t").instructions.dropNonOp, + assertSameCode(getSingleMethod(c, "t"), List(VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "scala/collection/immutable/List", "head", "()Ljava/lang/Object;", false), TypeOp(CHECKCAST, "java/lang/String"), Invoke(INVOKESTATIC, "C", "C$$$anonfun$1", "(Ljava/lang/String;)Ljava/lang/String;", false), Op(ARETURN))) @@ -103,7 +103,6 @@ class ClosureOptimizerTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(compiler)(code) - assertEquals(getSingleMethod(c, "t").instructions.summary, - List(NEW, DUP, LDC, "<init>", ATHROW)) + assertSameSummary(getSingleMethod(c, "t"), List(NEW, DUP, LDC, "<init>", ATHROW)) } } diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala index 54eddc868d..2c8f5e794e 100644 --- a/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala +++ b/test/junit/scala/tools/nsc/backend/jvm/opt/InlinerTest.scala @@ -100,7 +100,7 @@ class InlinerTest extends ClearAfterClass { val g = inlineTest(code) val gConv = convertMethod(g) - assertSameCode(gConv.instructions.dropNonOp, + assertSameCode(gConv, List( VarOp(ALOAD, 0), VarOp(ASTORE, 1), // store this Op(ICONST_1), VarOp(ISTORE, 2), Jump(GOTO, Label(10)), // store return value @@ -144,10 +144,10 @@ class InlinerTest extends ClearAfterClass { VarOp(ALOAD, 2), Op(ATHROW)) - assertSameCode(convertMethod(g).instructions.dropNonOp, gBeforeLocalOpt) + assertSameCode(convertMethod(g), gBeforeLocalOpt) compiler.genBCode.bTypes.localOpt.methodOptimizations(g, "C") - assertSameCode(convertMethod(g).instructions.dropNonOp, invokeQQQ :+ Op(ATHROW)) + assertSameCode(convertMethod(g), invokeQQQ :+ Op(ATHROW)) } @Test @@ -1313,60 +1313,40 @@ class InlinerTest extends ClearAfterClass { """.stripMargin val List(c, _, _) = compile(code) - assertEquals(getSingleMethod(c, "t1").instructions.summary, - List(BIPUSH, "C$$$anonfun$1", IRETURN)) - - assertEquals(getSingleMethod(c, "t1a").instructions.summary, - List(LCONST_1, "C$$$anonfun$2", IRETURN)) - - assertEquals(getSingleMethod(c, "t2").instructions.summary, List( - ICONST_1, ICONST_2, "C$$$anonfun$3",IRETURN)) + assertSameSummary(getSingleMethod(c, "t1"), List(BIPUSH, "C$$$anonfun$1", IRETURN)) + assertSameSummary(getSingleMethod(c, "t1a"), List(LCONST_1, "C$$$anonfun$2", IRETURN)) + assertSameSummary(getSingleMethod(c, "t2"), List(ICONST_1, ICONST_2, "C$$$anonfun$3",IRETURN)) // val a = new ValKl(n); new ValKl(anonfun(a.x)).x // value class instantiation-extraction should be optimized by boxing elim - assertEquals(getSingleMethod(c, "t3").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t3"), List( NEW, DUP, ICONST_1, "<init>", ASTORE, NEW, DUP, ALOAD, "x", "C$$$anonfun$4", "<init>", "x", IRETURN)) - assertEquals(getSingleMethod(c, "t4").instructions.summary, List( - BIPUSH, "C$$$anonfun$5", "boxToInteger", ARETURN)) - - assertEquals(getSingleMethod(c, "t4a").instructions.summary, List( - ICONST_1, LDC, "C$$$anonfun$6", LRETURN)) - - assertEquals(getSingleMethod(c, "t5").instructions.summary, List( - BIPUSH, ICONST_3, "C$$$anonfun$7", "boxToInteger", ARETURN)) - - assertEquals(getSingleMethod(c, "t5a").instructions.summary, List( - BIPUSH, BIPUSH, I2B, "C$$$anonfun$8", IRETURN)) - - assertEquals(getSingleMethod(c, "t6").instructions.summary, List( - BIPUSH, "C$$$anonfun$9", RETURN)) - - assertEquals(getSingleMethod(c, "t7").instructions.summary, List( - ICONST_1, "C$$$anonfun$10", RETURN)) - - assertEquals(getSingleMethod(c, "t8").instructions.summary, List( - ICONST_1, LDC, "C$$$anonfun$11", LRETURN)) - - assertEquals(getSingleMethod(c, "t9").instructions.summary, List( - ICONST_1, "boxToInteger", "C$$$anonfun$12", RETURN)) + assertSameSummary(getSingleMethod(c, "t4"), List(BIPUSH, "C$$$anonfun$5", "boxToInteger", ARETURN)) + assertSameSummary(getSingleMethod(c, "t4a"), List(ICONST_1, LDC, "C$$$anonfun$6", LRETURN)) + assertSameSummary(getSingleMethod(c, "t5"), List(BIPUSH, ICONST_3, "C$$$anonfun$7", "boxToInteger", ARETURN)) + assertSameSummary(getSingleMethod(c, "t5a"), List(BIPUSH, BIPUSH, I2B, "C$$$anonfun$8", IRETURN)) + assertSameSummary(getSingleMethod(c, "t6"), List(BIPUSH, "C$$$anonfun$9", RETURN)) + assertSameSummary(getSingleMethod(c, "t7"), List(ICONST_1, "C$$$anonfun$10", RETURN)) + assertSameSummary(getSingleMethod(c, "t8"), List(ICONST_1, LDC, "C$$$anonfun$11", LRETURN)) + assertSameSummary(getSingleMethod(c, "t9"), List(ICONST_1, "boxToInteger", "C$$$anonfun$12", RETURN)) // t9a inlines Range.foreach, which is quite a bit of code, so just testing the core assertInvoke(getSingleMethod(c, "t9a"), "C", "C$$$anonfun$13") - assert(getSingleMethod(c, "t9a").instructions.summary.contains("boxToInteger")) + assertInvoke(getSingleMethod(c, "t9a"), "scala/runtime/BoxesRunTime", "boxToInteger") - assertEquals(getSingleMethod(c, "t10").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t10"), List( ICONST_1, ISTORE, ALOAD, ILOAD, "C$$$anonfun$14", RETURN)) // t10a inlines Range.foreach assertInvoke(getSingleMethod(c, "t10a"), "C", "C$$$anonfun$15") - assert(!getSingleMethod(c, "t10a").instructions.summary.contains("boxToInteger")) + assertDoesNotInvoke(getSingleMethod(c, "t10a"), "boxToInteger") } @Test @@ -1389,7 +1369,7 @@ class InlinerTest extends ClearAfterClass { |} """.stripMargin val List(c) = compile(code) - assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(Op(ICONST_0), Op(ICONST_1), Op(IADD), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t1"), List(Op(ICONST_0), Op(ICONST_1), Op(IADD), Op(IRETURN))) assertEquals(getSingleMethod(c, "t2").instructions collect { case i: Invoke => i.owner +"."+ i.name }, List( "scala/runtime/IntRef.create", "C.C$$$anonfun$1")) } @@ -1430,9 +1410,9 @@ class InlinerTest extends ClearAfterClass { |} """.stripMargin val List(c) = compile(code) - assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(Op(ICONST_3), Op(ICONST_4), Op(IADD), Op(IRETURN))) - assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(Op(ICONST_1), Op(ICONST_2), Op(IADD), Op(IRETURN))) - assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(Op(ICONST_1), Op(ICONST_3), Op(ISUB), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t1"), List(Op(ICONST_3), Op(ICONST_4), Op(IADD), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t2"), List(Op(ICONST_1), Op(ICONST_2), Op(IADD), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t3"), List(Op(ICONST_1), Op(ICONST_3), Op(ISUB), Op(IRETURN))) assertNoInvoke(getSingleMethod(c, "t4")) assertNoInvoke(getSingleMethod(c, "t5")) } @@ -1461,9 +1441,9 @@ class InlinerTest extends ClearAfterClass { """.stripMargin val List(c, _) = compile(code) def casts(m: String) = getSingleMethod(c, m).instructions collect { case TypeOp(CHECKCAST, tp) => tp } - assertSameCode(getSingleMethod(c, "t1").instructions.dropNonOp, List(VarOp(ALOAD, 1), Op(ARETURN))) - assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(VarOp(ALOAD, 1), Op(ARETURN))) - assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(VarOp(ALOAD, 1), TypeOp(CHECKCAST, "C"), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t1"), List(VarOp(ALOAD, 1), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t2"), List(VarOp(ALOAD, 1), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t3"), List(VarOp(ALOAD, 1), TypeOp(CHECKCAST, "C"), Op(ARETURN))) assertEquals(casts("t4"), List("C")) assertEquals(casts("t5"), Nil) assertEquals(casts("t6"), Nil) @@ -1489,12 +1469,11 @@ class InlinerTest extends ClearAfterClass { val cls = compile(code) val test = cls.find(_.name == "Test$").get - assertEquals( - getSingleMethod(test, "f").instructions.summary, - List(GETSTATIC, "mkFoo", - BIPUSH, ISTORE, - IFNONNULL, ACONST_NULL, ATHROW, -1 /*label*/, - ILOAD, ICONST_1, IADD, IRETURN)) + assertSameSummary(getSingleMethod(test, "f"), List( + GETSTATIC, "mkFoo", + BIPUSH, ISTORE, + IFNONNULL, ACONST_NULL, ATHROW, -1 /*label*/, + ILOAD, ICONST_1, IADD, IRETURN)) } @Test // a test taken from the test suite for the 2.11 inliner @@ -1509,11 +1488,10 @@ class InlinerTest extends ClearAfterClass { val List(c) = compile(code) // box-unbox will clean it up - assertEquals(getSingleMethod(c, "t").instructions.summary, - List( - ALOAD, "C$$$anonfun$1", IFEQ /*A*/, - "C$$$anonfun$2", IRETURN, - -1 /*A*/, "C$$$anonfun$3", IRETURN)) + assertSameSummary(getSingleMethod(c, "t"), List( + ALOAD, "C$$$anonfun$1", IFEQ /*A*/, + "C$$$anonfun$2", IRETURN, + -1 /*A*/, "C$$$anonfun$3", IRETURN)) } @Test diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala index 8f18a84a1c..0a9a26cda7 100644 --- a/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala +++ b/test/junit/scala/tools/nsc/backend/jvm/opt/MethodLevelOptsTest.scala @@ -46,8 +46,7 @@ class MethodLevelOptsTest extends ClearAfterClass { val code = "def f = { try {} catch { case _: Throwable => 0 }; 1 }" val m = singleMethod(methodOptCompiler)(code) assertTrue(m.handlers.length == 0) - assertSameCode(m.instructions.dropNonOp, - List(Op(ICONST_1), Op(IRETURN))) + assertSameCode(m, List(Op(ICONST_1), Op(IRETURN))) } @Test @@ -89,7 +88,7 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val m = singleMethod(methodOptCompiler)(code) assertTrue(m.handlers.isEmpty) - assertSameCode(m.instructions.dropNonOp, List(Op(ICONST_3), Op(IRETURN))) + assertSameCode(m, List(Op(ICONST_3), Op(IRETURN))) } @Test @@ -108,8 +107,8 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertSameCode(getSingleMethod(c, "t").instructions.dropNonOp, - List(Op(ACONST_NULL), Invoke(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t"), List( + Op(ACONST_NULL), Invoke(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false), Op(ARETURN))) } @Test @@ -126,8 +125,7 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) assertSameCode( - getSingleMethod(c, "t").instructions.dropNonOp, - List(Ldc(LDC, "c"), Op(ARETURN))) + getSingleMethod(c, "t"), List(Ldc(LDC, "c"), Op(ARETURN))) } @Test @@ -147,13 +145,11 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals( - getSingleMethod(c, "t").instructions.dropNonOp, - List( - Ldc(LDC, "el"), VarOp(ASTORE, 1), - Field(GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"), VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "scala/Predef$", "println", "(Ljava/lang/Object;)V", false), - Op(ACONST_NULL), VarOp(ASTORE, 1), - Ldc(LDC, "zit"), VarOp(ASTORE, 1), VarOp(ALOAD, 1), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t"), List( + Ldc(LDC, "el"), VarOp(ASTORE, 1), + Field(GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"), VarOp(ALOAD, 1), Invoke(INVOKEVIRTUAL, "scala/Predef$", "println", "(Ljava/lang/Object;)V", false), + Op(ACONST_NULL), VarOp(ASTORE, 1), + Ldc(LDC, "zit"), VarOp(ASTORE, 1), VarOp(ALOAD, 1), Op(ARETURN))) } @Test @@ -172,8 +168,8 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t").instructions.dropNonOp, - List(IntOp(BIPUSH, 23), IntOp(NEWARRAY, 5), Op(POP), VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t"), List( + IntOp(BIPUSH, 23), IntOp(NEWARRAY, 5), Op(POP), VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN))) } @Test @@ -187,9 +183,9 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t").instructions.dropNonOp, - List(TypeOp(NEW, "java/lang/Integer"), Ldc(LDC, "nono"), Invoke(INVOKESPECIAL, "java/lang/Integer", "<init>", "(Ljava/lang/String;)V", false), - VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t"), List( + TypeOp(NEW, "java/lang/Integer"), Ldc(LDC, "nono"), Invoke(INVOKESPECIAL, "java/lang/Integer", "<init>", "(Ljava/lang/String;)V", false), + VarOp(ILOAD, 1), VarOp(ILOAD, 2), Op(IADD), Op(IRETURN))) } @Test @@ -213,8 +209,7 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t").instructions.dropNonOp, - List(Op(ICONST_0), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t"), List(Op(ICONST_0), Op(IRETURN))) } @Test @@ -230,14 +225,12 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals( - getSingleMethod(c, "t").instructions.dropNonOp, - List( - IntOp(BIPUSH, 30), VarOp(ISTORE, 3), // no constant propagation, so we keep the store (and load below) of a const - VarOp(ILOAD, 1), - VarOp(ILOAD, 2), - VarOp(ILOAD, 3), - Invoke(INVOKESTATIC, "C", "C$$$anonfun$1", "(III)I", false), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t"), List( + IntOp(BIPUSH, 30), VarOp(ISTORE, 3), // no constant propagation, so we keep the store (and load below) of a const + VarOp(ILOAD, 1), + VarOp(ILOAD, 2), + VarOp(ILOAD, 3), + Invoke(INVOKESTATIC, "C", "C$$$anonfun$1", "(III)I", false), Op(IRETURN))) } @Test @@ -342,14 +335,14 @@ class MethodLevelOptsTest extends ClearAfterClass { assertNoInvoke(getSingleMethod(c, "t5")) assertNoInvoke(getSingleMethod(c, "t6")) assertNoInvoke(getSingleMethod(c, "t7")) - assertEquals(getSingleMethod(c, "t8").instructions.summary, List(ICONST_0, IRETURN)) + assertSameSummary(getSingleMethod(c, "t8"), List(ICONST_0, IRETURN)) assertNoInvoke(getSingleMethod(c, "t9")) // t10: no invocation of unbox assertEquals(getSingleMethod(c, "t10").instructions collect { case Invoke(_, owner, name, _, _) => (owner, name) }, List( ("java/lang/Integer", "valueOf"), ("C", "escape"))) - assertEquals(getSingleMethod(c, "t11").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t11"), List( BIPUSH, "valueOf", ASTORE /*2*/, BIPUSH, "valueOf", ASTORE /*3*/, ALOAD /*0*/, ALOAD /*2*/, "escape", @@ -410,9 +403,9 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t1").instructions.summary, List(ICONST_0, IRETURN)) + assertSameSummary(getSingleMethod(c, "t1"), List(ICONST_0, IRETURN)) assertNoInvoke(getSingleMethod(c, "t2")) - assertEquals(getSingleMethod(c, "t3").instructions.summary, List(LDC, LDC, LADD, LRETURN)) + assertSameSummary(getSingleMethod(c, "t3"), List(LDC, LDC, LADD, LRETURN)) assertNoInvoke(getSingleMethod(c, "t4")) assertEquals(getSingleMethod(c, "t5").instructions collect { case Field(_, owner, name, _) => s"$owner.$name" }, List("scala/runtime/IntRef.elem")) @@ -475,16 +468,16 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) assertNoInvoke(getSingleMethod(c, "t1")) - assertEquals(getSingleMethod(c, "t2").instructions.summary, List(ICONST_1, ICONST_3, IADD, IRETURN)) - assertEquals(getSingleMethod(c, "t3").instructions.summary, List(ICONST_3, ICONST_4, IADD, IRETURN)) - assertEquals(getSingleMethod(c, "t4").instructions.summary, List(ICONST_3, "boxToInteger", ARETURN)) + assertSameSummary(getSingleMethod(c, "t2"), List(ICONST_1, ICONST_3, IADD, IRETURN)) + assertSameSummary(getSingleMethod(c, "t3"), List(ICONST_3, ICONST_4, IADD, IRETURN)) + assertSameSummary(getSingleMethod(c, "t4"), List(ICONST_3, "boxToInteger", ARETURN)) assertEquals(getSingleMethod(c, "t5").instructions collect { case Invoke(_, owner, name, _, _) => (owner, name) }, List( ("scala/runtime/BoxesRunTime", "boxToInteger"), ("scala/runtime/BoxesRunTime", "boxToInteger"), ("C", "tpl"), ("scala/Tuple2", "_1$mcI$sp"))) - assertEquals(getSingleMethod(c, "t6").instructions.summary, List(ICONST_1, ICONST_2, ISUB, IRETURN)) - assertEquals(getSingleMethod(c, "t7").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t6"), List(ICONST_1, ICONST_2, ISUB, IRETURN)) + assertSameSummary(getSingleMethod(c, "t7"), List( ICONST_1, ICONST_2, ISTORE, ISTORE, ICONST_3, ISTORE, ILOAD, ILOAD, IADD, ILOAD, IADD, IRETURN)) @@ -539,13 +532,13 @@ class MethodLevelOptsTest extends ClearAfterClass { |} """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t1").instructions.summary, List(NEW, DUP, "<init>", ARETURN)) - assertSameCode(getSingleMethod(c, "t2").instructions.dropNonOp, List(Op(LCONST_0), Op(LRETURN))) - assertSameCode(getSingleMethod(c, "t3").instructions.dropNonOp, List(Op(ICONST_1), Op(IRETURN))) - assertSameCode(getSingleMethod(c, "t4").instructions.dropNonOp, List(Op(ICONST_1), Op(IRETURN))) - assertSameCode(getSingleMethod(c, "t5").instructions.dropNonOp, List(Op(DCONST_0), Op(DRETURN))) - assertSameCode(getSingleMethod(c, "t6").instructions.dropNonOp, List(Op(ACONST_NULL), Op(ARETURN))) - assertSameCode(getSingleMethod(c, "t7").instructions.dropNonOp, List(Op(ICONST_0), Op(IRETURN))) + assertSameSummary(getSingleMethod(c, "t1"), List(NEW, DUP, "<init>", ARETURN)) + assertSameCode(getSingleMethod(c, "t2"), List(Op(LCONST_0), Op(LRETURN))) + assertSameCode(getSingleMethod(c, "t3"), List(Op(ICONST_1), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t4"), List(Op(ICONST_1), Op(IRETURN))) + assertSameCode(getSingleMethod(c, "t5"), List(Op(DCONST_0), Op(DRETURN))) + assertSameCode(getSingleMethod(c, "t6"), List(Op(ACONST_NULL), Op(ARETURN))) + assertSameCode(getSingleMethod(c, "t7"), List(Op(ICONST_0), Op(IRETURN))) } @Test @@ -560,8 +553,8 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) assertSameCode( - getSingleMethod(c, "t").instructions.dropNonOp, - List(VarOp(ALOAD, 1), Jump(IFNULL, Label(6)), Op(ICONST_1), Op(IRETURN), Label(6), Op(ICONST_0), Op(IRETURN))) + getSingleMethod(c, "t"), List( + VarOp(ALOAD, 1), Jump(IFNULL, Label(6)), Op(ICONST_1), Op(IRETURN), Label(6), Op(ICONST_0), Op(IRETURN))) } @Test @@ -703,15 +696,8 @@ class MethodLevelOptsTest extends ClearAfterClass { assertEquals(locals(c, "t2"), List(("this", 0), ("x", 1))) // we don't have constant propagation (yet). // the local var can't be optimized as a store;laod sequence, there's a GETSTATIC between the two - assertEquals( - textify(findAsmMethod(c, "t2")), - getSingleMethod(c, "t2").instructions.dropNonOp.map(_.opcode), - List( - ICONST_2, ISTORE, - GETSTATIC, // Predef.MODULE$ - ILOAD, INVOKESTATIC, // boxToInteger - INVOKEVIRTUAL, // println - RETURN)) + assertSameSummary(getSingleMethod(c, "t2"), List( + ICONST_2, ISTORE, GETSTATIC, ILOAD, "boxToInteger", "println", RETURN)) assertEquals(locals(c, "t3"), List(("this", 0))) assertEquals(locals(c, "t4"), List(("this", 0), ("x", 1))) @@ -736,10 +722,7 @@ class MethodLevelOptsTest extends ClearAfterClass { val t = getSingleMethod(c, "t") assertEquals(t.handlers, Nil) assertEquals(locals(c, "t"), List(("this", 0))) - assertEquals(t.instructions.summary, - List( - GETSTATIC, LDC, "print", - -1, GOTO)) + assertSameSummary(t, List(GETSTATIC, LDC, "print", -1, GOTO)) } @Test @@ -769,7 +752,7 @@ class MethodLevelOptsTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(methodOptCompiler)(code) - assertEquals(getSingleMethod(c, "t").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t"), List( BIPUSH, ILOAD, IF_ICMPNE, BIPUSH, ILOAD, IF_ICMPNE, LDC, ASTORE, GOTO, diff --git a/test/junit/scala/tools/nsc/backend/jvm/opt/UnreachableCodeTest.scala b/test/junit/scala/tools/nsc/backend/jvm/opt/UnreachableCodeTest.scala index 902709e041..0021a1784d 100644 --- a/test/junit/scala/tools/nsc/backend/jvm/opt/UnreachableCodeTest.scala +++ b/test/junit/scala/tools/nsc/backend/jvm/opt/UnreachableCodeTest.scala @@ -232,35 +232,33 @@ class UnreachableCodeTest extends ClearAfterClass { """.stripMargin val List(c) = compileClasses(noOptCompiler)(code) - assertEquals(getSingleMethod(c, "nl").instructions.summary, List(ACONST_NULL, ARETURN)) + assertSameSummary(getSingleMethod(c, "nl"), List(ACONST_NULL, ARETURN)) - assertEquals(getSingleMethod(c, "nt").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "nt"), List( NEW, DUP, LDC, "<init>", ATHROW)) - assertEquals(getSingleMethod(c, "t1").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t1"), List( ALOAD, ACONST_NULL, "cons", RETURN)) // GenBCode introduces POP; ACONST_NULL after loading an expression of type scala.runtime.Null$, // see comment in BCodeBodyBuilder.adapt - assertEquals(getSingleMethod(c, "t2").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t2"), List( ALOAD, ALOAD, "nl", POP, ACONST_NULL, "cons", RETURN)) // the bytecode generated by GenBCode is ... ATHROW; INVOKEVIRTUAL C.cons; RETURN // the ASM classfile writer creates a new basic block (creates a label) right after the ATHROW // and replaces all instructions by NOP*; ATHROW, see comment in BCodeBodyBuilder.adapt // NOTE: DCE is enabled by default and gets rid of the redundant code (tested below) - assertEquals(getSingleMethod(c, "t3").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t3"), List( ALOAD, NEW, DUP, LDC, "<init>", ATHROW, NOP, NOP, NOP, ATHROW)) // GenBCode introduces an ATHROW after the invocation of C.nt, see BCodeBodyBuilder.adapt // NOTE: DCE is enabled by default and gets rid of the redundant code (tested below) - assertEquals(getSingleMethod(c, "t4").instructions.summary, List( + assertSameSummary(getSingleMethod(c, "t4"), List( ALOAD, ALOAD, "nt", ATHROW, NOP, NOP, NOP, ATHROW)) val List(cDCE) = compileClasses(dceCompiler)(code) - assertEquals(getSingleMethod(cDCE, "t3").instructions.summary, List( - ALOAD, NEW, DUP, LDC, "<init>", ATHROW)) - assertEquals(getSingleMethod(cDCE, "t4").instructions.summary, List( - ALOAD, ALOAD, "nt", ATHROW)) + assertSameSummary(getSingleMethod(cDCE, "t3"), List(ALOAD, NEW, DUP, LDC, "<init>", ATHROW)) + assertSameSummary(getSingleMethod(cDCE, "t4"), List(ALOAD, ALOAD, "nt", ATHROW)) } } diff --git a/test/junit/scala/tools/nsc/transform/patmat/PatmatBytecodeTest.scala b/test/junit/scala/tools/nsc/transform/patmat/PatmatBytecodeTest.scala index 3fc3144eb2..ac558e2e21 100644 --- a/test/junit/scala/tools/nsc/transform/patmat/PatmatBytecodeTest.scala +++ b/test/junit/scala/tools/nsc/transform/patmat/PatmatBytecodeTest.scala @@ -18,7 +18,7 @@ import scala.tools.testing.ClearAfterClass object PatmatBytecodeTest extends ClearAfterClass.Clearable { var compiler = newCompiler() - var optCompiler = newCompiler(extraArgs = "-Yopt:l:method") + var optCompiler = newCompiler(extraArgs = "-Yopt:l:project") def clear(): Unit = { compiler = null; optCompiler = null } } @@ -96,10 +96,9 @@ class PatmatBytecodeTest extends ClearAfterClass { """.stripMargin val c = compileClasses(optCompiler)(code).head - assertEquals(textify(findAsmMethod(c, "a")), getSingleMethod(c, "a").instructions.summary, - List( - NEW, DUP, ICONST_1, LDC, "<init>", - "y", ARETURN)) + assertSameSummary(getSingleMethod(c, "a"), List( + NEW, DUP, ICONST_1, LDC, "<init>", + "y", ARETURN)) } @Test @@ -127,12 +126,12 @@ class PatmatBytecodeTest extends ClearAfterClass { |} """.stripMargin val c = compileClasses(optCompiler)(code).head - assertEquals(textify(findAsmMethod(c, "a")), getSingleMethod(c, "a").instructions.summary, - List(NEW, DUP, ICONST_1, "boxToInteger", LDC, "<init>", ASTORE /*1*/, - ALOAD /*1*/, "y", ASTORE /*2*/, - ALOAD /*1*/, "x", INSTANCEOF, IFNE /*R*/, - NEW, DUP, ALOAD /*1*/, "<init>", ATHROW, - /*R*/ -1, ALOAD /*2*/, ARETURN)) + assertSameSummary(getSingleMethod(c, "a"), List( + NEW, DUP, ICONST_1, "boxToInteger", LDC, "<init>", ASTORE /*1*/, + ALOAD /*1*/, "y", ASTORE /*2*/, + ALOAD /*1*/, "x", INSTANCEOF, IFNE /*R*/, + NEW, DUP, ALOAD /*1*/, "<init>", ATHROW, + /*R*/ -1, ALOAD /*2*/, ARETURN)) } @Test @@ -156,7 +155,41 @@ class PatmatBytecodeTest extends ClearAfterClass { -1 /*A*/ , NEW /*MatchError*/ , DUP, ALOAD /*1*/ , "<init>", ATHROW, -1 /*B*/ , ILOAD, IRETURN) - assertEquals(textify(findAsmMethod(c, "a")), getSingleMethod(c, "a").instructions.summary, expected) - assertEquals(textify(findAsmMethod(c, "b")), getSingleMethod(c, "b").instructions.summary, expected) + assertSameSummary(getSingleMethod(c, "a"), expected) + assertSameSummary(getSingleMethod(c, "b"), expected) + } + + @Test + def valPatterns(): Unit = { + val code = + """case class C(a: Any, b: Int) { + | def tplCall = ("hi", 3) + | @inline final def tplInline = (true, 'z') + | + | def t1 = { val (a, b) = (1, 2); a + b } + | def t2 = { val (a, _) = (1, 3); a } + | def t3 = { val (s, i) = tplCall; s.length + i } + | def t4 = { val (_, i) = tplCall; i } + | def t5 = { val (b, c) = tplInline; b || c == 'e' } + | def t6 = { val (_, c) = tplInline; c } + | + | def t7 = { val C(s: String, b) = this; s.length + b } + | def t8 = { val C(_, b) = this; b } + | def t9 = { val C(a, _) = C("hi", 23); a.toString } + |} + """.stripMargin + val List(c, cMod) = compileClasses(optCompiler)(code) + assertSameSummary(getSingleMethod(c, "t1"), List(ICONST_1, ICONST_2, IADD, IRETURN)) + assertSameSummary(getSingleMethod(c, "t2"), List(ICONST_1, IRETURN)) + assertInvokedMethods(getSingleMethod(c, "t3"), List("C.tplCall", "scala/Tuple2._1", "scala/Tuple2._2$mcI$sp", "scala/MatchError.<init>", "java/lang/String.length")) + assertInvokedMethods(getSingleMethod(c, "t4"), List("C.tplCall", "scala/Tuple2._2$mcI$sp", "scala/MatchError.<init>")) + assertNoInvoke(getSingleMethod(c, "t5")) + assertSameSummary(getSingleMethod(c, "t6"), List(BIPUSH, IRETURN)) + + // MatchError reachable because of the type pattern `s: String` + assertInvokedMethods(getSingleMethod(c, "t7"), List("C.a", "C.b", "scala/MatchError.<init>", "java/lang/String.length")) + assertSameSummary(getSingleMethod(c, "t8"), List(ALOAD, "b", IRETURN)) + // C allocation not eliminated - constructor may have side-effects. + assertSameSummary(getSingleMethod(c, "t9"), List(NEW, DUP, LDC, BIPUSH, "<init>", "a", "toString", ARETURN)) } } diff --git a/test/scaladoc/run/SI-6017.scala b/test/scaladoc/run/SI-6017.scala deleted file mode 100644 index 9951534c6d..0000000000 --- a/test/scaladoc/run/SI-6017.scala +++ /dev/null @@ -1,28 +0,0 @@ -import scala.tools.nsc.doc -import scala.tools.nsc.doc.model._ -import scala.tools.nsc.doc.html.page.{Index, ReferenceIndex} -import scala.tools.partest.ScaladocModelTest - -object Test extends ScaladocModelTest { - override def scaladocSettings = "" - override def code = """ - class STAR - class Star - """ - - def testModel(rootPackage: Package) { - model match { - case Some(universe) => { - val index = IndexModelFactory.makeIndex(universe) - // Because "STAR" and "Star" are different - assert(index.firstLetterIndex('s').keys.toSeq.length == 2) - - val indexPage = new Index(universe, index) - val letters = indexPage.letters - assert(letters.length > 1) - assert(letters(0).toString == "<span>#</span>") - } - case _ => assert(false) - } - } -} diff --git a/test/scaladoc/run/SI-9620.scala b/test/scaladoc/run/SI-9620.scala index 96260aad9a..cac34d1c18 100644 --- a/test/scaladoc/run/SI-9620.scala +++ b/test/scaladoc/run/SI-9620.scala @@ -21,7 +21,6 @@ object Test extends ScaladocModelTest { } """ - // no need for special settings def scaladocSettings = "-implicits" def testModel(rootPackage: Package) = { diff --git a/test/scaladoc/run/SI-6017.check b/test/scaladoc/run/shortDescription-annotation.check index 619c56180b..619c56180b 100644 --- a/test/scaladoc/run/SI-6017.check +++ b/test/scaladoc/run/shortDescription-annotation.check diff --git a/test/scaladoc/run/shortDescription-annotation.scala b/test/scaladoc/run/shortDescription-annotation.scala new file mode 100644 index 0000000000..0e2950f4f9 --- /dev/null +++ b/test/scaladoc/run/shortDescription-annotation.scala @@ -0,0 +1,55 @@ +import scala.tools.nsc.doc.model._ +import scala.tools.partest.ScaladocModelTest + +object Test extends ScaladocModelTest { + override def code = """ + package a + + /** This comment should not appear + * @shortDescription This one should appear + */ + class Foo { + /** This comment should appear */ + def foo: Int = 1 + + /** This comment should not appear + * @shortDescription This comment should appear + */ + def goo: Int = 2 + } + """ + + // no need for special settings + def scaladocSettings = "" + + def testModel(rootPackage: Package) = { + import scala.tools.nsc.doc.base.comment._ + import access._ + + def inlineToStr(inl: Inline): String = inl match { + case Chain(items) => items flatMap (inlineToStr(_)) mkString "" + case Italic(in) => inlineToStr(in) + case Bold(in) => inlineToStr(in) + case Underline(in) => inlineToStr(in) + case Monospace(in) => inlineToStr(in) + case Text(text) => text + case Summary(in) => inlineToStr(in) + case EntityLink(Text(text), _) => text + case _ => inl.toString + } + + val foo = rootPackage._package("a")._class("Foo") + + // Assert that the class has the correct short description + val classDesc = inlineToStr(foo.comment.get.short) + assert(classDesc == "This one should appear", classDesc) + + // Assert that the `foo` method has the correct short description + val fooDesc = inlineToStr(foo._method("foo").comment.get.short) + assert(fooDesc == "This comment should appear", fooDesc) + + // Assert that the `goo` method has the correct short description + val gooDesc = inlineToStr(foo._method("goo").comment.get.short) + assert(gooDesc == "This comment should appear", gooDesc) + } +} diff --git a/test/scaladoc/scalacheck/DeprecatedIndexTest.scala b/test/scaladoc/scalacheck/DeprecatedIndexTest.scala index 4a5a2001d4..2581b879da 100644 --- a/test/scaladoc/scalacheck/DeprecatedIndexTest.scala +++ b/test/scaladoc/scalacheck/DeprecatedIndexTest.scala @@ -1,6 +1,7 @@ import org.scalacheck._ import org.scalacheck.Prop._ +import scala.tools.nsc.ScalaDocReporter import scala.tools.nsc.doc import scala.tools.nsc.doc.html.page.DeprecatedIndex import java.net.{URLClassLoader, URLDecoder} @@ -32,7 +33,8 @@ object Test extends Properties("IndexScript") { def createDeprecatedScript(path: String) = docFactory.makeUniverse(Left(List(path))) match { case Some(universe) => { - val index = new DeprecatedIndex(universe, indexModelFactory.makeIndex(universe)) + val reporter = new ScalaDocReporter(universe.settings) + val index = new DeprecatedIndex(universe, indexModelFactory.makeIndex(universe), reporter) Some(index) } case _ => diff --git a/test/scaladoc/scalacheck/HtmlFactoryTest.scala b/test/scaladoc/scalacheck/HtmlFactoryTest.scala index f0f106b293..daa7de8545 100644 --- a/test/scaladoc/scalacheck/HtmlFactoryTest.scala +++ b/test/scaladoc/scalacheck/HtmlFactoryTest.scala @@ -26,6 +26,8 @@ object Test extends Properties("HtmlFactory") { final val RESOURCES = "test/scaladoc/resources/" + + import scala.tools.nsc.ScalaDocReporter import scala.tools.nsc.doc.{DocFactory, Settings} import scala.tools.nsc.doc.model.IndexModelFactory import scala.tools.nsc.doc.html.HtmlFactory @@ -59,7 +61,7 @@ object Test extends Properties("HtmlFactory") { createFactory.makeUniverse(Left(List(RESOURCES+basename))) match { case Some(universe) => { val index = IndexModelFactory.makeIndex(universe) - (new HtmlFactory(universe, index)).writeTemplates((page) => { + (new HtmlFactory(universe, index, new ScalaDocReporter(universe.settings))).writeTemplates((page) => { result += (page.absoluteLinkTo(page.path) -> page.body) }) } @@ -75,7 +77,8 @@ object Test extends Properties("HtmlFactory") { val index = IndexModelFactory.makeIndex(universe) val pages = index.firstLetterIndex.map({ case (key, value) => { - val page = new ReferenceIndex(key, index, universe) + val reporter = new ScalaDocReporter(universe.settings) + val page = new ReferenceIndex(key, index, universe, reporter) page.absoluteLinkTo(page.path) -> page.body } }) @@ -723,9 +726,9 @@ object Test extends Properties("HtmlFactory") { } case _ => false } - property("package") = files.get("com/example/p1/package.html") != None + property("package") = files.get("com/example/p1/index.html") != None - property("package object") = files("com/example/p1/package.html") match { + property("package object") = files("com/example/p1/index.html") match { case node: scala.xml.Node => node.toString contains "com.example.p1#packageObjectMethod" case _ => false @@ -743,13 +746,13 @@ object Test extends Properties("HtmlFactory") { property("SI-8514: No inconsistencies") = checkText("SI-8514.scala")( - (Some("a/package"), + (Some("a/index"), """class A extends AnyRef Some doc here Some doc here Annotations @DeveloperApi() """, true), - (Some("a/package"), + (Some("a/index"), """class B extends AnyRef Annotations @DeveloperApi() """, true) @@ -794,28 +797,28 @@ object Test extends Properties("HtmlFactory") { case _ => false } - property("SI-8144: Members' permalink - package") = check("some/package.html") { node => - ("type link" |: node.assertTypeLink("../index.html#some.package")) && - ("member: some.pack" |: node.assertValuesLink("some.pack", "../index.html#some.package@pack")) + property("SI-8144: Members' permalink - package") = check("some/index.html") { node => + ("type link" |: node.assertTypeLink("../some/index.html")) && + ("member: some.pack" |: node.assertValuesLink("some.pack", "../some/index.html#pack")) } - property("SI-8144: Members' permalink - inner package") = check("some/pack/package.html") { node => - ("type link" |: node.assertTypeLink("../../index.html#some.pack.package")) && - ("member: SomeType (object)" |: node.assertValuesLink("some.pack.SomeType", "../../index.html#some.pack.package@SomeType")) && - ("member: SomeType (class)" |: node.assertMemberLink("types")("some.pack.SomeType", "../../index.html#some.pack.package@SomeTypeextendsAnyRef")) + property("SI-8144: Members' permalink - inner package") = check("some/pack/index.html") { node => + ("type link" |: node.assertTypeLink("../../some/pack/index.html")) && + ("member: SomeType (object)" |: node.assertValuesLink("some.pack.SomeType", "../../some/pack/index.html#SomeType")) && + ("member: SomeType (class)" |: node.assertMemberLink("types")("some.pack.SomeType", "../../some/pack/index.html#SomeTypeextendsAnyRef")) } property("SI-8144: Members' permalink - companion object") = check("some/pack/SomeType$.html") { node => - ("type link" |: node.assertTypeLink("../../index.html#some.pack.SomeType$")) && - ("member: someVal" |: node.assertMemberLink("allMembers")("some.pack.SomeType#someVal", "../../index.html#some.pack.SomeType$@someVal:String")) + ("type link" |: node.assertTypeLink("../../some/pack/SomeType$.html")) && + ("member: someVal" |: node.assertMemberLink("allMembers")("some.pack.SomeType#someVal", "../../some/pack/SomeType$.html#someVal:String")) } property("SI-8144: Members' permalink - class") = check("some/pack/SomeType.html") { node => - ("type link" |: node.assertTypeLink("../../index.html#some.pack.SomeType")) && - ("constructor " |: node.assertMemberLink("constructors")("some.pack.SomeType#<init>", "../../index.html#some.pack.SomeType@<init>(arg:String):some.pack.SomeType")) && - ( "member: type TypeAlias" |: node.assertMemberLink("types")("some.pack.SomeType.TypeAlias", "../../index.html#some.pack.SomeType@TypeAlias=String")) && - ( "member: def >#<():Int " |: node.assertValuesLink("some.pack.SomeType#>#<", "../../index.html#some.pack.SomeType@>#<():Int")) && - ( "member: def >@<():TypeAlias " |: node.assertValuesLink("some.pack.SomeType#>@<", "../../index.html#some.pack.SomeType@>@<():SomeType.this.TypeAlias")) + ("type link" |: node.assertTypeLink("../../some/pack/SomeType.html")) && + ("constructor " |: node.assertMemberLink("constructors")("some.pack.SomeType#<init>", "../../some/pack/SomeType.html#<init>(arg:String):some.pack.SomeType")) && + ( "member: type TypeAlias" |: node.assertMemberLink("types")("some.pack.SomeType.TypeAlias", "../../some/pack/SomeType.html#TypeAlias=String")) && + ( "member: def >#<():Int " |: node.assertValuesLink("some.pack.SomeType#>#<", "../../some/pack/SomeType.html#>#<():Int")) && + ( "member: def >@<():TypeAlias " |: node.assertValuesLink("some.pack.SomeType#>@<", "../../some/pack/SomeType.html#>@<():SomeType.this.TypeAlias")) } } diff --git a/test/scaladoc/scalacheck/IndexTest.scala b/test/scaladoc/scalacheck/IndexTest.scala index 7dbd2103a6..036586c21d 100644 --- a/test/scaladoc/scalacheck/IndexTest.scala +++ b/test/scaladoc/scalacheck/IndexTest.scala @@ -1,6 +1,7 @@ import org.scalacheck._ import org.scalacheck.Prop._ +import scala.tools.nsc.ScalaDocReporter import scala.tools.nsc.doc import scala.tools.nsc.doc.html.page.Index import java.net.{URLClassLoader, URLDecoder} @@ -47,7 +48,8 @@ object Test extends Properties("Index") { maybeUniverse match { case Some(universe) => { - val index = new Index(universe, indexModelFactory.makeIndex(universe)) + val reporter = new ScalaDocReporter(universe.settings) + val index = new Index(universe, indexModelFactory.makeIndex(universe), reporter) return Some(index) } case _ => return None @@ -71,14 +73,6 @@ object Test extends Properties("Index") { case None => false } } - property("browser contains a script element") = { - createIndex("src/scaladoc/scala/tools/nsc/doc/html/page/Index.scala") match { - case Some(index) => - (index.browser \ "script").size == 1 - - case None => false - } - } property("package objects in index") = { createIndex("test/scaladoc/resources/SI-5558.scala") match { case Some(index) => diff --git a/versions.properties b/versions.properties index 7cdafc975a..c63b15a3f0 100644 --- a/versions.properties +++ b/versions.properties @@ -30,7 +30,7 @@ jline.version=2.12.1 scala-asm.version=5.0.4-scala-3 # external modules, used internally (not shipped) -partest.version.number=1.0.12 +partest.version.number=1.0.13 scalacheck.version.number=1.11.6 # TODO: modularize the compiler |