diff options
352 files changed, 8861 insertions, 3381 deletions
diff --git a/build.number b/build.number index b5c4e61d13..f28886751b 100644 --- a/build.number +++ b/build.number @@ -1,7 +1,7 @@ #Tue Sep 11 19:21:09 CEST 2007 version.major=2 version.minor=10 -version.patch=0 +version.patch=1 # This is the -N part of a version. if it's 0, it's dropped from maven versions. version.bnum=0 @@ -1749,7 +1749,7 @@ OSGi Artifacts </target> <target name="osgi.bundles" depends="osgi.init" unless="osgi.bundles.available"> - <stopwatch name="osgi.bundle.timer"/> + <stopwatch name="osgi.bundle.timer"/> <make-bundle name="scala-library" version="${osgi.version.number}" /> <make-bundle name="scala-actors" version="${osgi.version.number}" /> <make-bundle name="scala-actors-migration" version="${osgi.version.number}" /> @@ -1757,7 +1757,7 @@ OSGi Artifacts <make-bundle name="scala-compiler" version="${osgi.version.number}" /> <make-plugin-bundle name="continuations" version="${osgi.version.number}" /> <touch file="${build-osgi.dir}/bundles.complete" verbose="no"/> - <stopwatch name="osgi.bundle.timer" action="total"/> + <stopwatch name="osgi.bundle.timer" action="total"/> </target> <target name="osgi.bundles.swing" depends="osgi.init" if="has.java6" unless="osgi.bundles.available"> @@ -1801,7 +1801,7 @@ OSGi Artifacts </compilationpath> </scalacfork> <touch file="${build-osgi.dir}/test-compile.complete" verbose="no"/> - <stopwatch name="osgi.test.comp.timer" action="total"/> + <stopwatch name="osgi.test.comp.timer" action="total"/> </target> <target name="osgi.test" depends="osgi.test.comp"> @@ -1821,7 +1821,7 @@ OSGi Artifacts </batchtest> <formatter type="brief" usefile="false" /> </junit> - <stopwatch name="osgi.test.timer" action="total"/> + <stopwatch name="osgi.test.timer" action="total"/> </target> <target name="osgi.clean"> @@ -2322,6 +2322,7 @@ DOCUMENTATION <include name="swing/**"/> <include name="actors/**"/> <include name="actors-migration/**"/> + <include name="reflect/**"/> </source-includes> </doc-uptodate-check> </target> @@ -2336,7 +2337,7 @@ DOCUMENTATION docfooter="epfl" docsourceurl="${scaladoc.url}€{FILE_PATH}.scala#L1" docUncompilable="${src.dir}/library-aux" - skipPackages="scala.reflect.macros.internal" + skipPackages="scala.reflect.macros.internal:scala.reflect.internal:scala.reflect.io:scala.concurrent.impl" sourcepath="${src.dir}" classpathref="pack.classpath" addparams="${scalac.args.all}" @@ -2716,14 +2717,14 @@ DISTRIBUTION <macrodef name="copy-bundle"> <attribute name="name" /> <sequential> - <copy file="${build-osgi.dir}/org.scala-lang.@{name}.jar" + <copy file="${build-osgi.dir}/org.scala-lang.@{name}.jar" tofile="${dist.dir}/lib/@{name}.jar"/> </sequential> </macrodef> <macrodef name="copy-plugin-bundle"> <attribute name="name" /> <sequential> - <copy file="${build-osgi.dir}/org.scala-lang.plugins.@{name}.jar" + <copy file="${build-osgi.dir}/org.scala-lang.plugins.@{name}.jar" tofile="${dist.dir}/misc/scala-devel/plugins/@{name}.jar"/> </sequential> </macrodef> diff --git a/docs/examples/swing/ColorChooserDemo.scala b/docs/examples/swing/ColorChooserDemo.scala new file mode 100644 index 0000000000..1cb2bdefa2 --- /dev/null +++ b/docs/examples/swing/ColorChooserDemo.scala @@ -0,0 +1,61 @@ +package examples.swing + +import java.awt.{Color, Font, Dimension} +import swing._ +import event._ +import Swing._ +import BorderPanel._ + +/** + * Demo for ColorChooser. + * Based on http://download.oracle.com/javase/tutorial/uiswing/components/colorchooser.html + * + * @author andy@hicks.net + */ +object ColorChooserDemo extends SimpleSwingApplication { + def top = new MainFrame { + title = "ColorChooser Demo" + size = new Dimension(400, 400) + + contents = ui + } + + def ui = new BorderPanel { + val colorChooser = new ColorChooser { + reactions += { + case ColorChanged(_, c) => + banner.foreground = c + } + } + + colorChooser.border = TitledBorder(EtchedBorder, "Choose Text Color") + + val banner = new Label("Welcome to Scala Swing") { + horizontalAlignment = Alignment.Center + foreground = Color.yellow + background = Color.blue + opaque = true + font = new Font("SansSerif", Font.BOLD, 24) + } + + val bannerArea = new BorderPanel { + layout(banner) = Position.Center + border = TitledBorder(EtchedBorder, "Banner") + } + + // Display a color selection dialog when button pressed + val selectColor = new Button("Choose Background Color") { + reactions += { + case ButtonClicked(_) => + ColorChooser.showDialog(this, "Test", Color.red) match { + case Some(c) => banner.background = c + case None => + } + } + } + + layout(bannerArea) = Position.North + layout(colorChooser) = Position.Center + layout(selectColor) = Position.South + } +}
\ No newline at end of file diff --git a/docs/examples/swing/PopupDemo.scala b/docs/examples/swing/PopupDemo.scala new file mode 100644 index 0000000000..6a9eeb125b --- /dev/null +++ b/docs/examples/swing/PopupDemo.scala @@ -0,0 +1,33 @@ +package examples.swing + +import swing._ +import event._ +import Swing._ + +/** + * @author John Sullivan + * @author Ingo Maier + */ +object PopupDemo extends SimpleSwingApplication { + def top = new MainFrame { + val popupMenu = new PopupMenu { + contents += new Menu("menu 1") { + contents += new RadioMenuItem("radio 1.1") + contents += new RadioMenuItem("radio 1.2") + } + contents += new Menu("menu 2") { + contents += new RadioMenuItem("radio 2.1") + contents += new RadioMenuItem("radio 2.2") + } + } + val button = new Button("Show Popup Menu") + reactions += { + case ButtonClicked(b) => popupMenu.show(b, 0, b.bounds.height) + case PopupMenuCanceled(m) => println("Menu " + m + " canceled.") + } + listenTo(popupMenu) + listenTo(button) + + contents = new FlowPanel(button) + } +}
\ No newline at end of file diff --git a/src/actors-migration/scala/actors/migration/ActorDSL.scala b/src/actors-migration/scala/actors/migration/ActorDSL.scala new file mode 100644 index 0000000000..b8cb8ec998 --- /dev/null +++ b/src/actors-migration/scala/actors/migration/ActorDSL.scala @@ -0,0 +1,56 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2005-2011, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.actors +package migration + +import scala.actors.{ Actor, ActorRef, InternalActorRef } +import scala.collection.immutable +import scala.reflect.ClassTag + +object ActorDSL { + + private[migration] val contextStack = new ThreadLocal[immutable.Stack[Boolean]] { + override def initialValue() = immutable.Stack[Boolean]() + } + + private[this] def withCleanContext(block: => ActorRef): ActorRef = { + // push clean marker + val old = contextStack.get + contextStack.set(old.push(true)) + try { + val instance = block + + if (instance eq null) + throw new Exception("ActorRef can't be 'null'") + + instance + } finally { + val stackAfter = contextStack.get + if (stackAfter.nonEmpty) + contextStack.set(if (!stackAfter.head) stackAfter.pop.pop else stackAfter.pop) + } + } + + /** + * Create an actor from the given thunk which must produce an [[scala.actors.Actor]]. + * + * @param ctor is a by-name argument which captures an [[scala.actors.Actor]] + * factory; <b>do not make the generated object accessible to code + * outside and do not return the same object upon subsequent invocations.</b> + */ + def actor[T <: InternalActor: ClassTag](ctor: ⇒ T): ActorRef = { + withCleanContext { + val newActor = ctor + val newRef = new InternalActorRef(newActor) + newActor.start() + newRef + } + } + +} diff --git a/src/actors-migration/scala/actors/migration/MigrationSystem.scala b/src/actors-migration/scala/actors/migration/MigrationSystem.scala deleted file mode 100644 index 3dcb38e634..0000000000 --- a/src/actors-migration/scala/actors/migration/MigrationSystem.scala +++ /dev/null @@ -1,37 +0,0 @@ -package scala.actors.migration - -import scala.actors._ -import scala.collection._ - -object MigrationSystem { - - private[migration] val contextStack = new ThreadLocal[immutable.Stack[Boolean]] { - override def initialValue() = immutable.Stack[Boolean]() - } - - private[this] def withCleanContext(block: => ActorRef): ActorRef = { - // push clean marker - val old = contextStack.get - contextStack.set(old.push(true)) - try { - val instance = block - - if (instance eq null) - throw new Exception("Actor instance passed to actorOf can't be 'null'") - - instance - } finally { - val stackAfter = contextStack.get - if (stackAfter.nonEmpty) - contextStack.set(if (!stackAfter.head) stackAfter.pop.pop else stackAfter.pop) - } - } - - def actorOf(props: Props): ActorRef = withCleanContext { - val creator = props.creator() - val r = new InternalActorRef(creator) - creator.start() - r - } - -}
\ No newline at end of file diff --git a/src/actors-migration/scala/actors/migration/Props.scala b/src/actors-migration/scala/actors/migration/Props.scala index c12384ea55..00bc9d93f8 100644 --- a/src/actors-migration/scala/actors/migration/Props.scala +++ b/src/actors-migration/scala/actors/migration/Props.scala @@ -10,6 +10,5 @@ case class Props(creator: () ⇒ InternalActor, dispatcher: String) { /** * Returns a new Props with the specified creator set */ - def withCreator(c: ⇒ InternalActor) = copy(creator = () ⇒ c) - + final def withCreator(c: ⇒ InternalActor) = copy(creator = () ⇒ c) } diff --git a/src/actors-migration/scala/actors/migration/StashingActor.scala b/src/actors-migration/scala/actors/migration/StashingActor.scala index 9c3917b65e..12bad2ed1c 100644 --- a/src/actors-migration/scala/actors/migration/StashingActor.scala +++ b/src/actors-migration/scala/actors/migration/StashingActor.scala @@ -13,12 +13,12 @@ object StashingActor extends Combinators { } } -@deprecated("Scala Actors are being removed from the standard library. Please refer to the migration guide.", "2.10") +@deprecated("Scala Actors are being removed from the standard library. Please refer to the migration guide.", "2.10.0") trait StashingActor extends InternalActor { type Receive = PartialFunction[Any, Unit] // checks if StashingActor is created within the actorOf block - creationCheck; + creationCheck() private[actors] val ref = new InternalActorRef(this) @@ -110,19 +110,18 @@ trait StashingActor extends InternalActor { private[actors] var behaviorStack = immutable.Stack[PartialFunction[Any, Unit]]() /* - * Checks that StashingActor can be created only by MigrationSystem.actorOf method. + * Checks that StashingActor instances can only be created using the ActorDSL. */ - private[this] def creationCheck = { - + private[this] def creationCheck(): Unit = { // creation check (see ActorRef) - val context = MigrationSystem.contextStack.get + val context = ActorDSL.contextStack.get if (context.isEmpty) - throw new RuntimeException("In order to create StashingActor one must use actorOf.") + throw new RuntimeException("In order to create a StashingActor one must use the ActorDSL object") else { if (!context.head) - throw new RuntimeException("Only one actor can be created per actorOf call.") + throw new RuntimeException("Cannot create more than one actor") else - MigrationSystem.contextStack.set(context.push(false)) + ActorDSL.contextStack.set(context.push(false)) } } diff --git a/src/actors/scala/actors/ActorRef.scala b/src/actors/scala/actors/ActorRef.scala index 5e0ca1554a..cca78b0832 100644 --- a/src/actors/scala/actors/ActorRef.scala +++ b/src/actors/scala/actors/ActorRef.scala @@ -8,7 +8,7 @@ import scala.concurrent.ExecutionContext.Implicits.global /** * Trait used for migration of Scala actors to Akka. */ -@deprecated("ActorRef ought to be used only with the Actor Migration Kit.") +@deprecated("ActorRef ought to be used only with the Actor Migration Kit.", "2.10.0") trait ActorRef { /** diff --git a/src/compiler/scala/reflect/macros/runtime/Aliases.scala b/src/compiler/scala/reflect/macros/runtime/Aliases.scala index 30e72997f7..ff870e728e 100644 --- a/src/compiler/scala/reflect/macros/runtime/Aliases.scala +++ b/src/compiler/scala/reflect/macros/runtime/Aliases.scala @@ -10,17 +10,20 @@ trait Aliases { override type TermName = universe.TermName override type TypeName = universe.TypeName override type Tree = universe.Tree - // override type Position = universe.Position + override type Position = universe.Position override type Scope = universe.Scope override type Modifiers = universe.Modifiers override type Expr[+T] = universe.Expr[T] override val Expr = universe.Expr + def Expr[T: WeakTypeTag](tree: Tree): Expr[T] = universe.Expr[T](mirror, universe.FixedMirrorTreeCreator(mirror, tree)) override type WeakTypeTag[T] = universe.WeakTypeTag[T] override type TypeTag[T] = universe.TypeTag[T] override val WeakTypeTag = universe.WeakTypeTag override val TypeTag = universe.TypeTag + def WeakTypeTag[T](tpe: Type): WeakTypeTag[T] = universe.WeakTypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) + def TypeTag[T](tpe: Type): TypeTag[T] = universe.TypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) override def weakTypeTag[T](implicit attag: WeakTypeTag[T]) = attag override def typeTag[T](implicit ttag: TypeTag[T]) = ttag override def weakTypeOf[T](implicit attag: WeakTypeTag[T]): Type = attag.tpe diff --git a/src/compiler/scala/reflect/macros/runtime/CapturedVariables.scala b/src/compiler/scala/reflect/macros/runtime/CapturedVariables.scala deleted file mode 100644 index 78fb7100b0..0000000000 --- a/src/compiler/scala/reflect/macros/runtime/CapturedVariables.scala +++ /dev/null @@ -1,15 +0,0 @@ -package scala.reflect.macros -package runtime - -trait CapturedVariables { - self: Context => - - import mirror._ - import universe._ - - def captureVariable(vble: Symbol): Unit = universe.captureVariable(vble) - - def referenceCapturedVariable(vble: Symbol): Tree = universe.referenceCapturedVariable(vble) - - def capturedVariableType(vble: Symbol): Type = universe.capturedVariableType(vble) -}
\ No newline at end of file diff --git a/src/compiler/scala/reflect/macros/runtime/Context.scala b/src/compiler/scala/reflect/macros/runtime/Context.scala index 8bbfef44a3..8e8b0fcea1 100644 --- a/src/compiler/scala/reflect/macros/runtime/Context.scala +++ b/src/compiler/scala/reflect/macros/runtime/Context.scala @@ -5,24 +5,20 @@ import scala.tools.nsc.Global abstract class Context extends scala.reflect.macros.Context with Aliases - with CapturedVariables - with Infrastructure with Enclosures with Names with Reifiers with FrontEnds - with Settings + with Infrastructure with Typers with Parsers - with Exprs - with TypeTags with Evals with ExprUtils with Traces { val universe: Global - val mirror: MirrorOf[universe.type] = universe.rootMirror + val mirror: universe.Mirror = universe.rootMirror val callsiteTyper: universe.analyzer.Typer diff --git a/src/compiler/scala/reflect/macros/runtime/Enclosures.scala b/src/compiler/scala/reflect/macros/runtime/Enclosures.scala index b5c988ca83..be5f2dbe83 100644 --- a/src/compiler/scala/reflect/macros/runtime/Enclosures.scala +++ b/src/compiler/scala/reflect/macros/runtime/Enclosures.scala @@ -19,5 +19,6 @@ trait Enclosures { val enclosingMacros: List[Context] = this :: universe.analyzer.openMacros // include self val enclosingMethod: Tree = site.enclMethod.tree val enclosingPosition: Position = if (enclPoses.isEmpty) NoPosition else enclPoses.head.pos - val enclosingUnit: CompilationUnit = currentRun.currentUnit + val enclosingUnit: CompilationUnit = universe.currentRun.currentUnit + val enclosingRun: Run = universe.currentRun } diff --git a/src/compiler/scala/reflect/macros/runtime/Evals.scala b/src/compiler/scala/reflect/macros/runtime/Evals.scala index acafeb5b02..1f7b5f2ff1 100644 --- a/src/compiler/scala/reflect/macros/runtime/Evals.scala +++ b/src/compiler/scala/reflect/macros/runtime/Evals.scala @@ -7,7 +7,7 @@ import scala.tools.reflect.ToolBox trait Evals { self: Context => - private lazy val evalMirror = ru.runtimeMirror(libraryClassLoader) + private lazy val evalMirror = ru.runtimeMirror(universe.analyzer.macroClassloader) private lazy val evalToolBox = evalMirror.mkToolBox() private lazy val evalImporter = ru.mkImporter(universe).asInstanceOf[ru.Importer { val from: universe.type }] diff --git a/src/compiler/scala/reflect/macros/runtime/Exprs.scala b/src/compiler/scala/reflect/macros/runtime/Exprs.scala deleted file mode 100644 index ebf8fa2b96..0000000000 --- a/src/compiler/scala/reflect/macros/runtime/Exprs.scala +++ /dev/null @@ -1,8 +0,0 @@ -package scala.reflect.macros -package runtime - -trait Exprs { - self: Context => - - def Expr[T: WeakTypeTag](tree: Tree): Expr[T] = universe.Expr[T](mirror, universe.FixedMirrorTreeCreator(mirror, tree)) -} diff --git a/src/compiler/scala/reflect/macros/runtime/FrontEnds.scala b/src/compiler/scala/reflect/macros/runtime/FrontEnds.scala index 9f328eb82b..a6a198e1b4 100644 --- a/src/compiler/scala/reflect/macros/runtime/FrontEnds.scala +++ b/src/compiler/scala/reflect/macros/runtime/FrontEnds.scala @@ -1,28 +1,9 @@ package scala.reflect.macros package runtime -trait FrontEnds extends scala.tools.reflect.FrontEnds { +trait FrontEnds { self: Context => - import universe._ - import mirror._ - - override type Position = universe.Position - - def frontEnd: FrontEnd = wrapReporter(universe.reporter) - - def setFrontEnd(frontEnd: FrontEnd): this.type = { - universe.reporter = wrapFrontEnd(frontEnd) - this - } - - def withFrontEnd[T](frontEnd: FrontEnd)(op: => T): T = { - val old = universe.reporter - setFrontEnd(frontEnd) - try op - finally universe.reporter = old - } - def echo(pos: Position, msg: String): Unit = universe.reporter.echo(pos, msg) def info(pos: Position, msg: String, force: Boolean): Unit = universe.reporter.info(pos, msg, force) @@ -36,9 +17,4 @@ trait FrontEnds extends scala.tools.reflect.FrontEnds { def error(pos: Position, msg: String): Unit = callsiteTyper.context.error(pos, msg) def abort(pos: Position, msg: String): Nothing = throw new AbortMacroException(pos, msg) - - def interactive(): Unit = universe.reporter match { - case reporter: scala.tools.nsc.reporters.AbstractReporter => reporter.displayPrompt() - case _ => () - } } diff --git a/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala b/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala index a8cc61e0f9..7781693822 100644 --- a/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala +++ b/src/compiler/scala/reflect/macros/runtime/Infrastructure.scala @@ -1,36 +1,16 @@ package scala.reflect.macros package runtime -import scala.tools.nsc.util.ScalaClassLoader - trait Infrastructure { self: Context => - val forJVM: Boolean = universe.forJVM - - val forMSIL: Boolean = universe.forMSIL - - val forInteractive: Boolean = universe.forInteractive - - val forScaladoc: Boolean = universe.forScaladoc - - val currentRun: Run = universe.currentRun - - val libraryClassPath: List[java.net.URL] = universe.classPath.asURLs - - lazy val libraryClassLoader: ClassLoader = universe.analyzer.macroClassloader - - type Run = universe.Run - - object Run extends RunExtractor { - def unapply(run: Run): Option[(CompilationUnit, List[CompilationUnit])] = Some(run.currentUnit, run.units.toList) + def settings: List[String] = { + val us = universe.settings + import us._ + userSetSettings collectFirst { case x: MultiStringSetting if x.name == XmacroSettings.name => x.value } getOrElse Nil } - type CompilationUnit = universe.CompilationUnit - - object CompilationUnit extends CompilationUnitExtractor { - def unapply(compilationUnit: CompilationUnit): Option[(java.io.File, Array[Char], Tree)] = Some(compilationUnit.source.file.file, compilationUnit.source.content, compilationUnit.body) - } + def compilerSettings: List[String] = universe.settings.recreateArgs - val currentMacro: Symbol = expandee.symbol + def classPath: List[java.net.URL] = global.classPath.asURLs } diff --git a/src/compiler/scala/reflect/macros/runtime/Parsers.scala b/src/compiler/scala/reflect/macros/runtime/Parsers.scala index 5096526fdb..566bcde73d 100644 --- a/src/compiler/scala/reflect/macros/runtime/Parsers.scala +++ b/src/compiler/scala/reflect/macros/runtime/Parsers.scala @@ -10,6 +10,7 @@ trait Parsers { def parse(code: String): Tree = // todo. provide decent implementation + // see `Typers.typedUseCase` for details try { import scala.reflect.runtime.{universe => ru} val parsed = ru.rootMirror.mkToolBox().parse(code) @@ -17,9 +18,7 @@ trait Parsers { importer.importTree(parsed) } catch { case ToolBoxError(msg, cause) => - throw new ParseError(universe.NoPosition, msg) + // todo. provide a position + throw new ParseException(universe.NoPosition, msg) } - - case class ParseError(val pos: Position, val msg: String) extends Throwable(msg) - object ParseError extends ParseErrorExtractor } diff --git a/src/compiler/scala/reflect/macros/runtime/Reifiers.scala b/src/compiler/scala/reflect/macros/runtime/Reifiers.scala index f15a7ad502..9e11e5e26d 100644 --- a/src/compiler/scala/reflect/macros/runtime/Reifiers.scala +++ b/src/compiler/scala/reflect/macros/runtime/Reifiers.scala @@ -13,8 +13,6 @@ trait Reifiers { import universe._ import definitions._ - lazy val runtimeUniverse: Tree = gen.mkRuntimeUniverseRef - def reifyTree(universe: Tree, mirror: Tree, tree: Tree): Tree = { assert(ExprClass != NoSymbol) val result = scala.reflect.reify.`package`.reifyTree(self.universe)(callsiteTyper, universe, mirror, tree) diff --git a/src/compiler/scala/reflect/macros/runtime/Settings.scala b/src/compiler/scala/reflect/macros/runtime/Settings.scala deleted file mode 100644 index e9d9a17b81..0000000000 --- a/src/compiler/scala/reflect/macros/runtime/Settings.scala +++ /dev/null @@ -1,35 +0,0 @@ -package scala.reflect.macros -package runtime - -trait Settings { - self: Context => - - def settings: List[String] = { - val us = universe.settings - import us._ - userSetSettings collectFirst { case x: MultiStringSetting if x.name == XmacroSettings.name => x.value } getOrElse Nil - } - - def compilerSettings: List[String] = universe.settings.recreateArgs - - def setCompilerSettings(options: String): this.type = - // SI-5925: doesn't work with arguments that contains whitespaces - setCompilerSettings(options.split(" ").toList) - - def setCompilerSettings(options: List[String]): this.type = { - val settings = new scala.tools.nsc.Settings(_ => ()) - settings.copyInto(universe.settings) - this - } - - def withCompilerSettings[T](options: String)(op: => T): T = - // SI-5925: doesn't work with arguments that contains whitespaces - withCompilerSettings(options.split(" ").toList)(op) - - def withCompilerSettings[T](options: List[String])(op: => T): T = { - val old = options - setCompilerSettings(options) - try op - finally setCompilerSettings(old) - } -} diff --git a/src/compiler/scala/reflect/macros/runtime/TypeTags.scala b/src/compiler/scala/reflect/macros/runtime/TypeTags.scala deleted file mode 100644 index 19b60159de..0000000000 --- a/src/compiler/scala/reflect/macros/runtime/TypeTags.scala +++ /dev/null @@ -1,9 +0,0 @@ -package scala.reflect.macros -package runtime - -trait TypeTags { - self: Context => - - def WeakTypeTag[T](tpe: Type): WeakTypeTag[T] = universe.WeakTypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) - def TypeTag[T](tpe: Type): TypeTag[T] = universe.TypeTag[T](mirror, universe.FixedMirrorTypeCreator(mirror, tpe)) -} diff --git a/src/compiler/scala/reflect/macros/runtime/Typers.scala b/src/compiler/scala/reflect/macros/runtime/Typers.scala index 9fa8567ada..f9add91b9a 100644 --- a/src/compiler/scala/reflect/macros/runtime/Typers.scala +++ b/src/compiler/scala/reflect/macros/runtime/Typers.scala @@ -8,6 +8,9 @@ trait Typers { def openImplicits: List[(Type, Tree)] = callsiteTyper.context.openImplicits + /** + * @see [[scala.tools.reflect.Toolbox.typeCheck]] + */ def typeCheck(tree: Tree, pt: Type = universe.WildcardType, silent: Boolean = false, withImplicitViewsDisabled: Boolean = false, withMacrosDisabled: Boolean = false): Tree = { macroLogVerbose("typechecking %s with expected type %s, implicit views = %s, macros = %s".format(tree, pt, !withImplicitViewsDisabled, !withMacrosDisabled)) val context = callsiteTyper.context @@ -25,7 +28,7 @@ trait Typers { result case error @ universe.analyzer.SilentTypeError(_) => macroLogVerbose(error.err.errMsg) - if (!silent) throw new universe.TypeError(error.err.errPos, error.err.errMsg) + if (!silent) throw new TypecheckException(error.err.errPos, error.err.errMsg) universe.EmptyTree }) } @@ -49,19 +52,13 @@ trait Typers { wrapper(universe.analyzer.inferImplicit(tree, pt, reportAmbiguous = true, isView = isView, context = context, saveAmbiguousDivergent = !silent, pos = pos)) match { case failure if failure.tree.isEmpty => macroLogVerbose("implicit search has failed. to find out the reason, turn on -Xlog-implicits") - if (context.hasErrors) throw new universe.TypeError(context.errBuffer.head.errPos, context.errBuffer.head.errMsg) + if (context.hasErrors) throw new TypecheckException(context.errBuffer.head.errPos, context.errBuffer.head.errMsg) universe.EmptyTree case success => success.tree } } - type TypeError = universe.TypeError - - object TypeError extends TypeErrorExtractor { - def unapply(error: TypeError): Option[(Position, String)] = Some((error.pos, error.msg)) - } - def resetAllAttrs(tree: Tree): Tree = universe.resetAllAttrs(tree) def resetLocalAttrs(tree: Tree): Tree = universe.resetLocalAttrs(tree) diff --git a/src/compiler/scala/reflect/reify/Errors.scala b/src/compiler/scala/reflect/reify/Errors.scala index 73c13901b6..b8b5f8033b 100644 --- a/src/compiler/scala/reflect/reify/Errors.scala +++ b/src/compiler/scala/reflect/reify/Errors.scala @@ -1,7 +1,7 @@ package scala.reflect.reify -import scala.reflect.macros.ReificationError -import scala.reflect.macros.UnexpectedReificationError +import scala.reflect.macros.ReificationException +import scala.reflect.macros.UnexpectedReificationException trait Errors { self: Reifier => @@ -19,17 +19,17 @@ trait Errors { def CannotReifyType(tpe: Type) = { val msg = "implementation restriction: cannot reify type %s (%s)".format(tpe, tpe.kind) - throw new ReificationError(defaultErrorPosition, msg) + throw new ReificationException(defaultErrorPosition, msg) } def CannotReifySymbol(sym: Symbol) = { val msg = "implementation restriction: cannot reify symbol %s (%s)".format(sym, sym.accurateKindString) - throw new ReificationError(defaultErrorPosition, msg) + throw new ReificationException(defaultErrorPosition, msg) } def CannotReifyWeakType(details: Any) = { val msg = "cannot create a TypeTag" + details - throw new ReificationError(defaultErrorPosition, msg) + throw new ReificationException(defaultErrorPosition, msg) } def CannotConvertManifestToTagWithoutScalaReflect(tpe: Type, manifestInScope: Tree) = { @@ -37,7 +37,7 @@ trait Errors { |to create a type tag here, it is necessary to interoperate with the manifest `$manifestInScope` in scope. |however manifest -> typetag conversion requires Scala reflection, which is not present on the classpath. |to proceed put scala-reflect.jar on your compilation classpath and recompile.""".trim.stripMargin - throw new ReificationError(defaultErrorPosition, msg) + throw new ReificationException(defaultErrorPosition, msg) } def CannotReifyRuntimeSplice(tree: Tree) = { @@ -46,7 +46,7 @@ trait Errors { |cross-stage evaluations need to be invoked explicitly, so we're showing you this error. |if you're sure this is not an oversight, add scala-compiler.jar to the classpath, |import `scala.tools.reflect.Eval` and call `<your expr>.eval` instead.""".trim.stripMargin - throw new ReificationError(tree.pos, msg) + throw new ReificationException(tree.pos, msg) } // unexpected errors: these can never happen under normal conditions unless there's a bug in the compiler (or in a compiler plugin or in a macro) @@ -54,21 +54,26 @@ trait Errors { def CannotReifyUntypedPrefix(prefix: Tree) = { val msg = "internal error: untyped prefixes are not supported, consider typechecking the prefix before passing it to the reifier" - throw new UnexpectedReificationError(defaultErrorPosition, msg) + throw new UnexpectedReificationException(defaultErrorPosition, msg) } def CannotReifyUntypedReifee(reifee: Any) = { val msg = "internal error: untyped trees are not supported, consider typechecking the reifee before passing it to the reifier" - throw new UnexpectedReificationError(defaultErrorPosition, msg) + throw new UnexpectedReificationException(defaultErrorPosition, msg) } def CannotReifyErroneousPrefix(prefix: Tree) = { val msg = "internal error: erroneous prefixes are not supported, make sure that your prefix has typechecked successfully before passing it to the reifier" - throw new UnexpectedReificationError(defaultErrorPosition, msg) + throw new UnexpectedReificationException(defaultErrorPosition, msg) } def CannotReifyErroneousReifee(reifee: Any) = { val msg = "internal error: erroneous reifees are not supported, make sure that your reifee has typechecked successfully before passing it to the reifier" - throw new UnexpectedReificationError(defaultErrorPosition, msg) + throw new UnexpectedReificationException(defaultErrorPosition, msg) + } + + def CannotReifyInvalidLazyVal(tree: ValDef) = { + val msg = "internal error: could not reconstruct original lazy val due to missing accessor" + throw new UnexpectedReificationException(tree.pos, msg) } } diff --git a/src/compiler/scala/reflect/reify/Reifier.scala b/src/compiler/scala/reflect/reify/Reifier.scala index 6f779be17d..47669f57b0 100644 --- a/src/compiler/scala/reflect/reify/Reifier.scala +++ b/src/compiler/scala/reflect/reify/Reifier.scala @@ -1,8 +1,8 @@ package scala.reflect.reify import scala.tools.nsc.Global -import scala.reflect.macros.ReificationError -import scala.reflect.macros.UnexpectedReificationError +import scala.reflect.macros.ReificationException +import scala.reflect.macros.UnexpectedReificationException import scala.reflect.reify.utils.Utils /** Given a tree or a type, generate a tree that when executed at runtime produces the original tree or type. @@ -108,7 +108,7 @@ abstract class Reifier extends States // needs to be solved some day // maybe try `resetLocalAttrs` once the dust settles var importantSymbols = Set[Symbol]( - NothingClass, AnyClass, SingletonClass, PredefModule, ScalaRunTimeModule, TypeCreatorClass, TreeCreatorClass, MirrorOfClass, + NothingClass, AnyClass, SingletonClass, PredefModule, ScalaRunTimeModule, TypeCreatorClass, TreeCreatorClass, MirrorClass, ApiUniverseClass, JavaUniverseClass, ReflectRuntimePackage, ReflectRuntimeCurrentMirror) importantSymbols ++= importantSymbols map (_.companionSymbol) importantSymbols ++= importantSymbols map (_.moduleClass) @@ -132,12 +132,12 @@ abstract class Reifier extends States untyped } catch { - case ex: ReificationError => + case ex: ReificationException => throw ex - case ex: UnexpectedReificationError => + case ex: UnexpectedReificationException => throw ex case ex: Throwable => - throw new UnexpectedReificationError(defaultErrorPosition, "reification crashed", ex) + throw new UnexpectedReificationException(defaultErrorPosition, "reification crashed", ex) } } }
\ No newline at end of file diff --git a/src/compiler/scala/reflect/reify/Taggers.scala b/src/compiler/scala/reflect/reify/Taggers.scala index 7db6394734..cbaee41890 100644 --- a/src/compiler/scala/reflect/reify/Taggers.scala +++ b/src/compiler/scala/reflect/reify/Taggers.scala @@ -1,6 +1,6 @@ package scala.reflect.reify -import scala.reflect.macros.{ReificationError, UnexpectedReificationError} +import scala.reflect.macros.{ReificationException, UnexpectedReificationException, TypecheckException} import scala.reflect.macros.runtime.Context abstract class Taggers { @@ -65,22 +65,22 @@ abstract class Taggers { translatingReificationErrors(materializer) } try c.typeCheck(result) - catch { case terr @ c.TypeError(pos, msg) => failTag(result, terr) } + catch { case terr @ TypecheckException(pos, msg) => failTag(result, terr) } } def materializeExpr(universe: Tree, mirror: Tree, expr: Tree): Tree = { val result = translatingReificationErrors(c.reifyTree(universe, mirror, expr)) try c.typeCheck(result) - catch { case terr @ c.TypeError(pos, msg) => failExpr(result, terr) } + catch { case terr @ TypecheckException(pos, msg) => failExpr(result, terr) } } private def translatingReificationErrors(materializer: => Tree): Tree = { try materializer catch { - case ReificationError(pos, msg) => + case ReificationException(pos, msg) => c.error(pos.asInstanceOf[c.Position], msg) // this cast is a very small price for the sanity of exception handling EmptyTree - case UnexpectedReificationError(pos, err, cause) if cause != null => + case UnexpectedReificationException(pos, err, cause) if cause != null => throw cause } } diff --git a/src/compiler/scala/reflect/reify/package.scala b/src/compiler/scala/reflect/reify/package.scala index 5a23ab7214..55f8684df2 100644 --- a/src/compiler/scala/reflect/reify/package.scala +++ b/src/compiler/scala/reflect/reify/package.scala @@ -1,7 +1,7 @@ package scala.reflect import scala.language.implicitConversions -import scala.reflect.macros.{Context, ReificationError, UnexpectedReificationError} +import scala.reflect.macros.{Context, ReificationException, UnexpectedReificationException} import scala.tools.nsc.Global package object reify { @@ -53,7 +53,7 @@ package object reify { if (tpe.isSpliceable) { val classTagInScope = typer0.resolveClassTag(enclosingMacroPosition, tpe, allowMaterialization = false) if (!classTagInScope.isEmpty) return Select(classTagInScope, nme.runtimeClass) - if (concrete) throw new ReificationError(enclosingMacroPosition, "tpe %s is an unresolved spliceable type".format(tpe)) + if (concrete) throw new ReificationException(enclosingMacroPosition, "tpe %s is an unresolved spliceable type".format(tpe)) } tpe.normalize match { diff --git a/src/compiler/scala/reflect/reify/phases/Reshape.scala b/src/compiler/scala/reflect/reify/phases/Reshape.scala index b5894e8eb6..1b7509fdbe 100644 --- a/src/compiler/scala/reflect/reify/phases/Reshape.scala +++ b/src/compiler/scala/reflect/reify/phases/Reshape.scala @@ -46,13 +46,13 @@ trait Reshape { if (discard) hk else ta case classDef @ ClassDef(mods, name, params, impl) => val Template(parents, self, body) = impl - var body1 = trimAccessors(classDef, body) + var body1 = trimAccessors(classDef, reshapeLazyVals(body)) body1 = trimSyntheticCaseClassMembers(classDef, body1) var impl1 = Template(parents, self, body1).copyAttrs(impl) ClassDef(mods, name, params, impl1).copyAttrs(classDef) case moduledef @ ModuleDef(mods, name, impl) => val Template(parents, self, body) = impl - var body1 = trimAccessors(moduledef, body) + var body1 = trimAccessors(moduledef, reshapeLazyVals(body)) body1 = trimSyntheticCaseClassMembers(moduledef, body1) var impl1 = Template(parents, self, body1).copyAttrs(impl) ModuleDef(mods, name, impl1).copyAttrs(moduledef) @@ -60,15 +60,11 @@ trait Reshape { val discardedParents = parents collect { case tt: TypeTree => tt } filter isDiscarded if (reifyDebug && discardedParents.length > 0) println("discarding parents in Template: " + discardedParents.mkString(", ")) val parents1 = parents diff discardedParents - val body1 = trimSyntheticCaseClassCompanions(body) + val body1 = reshapeLazyVals(trimSyntheticCaseClassCompanions(body)) Template(parents1, self, body1).copyAttrs(template) case block @ Block(stats, expr) => - val stats1 = trimSyntheticCaseClassCompanions(stats) + val stats1 = reshapeLazyVals(trimSyntheticCaseClassCompanions(stats)) Block(stats1, expr).copyAttrs(block) - case valdef @ ValDef(mods, name, tpt, rhs) if valdef.symbol.isLazy => - if (reifyDebug) println("dropping $lzy in lazy val's name: " + tree) - val name1 = if (name endsWith nme.LAZY_LOCAL) name dropRight nme.LAZY_LOCAL.length else name - ValDef(mods, name1, tpt, rhs).copyAttrs(valdef) case unapply @ UnApply(fun, args) => def extractExtractor(tree: Tree): Tree = { val Apply(fun, args) = tree @@ -248,6 +244,20 @@ trait Reshape { New(TypeTree(ann.atp) setOriginal extractOriginal(ann.original), List(args)) } + private def toPreTyperLazyVal(ddef: DefDef): ValDef = { + def extractRhs(rhs: Tree) = rhs match { + case Block(Assign(lhs, rhs)::Nil, _) if lhs.symbol.isLazy => rhs + case _ => rhs // unit or trait case + } + val DefDef(mods0, name0, _, _, tpt0, rhs0) = ddef + val name1 = nme.dropLocalSuffix(name0) + val Modifiers(flags0, privateWithin0, annotations0) = mods0 + var flags1 = (flags0 & GetterFlags) & ~(STABLE | ACCESSOR | METHOD) + val mods1 = Modifiers(flags1, privateWithin0, annotations0) setPositions mods0.positions + val mods2 = toPreTyperModifiers(mods1, ddef.symbol) + ValDef(mods2, name1, tpt0, extractRhs(rhs0)) + } + private def trimAccessors(deff: Tree, stats: List[Tree]): List[Tree] = { val symdefs = (stats collect { case vodef: ValOrDefDef => vodef } map (vodeff => vodeff.symbol -> vodeff)).toMap val accessors = scala.collection.mutable.Map[ValDef, List[DefDef]]() @@ -270,7 +280,7 @@ trait Reshape { }); var stats1 = stats flatMap { - case vdef @ ValDef(mods, name, tpt, rhs) => + case vdef @ ValDef(mods, name, tpt, rhs) if !mods.isLazy => val mods1 = if (accessors.contains(vdef)) { val ddef = accessors(vdef)(0) // any accessor will do val Modifiers(flags, privateWithin, annotations) = mods @@ -287,7 +297,9 @@ trait Reshape { val vdef1 = ValDef(mods2, name1, tpt, rhs) if (reifyDebug) println("resetting visibility of field: %s => %s".format(vdef, vdef1)) Some(vdef1) // no copyAttrs here, because new ValDef and old symbols are now out of sync - case ddef @ DefDef(mods, name, tparams, vparamss, tpt, rhs) => + case ddef: DefDef if !ddef.mods.isLazy => + // lazy val accessors are removed in reshapeLazyVals + // as they are needed to recreate lazy vals if (accessors.values.exists(_.contains(ddef))) { if (reifyDebug) println("discarding accessor method: " + ddef) None @@ -301,6 +313,34 @@ trait Reshape { stats1 } + private def reshapeLazyVals(stats: List[Tree]): List[Tree] = { + val lazyvaldefs:Map[Symbol, DefDef] = stats.collect({ case ddef: DefDef if ddef.mods.isLazy => ddef }). + map((ddef: DefDef) => ddef.symbol -> ddef).toMap + // lazy valdef and defdef are in the same block. + // only that valdef needs to have its rhs rebuilt from defdef + stats flatMap (stat => stat match { + case vdef: ValDef if vdef.symbol.isLazy => + if (reifyDebug) println(s"reconstructing original lazy value for $vdef") + val ddefSym = vdef.symbol.lazyAccessor + val vdef1 = lazyvaldefs.get(ddefSym) match { + case Some(ddef) => + toPreTyperLazyVal(ddef) + case None => + CannotReifyInvalidLazyVal(vdef) + } + if (reifyDebug) println(s"reconstructed lazy val is $vdef1") + vdef1::Nil + case ddef: DefDef if ddef.symbol.isLazy => + def hasUnitType(sym: Symbol) = (sym.tpe.typeSymbol == UnitClass) && sym.tpe.annotations.isEmpty + if (hasUnitType(ddef.symbol)) { + // since lazy values of type Unit don't have val's + // we need to create them from scratch + toPreTyperLazyVal(ddef) :: Nil + } else Nil + case _ => stat::Nil + }) + } + private def trimSyntheticCaseClassMembers(deff: Tree, stats: List[Tree]): List[Tree] = stats filterNot (memberDef => memberDef.isDef && { val isSynthetic = memberDef.symbol.isSynthetic diff --git a/src/compiler/scala/reflect/reify/utils/Extractors.scala b/src/compiler/scala/reflect/reify/utils/Extractors.scala index bf211ceec4..b60d15c1d4 100644 --- a/src/compiler/scala/reflect/reify/utils/Extractors.scala +++ b/src/compiler/scala/reflect/reify/utils/Extractors.scala @@ -19,7 +19,7 @@ trait Extractors { // $treecreator1.super.<init>(); // () // }; - // def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Tree = { + // def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Tree = { // val $u: U = $m$untyped.universe; // val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; // $u.Apply($u.Select($u.Select($u.build.This($m.staticPackage("scala.collection.immutable").moduleClass), $u.newTermName("List")), $u.newTermName("apply")), List($u.Literal($u.Constant(1)), $u.Literal($u.Constant(2)))) @@ -32,7 +32,7 @@ trait Extractors { // $typecreator1.super.<init>(); // () // }; - // def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Type = { + // def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = { // val $u: U = $m$untyped.universe; // val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; // $u.TypeRef($u.ThisType($m.staticPackage("scala.collection.immutable").moduleClass), $m.staticClass("scala.collection.immutable.List"), List($m.staticClass("scala.Int").toTypeConstructor)) @@ -81,7 +81,7 @@ trait Extractors { DefDef(NoMods, reifierName, List(TypeDef(Modifiers(PARAM), tparamu, List(), TypeBoundsTree(Ident(NothingClass), CompoundTypeTree(Template(List(Ident(reifierUniverse), Ident(SingletonClass)), emptyValDef, List()))))), - List(List(ValDef(Modifiers(PARAM), nme.MIRROR_UNTYPED, AppliedTypeTree(Ident(MirrorOfClass), List(Ident(tparamu))), EmptyTree))), + List(List(ValDef(Modifiers(PARAM), nme.MIRROR_UNTYPED, AppliedTypeTree(Ident(MirrorClass), List(Ident(tparamu))), EmptyTree))), reifierTpt, reifierBody)))) Block(tpec, ApplyConstructor(Ident(tpec.name), List())) } @@ -92,11 +92,18 @@ trait Extractors { Block(List(universeAlias, mirrorAlias), wrappee) } + // if we're reifying a MethodType, we can't use it as a type argument for TypeTag ctor + // http://groups.google.com/group/scala-internals/browse_thread/thread/2d7bb85bfcdb2e2 + private def mkTarg(tpe: Type): Tree = ( + if ((tpe eq null) || !isUseableAsTypeArg(tpe)) TypeTree(AnyTpe) + else TypeTree(tpe) + ) + object ReifiedTree { def apply(universe: Tree, mirror: Tree, symtab: SymbolTable, rtree: Tree, tpe: Type, rtpe: Tree, concrete: Boolean): Tree = { val tagFactory = if (concrete) nme.TypeTag else nme.WeakTypeTag - val tagCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(TypeTree(tpe))) - val exprCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), nme.Expr), nme.apply), List(TypeTree(tpe))) + val tagCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(mkTarg(tpe))) + val exprCtor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), nme.Expr), nme.apply), List(mkTarg(tpe))) val tagArgs = List(Ident(nme.MIRROR_SHORT), mkCreator(tpnme.REIFY_TYPECREATOR_PREFIX, symtab, rtpe)) val unwrapped = Apply(Apply(exprCtor, List(Ident(nme.MIRROR_SHORT), mkCreator(tpnme.REIFY_TREECREATOR_PREFIX, symtab, rtree))), List(Apply(tagCtor, tagArgs))) mkWrapper(universe, mirror, unwrapped) @@ -114,7 +121,7 @@ trait Extractors { case Select(Select(_, tagFlavor), _) => tagFlavor case Select(_, tagFlavor) => tagFlavor } - Some(universe, mirror, SymbolTable(symbolTable1 ++ symbolTable2), rtree, ttpe.tpe, rtpe, tagFlavor == nme.TypeTag) + Some((universe, mirror, SymbolTable(symbolTable1 ++ symbolTable2), rtree, ttpe.tpe, rtpe, tagFlavor == nme.TypeTag)) case _ => None } @@ -123,7 +130,7 @@ trait Extractors { object ReifiedType { def apply(universe: Tree, mirror: Tree, symtab: SymbolTable, tpe: Type, rtpe: Tree, concrete: Boolean) = { val tagFactory = if (concrete) nme.TypeTag else nme.WeakTypeTag - val ctor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(TypeTree(tpe))) + val ctor = TypeApply(Select(Select(Ident(nme.UNIVERSE_SHORT), tagFactory), nme.apply), List(mkTarg(tpe))) val args = List(Ident(nme.MIRROR_SHORT), mkCreator(tpnme.REIFY_TYPECREATOR_PREFIX, symtab, rtpe)) val unwrapped = Apply(ctor, args) mkWrapper(universe, mirror, unwrapped) @@ -139,7 +146,7 @@ trait Extractors { case Select(Select(_, tagFlavor), _) => tagFlavor case Select(_, tagFlavor) => tagFlavor } - Some(universe, mirror, SymbolTable(symtab), ttpe.tpe, rtpe, tagFlavor == nme.TypeTag) + Some((universe, mirror, SymbolTable(symtab), ttpe.tpe, rtpe, tagFlavor == nme.TypeTag)) case _ => None } @@ -160,9 +167,9 @@ trait Extractors { object FreeDef { def unapply(tree: Tree): Option[(Tree, TermName, Tree, Long, String)] = tree match { case FreeTermDef(uref, name, binding, flags, origin) => - Some(uref, name, binding, flags, origin) + Some((uref, name, binding, flags, origin)) case FreeTypeDef(uref, name, binding, flags, origin) => - Some(uref, name, binding, flags, origin) + Some((uref, name, binding, flags, origin)) case _ => None } @@ -207,7 +214,7 @@ trait Extractors { def unapply(tree: Tree): Option[(Tree, TermName)] = tree match { case Apply(Select(Select(uref @ Ident(_), build), ident), List(Ident(name: TermName))) if build == nme.build && ident == nme.Ident && name.startsWith(nme.REIFY_FREE_PREFIX) => - Some(uref, name) + Some((uref, name)) case _ => None } @@ -226,7 +233,7 @@ trait Extractors { Literal(Constant(isClass: Boolean))))) if uref1.name == nme.UNIVERSE_SHORT && build1 == nme.build && newNestedSymbol == nme.newNestedSymbol && uref2.name == nme.UNIVERSE_SHORT && build2 == nme.build && flagsFromBits == nme.flagsFromBits => - Some(uref1, name, flags, isClass) + Some((uref1, name, flags, isClass)) case _ => None } diff --git a/src/compiler/scala/reflect/reify/utils/NodePrinters.scala b/src/compiler/scala/reflect/reify/utils/NodePrinters.scala index f0480e0699..000e500c69 100644 --- a/src/compiler/scala/reflect/reify/utils/NodePrinters.scala +++ b/src/compiler/scala/reflect/reify/utils/NodePrinters.scala @@ -75,7 +75,7 @@ trait NodePrinters { val printout = scala.collection.mutable.ListBuffer[String](); printout += universe.trim - if (mirrorIsUsed) printout += mirror.replace("MirrorOf[", "scala.reflect.api.MirrorOf[").trim + if (mirrorIsUsed) printout += mirror.replace("Mirror[", "scala.reflect.api.Mirror[").trim val imports = scala.collection.mutable.ListBuffer[String](); imports += nme.UNIVERSE_SHORT // if (buildIsUsed) imports += nme.build diff --git a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala index 3ec43c863d..dbb0836e0a 100644 --- a/src/compiler/scala/reflect/reify/utils/SymbolTables.scala +++ b/src/compiler/scala/reflect/reify/utils/SymbolTables.scala @@ -28,7 +28,7 @@ trait SymbolTables { symtab.get(sym) match { case Some(FreeDef(_, name, _, _, _)) => name case Some(SymDef(_, name, _, _)) => name - case None => EmptyTermName + case None => nme.EMPTY } def symAliases(sym: Symbol): List[TermName] = diff --git a/src/compiler/scala/tools/nsc/CompilationUnits.scala b/src/compiler/scala/tools/nsc/CompilationUnits.scala index 6d3fd2e09e..5a2d5ef165 100644 --- a/src/compiler/scala/tools/nsc/CompilationUnits.scala +++ b/src/compiler/scala/tools/nsc/CompilationUnits.scala @@ -23,7 +23,7 @@ trait CompilationUnits { self: Global => /** One unit of compilation that has been submitted to the compiler. * It typically corresponds to a single file of source code. It includes * error-reporting hooks. */ - class CompilationUnit(val source: SourceFile) { + class CompilationUnit(val source: SourceFile) extends CompilationUnitContextApi { /** the fresh name creator */ var fresh: FreshNameCreator = new FreshNameCreator.Default diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 58fcee4b30..12c3338e0d 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -1047,7 +1047,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) * * @param sym A class symbol, object symbol, package, or package class. */ - @deprecated("use invalidateClassPathEntries instead") + @deprecated("use invalidateClassPathEntries instead", "2.10.0") def clearOnNextRun(sym: Symbol) = false /* To try out clearOnNext run on the scala.tools.nsc project itself * replace `false` above with the following code @@ -1079,12 +1079,12 @@ class Global(var currentSettings: Settings, var reporter: Reporter) * of what file was being compiled when it broke. Since I really * really want to know, this hack. */ - private var lastSeenSourceFile: SourceFile = NoSourceFile + protected var lastSeenSourceFile: SourceFile = NoSourceFile /** Let's share a lot more about why we crash all over the place. * People will be very grateful. */ - private var lastSeenContext: analyzer.Context = null + protected var lastSeenContext: analyzer.Context = null /** The currently active run */ @@ -1204,7 +1204,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) /** A Run is a single execution of the compiler on a sets of units */ - class Run { + class Run extends RunContextApi { /** Have been running into too many init order issues with Run * during erroneous conditions. Moved all these vals up to the * top of the file so at least they're not trivially null. @@ -1305,7 +1305,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) /** Reset all classes contained in current project, as determined by * the clearOnNextRun hook */ - @deprecated("use invalidateClassPathEntries instead") + @deprecated("use invalidateClassPathEntries instead", "2.10.0") def resetProjectClasses(root: Symbol): Unit = try { def unlink(sym: Symbol) = if (sym != NoSymbol) root.info.decls.unlink(sym) diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala index 9e46155d14..3e1d606877 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala @@ -45,11 +45,4 @@ abstract class TreeInfo extends scala.reflect.internal.TreeInfo { def isInterface(mods: HasFlags, body: List[Tree]) = mods.isTrait && (body forall isInterfaceMember) - - def isAllowedInUniversalTrait(stat: Tree): Boolean = stat match { - case _: ValDef => false - case Import(_, _) | EmptyTree => true - case _: DefTree => true - case _ => false - } } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index eaee39d7e6..a7da857429 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -1750,7 +1750,7 @@ self => in.nextToken() if (in.token == SUBTYPE || in.token == SUPERTYPE) wildcardType(start) else atPos(start) { Bind(tpnme.WILDCARD, EmptyTree) } - case IDENTIFIER if treeInfo.isVariableName(in.name) => + case IDENTIFIER if nme.isVariableName(in.name) => atPos(start) { Bind(identForType(), EmptyTree) } case _ => typ() diff --git a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala index a1785e5262..69091e4880 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala @@ -360,7 +360,7 @@ trait Scanners extends ScannersCommon { if (ch == '"' && token == IDENTIFIER) token = INTERPOLATIONID case '<' => // is XMLSTART? - def fetchLT = { + def fetchLT() = { val last = if (charOffset >= 2) buf(charOffset - 2) else ' ' nextChar() last match { @@ -389,7 +389,7 @@ trait Scanners extends ScannersCommon { getOperatorRest() } case '0' => - def fetchZero = { + def fetchZero() = { putChar(ch) nextChar() if (ch == 'x' || ch == 'X') { @@ -416,7 +416,7 @@ trait Scanners extends ScannersCommon { case '`' => getBackquotedIdent() case '\"' => - def fetchDoubleQuote = { + def fetchDoubleQuote() = { if (token == INTERPOLATIONID) { nextRawChar() if (ch == '\"') { @@ -452,7 +452,7 @@ trait Scanners extends ScannersCommon { } fetchDoubleQuote case '\'' => - def fetchSingleQuote = { + def fetchSingleQuote() = { nextChar() if (isIdentifierStart(ch)) charLitOr(getIdentRest) @@ -500,7 +500,7 @@ trait Scanners extends ScannersCommon { nextChar() } case _ => - def fetchOther = { + def fetchOther() = { if (ch == '\u21D2') { nextChar(); token = ARROW } else if (ch == '\u2190') { diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index 5a5059d58c..f9eeb41e6d 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -832,15 +832,10 @@ abstract class GenASM extends SubComponent with BytecodeWriters { * * The contents of that attribute are determined by the `String[] exceptions` argument to ASM's ClassVisitor.visitMethod() * This method returns such list of internal names. - * */ - def getExceptions(excs: List[AnnotationInfo]): List[String] = { - for (AnnotationInfo(tp, List(exc), _) <- excs.distinct if tp.typeSymbol == ThrowsClass) - yield { - val Literal(const) = exc - javaName(const.typeValue.typeSymbol) - } - } + def getExceptions(excs: List[AnnotationInfo]): List[String] = + for (ThrownException(exc) <- excs.distinct) + yield javaName(exc) /** Whether an annotation should be emitted as a Java annotation * .initialize: if 'annot' is read from pickle, atp might be un-initialized @@ -2407,7 +2402,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { (instr.category: @scala.annotation.switch) match { case icodes.localsCat => - def genLocalInstr = (instr: @unchecked) match { + def genLocalInstr() = (instr: @unchecked) match { case THIS(_) => jmethod.visitVarInsn(Opcodes.ALOAD, 0) case LOAD_LOCAL(local) => jcode.load(indexOf(local), local.kind) case STORE_LOCAL(local) => jcode.store(indexOf(local), local.kind) @@ -2440,7 +2435,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genLocalInstr case icodes.stackCat => - def genStackInstr = (instr: @unchecked) match { + def genStackInstr() = (instr: @unchecked) match { case LOAD_MODULE(module) => // assert(module.isModule, "Expected module: " + module) @@ -2468,7 +2463,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { case icodes.arilogCat => genPrimitive(instr.asInstanceOf[CALL_PRIMITIVE].primitive, instr.pos) case icodes.castsCat => - def genCastInstr = (instr: @unchecked) match { + def genCastInstr() = (instr: @unchecked) match { case IS_INSTANCE(tpe) => val jtyp: asm.Type = @@ -2498,7 +2493,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genCastInstr case icodes.objsCat => - def genObjsInstr = (instr: @unchecked) match { + def genObjsInstr() = (instr: @unchecked) match { case BOX(kind) => val MethodNameAndType(mname, mdesc) = jBoxTo(kind) @@ -2518,7 +2513,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genObjsInstr case icodes.fldsCat => - def genFldsInstr = (instr: @unchecked) match { + def genFldsInstr() = (instr: @unchecked) match { case lf @ LOAD_FIELD(field, isStatic) => var owner = javaName(lf.hostClass) @@ -2539,7 +2534,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genFldsInstr case icodes.mthdsCat => - def genMethodsInstr = (instr: @unchecked) match { + def genMethodsInstr() = (instr: @unchecked) match { /** Special handling to access native Array.clone() */ case call @ CALL_METHOD(definitions.Array_clone, Dynamic) => @@ -2552,7 +2547,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genMethodsInstr case icodes.arraysCat => - def genArraysInstr = (instr: @unchecked) match { + def genArraysInstr() = (instr: @unchecked) match { case LOAD_ARRAY_ITEM(kind) => jcode.aload(kind) case STORE_ARRAY_ITEM(kind) => jcode.astore(kind) case CREATE_ARRAY(elem, 1) => jcode newarray elem @@ -2561,7 +2556,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genArraysInstr case icodes.jumpsCat => - def genJumpInstr = (instr: @unchecked) match { + def genJumpInstr() = (instr: @unchecked) match { case sw @ SWITCH(tagss, branches) => assert(branches.length == tagss.length + 1, sw) @@ -2691,7 +2686,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genJumpInstr case icodes.retCat => - def genRetInstr = (instr: @unchecked) match { + def genRetInstr() = (instr: @unchecked) match { case RETURN(kind) => jcode emitRETURN kind case THROW(_) => emit(Opcodes.ATHROW) } @@ -2781,7 +2776,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { case Negation(kind) => jcode.neg(kind) case Arithmetic(op, kind) => - def genArith = { + def genArith() = { op match { case ADD => jcode.add(kind) @@ -2811,7 +2806,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { // TODO GenICode uses `toTypeKind` to define that elem, `toValueTypeKind` would be needed instead. // TODO How about adding some asserts to Logical and similar ones to capture the remaining constraint (UNIT not allowed). case Logical(op, kind) => - def genLogical = op match { + def genLogical() = op match { case AND => kind match { case LONG => emit(Opcodes.LAND) @@ -2840,7 +2835,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genLogical case Shift(op, kind) => - def genShift = op match { + def genShift() = op match { case LSL => kind match { case LONG => emit(Opcodes.LSHL) @@ -2869,7 +2864,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters { genShift case Comparison(op, kind) => - def genCompare = op match { + def genCompare() = op match { case CMP => (kind: @unchecked) match { case LONG => emit(Opcodes.LCMP) diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index 62c281b82f..cb6156c59c 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -606,11 +606,10 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with // put some random value; the actual number is determined at the end buf putShort 0xbaba.toShort - for (AnnotationInfo(tp, List(exc), _) <- excs.distinct if tp.typeSymbol == ThrowsClass) { - val Literal(const) = exc + for (ThrownException(exc) <- excs.distinct) { buf.putShort( cpool.addClass( - javaName(const.typeValue.typeSymbol)).shortValue) + javaName(exc)).shortValue) nattr += 1 } diff --git a/src/compiler/scala/tools/nsc/doc/DocFactory.scala b/src/compiler/scala/tools/nsc/doc/DocFactory.scala index cd0c242f22..02b69034ef 100644 --- a/src/compiler/scala/tools/nsc/doc/DocFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/DocFactory.scala @@ -86,7 +86,7 @@ class DocFactory(val reporter: Reporter, val settings: doc.Settings) { processor with model.comment.CommentFactory with model.TreeFactory with model.MemberLookup { - override def templateShouldDocument(sym: compiler.Symbol, inTpl: TemplateImpl) = + override def templateShouldDocument(sym: compiler.Symbol, inTpl: DocTemplateImpl) = extraTemplatesToDocument(sym) || super.templateShouldDocument(sym, inTpl) } ) diff --git a/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala index 2c719e5d70..b47e9f5784 100644 --- a/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala +++ b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala @@ -117,7 +117,7 @@ abstract class HtmlPage extends Page { thisPage => case Underline(in) => <u>{ inlineToHtml(in) }</u> case Superscript(in) => <sup>{ inlineToHtml(in) }</sup> case Subscript(in) => <sub>{ inlineToHtml(in) }</sub> - case Link(raw, title) => <a href={ raw }>{ inlineToHtml(title) }</a> + case Link(raw, title) => <a href={ raw } target="_blank">{ inlineToHtml(title) }</a> case Monospace(in) => <code>{ inlineToHtml(in) }</code> case Text(text) => scala.xml.Text(text) case Summary(in) => inlineToHtml(in) diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js index d223b4aced..7b2637e25a 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js @@ -1,401 +1,563 @@ /*! - * jQuery UI 1.9m2 + * jQuery UI CSS Framework 1.8.24 * - * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT (MIT-LICENSE.txt) - * and GPL (GPL-LICENSE.txt) licenses. + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license * - * http://docs.jquery.com/UI + * http://docs.jquery.com/UI/Theming/API */ -(function(c){c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.9m2",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")== -"hidden")return false;b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108, -NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect", -"none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x", -1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)? -!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery); -(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],g;a=a.split(".")[1];g=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][g]=function(f){return!!b.data(f,a)};b[e]=b[e]||{};b[e][a]=function(f,i){arguments.length&&this._createWidget(f,i)};var h=new c;h.options=b.extend({},h.options);b[e][a].prototype= -b.extend(true,h,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:g,base:c.prototype},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",g=Array.prototype.slice.call(arguments,1),h=this;d=!e&&g.length?b.extend.apply(null,[true,d].concat(g)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var f=b.data(this,a),i=f&&b.isFunction(f[d])?f[d].apply(f,g):f;if(i!==f&&i!==undefined){h=i; -return false}}):this.each(function(){var f=b.data(this,a);if(f){d&&f.option(d);f._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName, -function(){d.destroy()});this._create();this._init()},_create:function(){},_init:function(){},_super:function(a){return this.base[a].apply(this,Array.prototype.slice.call(arguments,1))},_superApply:function(a,c){return this.base[a].apply(this,c)},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element}, -option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(g,h){e._setOption(g,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled", -true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var g;a;){g=b.event.props[--a];c[g]=c.originalEvent[g]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery); -(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&& -this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault(); -return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&& -this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX- -a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery); -(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper== -"original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:function(a){var b= -this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top- -this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions(); -d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis|| -this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if(!this.element[0]||!this.element[0].parentNode)return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&this.options.revert.call(this.element, -b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this== -a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]|| -0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], -this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top- -(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment== -"parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&& -a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"), -10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], -this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft(): -f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+ -this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e=this.originalPageX+ -Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left- -this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs= -this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.9m2"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data(this,"sortable"); -if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper; -c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver= -1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left; -this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper= -this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","iframeFix",{start:function(){var a= -d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options; -if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!= -"HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX- -b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()- -c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this, -width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+e&&j-e<o&& -o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k}).left-c.margins.left}var t= -p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width}).left-c.margins.left}if(!c.snapElements[h].snapping&& -(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"), -10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery); -(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this); -a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&& -this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options.hoverClass); -this._trigger("over",a,this.ui(b))}},_out:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b))}},_drop:function(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g= -d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("drop", -a,this.ui(c));return this.element}return false},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.9m2"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height; -switch(c){case "fit":return i<e&&g<k&&j<f&&h<l;case "intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case "touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l)&&(e>=i&& -e<=k||g>=i&&g<=k||e<i&&g>k);default:return false}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++)if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++)if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a}c[f].visible=c[f].element.css("display")!= -"none";if(c[f].visible){c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};e=="mousedown"&&c[f]._activate.call(c[f],b)}}},drop:function(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem|| -a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e= -d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})}}})(jQuery); -(function(e){e.widget("ui.resizable",e.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1E3},_create:function(){var b=this,a=this.options;this.element.addClass("ui-resizable");e.extend(this,{_aspectRatio:!!a.aspectRatio,aspectRatio:a.aspectRatio,originalElement:this.element, -_proportionallyResizeElements:[],_helper:a.helper||a.ghost||a.animate?a.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){/relative/.test(this.element.css("position"))&&e.browser.opera&&this.element.css({position:"relative",top:"auto",left:"auto"});this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(), -top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle= -this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=a.handles||(!e(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne", -nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all")this.handles="n,e,s,w,se,sw,ne,nw";var c=this.handles.split(",");this.handles={};for(var d=0;d<c.length;d++){var f=e.trim(c[d]),g=e('<div class="ui-resizable-handle '+("ui-resizable-"+f)+'"></div>');/sw|se|ne|nw/.test(f)&&g.css({zIndex:++a.zIndex});"se"==f&&g.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[f]=".ui-resizable-"+f;this.element.append(g)}}this._renderAxis=function(h){h=h||this.element;for(var i in this.handles){if(this.handles[i].constructor== -String)this.handles[i]=e(this.handles[i],this.element).show();if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var j=e(this.handles[i],this.element),k=0;k=/sw|ne|nw|se|n|s/.test(i)?j.outerHeight():j.outerWidth();j=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join("");h.css(j,k);this._proportionallyResize()}e(this.handles[i])}};this._renderAxis(this.element);this._handles=e(".ui-resizable-handle",this.element).disableSelection(); -this._handles.mouseover(function(){if(!b.resizing){if(this.className)var h=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=h&&h[1]?h[1]:"se"}});if(a.autoHide){this._handles.hide();e(this.element).addClass("ui-resizable-autohide").hover(function(){e(this).removeClass("ui-resizable-autohide");b._handles.show()},function(){if(!b.resizing){e(this).addClass("ui-resizable-autohide");b._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(c){e(c).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()}; -if(this.elementIsWrapper){b(this.element);var a=this.element;a.after(this.originalElement.css({position:a.css("position"),width:a.outerWidth(),height:a.outerHeight(),top:a.css("top"),left:a.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);b(this.originalElement);return this},_mouseCapture:function(b){var a=false;for(var c in this.handles)if(e(this.handles[c])[0]==b.target)a=true;return!this.options.disabled&&a},_mouseStart:function(b){var a=this.options,c=this.element.position(), -d=this.element;this.resizing=true;this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()};if(d.is(".ui-draggable")||/absolute/.test(d.css("position")))d.css({position:"absolute",top:c.top,left:c.left});e.browser.opera&&/relative/.test(d.css("position"))&&d.css({position:"relative",top:"auto",left:"auto"});this._renderProxy();c=m(this.helper.css("left"));var f=m(this.helper.css("top"));if(a.containment){c+=e(a.containment).scrollLeft()||0;f+=e(a.containment).scrollTop()||0}this.offset= -this.helper.offset();this.position={left:c,top:f};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:c,top:f};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:b.pageX,top:b.pageY};this.aspectRatio=typeof a.aspectRatio=="number"?a.aspectRatio: -this.originalSize.width/this.originalSize.height||1;a=e(".ui-resizable-"+this.axis).css("cursor");e("body").css("cursor",a=="auto"?this.axis+"-resize":a);d.addClass("ui-resizable-resizing");this._propagate("start",b);return true},_mouseDrag:function(b){var a=this.helper,c=this.originalMousePosition,d=this._change[this.axis];if(!d)return false;c=d.apply(this,[b,b.pageX-c.left||0,b.pageY-c.top||0]);if(this._aspectRatio||b.shiftKey)c=this._updateRatio(c,b);c=this._respectSize(c,b);this._propagate("resize", -b);a.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();this._updateCache(c);this._trigger("resize",b,this.ui());return false},_mouseStop:function(b){this.resizing=false;var a=this.options,c=this;if(this._helper){var d=this._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName);d=f&&e.ui.hasScroll(d[0],"left")?0:c.sizeDiff.height; -f={width:c.size.width-(f?0:c.sizeDiff.width),height:c.size.height-d};d=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null;var g=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null;a.animate||this.element.css(e.extend(f,{top:g,left:d}));c.helper.height(c.size.height);c.helper.width(c.size.width);this._helper&&!a.animate&&this._proportionallyResize()}e("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop", -b);this._helper&&this.helper.remove();return false},_updateCache:function(b){this.offset=this.helper.offset();if(l(b.left))this.position.left=b.left;if(l(b.top))this.position.top=b.top;if(l(b.height))this.size.height=b.height;if(l(b.width))this.size.width=b.width},_updateRatio:function(b){var a=this.position,c=this.size,d=this.axis;if(b.height)b.width=c.height*this.aspectRatio;else if(b.width)b.height=c.width/this.aspectRatio;if(d=="sw"){b.left=a.left+(c.width-b.width);b.top=null}if(d=="nw"){b.top= -a.top+(c.height-b.height);b.left=a.left+(c.width-b.width)}return b},_respectSize:function(b){var a=this.options,c=this.axis,d=l(b.width)&&a.maxWidth&&a.maxWidth<b.width,f=l(b.height)&&a.maxHeight&&a.maxHeight<b.height,g=l(b.width)&&a.minWidth&&a.minWidth>b.width,h=l(b.height)&&a.minHeight&&a.minHeight>b.height;if(g)b.width=a.minWidth;if(h)b.height=a.minHeight;if(d)b.width=a.maxWidth;if(f)b.height=a.maxHeight;var i=this.originalPosition.left+this.originalSize.width,j=this.position.top+this.size.height, -k=/sw|nw|w/.test(c);c=/nw|ne|n/.test(c);if(g&&k)b.left=i-a.minWidth;if(d&&k)b.left=i-a.maxWidth;if(h&&c)b.top=j-a.minHeight;if(f&&c)b.top=j-a.maxHeight;if((a=!b.width&&!b.height)&&!b.left&&b.top)b.top=null;else if(a&&!b.top&&b.left)b.left=null;return b},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var b=this.helper||this.element,a=0;a<this._proportionallyResizeElements.length;a++){var c=this._proportionallyResizeElements[a];if(!this.borderDif){var d=[c.css("borderTopWidth"), -c.css("borderRightWidth"),c.css("borderBottomWidth"),c.css("borderLeftWidth")],f=[c.css("paddingTop"),c.css("paddingRight"),c.css("paddingBottom"),c.css("paddingLeft")];this.borderDif=e.map(d,function(g,h){g=parseInt(g,10)||0;h=parseInt(f[h],10)||0;return g+h})}e.browser.msie&&(e(b).is(":hidden")||e(b).parents(":hidden").length)||c.css({height:b.height()-this.borderDif[0]-this.borderDif[2]||0,width:b.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var b=this.options;this.elementOffset= -this.element.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var a=e.browser.msie&&e.browser.version<7,c=a?1:0;a=a?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+a,height:this.element.outerHeight()+a,position:"absolute",left:this.elementOffset.left-c+"px",top:this.elementOffset.top-c+"px",zIndex:++b.zIndex});this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(b,a){return{width:this.originalSize.width+ -a}},w:function(b,a){return{left:this.originalPosition.left+a,width:this.originalSize.width-a}},n:function(b,a,c){return{top:this.originalPosition.top+c,height:this.originalSize.height-c}},s:function(b,a,c){return{height:this.originalSize.height+c}},se:function(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,a,c]))},sw:function(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,a,c]))},ne:function(b,a,c){return e.extend(this._change.n.apply(this, -arguments),this._change.e.apply(this,[b,a,c]))},nw:function(b,a,c){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,a,c]))}},_propagate:function(b,a){e.ui.plugin.call(this,b,[a,this.ui()]);b!="resize"&&this._trigger(b,a,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});e.extend(e.ui.resizable, -{version:"1.9m2"});e.ui.plugin.add("resizable","alsoResize",{start:function(){var b=e(this).data("resizable").options,a=function(c){e(c).each(function(){var d=e(this);d.data("resizable-alsoresize",{width:parseInt(d.width(),10),height:parseInt(d.height(),10),left:parseInt(d.css("left"),10),top:parseInt(d.css("top"),10),position:d.css("position")})})};if(typeof b.alsoResize=="object"&&!b.alsoResize.parentNode)if(b.alsoResize.length){b.alsoResize=b.alsoResize[0];a(b.alsoResize)}else e.each(b.alsoResize, -function(c){a(c)});else a(b.alsoResize)},resize:function(b,a){var c=e(this).data("resizable");b=c.options;var d=c.originalSize,f=c.originalPosition,g={height:c.size.height-d.height||0,width:c.size.width-d.width||0,top:c.position.top-f.top||0,left:c.position.left-f.left||0},h=function(i,j){e(i).each(function(){var k=e(this),r=e(this).data("resizable-alsoresize"),q={},s=j&&j.length?j:k.parents(a.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(s,function(n,p){if((n= -(r[p]||0)+(g[p]||0))&&n>=0)q[p]=n||null});if(e.browser.opera&&/relative/.test(k.css("position"))){c._revertToRelativePosition=true;k.css({position:"absolute",top:"auto",left:"auto"})}k.css(q)})};typeof b.alsoResize=="object"&&!b.alsoResize.nodeType?e.each(b.alsoResize,function(i,j){h(i,j)}):h(b.alsoResize)},stop:function(){var b=e(this).data("resizable"),a=function(c){e(c).each(function(){var d=e(this);d.css({position:d.data("resizable-alsoresize").position})})};if(b._revertToRelativePosition){b._revertToRelativePosition= -false;typeof o.alsoResize=="object"&&!o.alsoResize.nodeType?e.each(o.alsoResize,function(c){a(c)}):a(o.alsoResize)}e(this).removeData("resizable-alsoresize")}});e.ui.plugin.add("resizable","animate",{stop:function(b){var a=e(this).data("resizable"),c=a.options,d=a._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName),g=f&&e.ui.hasScroll(d[0],"left")?0:a.sizeDiff.height;f={width:a.size.width-(f?0:a.sizeDiff.width),height:a.size.height-g};g=parseInt(a.element.css("left"),10)+(a.position.left- -a.originalPosition.left)||null;var h=parseInt(a.element.css("top"),10)+(a.position.top-a.originalPosition.top)||null;a.element.animate(e.extend(f,h&&g?{top:h,left:g}:{}),{duration:c.animateDuration,easing:c.animateEasing,step:function(){var i={width:parseInt(a.element.css("width"),10),height:parseInt(a.element.css("height"),10),top:parseInt(a.element.css("top"),10),left:parseInt(a.element.css("left"),10)};d&&d.length&&e(d[0]).css({width:i.width,height:i.height});a._updateCache(i);a._propagate("resize", -b)}})}});e.ui.plugin.add("resizable","containment",{start:function(){var b=e(this).data("resizable"),a=b.element,c=b.options.containment;if(a=c instanceof e?c.get(0):/parent/.test(c)?a.parent().get(0):c){b.containerElement=e(a);if(/document/.test(c)||c==document){b.containerOffset={left:0,top:0};b.containerPosition={left:0,top:0};b.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}}else{var d=e(a),f=[];e(["Top", -"Right","Left","Bottom"]).each(function(i,j){f[i]=m(d.css("padding"+j))});b.containerOffset=d.offset();b.containerPosition=d.position();b.containerSize={height:d.innerHeight()-f[3],width:d.innerWidth()-f[1]};c=b.containerOffset;var g=b.containerSize.height,h=b.containerSize.width;h=e.ui.hasScroll(a,"left")?a.scrollWidth:h;g=e.ui.hasScroll(a)?a.scrollHeight:g;b.parentData={element:a,left:c.left,top:c.top,width:h,height:g}}}},resize:function(b){var a=e(this).data("resizable"),c=a.options,d=a.containerOffset, -f=a.position;b=a._aspectRatio||b.shiftKey;var g={top:0,left:0},h=a.containerElement;if(h[0]!=document&&/static/.test(h.css("position")))g=d;if(f.left<(a._helper?d.left:0)){a.size.width+=a._helper?a.position.left-d.left:a.position.left-g.left;if(b)a.size.height=a.size.width/c.aspectRatio;a.position.left=c.helper?d.left:0}if(f.top<(a._helper?d.top:0)){a.size.height+=a._helper?a.position.top-d.top:a.position.top;if(b)a.size.width=a.size.height*c.aspectRatio;a.position.top=a._helper?d.top:0}a.offset.left= -a.parentData.left+a.position.left;a.offset.top=a.parentData.top+a.position.top;c=Math.abs((a._helper?a.offset.left-g.left:a.offset.left-g.left)+a.sizeDiff.width);d=Math.abs((a._helper?a.offset.top-g.top:a.offset.top-d.top)+a.sizeDiff.height);f=a.containerElement.get(0)==a.element.parent().get(0);g=/relative|absolute/.test(a.containerElement.css("position"));if(f&&g)c-=a.parentData.left;if(c+a.size.width>=a.parentData.width){a.size.width=a.parentData.width-c;if(b)a.size.height=a.size.width/a.aspectRatio}if(d+ -a.size.height>=a.parentData.height){a.size.height=a.parentData.height-d;if(b)a.size.width=a.size.height*a.aspectRatio}},stop:function(){var b=e(this).data("resizable"),a=b.options,c=b.containerOffset,d=b.containerPosition,f=b.containerElement,g=e(b.helper),h=g.offset(),i=g.outerWidth()-b.sizeDiff.width;g=g.outerHeight()-b.sizeDiff.height;b._helper&&!a.animate&&/relative/.test(f.css("position"))&&e(this).css({left:h.left-d.left-c.left,width:i,height:g});b._helper&&!a.animate&&/static/.test(f.css("position"))&& -e(this).css({left:h.left-d.left-c.left,width:i,height:g})}});e.ui.plugin.add("resizable","ghost",{start:function(){var b=e(this).data("resizable"),a=b.options,c=b.size;b.ghost=b.originalElement.clone();b.ghost.css({opacity:0.25,display:"block",position:"relative",height:c.height,width:c.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof a.ghost=="string"?a.ghost:"");b.ghost.appendTo(b.helper)},resize:function(){var b=e(this).data("resizable");b.ghost&&b.ghost.css({position:"relative", -height:b.size.height,width:b.size.width})},stop:function(){var b=e(this).data("resizable");b.ghost&&b.helper&&b.helper.get(0).removeChild(b.ghost.get(0))}});e.ui.plugin.add("resizable","grid",{resize:function(){var b=e(this).data("resizable"),a=b.options,c=b.size,d=b.originalSize,f=b.originalPosition,g=b.axis;a.grid=typeof a.grid=="number"?[a.grid,a.grid]:a.grid;var h=Math.round((c.width-d.width)/(a.grid[0]||1))*(a.grid[0]||1);a=Math.round((c.height-d.height)/(a.grid[1]||1))*(a.grid[1]||1);if(/^(se|s|e)$/.test(g)){b.size.width= -d.width+h;b.size.height=d.height+a}else if(/^(ne)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a}else{if(/^(sw)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a}else{b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a}b.position.left=f.left-h}}});var m=function(b){return parseInt(b,10)||0},l=function(b){return!isNaN(parseInt(b,10))}})(jQuery); -(function(e){e.widget("ui.selectable",e.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function(){var c=this;this.element.addClass("ui-selectable");this.dragged=false;var f;this.refresh=function(){f=e(c.options.filter,c.element[0]);f.each(function(){var d=e(this),b=d.offset();e.data(this,"selectable-item",{element:this,$element:d,left:b.left,top:b.top,right:b.left+d.outerWidth(),bottom:b.top+d.outerHeight(),startselected:false,selected:d.hasClass("ui-selected"), -selecting:d.hasClass("ui-selecting"),unselecting:d.hasClass("ui-unselecting")})})};this.refresh();this.selectees=f.addClass("ui-selectee");this._mouseInit();this.helper=e("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},_mouseStart:function(c){var f=this;this.opos=[c.pageX, -c.pageY];if(!this.options.disabled){var d=this.options;this.selectees=e(d.filter,this.element[0]);this._trigger("start",c);e(d.appendTo).append(this.helper);this.helper.css({left:c.clientX,top:c.clientY,width:0,height:0});d.autoRefresh&&this.refresh();this.selectees.filter(".ui-selected").each(function(){var b=e.data(this,"selectable-item");b.startselected=true;if(!c.metaKey){b.$element.removeClass("ui-selected");b.selected=false;b.$element.addClass("ui-unselecting");b.unselecting=true;f._trigger("unselecting", -c,{unselecting:b.element})}});e(c.target).parents().andSelf().each(function(){var b=e.data(this,"selectable-item");if(b){var g=!c.metaKey||!b.$element.hasClass("ui-selected");b.$element.removeClass(g?"ui-unselecting":"ui-selected").addClass(g?"ui-selecting":"ui-unselecting");b.unselecting=!g;b.selecting=g;(b.selected=g)?f._trigger("selecting",c,{selecting:b.element}):f._trigger("unselecting",c,{unselecting:b.element});return false}})}},_mouseDrag:function(c){var f=this;this.dragged=true;if(!this.options.disabled){var d= -this.options,b=this.opos[0],g=this.opos[1],h=c.pageX,i=c.pageY;if(b>h){var j=h;h=b;b=j}if(g>i){j=i;i=g;g=j}this.helper.css({left:b,top:g,width:h-b,height:i-g});this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!(!a||a.element==f.element[0])){var k=false;if(d.tolerance=="touch")k=!(a.left>h||a.right<b||a.top>i||a.bottom<g);else if(d.tolerance=="fit")k=a.left>b&&a.right<h&&a.top>g&&a.bottom<i;if(k){if(a.selected){a.$element.removeClass("ui-selected");a.selected=false}if(a.unselecting){a.$element.removeClass("ui-unselecting"); -a.unselecting=false}if(!a.selecting){a.$element.addClass("ui-selecting");a.selecting=true;f._trigger("selecting",c,{selecting:a.element})}}else{if(a.selecting)if(c.metaKey&&a.startselected){a.$element.removeClass("ui-selecting");a.selecting=false;a.$element.addClass("ui-selected");a.selected=true}else{a.$element.removeClass("ui-selecting");a.selecting=false;if(a.startselected){a.$element.addClass("ui-unselecting");a.unselecting=true}f._trigger("unselecting",c,{unselecting:a.element})}if(a.selected)if(!c.metaKey&& -!a.startselected){a.$element.removeClass("ui-selected");a.selected=false;a.$element.addClass("ui-unselecting");a.unselecting=true;f._trigger("unselecting",c,{unselecting:a.element})}}}});return false}},_mouseStop:function(c){var f=this;this.dragged=false;e(".ui-unselecting",this.element[0]).each(function(){var d=e.data(this,"selectable-item");d.$element.removeClass("ui-unselecting");d.unselecting=false;d.startselected=false;f._trigger("unselected",c,{unselected:d.element})});e(".ui-selecting",this.element[0]).each(function(){var d= -e.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected");d.selecting=false;d.selected=true;d.startselected=true;f._trigger("selected",c,{selected:d.element})});this._trigger("stop",c);this.helper.remove();return false}});e.extend(e.ui.selectable,{version:"1.9m2"})})(jQuery); -(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function(){this.containerCache={};this.element.addClass("ui-sortable"); -this.refresh();this.floating=this.items.length?/left|right/.test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--)this.items[a].item.removeData("sortable-item");return this},_setOption:function(a,b){if(a==="disabled"){this.options[a]=b;this.widget()[b?"addClass":"removeClass"]("ui-sortable-disabled")}else this._superApply("_setOption", -arguments)},_mouseCapture:function(a,b){if(this.reverting)return false;if(this.options.disabled||this.options.type=="static")return false;this._refreshItems(a);var c=null,e=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==e){c=d(this);return false}});if(d.data(a.target,"sortable-item")==e)c=d(a.target);if(!c)return false;if(this.options.handle&&!b){var f=false;d(this.options.handle,c).find("*").andSelf().each(function(){if(this==a.target)f=true});if(!f)return false}this.currentItem= -c;this._removeCurrentsFromItems();return true},_mouseStart:function(a,b,c){b=this.options;var e=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");d.extend(this.offset, -{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();b.containment&&this._setContainment(); -if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor)}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity)}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=this.scrollParent.offset();this._trigger("start", -a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!c)for(c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("activate",a,e._uiHash(this));if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);return true},_mouseDrag:function(a){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute"); -if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-b.scrollSpeed;if(this.overflowOffset.left+ -this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-b.scrollSpeed}else{if(a.pageY-d(document).scrollTop()<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()-b.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()+ -b.scrollSpeed);if(a.pageX-d(document).scrollLeft()<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed)}c!==false&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+ -"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){c=this.items[b];var e=c.item[0],f=this._intersectsWithPointer(c);if(f)if(e!=this.currentItem[0]&&this.placeholder[f==1?"next":"prev"]()[0]!=e&&!d.ui.contains(this.placeholder[0],e)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],e):true)){this.direction=f==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(c))this._rearrange(a, -c);else break;this._trigger("change",a,this._uiHash());break}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var c=this;b=c.placeholder.offset();c.reverting=true;d(this.helper).animate({left:b.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]== -document.body?0:this.offsetParent[0].scrollLeft),top:b.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(a)})}else this._clear(a,b);return false}},cancel:function(){var a=this;if(this.dragging){this._mouseUp();this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var b=this.containers.length-1;b>=0;b--){this.containers[b]._trigger("deactivate", -null,a._uiHash(this));if(this.containers[b].containerCache.over){this.containers[b]._trigger("out",null,a._uiHash(this));this.containers[b].containerCache.over=0}}}this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove();d.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});this.domPosition.prev?d(this.domPosition.prev).after(this.currentItem): -d(this.domPosition.parent).prepend(this.currentItem);return this},serialize:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};d(b).each(function(){var e=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);if(e)c.push((a.key||e[1]+"[]")+"="+(a.key&&a.expression?e[1]:e[2]))});return c.join("&")},toArray:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};b.each(function(){c.push(d(a.item||this).attr(a.attribute||"id")||"")});return c}, -_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,e=this.positionAbs.top,f=e+this.helperProportions.height,g=a.left,h=g+a.width,i=a.top,k=i+a.height,j=this.offset.click.top,l=this.offset.click.left;j=e+j>i&&e+j<k&&b+l>g&&b+l<h;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?j:g<b+this.helperProportions.width/ -2&&c-this.helperProportions.width/2<h&&i<e+this.helperProportions.height/2&&f-this.helperProportions.height/2<k},_intersectsWithPointer:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width);b=b&&a;a=this._getDragVerticalDirection();var c=this._getDragHorizontalDirection();if(!b)return false;return this.floating?c&&c=="right"||a=="down"?2:1:a&&(a=="down"?2:1)},_intersectsWithSides:function(a){var b= -d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width);var c=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return this.floating&&e?e=="right"&&a||e=="left"&&!a:c&&(c=="down"&&b||c=="up"&&!b)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a= -this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a);this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(a){var b=[],c=[],e=this._connectWith();if(e&&a)for(a=e.length-1;a>=0;a--)for(var f=d(e[a]),g=f.length-1;g>=0;g--){var h=d.data(f[g],"sortable");if(h&&h!=this&&!h.options.disabled)c.push([d.isFunction(h.options.items)? -h.options.items.call(h.element):d(h.options.items,h.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),h])}c.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(a=c.length-1;a>=0;a--)c[a][0].each(function(){b.push(this)});return d(b)},_removeCurrentsFromItems:function(){for(var a=this.currentItem.find(":data(sortable-item)"), -b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(a){this.items=[];this.containers=[this];var b=this.items,c=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),this]],e=this._connectWith();if(e)for(var f=e.length-1;f>=0;f--)for(var g=d(e[f]),h=g.length-1;h>=0;h--){var i=d.data(g[h],"sortable");if(i&&i!=this&&!i.options.disabled){c.push([d.isFunction(i.options.items)? -i.options.items.call(i.element[0],a,{item:this.currentItem}):d(i.options.items,i.element),i]);this.containers.push(i)}}for(f=c.length-1;f>=0;f--){a=c[f][1];e=c[f][0];h=0;for(g=e.length;h<g;h++){i=d(e[h]);i.data("sortable-item",a);b.push({item:i,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(a){if(this.offsetParent&&this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var c=this.items[b],e=this.options.toleranceElement?d(this.options.toleranceElement, -c.item):c.item;if(!a){c.width=e.outerWidth();c.height=e.outerHeight()}e=e.offset();c.left=e.left;c.top=e.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--){e=this.containers[b].element.offset();this.containers[b].containerCache.left=e.left;this.containers[b].containerCache.top=e.top;this.containers[b].containerCache.width=this.containers[b].element.outerWidth();this.containers[b].containerCache.height= -this.containers[b].element.outerHeight()}return this},_createPlaceholder:function(a){var b=a||this,c=b.options;if(!c.placeholder||c.placeholder.constructor==String){var e=c.placeholder;c.placeholder={element:function(){var f=d(document.createElement(b.currentItem[0].nodeName)).addClass(e||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!e)f.style.visibility="hidden";return f},update:function(f,g){if(!(e&&!c.forcePlaceholderSize)){g.height()||g.height(b.currentItem.innerHeight()- -parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));g.width()||g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=d(c.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);c.placeholder.update(b,b.placeholder)},_contactContainers:function(a){for(var b=null,c=null,e=this.containers.length-1;e>=0;e--)if(!d.ui.contains(this.currentItem[0], -this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(!(b&&d.ui.contains(this.containers[e].element[0],b.element[0]))){b=this.containers[e];c=e}}else if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",a,this._uiHash(this));this.containers[e].containerCache.over=0}if(b)if(this.containers.length===1){this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}else if(this.currentContainer!=this.containers[c]){b= -1E4;e=null;for(var f=this.positionAbs[this.containers[c].floating?"left":"top"],g=this.items.length-1;g>=0;g--)if(d.ui.contains(this.containers[c].element[0],this.items[g].item[0])){var h=this.items[g][this.containers[c].floating?"left":"top"];if(Math.abs(h-f)<b){b=Math.abs(h-f);e=this.items[g]}}if(e||this.options.dropOnEmpty){this.currentContainer=this.containers[c];e?this._rearrange(a,e,null,true):this._rearrange(a,null,this.containers[c].element,true);this._trigger("change",a,this._uiHash());this.containers[c]._trigger("change", -a,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}}},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!="parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0]);if(a[0]== -this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(a[0].style.width==""||b.forceHelperSize)a.width(this.currentItem.width());if(a[0].style.height==""||b.forceHelperSize)a.height(this.currentItem.height());return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]|| -0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], -this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top- -(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options; -if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)){var b= -d(a.containment)[0];a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width- -this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);return{top:b.top+ -this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0], -this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var f=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])f=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top; -if(a.pageX-this.offset.click.left>this.containment[2])f=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;f=this.originalPageX+Math.round((f- -this.originalPageX)/b.grid[0])*b.grid[0];f=this.containment?!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:!(f-this.offset.click.left<this.containment[0])?f-b.grid[0]:f+b.grid[0]:f}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+ -(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())}},_rearrange:function(a,b,c,e){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var f=this,g=this.counter;window.setTimeout(function(){g==f.counter&&f.refreshPositions(!e)},0)},_clear:function(a,b){this.reverting=false;var c=[];!this._noFinalSort&& -this.currentItem[0].parentNode&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS)if(this._storedCSS[e]=="auto"||this._storedCSS[e]=="static")this._storedCSS[e]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!b&&c.push(function(f){this._trigger("receive",f,this._uiHash(this.fromOutside))});if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]|| -this.domPosition.parent!=this.currentItem.parent()[0])&&!b)c.push(function(f){this._trigger("update",f,this._uiHash())});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||c.push(function(f){this._trigger("remove",f,this._uiHash())});for(e=this.containers.length-1;e>=0;e--)if(d.ui.contains(this.containers[e].element[0],this.currentItem[0])&&!b){c.push(function(f){return function(g){f._trigger("receive",g,this._uiHash(this))}}.call(this,this.containers[e]));c.push(function(f){return function(g){f._trigger("update", -g,this._uiHash(this))}}.call(this,this.containers[e]))}}for(e=this.containers.length-1;e>=0;e--){b||c.push(function(f){return function(g){f._trigger("deactivate",g,this._uiHash(this))}}.call(this,this.containers[e]));if(this.containers[e].containerCache.over){c.push(function(f){return function(g){f._trigger("out",g,this._uiHash(this))}}.call(this,this.containers[e]));this.containers[e].containerCache.over=0}}this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpacity&&this.helper.css("opacity", -this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(e=0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}return false}b||this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helper=null;if(!b){for(e= -0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){d.Widget.prototype._trigger.apply(this,arguments)===false&&this.cancel()},_uiHash:function(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null}}});d.extend(d.ui.sortable,{version:"1.9m2"})})(jQuery); -jQuery.effects||function(f){function k(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1], -16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return l.transparent;return l[f.trim(c).toLowerCase()]}function q(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return k(b)}function m(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle, -a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function n(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in r||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function s(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function j(c,a,b,d){if(typeof c=="object"){d= -a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(f.isFunction(b)){d=b;b=null}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=q(b.elem,a);b.end=k(b.end);b.colorInit= -true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var l={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189, -183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255, -165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},o=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=n(m.call(this)),p,t=e.attr("className");f.each(o,function(u, -i){c[i]&&e[i+"Class"](c[i])});p=n(m.call(this));e.attr("className",t);e.animate(s(h,p),a,b,function(){f.each(o,function(u,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a? -f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===undefined?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.9m2",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!== -null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent(); -var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"}); -c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=j.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,show:function(c){if(!c|| -typeof c=="number"||f.fx.speeds[c])return this._show.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c])return this._hide.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||typeof c=="boolean"||f.isFunction(c))return this.__toggle.apply(this, -arguments);else{var a=j.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c, -a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+ -b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2, -10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)* -a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c, -a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c, -a,b,d,e,g){if(g==undefined)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0, -d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery); -(function(b){b.effects.blind=function(c){return this.queue(function(){var a=b(this),g=["position","top","left"],f=b.effects.setMode(a,c.options.mode||"hide"),d=c.options.direction||"vertical";b.effects.save(a,g);a.show();var e=b.effects.createWrapper(a).css({overflow:"hidden"}),h=d=="vertical"?"height":"width";d=d=="vertical"?e.height():e.width();f=="show"&&e.css(h,0);var i={};i[h]=f=="show"?d:0;e.animate(i,c.duration,c.options.easing,function(){f=="hide"&&a.hide();b.effects.restore(a,g);b.effects.removeWrapper(a); -c.callback&&c.callback.apply(a[0],arguments);a.dequeue()})})}})(jQuery); -(function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","left"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWidth({margin:true})/ -3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restore(a,l);e.effects.removeWrapper(a); -b.callback&&b.callback.apply(this,arguments)})}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments)})}a.queue("fx",function(){a.dequeue()});a.dequeue()})}})(jQuery); -(function(b){b.effects.clip=function(e){return this.queue(function(){var a=b(this),i=["position","top","left","height","width"],f=b.effects.setMode(a,e.options.mode||"hide"),c=e.options.direction||"vertical";b.effects.save(a,i);a.show();var d=b.effects.createWrapper(a).css({overflow:"hidden"});d=a[0].tagName=="IMG"?d:a;var g={size:c=="vertical"?"height":"width",position:c=="vertical"?"top":"left"};c=c=="vertical"?d.height():d.width();if(f=="show"){d.css(g.size,0);d.css(g.position,c/2)}var h={};h[g.size]= -f=="show"?c:0;h[g.position]=f=="show"?0:c/2;d.animate(h,{queue:false,duration:e.duration,easing:e.options.easing,complete:function(){f=="hide"&&a.hide();b.effects.restore(a,i);b.effects.removeWrapper(a);e.callback&&e.callback.apply(a[0],arguments);a.dequeue()}})})}})(jQuery); -(function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","left","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true})/2:a.outerWidth({margin:true})/2);if(e=="show")a.css("opacity",0).css(f,b=="pos"?-g:g);var i={opacity:e=="show"?1: -0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); -(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f= -0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+ -e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery); -(function(b){b.effects.fade=function(a){return this.queue(function(){var c=b(this),d=b.effects.setMode(c,a.options.mode||"hide");c.animate({opacity:d},{queue:false,duration:a.duration,easing:a.options.easing,complete:function(){a.callback&&a.callback.apply(this,arguments);c.dequeue()}})})}})(jQuery); -(function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","left"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1],10)/100* -f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery); -(function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="show"&&!b.support.opacity&& -this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); -(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c<times;c++){b.animate({opacity:animateTo},duration,a.options.easing);animateTo=(animateTo+1)%2}b.animate({opacity:animateTo},duration, -a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()}).dequeue()})}})(jQuery); -(function(c){c.effects.puff=function(b){return this.queue(function(){var a=c(this),e=c.effects.setMode(a,b.options.mode||"hide"),g=parseInt(b.options.percent,10)||150,h=g/100,i={height:a.height(),width:a.width()};c.extend(b.options,{fade:true,mode:e,percent:e=="hide"?g:100,from:e=="hide"?i:{height:i.height*h,width:i.width*h}});a.effect("scale",b.options,b.duration,b.callback);a.dequeue()})};c.effects.scale=function(b){return this.queue(function(){var a=c(this),e=c.extend(true,{},b.options),g=c.effects.setMode(a, -b.options.mode||"effect"),h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:g=="hide"?0:100),i=b.options.direction||"both",f=b.options.origin;if(g!="effect"){e.origin=f||["middle","center"];e.restore=true}f={height:a.height(),width:a.width()};a.from=b.options.from||(g=="show"?{height:0,width:0}:f);h={y:i!="horizontal"?h/100:1,x:i!="vertical"?h/100:1};a.to={height:f.height*h.y,width:f.width*h.x};if(b.options.fade){if(g=="show"){a.from.opacity=0;a.to.opacity=1}if(g=="hide"){a.from.opacity= -1;a.to.opacity=0}}e.from=a.from;e.to=a.to;e.mode=g;a.effect("size",e,b.duration,b.callback);a.dequeue()})};c.effects.size=function(b){return this.queue(function(){var a=c(this),e=["position","top","left","width","height","overflow","opacity"],g=["position","top","left","overflow","opacity"],h=["width","height","overflow"],i=["fontSize"],f=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],k=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=c.effects.setMode(a, -b.options.mode||"effect"),n=b.options.restore||false,m=b.options.scale||"both",l=b.options.origin,j={height:a.height(),width:a.width()};a.from=b.options.from||j;a.to=b.options.to||j;if(l){l=c.effects.getBaseline(l,j);a.from.top=(j.height-a.from.height)*l.y;a.from.left=(j.width-a.from.width)*l.x;a.to.top=(j.height-a.to.height)*l.y;a.to.left=(j.width-a.to.width)*l.x}var d={from:{y:a.from.height/j.height,x:a.from.width/j.width},to:{y:a.to.height/j.height,x:a.to.width/j.width}};if(m=="box"||m=="both"){if(d.from.y!= -d.to.y){e=e.concat(f);a.from=c.effects.setTransition(a,f,d.from.y,a.from);a.to=c.effects.setTransition(a,f,d.to.y,a.to)}if(d.from.x!=d.to.x){e=e.concat(k);a.from=c.effects.setTransition(a,k,d.from.x,a.from);a.to=c.effects.setTransition(a,k,d.to.x,a.to)}}if(m=="content"||m=="both")if(d.from.y!=d.to.y){e=e.concat(i);a.from=c.effects.setTransition(a,i,d.from.y,a.from);a.to=c.effects.setTransition(a,i,d.to.y,a.to)}c.effects.save(a,n?e:g);a.show();c.effects.createWrapper(a);a.css("overflow","hidden").css(a.from); -if(m=="content"||m=="both"){f=f.concat(["marginTop","marginBottom"]).concat(i);k=k.concat(["marginLeft","marginRight"]);h=e.concat(f).concat(k);a.find("*[width]").each(function(){child=c(this);n&&c.effects.save(child,h);var o={height:child.height(),width:child.width()};child.from={height:o.height*d.from.y,width:o.width*d.from.x};child.to={height:o.height*d.to.y,width:o.width*d.to.x};if(d.from.y!=d.to.y){child.from=c.effects.setTransition(child,f,d.from.y,child.from);child.to=c.effects.setTransition(child, -f,d.to.y,child.to)}if(d.from.x!=d.to.x){child.from=c.effects.setTransition(child,k,d.from.x,child.from);child.to=c.effects.setTransition(child,k,d.to.x,child.to)}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){n&&c.effects.restore(child,h)})})}a.animate(a.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){a.to.opacity===0&&a.css("opacity",a.from.opacity);p=="hide"&&a.hide();c.effects.restore(a,n?e:g);c.effects.removeWrapper(a);b.callback&& -b.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); -(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","left"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="pos"?"-=":"+=")+ -e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++)b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery); -(function(c){c.effects.slide=function(d){return this.queue(function(){var a=c(this),h=["position","top","left"],e=c.effects.setMode(a,d.options.mode||"show"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a).css({overflow:"hidden"});var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true}):a.outerWidth({margin:true}));if(e=="show")a.css(f,b=="pos"?-g:g);var i={};i[f]=(e=="show"?b=="pos"? -"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); -(function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments); -b.dequeue()})})}})(jQuery); -(function(d){d.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},_create:function(){var a=this.options,b=this;this.running=0;this.element.addClass("ui-accordion ui-widget ui-helper-reset"); -this.element.children("li").addClass("ui-accordion-li-fix");this.headers=this.element.find(a.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){d(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){d(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){d(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){d(this).removeClass("ui-state-focus")});this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); -if(a.navigation){var c=this.element.find("a").filter(a.navigationFilter);if(c.length){var f=c.closest(".ui-accordion-header");this.active=f.length?f:c.closest(".ui-accordion-content").prev()}}this.active=this._findActive(this.active||a.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass("ui-accordion-content-active");this._createIcons();this.resize();this.element.attr("role","tablist");this.headers.attr("role", -"tab").bind("keydown",function(g){return b._keydown(g)}).next().attr("role","tabpanel");this.headers.not(this.active||"").attr("aria-expanded","false").attr("tabIndex","-1").next().hide();this.active.length?this.active.attr("aria-expanded","true").attr("tabIndex","0"):this.headers.eq(0).attr("tabIndex","0");d.browser.safari||this.headers.find("a").attr("tabIndex","-1");a.event&&this.headers.bind(a.event+".accordion",function(g){b._clickHandler.call(b,g,this);g.preventDefault()})},_createIcons:function(){var a= -this.options;if(a.icons){d("<span/>").addClass("ui-icon "+a.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind(".accordion").removeData("accordion"); -this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(a.autoHeight||a.fillHeight)b.css("height", -"");return this},_setOption:function(a,b){this._superApply("_setOption",arguments);a=="active"&&this.activate(b);if(a=="icons"){this._destroyIcons();b&&this._createIcons()}},_keydown:function(a){var b=d.ui.keyCode;if(!(this.options.disabled||a.altKey||a.ctrlKey)){var c=this.headers.length,f=this.headers.index(a.target),g=false;switch(a.keyCode){case b.RIGHT:case b.DOWN:g=this.headers[(f+1)%c];break;case b.LEFT:case b.UP:g=this.headers[(f-1+c)%c];break;case b.SPACE:case b.ENTER:this._clickHandler({target:a.target}, -a.target);a.preventDefault()}if(g){d(a.target).attr("tabIndex","-1");d(g).attr("tabIndex","0");g.focus();return false}return true}},resize:function(){var a=this.options,b;if(a.fillSpace){if(d.browser.msie){var c=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}b=this.element.parent().height();d.browser.msie&&this.element.parent().css("overflow",c);this.headers.each(function(){b-=d(this).outerHeight(true)});this.headers.next().each(function(){d(this).height(Math.max(0, -b-d(this).innerHeight()+d(this).height()))}).css("overflow","auto")}else if(a.autoHeight){b=0;this.headers.next().each(function(){b=Math.max(b,d(this).height())}).height(b)}return this},activate:function(a){this.options.active=a;a=this._findActive(a)[0];this._clickHandler({target:a},a);return this},_findActive:function(a){return a?typeof a=="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===false?d([]):this.headers.filter(":eq(0)")},_clickHandler:function(a,b){var c= -this.options;if(!c.disabled)if(a.target){a=d(a.currentTarget||b);b=a[0]==this.active[0];c.active=c.collapsible&&b?false:d(".ui-accordion-header",this.element).index(a);if(!(this.running||!c.collapsible&&b)){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(c.icons.headerSelected).addClass(c.icons.header);if(!b){a.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui-icon").removeClass(c.icons.header).addClass(c.icons.headerSelected); -a.next().addClass("ui-accordion-content-active")}e=a.next();f=this.active.next();g={options:c,newHeader:b&&c.collapsible?d([]):a,oldHeader:this.active,newContent:b&&c.collapsible?d([]):e,oldContent:f};c=this.headers.index(this.active[0])>this.headers.index(a[0]);this.active=b?d([]):a;this._toggle(e,f,g,b,c)}}else if(c.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(c.icons.headerSelected).addClass(c.icons.header); -this.active.next().addClass("ui-accordion-content-active");var f=this.active.next(),g={options:c,newHeader:d([]),oldHeader:c.active,newContent:d([]),oldContent:f},e=this.active=d([]);this._toggle(e,f,g)}},_toggle:function(a,b,c,f,g){var e=this.options,k=this;this.toShow=a;this.toHide=b;this.data=c;var i=function(){if(k)return k._completed.apply(k,arguments)};this._trigger("changestart",null,this.data);this.running=b.size()===0?a.size():b.size();if(e.animated){c={};c=e.collapsible&&f?{toShow:d([]), -toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace}:{toShow:a,toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace};if(!e.proxied)e.proxied=e.animated;if(!e.proxiedDuration)e.proxiedDuration=e.duration;e.animated=d.isFunction(e.proxied)?e.proxied(c):e.proxied;e.duration=d.isFunction(e.proxiedDuration)?e.proxiedDuration(c):e.proxiedDuration;f=d.ui.accordion.animations;var h=e.duration,j=e.animated;if(j&&!f[j]&&!d.easing[j])j="slide";f[j]||(f[j]=function(l){this.slide(l,{easing:j, -duration:h||700})});f[j](c)}else{if(e.collapsible&&f)a.toggle();else{b.hide();a.show()}i(true)}b.prev().attr("aria-expanded","false").attr("tabIndex","-1").blur();a.prev().attr("aria-expanded","true").attr("tabIndex","0").focus()},_completed:function(a){var b=this.options;this.running=a?0:--this.running;if(!this.running){b.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");this._trigger("change",null,this.data)}}});d.extend(d.ui.accordion, -{version:"1.9m2",animations:{slide:function(a,b){a=d.extend({easing:"swing",duration:300},a,b);if(a.toHide.size())if(a.toShow.size()){var c=a.toShow.css("overflow"),f=0,g={},e={},k;b=a.toShow;k=b[0].style.width;b.width(parseInt(b.parent().width(),10)-parseInt(b.css("paddingLeft"),10)-parseInt(b.css("paddingRight"),10)-(parseInt(b.css("borderLeftWidth"),10)||0)-(parseInt(b.css("borderRightWidth"),10)||0));d.each(["height","paddingTop","paddingBottom"],function(i,h){e[h]="hide";i=(""+d.css(a.toShow[0], -h)).match(/^([\d+-.]+)(.*)$/);g[h]={value:i[1],unit:i[2]||"px"}});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(e,{step:function(i,h){if(h.prop=="height")f=h.end-h.start===0?0:(h.now-h.start)/(h.end-h.start);a.toShow[0].style[h.prop]=f*g[h.prop].value+g[h.prop].unit},duration:a.duration,easing:a.easing,complete:function(){a.autoHeight||a.toShow.css("height","");a.toShow.css("width",k);a.toShow.css({overflow:c});a.complete()}})}else a.toHide.animate({height:"hide"}, -a);else a.toShow.animate({height:"show"},a)},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:200})}}})})(jQuery); -(function(e){e.widget("ui.autocomplete",{options:{minLength:1,delay:300},_create:function(){var a=this,d=this.element[0].ownerDocument;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){var b=e.ui.keyCode;switch(c.keyCode){case b.PAGE_UP:a._move("previousPage",c);break;case b.PAGE_DOWN:a._move("nextPage",c);break;case b.UP:a._move("previous",c);c.preventDefault(); -break;case b.DOWN:a._move("next",c);c.preventDefault();break;case b.ENTER:case b.NUMPAD_ENTER:a.menu.active&&c.preventDefault();case b.TAB:if(!a.menu.active)return;a.menu.select(c);break;case b.ESCAPE:a.element.val(a.term);a.close(c);break;case b.LEFT:case b.RIGHT:case b.SHIFT:case b.CONTROL:case b.ALT:case b.COMMAND:case b.COMMAND_RIGHT:case b.INSERT:case b.CAPS_LOCK:case b.END:case b.HOME:break;default:clearTimeout(a.searching);a.searching=setTimeout(function(){a.search(null,c)},a.options.delay); -break}}).bind("focus.autocomplete",function(){a.selectedItem=null;a.previous=a.element.val()}).bind("blur.autocomplete",function(c){clearTimeout(a.searching);a.closing=setTimeout(function(){a.close(c);a._change(c)},150)});this._initSource();this.response=function(){return a._response.apply(a,arguments)};this.menu=e("<ul></ul>").addClass("ui-autocomplete").appendTo("body",d).mousedown(function(){setTimeout(function(){clearTimeout(a.closing)},13)}).menu({input:e(),focus:function(c,b){b=b.item.data("item.autocomplete"); -false!==a._trigger("focus",null,{item:b})&&/^key/.test(c.originalEvent.type)&&a.element.val(b.value)},select:function(c,b){b=b.item.data("item.autocomplete");false!==a._trigger("select",c,{item:b})&&a.element.val(b.value);a.close(c);c=a.previous;if(a.element[0]!==d.activeElement){a.element.focus();a.previous=c}a.selectedItem=b},blur:function(){a.menu.element.is(":visible")&&a.element.val(a.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");e.fn.bgiframe&&this.menu.element.bgiframe()}, -destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");this.menu.element.remove();this._super("destroy")},_setOption:function(a){this._superApply("_setOption",arguments);a==="source"&&this._initSource()},_initSource:function(){var a,d;if(e.isArray(this.options.source)){a=this.options.source;this.source=function(c,b){b(e.ui.autocomplete.filter(a,c.term))}}else if(typeof this.options.source=== -"string"){d=this.options.source;this.source=function(c,b){e.getJSON(d,c,b)}}else this.source=this.options.source},search:function(a,d){a=a!=null?a:this.element.val();if(a.length<this.options.minLength)return this.close(d);clearTimeout(this.closing);if(this._trigger("search")!==false)return this._search(a)},_search:function(a){this.term=this.element.addClass("ui-autocomplete-loading").val();this.source({term:a},this.response)},_response:function(a){if(a.length){a=this._normalize(a);this._suggest(a); -this._trigger("open")}else this.close();this.element.removeClass("ui-autocomplete-loading")},close:function(a){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this._trigger("close",a);this.menu.element.hide();this.menu.deactivate()}},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(a){if(a.length&&a[0].label&&a[0].value)return a;return e.map(a,function(d){if(typeof d==="string")return{label:d,value:d};return e.extend({label:d.label|| -d.value,value:d.value||d.label},d)})},_suggest:function(a){var d=this.menu.element.empty().zIndex(this.element.zIndex()+1),c;this._renderMenu(d,a);this.menu.deactivate();this.menu.refresh();this.menu.element.show().position({my:"left top",at:"left bottom",of:this.element,collision:"none"});a=d.width("").width();c=this.element.width();d.width(Math.max(a,c))},_renderMenu:function(a,d){var c=this;e.each(d,function(b,f){c._renderItem(a,f)})},_renderItem:function(a,d){return e("<li></li>").data("item.autocomplete", -d).append("<a>"+d.label+"</a>").appendTo(a)},_move:function(a,d){if(this.menu.element.is(":visible"))if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term);this.menu.deactivate()}else this.menu[a](d);else this.search(null,d)},widget:function(){return this.menu.element}});e.extend(e.ui.autocomplete,{escapeRegex:function(a){return a.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")},filter:function(a,d){var c=new RegExp(e.ui.autocomplete.escapeRegex(d), -"i");return e.grep(a,function(b){return c.test(b.label||b.value||b)})}})})(jQuery); -(function(a){var g,i=function(b){a(":ui-button",b.target.form).each(function(){var c=a(this).data("button");setTimeout(function(){c.refresh()},1)})},h=function(b){var c=b.name,d=b.form,e=a([]);if(c)e=d?a(d).find("[name='"+c+"']"):a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form});return e};a.widget("ui.button",{options:{text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",i);this._determineButtonType(); -this.hasTitle=!!this.buttonElement.attr("title");var b=this,c=this.options,d=this.type==="checkbox"||this.type==="radio",e="ui-state-hover"+(!d?" ui-state-active":"");if(c.label===null)c.label=this.buttonElement.html();if(this.element.is(":disabled"))c.disabled=true;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){if(!c.disabled){a(this).addClass("ui-state-hover");this===g&&a(this).addClass("ui-state-active")}}).bind("mouseleave.button", -function(){c.disabled||a(this).removeClass(e)}).bind("focus.button",function(){a(this).addClass("ui-state-focus")}).bind("blur.button",function(){a(this).removeClass("ui-state-focus")});d&&this.element.bind("change.button",function(){b.refresh()});if(this.type==="checkbox")this.buttonElement.bind("click.button",function(){if(c.disabled)return false;a(this).toggleClass("ui-state-active");b.buttonElement.attr("aria-pressed",b.element[0].checked)});else if(this.type==="radio")this.buttonElement.bind("click.button", -function(){if(c.disabled)return false;a(this).addClass("ui-state-active");b.buttonElement.attr("aria-pressed",true);var f=b.element[0];h(f).not(f).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed",false)});else{this.buttonElement.bind("mousedown.button",function(){if(c.disabled)return false;a(this).addClass("ui-state-active");g=this;a(document).one("mouseup",function(){g=null})}).bind("mouseup.button",function(){if(c.disabled)return false;a(this).removeClass("ui-state-active")}).bind("keydown.button", -function(f){if(c.disabled)return false;if(f.keyCode==a.ui.keyCode.SPACE||f.keyCode==a.ui.keyCode.ENTER)a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")});this.buttonElement.is("a")&&this.buttonElement.keyup(function(f){f.keyCode===a.ui.keyCode.SPACE&&a(this).click()})}this._setOption("disabled",c.disabled)},_determineButtonType:function(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.element.is("input")? -"input":"button";if(this.type==="checkbox"||this.type==="radio"){this.buttonElement=this.element.parents().last().find("[for="+this.element.attr("id")+"]");this.element.addClass("ui-helper-hidden-accessible");var b=this.element.is(":checked");b&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",b)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass("ui-button ui-widget ui-state-default ui-corner-all ui-state-hover ui-state-active ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only").removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()); -this.hasTitle||this.buttonElement.removeAttr("title");this._super("destroy")},_setOption:function(b,c){this._superApply("_setOption",arguments);if(b==="disabled")c?this.element.attr("disabled",true):this.element.removeAttr("disabled");this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b);if(this.type==="radio")h(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed", -true):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed",false)});else if(this.type==="checkbox")this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed",true):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed",false)},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var b=this.buttonElement.removeClass("ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only"), -c=a("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary;if(d.primary||d.secondary){b.addClass("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary"));d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>");d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>");if(!this.options.text){b.addClass(e?"ui-button-icons-only":"ui-button-icon-only").removeClass("ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary"); -this.hasTitle||b.attr("title",c)}}else b.addClass("ui-button-text-only")}}});a.widget("ui.buttonset",{_create:function(){this.element.addClass("ui-buttonset");this._init()},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c);this._superApply("_setOption",arguments)},refresh:function(){this.buttons=this.element.find(":button, :submit, :reset, :checkbox, :radio, a, :data(button)").filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass("ui-corner-left").end().filter(":last").addClass("ui-corner-right").end().end()}, -destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");this._super("destroy")}})})(jQuery); -(function(d){function K(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._inDialog=this._datepickerShowing=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass= -"ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su", -"Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10", -minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false};d.extend(this._defaults,this.regional[""]);this.dpDiv=d('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}function E(a,b){d.extend(a, -b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}d.extend(d.ui,{datepicker:{version:"1.9m2"}});var y=(new Date).getTime();d.extend(K.prototype,{markerClassName:"hasDatepicker",log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){E(this._defaults,a||{});return this},_attachDatepicker:function(a,b){var c=null;for(var e in this._defaults){var f=a.getAttribute("date:"+e);if(f){c=c||{};try{c[e]=eval(f)}catch(h){c[e]= -f}}}e=a.nodeName.toLowerCase();f=e=="div"||e=="span";if(!a.id){this.uuid+=1;a.id="dp"+this.uuid}var i=this._newInst(d(a),f);i.settings=d.extend({},b||{},c||{});if(e=="input")this._connectDatepicker(a,i);else f&&this._inlineDatepicker(a,i)},_newInst:function(a,b){return{id:a[0].id.replace(/([^A-Za-z0-9_])/g,"\\\\$1"),input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:!b?this.dpDiv:d('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')}}, -_connectDatepicker:function(a,b){var c=d(a);b.append=d([]);b.trigger=d([]);if(!c.hasClass(this.markerClassName)){this._attachments(c,b);c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});this._autoSize(b);d.data(a,"datepicker",b)}},_attachments:function(a,b){var c=this._get(b,"appendText"),e=this._get(b,"isRTL");b.append&& -b.append.remove();if(c){b.append=d('<span class="'+this._appendClass+'">'+c+"</span>");a[e?"before":"after"](b.append)}a.unbind("focus",this._showDatepicker);b.trigger&&b.trigger.remove();c=this._get(b,"showOn");if(c=="focus"||c=="both")a.focus(this._showDatepicker);if(c=="button"||c=="both"){c=this._get(b,"buttonText");var f=this._get(b,"buttonImage");b.trigger=d(this._get(b,"buttonImageOnly")?d("<img/>").addClass(this._triggerClass).attr({src:f,alt:c,title:c}):d('<button type="button"></button>').addClass(this._triggerClass).html(f== -""?c:d("<img/>").attr({src:f,alt:c,title:c})));a[e?"before":"after"](b.trigger);b.trigger.click(function(){d.datepicker._datepickerShowing&&d.datepicker._lastInput==a[0]?d.datepicker._hideDatepicker():d.datepicker._showDatepicker(a[0]);return false})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var e=function(f){for(var h=0,i=0,g=0;g<f.length;g++)if(f[g].length>h){h=f[g].length;i=g}return i};b.setMonth(e(this._get(a, -c.match(/MM/)?"monthNames":"monthNamesShort")));b.setDate(e(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=d(a);if(!c.hasClass(this.markerClassName)){c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});d.data(a,"datepicker",b);this._setDate(b,this._getDefaultDate(b), -true);this._updateDatepicker(b);this._updateAlternate(b)}},_dialogDatepicker:function(a,b,c,e,f){a=this._dialogInst;if(!a){this.uuid+=1;this._dialogInput=d('<input type="text" id="'+("dp"+this.uuid)+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');this._dialogInput.keydown(this._doKeyDown);d("body").append(this._dialogInput);a=this._dialogInst=this._newInst(this._dialogInput,false);a.settings={};d.data(this._dialogInput[0],"datepicker",a)}E(a.settings,e||{});b=b&&b.constructor== -Date?this._formatDate(a,b):b;this._dialogInput.val(b);this._pos=f?f.length?f:[f.pageX,f.pageY]:null;if(!this._pos)this._pos=[document.documentElement.clientWidth/2-100+(document.documentElement.scrollLeft||document.body.scrollLeft),document.documentElement.clientHeight/2-150+(document.documentElement.scrollTop||document.body.scrollTop)];this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");a.settings.onSelect=c;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]); -d.blockUI&&d.blockUI(this.dpDiv);d.data(this._dialogInput[0],"datepicker",a);return this},_destroyDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();d.removeData(a,"datepicker");if(e=="input"){c.append.remove();c.trigger.remove();b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else if(e=="div"||e=="span")b.removeClass(this.markerClassName).empty()}}, -_enableDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=false;c.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().removeClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f})}},_disableDatepicker:function(a){var b= -d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=true;c.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().addClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f});this._disabledInputs[this._disabledInputs.length]=a}},_isDisabledDatepicker:function(a){if(!a)return false; -for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return true;return false},_getInst:function(a){try{return d.data(a,"datepicker")}catch(b){throw"Missing instance data for this datepicker";}},_optionDatepicker:function(a,b,c){var e=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?d.extend({},d.datepicker._defaults):e?b=="all"?d.extend({},e.settings):this._get(e,b):null;var f=b||{};if(typeof b=="string"){f={};f[b]=c}if(e){this._curInst==e&& -this._hideDatepicker();var h=this._getDateDatepicker(a,true);E(e.settings,f);this._attachments(d(a),e);this._autoSize(e);this._setDateDatepicker(a,h);this._updateDatepicker(e)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){(a=this._getInst(a))&&this._updateDatepicker(a)},_setDateDatepicker:function(a,b){if(a=this._getInst(a)){this._setDate(a,b);this._updateDatepicker(a);this._updateAlternate(a)}},_getDateDatepicker:function(a,b){(a=this._getInst(a))&& -!a.inline&&this._setDateFromField(a,b);return a?this._getDate(a):null},_doKeyDown:function(a){var b=d.datepicker._getInst(a.target),c=true,e=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=true;if(d.datepicker._datepickerShowing)switch(a.keyCode){case 9:d.datepicker._hideDatepicker();c=false;break;case 13:c=d("td."+d.datepicker._dayOverClass,b.dpDiv).add(d("td."+d.datepicker._currentClass,b.dpDiv));c[0]?d.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,c[0]):d.datepicker._hideDatepicker(); -return false;case 27:d.datepicker._hideDatepicker();break;case 33:d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 34:d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 35:if(a.ctrlKey||a.metaKey)d.datepicker._clearDate(a.target);c=a.ctrlKey||a.metaKey;break;case 36:if(a.ctrlKey||a.metaKey)d.datepicker._gotoToday(a.target);c=a.ctrlKey|| -a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?+1:-1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 38:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,-7,"D");c=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?-1:+1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target, -a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 40:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,+7,"D");c=a.ctrlKey||a.metaKey;break;default:c=false}else if(a.keyCode==36&&a.ctrlKey)d.datepicker._showDatepicker(this);else c=false;if(c){a.preventDefault();a.stopPropagation()}},_doKeyPress:function(a){var b=d.datepicker._getInst(a.target);if(d.datepicker._get(b,"constrainInput")){b=d.datepicker._possibleChars(d.datepicker._get(b,"dateFormat")); -var c=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||c<" "||!b||b.indexOf(c)>-1}},_doKeyUp:function(a){a=d.datepicker._getInst(a.target);if(a.input.val()!=a.lastVal)try{if(d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,d.datepicker._getFormatConfig(a))){d.datepicker._setDateFromField(a);d.datepicker._updateAlternate(a);d.datepicker._updateDatepicker(a)}}catch(b){d.datepicker.log(b)}return true},_showDatepicker:function(a){a=a.target|| -a;if(a.nodeName.toLowerCase()!="input")a=d("input",a.parentNode)[0];if(!(d.datepicker._isDisabledDatepicker(a)||d.datepicker._lastInput==a)){var b=d.datepicker._getInst(a);d.datepicker._curInst&&d.datepicker._curInst!=b&&d.datepicker._curInst.dpDiv.stop(true,true);var c=d.datepicker._get(b,"beforeShow");E(b.settings,c?c.apply(a,[a,b]):{});b.lastVal=null;d.datepicker._lastInput=a;d.datepicker._setDateFromField(b);if(d.datepicker._inDialog)a.value="";if(!d.datepicker._pos){d.datepicker._pos=d.datepicker._findPos(a); -d.datepicker._pos[1]+=a.offsetHeight}var e=false;d(a).parents().each(function(){e|=d(this).css("position")=="fixed";return!e});if(e&&d.browser.opera){d.datepicker._pos[0]-=document.documentElement.scrollLeft;d.datepicker._pos[1]-=document.documentElement.scrollTop}c={left:d.datepicker._pos[0],top:d.datepicker._pos[1]};d.datepicker._pos=null;b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});d.datepicker._updateDatepicker(b);c=d.datepicker._checkOffset(b,c,e);b.dpDiv.css({position:d.datepicker._inDialog&& -d.blockUI?"static":e?"fixed":"absolute",display:"none",left:c.left+"px",top:c.top+"px"});if(!b.inline){c=d.datepicker._get(b,"showAnim");var f=d.datepicker._get(b,"duration"),h=function(){d.datepicker._datepickerShowing=true;var i=d.datepicker._getBorders(b.dpDiv);b.dpDiv.find("iframe.ui-datepicker-cover").css({left:-i[0],top:-i[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})};b.dpDiv.zIndex(d(a).zIndex()+1);d.effects&&d.effects[c]?b.dpDiv.show(c,d.datepicker._get(b,"showOptions"),f, -h):b.dpDiv[c||"show"](c?f:null,h);if(!c||!f)h();b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus();d.datepicker._curInst=b}}},_updateDatepicker:function(a){var b=this,c=d.datepicker._getBorders(a.dpDiv);a.dpDiv.empty().append(this._generateHTML(a)).find("iframe.ui-datepicker-cover").css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){d(this).removeClass("ui-state-hover"); -this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).removeClass("ui-datepicker-prev-hover");this.className.indexOf("ui-datepicker-next")!=-1&&d(this).removeClass("ui-datepicker-next-hover")}).bind("mouseover",function(){if(!b._isDisabledDatepicker(a.inline?a.dpDiv.parent()[0]:a.input[0])){d(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");d(this).addClass("ui-state-hover");this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).addClass("ui-datepicker-prev-hover"); -this.className.indexOf("ui-datepicker-next")!=-1&&d(this).addClass("ui-datepicker-next-hover")}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();c=this._getNumberOfMonths(a);var e=c[1];e>1?a.dpDiv.addClass("ui-datepicker-multi-"+e).css("width",17*e+"em"):a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");a.dpDiv[(c[0]!=1||c[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"); -a==d.datepicker._curInst&&d.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input.focus()},_getBorders:function(a){var b=function(c){return{thin:1,medium:2,thick:3}[c]||c};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var e=a.dpDiv.outerWidth(),f=a.dpDiv.outerHeight(),h=a.input?a.input.outerWidth():0,i=a.input?a.input.outerHeight():0,g=document.documentElement.clientWidth+d(document).scrollLeft(), -k=document.documentElement.clientHeight+d(document).scrollTop();b.left-=this._get(a,"isRTL")?e-h:0;b.left-=c&&b.left==a.input.offset().left?d(document).scrollLeft():0;b.top-=c&&b.top==a.input.offset().top+i?d(document).scrollTop():0;b.left-=Math.min(b.left,b.left+e>g&&g>e?Math.abs(b.left+e-g):0);b.top-=Math.min(b.top,b.top+f>k&&k>f?Math.abs(f+i):0);return b},_findPos:function(a){for(var b=this._get(this._getInst(a),"isRTL");a&&(a.type=="hidden"||a.nodeType!=1);)a=a[b?"previousSibling":"nextSibling"]; -a=d(a).offset();return[a.left,a.top]},_hideDatepicker:function(a){var b=this._curInst;if(!(!b||a&&b!=d.data(a,"datepicker")))if(this._datepickerShowing){a=this._get(b,"showAnim");var c=this._get(b,"duration"),e=function(){d.datepicker._tidyDialog(b);this._curInst=null};d.effects&&d.effects[a]?b.dpDiv.hide(a,d.datepicker._get(b,"showOptions"),c,e):b.dpDiv[a=="slideDown"?"slideUp":a=="fadeIn"?"fadeOut":"hide"](a?c:null,e);a||e();if(a=this._get(b,"onClose"))a.apply(b.input?b.input[0]:null,[b.input?b.input.val(): -"",b]);this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if(d.blockUI){d.unblockUI();d("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(d.datepicker._curInst){a=d(a.target);a[0].id!=d.datepicker._mainDivId&&a.parents("#"+d.datepicker._mainDivId).length==0&&!a.hasClass(d.datepicker.markerClassName)&& -!a.hasClass(d.datepicker._triggerClass)&&d.datepicker._datepickerShowing&&!(d.datepicker._inDialog&&d.blockUI)&&d.datepicker._hideDatepicker()}},_adjustDate:function(a,b,c){a=d(a);var e=this._getInst(a[0]);if(!this._isDisabledDatepicker(a[0])){this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c);this._updateDatepicker(e)}},_gotoToday:function(a){a=d(a);var b=this._getInst(a[0]);if(this._get(b,"gotoCurrent")&&b.currentDay){b.selectedDay=b.currentDay;b.drawMonth=b.selectedMonth=b.currentMonth; -b.drawYear=b.selectedYear=b.currentYear}else{var c=new Date;b.selectedDay=c.getDate();b.drawMonth=b.selectedMonth=c.getMonth();b.drawYear=b.selectedYear=c.getFullYear()}this._notifyChange(b);this._adjustDate(a)},_selectMonthYear:function(a,b,c){a=d(a);var e=this._getInst(a[0]);e._selectingMonthYear=false;e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10);this._notifyChange(e);this._adjustDate(a)},_clickMonthYear:function(a){a=this._getInst(d(a)[0]); -a.input&&a._selectingMonthYear&&!d.browser.msie&&a.input.focus();a._selectingMonthYear=!a._selectingMonthYear},_selectDay:function(a,b,c,e){var f=d(a);if(!(d(e).hasClass(this._unselectableClass)||this._isDisabledDatepicker(f[0]))){f=this._getInst(f[0]);f.selectedDay=f.currentDay=d("a",e).html();f.selectedMonth=f.currentMonth=b;f.selectedYear=f.currentYear=c;this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))}},_clearDate:function(a){a=d(a);this._getInst(a[0]);this._selectDate(a, -"")},_selectDate:function(a,b){a=this._getInst(d(a)[0]);b=b!=null?b:this._formatDate(a);a.input&&a.input.val(b);this._updateAlternate(a);var c=this._get(a,"onSelect");if(c)c.apply(a.input?a.input[0]:null,[b,a]);else a.input&&a.input.trigger("change");if(a.inline)this._updateDatepicker(a);else{this._hideDatepicker();this._lastInput=a.input[0];typeof a.input[0]!="object"&&a.input.focus();this._lastInput=null}},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")|| -this._get(a,"dateFormat"),e=this._getDate(a),f=this.formatDate(c,e,this._getFormatConfig(a));d(b).each(function(){d(this).val(f)})}},noWeekends:function(a){a=a.getDay();return[a>0&&a<6,""]},iso8601Week:function(a){a=new Date(a.getTime());a.setDate(a.getDate()+4-(a.getDay()||7));var b=a.getTime();a.setMonth(0);a.setDate(1);return Math.floor(Math.round((b-a)/864E5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null; -for(var e=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,h=(c?c.dayNames:null)||this._defaults.dayNames,i=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,k=c=-1,l=-1,u=-1,j=false,o=function(p){(p=z+1<a.length&&a.charAt(z+1)==p)&&z++;return p},m=function(p){o(p);p=new RegExp("^\\d{1,"+(p=="@"?14:p=="!"?20:p=="y"?4:p=="o"?3:2)+"}");p=b.substring(s).match(p);if(!p)throw"Missing number at position "+ -s;s+=p[0].length;return parseInt(p[0],10)},n=function(p,w,G){p=o(p)?G:w;for(w=0;w<p.length;w++)if(b.substr(s,p[w].length)==p[w]){s+=p[w].length;return w+1}throw"Unknown name at position "+s;},r=function(){if(b.charAt(s)!=a.charAt(z))throw"Unexpected literal at position "+s;s++},s=0,z=0;z<a.length;z++)if(j)if(a.charAt(z)=="'"&&!o("'"))j=false;else r();else switch(a.charAt(z)){case "d":l=m("d");break;case "D":n("D",f,h);break;case "o":u=m("o");break;case "m":k=m("m");break;case "M":k=n("M",i,g);break; -case "y":c=m("y");break;case "@":var v=new Date(m("@"));c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "!":v=new Date((m("!")-this._ticksTo1970)/1E4);c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "'":if(o("'"))r();else j=true;break;default:r()}if(c==-1)c=(new Date).getFullYear();else if(c<100)c+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c<=e?0:-100);if(u>-1){k=1;l=u;do{e=this._getDaysInMonth(c,k-1);if(l<=e)break;k++;l-=e}while(1)}v=this._daylightSavingAdjust(new Date(c, -k-1,l));if(v.getFullYear()!=c||v.getMonth()+1!=k||v.getDate()!=l)throw"Invalid date";return v},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1E7,formatDate:function(a,b,c){if(!b)return"";var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c? -c.dayNames:null)||this._defaults.dayNames,h=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort;c=(c?c.monthNames:null)||this._defaults.monthNames;var i=function(o){(o=j+1<a.length&&a.charAt(j+1)==o)&&j++;return o},g=function(o,m,n){m=""+m;if(i(o))for(;m.length<n;)m="0"+m;return m},k=function(o,m,n,r){return i(o)?r[m]:n[m]},l="",u=false;if(b)for(var j=0;j<a.length;j++)if(u)if(a.charAt(j)=="'"&&!i("'"))u=false;else l+=a.charAt(j);else switch(a.charAt(j)){case "d":l+=g("d",b.getDate(),2);break; -case "D":l+=k("D",b.getDay(),e,f);break;case "o":l+=g("o",(b.getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864E5,3);break;case "m":l+=g("m",b.getMonth()+1,2);break;case "M":l+=k("M",b.getMonth(),h,c);break;case "y":l+=i("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case "@":l+=b.getTime();break;case "!":l+=b.getTime()*1E4+this._ticksTo1970;break;case "'":if(i("'"))l+="'";else u=true;break;default:l+=a.charAt(j)}return l},_possibleChars:function(a){for(var b="",c=false, -e=function(h){(h=f+1<a.length&&a.charAt(f+1)==h)&&f++;return h},f=0;f<a.length;f++)if(c)if(a.charAt(f)=="'"&&!e("'"))c=false;else b+=a.charAt(f);else switch(a.charAt(f)){case "d":case "m":case "y":case "@":b+="0123456789";break;case "D":case "M":return null;case "'":if(e("'"))b+="'";else c=true;break;default:b+=a.charAt(f)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()!=a.lastVal){var c=this._get(a,"dateFormat"), -e=a.lastVal=a.input?a.input.val():null,f,h;f=h=this._getDefaultDate(a);var i=this._getFormatConfig(a);try{f=this.parseDate(c,e,i)||h}catch(g){this.log(g);e=b?"":e}a.selectedDay=f.getDate();a.drawMonth=a.selectedMonth=f.getMonth();a.drawYear=a.selectedYear=f.getFullYear();a.currentDay=e?f.getDate():0;a.currentMonth=e?f.getMonth():0;a.currentYear=e?f.getFullYear():0;this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))}, -_determineDate:function(a,b,c){var e=function(h){var i=new Date;i.setDate(i.getDate()+h);return i},f=function(h){try{return d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),h,d.datepicker._getFormatConfig(a))}catch(i){}var g=(h.toLowerCase().match(/^c/)?d.datepicker._getDate(a):null)||new Date,k=g.getFullYear(),l=g.getMonth();g=g.getDate();for(var u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,j=u.exec(h);j;){switch(j[2]||"d"){case "d":case "D":g+=parseInt(j[1],10);break;case "w":case "W":g+=parseInt(j[1], -10)*7;break;case "m":case "M":l+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break;case "y":case "Y":k+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break}j=u.exec(h)}return new Date(k,l,g)};if(b=(b=b==null?c:typeof b=="string"?f(b):typeof b=="number"?isNaN(b)?c:e(b):b)&&b.toString()=="Invalid Date"?c:b){b.setHours(0);b.setMinutes(0);b.setSeconds(0);b.setMilliseconds(0)}return this._daylightSavingAdjust(b)},_daylightSavingAdjust:function(a){if(!a)return null; -a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){var e=!b,f=a.selectedMonth,h=a.selectedYear;b=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=b.getDate();a.drawMonth=a.selectedMonth=a.currentMonth=b.getMonth();a.drawYear=a.selectedYear=a.currentYear=b.getFullYear();if((f!=a.selectedMonth||h!=a.selectedYear)&&!c)this._notifyChange(a);this._adjustInstDate(a);if(a.input)a.input.val(e?"":this._formatDate(a))},_getDate:function(a){return!a.currentYear|| -a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay))},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),e=this._get(a,"showButtonPanel"),f=this._get(a,"hideIfNoPrevNext"),h=this._get(a,"navigationAsDateFormat"),i=this._getNumberOfMonths(a),g=this._get(a,"showCurrentAtPos"),k=this._get(a,"stepMonths"),l=i[0]!=1||i[1]!=1,u=this._daylightSavingAdjust(!a.currentDay? -new Date(9999,9,9):new Date(a.currentYear,a.currentMonth,a.currentDay)),j=this._getMinMaxDate(a,"min"),o=this._getMinMaxDate(a,"max");g=a.drawMonth-g;var m=a.drawYear;if(g<0){g+=12;m--}if(o){var n=this._daylightSavingAdjust(new Date(o.getFullYear(),o.getMonth()-i[0]*i[1]+1,o.getDate()));for(n=j&&n<j?j:n;this._daylightSavingAdjust(new Date(m,g,1))>n;){g--;if(g<0){g=11;m--}}}a.drawMonth=g;a.drawYear=m;n=this._get(a,"prevText");n=!h?n:this.formatDate(n,this._daylightSavingAdjust(new Date(m,g-k,1)),this._getFormatConfig(a)); -n=this._canAdjustMonth(a,-1,m,g)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', -"+k+", 'M');\" title=\""+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>":f?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>";var r=this._get(a,"nextText");r=!h?r:this.formatDate(r,this._daylightSavingAdjust(new Date(m, -g+k,1)),this._getFormatConfig(a));f=this._canAdjustMonth(a,+1,m,g)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', +"+k+", 'M');\" title=\""+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>":f?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>";k=this._get(a,"currentText");r=this._get(a,"gotoCurrent")&& -a.currentDay?u:b;k=!h?k:this.formatDate(k,r,this._getFormatConfig(a));h=!a.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+y+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>":"";e=e?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?h:"")+(this._isInRange(a,r)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+ -y+".datepicker._gotoToday('#"+a.id+"');\">"+k+"</button>":"")+(c?"":h)+"</div>":"";h=parseInt(this._get(a,"firstDay"),10);h=isNaN(h)?0:h;k=this._get(a,"showWeek");r=this._get(a,"dayNames");this._get(a,"dayNamesShort");var s=this._get(a,"dayNamesMin"),z=this._get(a,"monthNames"),v=this._get(a,"monthNamesShort"),p=this._get(a,"beforeShowDay"),w=this._get(a,"showOtherMonths"),G=this._get(a,"selectOtherMonths");this._get(a,"calculateWeek");for(var L=this._getDefaultDate(a),H="",C=0;C<i[0];C++){for(var M= -"",D=0;D<i[1];D++){var I=this._daylightSavingAdjust(new Date(m,g,a.selectedDay)),t=" ui-corner-all",x="";if(l){x+='<div class="ui-datepicker-group';if(i[1]>1)switch(D){case 0:x+=" ui-datepicker-group-first";t=" ui-corner-"+(c?"right":"left");break;case i[1]-1:x+=" ui-datepicker-group-last";t=" ui-corner-"+(c?"left":"right");break;default:x+=" ui-datepicker-group-middle";t="";break}x+='">'}x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c? -f:n:"")+(/all|right/.test(t)&&C==0?c?n:f:"")+this._generateMonthYearHeader(a,g,m,j,o,C>0||D>0,z,v)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var A=k?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(t=0;t<7;t++){var q=(t+h)%7;A+="<th"+((t+h+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+r[q]+'">'+s[q]+"</span></th>"}x+=A+"</tr></thead><tbody>";A=this._getDaysInMonth(m,g);if(m==a.selectedYear&&g==a.selectedMonth)a.selectedDay=Math.min(a.selectedDay, -A);t=(this._getFirstDayOfMonth(m,g)-h+7)%7;A=l?6:Math.ceil((t+A)/7);q=this._daylightSavingAdjust(new Date(m,g,1-t));for(var N=0;N<A;N++){x+="<tr>";var O=!k?"":'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(q)+"</td>";for(t=0;t<7;t++){var F=p?p.apply(a.input?a.input[0]:null,[q]):[true,""],B=q.getMonth()!=g,J=B&&!G||!F[0]||j&&q<j||o&&q>o;O+='<td class="'+((t+h+6)%7>=5?" ui-datepicker-week-end":"")+(B?" ui-datepicker-other-month":"")+(q.getTime()==I.getTime()&&g==a.selectedMonth&& -a._keyEvent||L.getTime()==q.getTime()&&L.getTime()==I.getTime()?" "+this._dayOverClass:"")+(J?" "+this._unselectableClass+" ui-state-disabled":"")+(B&&!w?"":" "+F[1]+(q.getTime()==u.getTime()?" "+this._currentClass:"")+(q.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!B||w)&&F[2]?' title="'+F[2]+'"':"")+(J?"":' onclick="DP_jQuery_'+y+".datepicker._selectDay('#"+a.id+"',"+q.getMonth()+","+q.getFullYear()+', this);return false;"')+">"+(B&&!w?" ":J?'<span class="ui-state-default">'+q.getDate()+ -"</span>":'<a class="ui-state-default'+(q.getTime()==b.getTime()?" ui-state-highlight":"")+(q.getTime()==I.getTime()?" ui-state-active":"")+(B?" ui-priority-secondary":"")+'" href="#">'+q.getDate()+"</a>")+"</td>";q.setDate(q.getDate()+1);q=this._daylightSavingAdjust(q)}x+=O+"</tr>"}g++;if(g>11){g=0;m++}x+="</tbody></table>"+(l?"</div>"+(i[0]>0&&D==i[1]-1?'<div class="ui-datepicker-row-break"></div>':""):"");M+=x}H+=M}H+=e+(d.browser.msie&&parseInt(d.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>': -"");a._keyEvent=false;return H},_generateMonthYearHeader:function(a,b,c,e,f,h,i,g){var k=this._get(a,"changeMonth"),l=this._get(a,"changeYear"),u=this._get(a,"showMonthAfterYear"),j='<div class="ui-datepicker-title">',o="";if(h||!k)o+='<span class="ui-datepicker-month">'+i[b]+"</span>";else{i=e&&e.getFullYear()==c;var m=f&&f.getFullYear()==c;o+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+ -a.id+"');\">";for(var n=0;n<12;n++)if((!i||n>=e.getMonth())&&(!m||n<=f.getMonth()))o+='<option value="'+n+'"'+(n==b?' selected="selected"':"")+">"+g[n]+"</option>";o+="</select>"}u||(j+=o+(h||!(k&&l)?" ":""));if(h||!l)j+='<span class="ui-datepicker-year">'+c+"</span>";else{g=this._get(a,"yearRange").split(":");var r=(new Date).getFullYear();i=function(s){s=s.match(/c[+-].*/)?c+parseInt(s.substring(1),10):s.match(/[+-].*/)?r+parseInt(s,10):parseInt(s,10);return isNaN(s)?r:s};b=i(g[0]);g=Math.max(b, -i(g[1]||""));b=e?Math.max(b,e.getFullYear()):b;g=f?Math.min(g,f.getFullYear()):g;for(j+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)j+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";j+="</select>"}j+=this._get(a,"yearSuffix");if(u)j+=(h||!(k&&l)?" ":"")+o;j+="</div>";return j},_adjustInstDate:function(a,b,c){var e= -a.drawYear+(c=="Y"?b:0),f=a.drawMonth+(c=="M"?b:0);b=Math.min(a.selectedDay,this._getDaysInMonth(e,f))+(c=="D"?b:0);e=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,b)));a.selectedDay=e.getDate();a.drawMonth=a.selectedMonth=e.getMonth();a.drawYear=a.selectedYear=e.getFullYear();if(c=="M"||c=="Y")this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");b=c&&b<c?c:b;return b=a&&b>a?a:b},_notifyChange:function(a){var b=this._get(a, -"onChangeMonthYear");if(b)b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){a=this._get(a,"numberOfMonths");return a==null?[1,1]:typeof a=="number"?[1,a]:a},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,e){var f=this._getNumberOfMonths(a); -c=this._daylightSavingAdjust(new Date(c,e+(b<0?b:f[0]*f[1]),1));b<0&&c.setDate(this._getDaysInMonth(c.getFullYear(),c.getMonth()));return this._isInRange(a,c)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!a||b.getTime()<=a.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort:this._get(a, -"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,e){if(!b){a.currentDay=a.selectedDay;a.currentMonth=a.selectedMonth;a.currentYear=a.selectedYear}b=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(e,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),b,this._getFormatConfig(a))}});d.fn.datepicker= -function(a){if(!d.datepicker.initialized){d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv);d.datepicker.initialized=true}var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"))return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b)); -return this.each(function(){typeof a=="string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this].concat(b)):d.datepicker._attachDatepicker(this,a)})};d.datepicker=new K;d.datepicker.initialized=false;d.datepicker.uuid=(new Date).getTime();d.datepicker.version="1.9m2";window["DP_jQuery_"+y]=d})(jQuery); -(function(c){c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");var a=this,b=a.options,d=b.title||a.originalTitle||" ",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+ -b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g), -h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id", -e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"); -a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!== -b.uiDialog[0])d=Math.max(d,c(this).css("z-index"))});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+=1;d.uiDialog.css("z-index", -c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;d.next().length&&d.appendTo("body");a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false}else if(e.target=== -f[0]&&e.shiftKey){g.focus(1);return false}}});c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();a._trigger("open");a._isOpen=true;return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,function(){return!(d=true)});if(d){c.each(a, -function(g,f){g=c('<button type="button"></button>').text(g).click(function(){f.apply(b.element[0],arguments)}).appendTo(e);c.fn.button&&g.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging"); -b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size}}a=a===undefined?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position"); -a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop", -f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0];a=a||c.ui.dialog.prototype.options.position;if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(e,g){if(+b[e]===b[e]){d[e]=b[e];b[e]= -g}})}else if(typeof a==="object"){if("left"in a){b[0]="left";d[0]=a.left}else if("right"in a){b[0]="right";d[0]=-a.right}if("top"in a){b[1]="top";d[1]=a.top}else if("bottom"in a){b[1]="bottom";d[1]=-a.bottom}}(a=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position({my:b.join(" "),at:b.join(" "),offset:d.join(" "),of:window,collision:"fit",using:function(e){var g=c(this).css(e).offset().top;g<0&&c(this).css("top",e.top-g)}});a||this.uiDialog.hide()},_setOption:function(a, -b){var d=this,e=d.uiDialog,g=e.is(":data(resizable)"),f=false;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case "draggable":b?d._makeDraggable():e.draggable("destroy");break; -case "height":f=true;break;case "maxHeight":g&&e.resizable("option","maxHeight",b);f=true;break;case "maxWidth":g&&e.resizable("option","maxWidth",b);f=true;break;case "minHeight":g&&e.resizable("option","minHeight",b);f=true;break;case "minWidth":g&&e.resizable("option","minWidth",b);f=true;break;case "position":d._position(b);break;case "resizable":g&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "title":c(".ui-dialog-title", -d.uiDialogTitlebar).html(""+(b||" "));break;case "width":f=true;break}c.Widget.prototype._setOption.apply(d,arguments);f&&d._size()},_size:function(){var a=this.options,b;this.element.css({width:"auto",minHeight:0,height:0});b=this.uiDialog.css({height:"auto",width:a.width}).height();this.element.css(a.height==="auto"?{minHeight:Math.max(a.minHeight-b,0),height:"auto"}:{minHeight:0,height:Math.max(a.height-b,0)}).show();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight", -this._minHeight())}});c.extend(c.ui.dialog,{version:"1.9m2",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=c.ui.dialog.overlay.create(a)}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&& -c(document).bind(c.ui.dialog.overlay.events,function(d){return c(d.target).zIndex()>=c.ui.dialog.overlay.maxZ})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});c.fn.bgiframe&& -b.bgiframe();this.instances.push(b);return b},destroy:function(a){this.oldInstances.push(this.instances.splice(c.inArray(a,this.instances),1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var b=0;c.each(this.instances,function(){b=Math.max(b,this.css("z-index"))});this.maxZ=b},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.documentElement.offsetHeight, -document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(this)});a.css({width:0, -height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery); -(function(c){c.widget("ui.menu",{_create:function(){var a=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).bind("click.menu",function(b){if(a.options.disabled)return false;if(c(b.target).closest(".ui-menu-item a").length){b.preventDefault();a.select(b)}});this.refresh();if(!this.options.input)this.options.input=this.element.attr("tabIndex",0);this.options.input.bind("keydown.menu",function(b){if(!a.options.disabled)switch(b.keyCode){case c.ui.keyCode.PAGE_UP:a.previousPage(); -b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.PAGE_DOWN:a.nextPage();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.UP:a.previous();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.DOWN:a.next();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.ENTER:a.select();b.preventDefault();b.stopImmediatePropagation();break}})},destroy:function(){c.Widget.prototype.destroy.apply(this,arguments);this.element.removeClass("ui-menu ui-widget ui-widget-content ui-corner-all").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-activedescendant"); -this.element.children(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").children("a").removeClass("ui-corner-all").removeAttr("tabIndex").unbind(".menu")},refresh:function(){var a=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabIndex",-1).bind("mouseenter.menu",function(b){a.options.disabled||a.activate(b,c(this).parent())}).bind("mouseleave.menu",function(){a.options.disabled|| -a.deactivate()})},activate:function(a,b){this.deactivate();if(this._hasScroll()){var d=b.offset().top-this.element.offset().top,e=this.element.attr("scrollTop"),f=this.element.height();if(d<0)this.element.attr("scrollTop",e+d);else d>f&&this.element.attr("scrollTop",e+d-f+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",a,{item:b})},deactivate:function(){if(this.active){this.active.children("a").removeClass("ui-state-hover").removeAttr("id"); -this._trigger("blur");this.active=null}},next:function(a){this._move("next",".ui-menu-item:first",a)},previous:function(a){this._move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(a,b,d){if(this.active){a=this.active[a+"All"](".ui-menu-item").eq(0);a.length?this.activate(d,a):this.activate(d,this.element.children(b))}else this.activate(d, -this.element.children(b))},nextPage:function(a){if(this._hasScroll())if(!this.active||this.last())this.activate(a,this.element.children(":first"));else{var b=this.active.offset().top,d=this.element.height(),e=this.element.children("li").filter(function(){var f=c(this).offset().top-b-d+c(this).height();return f<10&&f>-10});e.length||(e=this.element.children(":last"));this.activate(a,e)}else this.activate(a,this.element.children(!this.active||this.last()?":first":":last"))},previousPage:function(a){if(this._hasScroll())if(!this.active|| -this.first())this.activate(a,this.element.children(":last"));else{var b=this.active.offset().top,d=this.element.height();result=this.element.children("li").filter(function(){var e=c(this).offset().top-b+d-c(this).height();return e<10&&e>-10});result.length||(result=this.element.children(":first"));this.activate(a,result)}else this.activate(a,this.element.children(!this.active||this.first()?":last":":first"))},_hasScroll:function(){return this.element.height()<this.element.attr("scrollHeight")},select:function(a){this._trigger("select", -a,{item:this.active})}})})(jQuery); -(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h= -0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+= -g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k, -elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"? --b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position= -"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery); -(function(b){b.widget("ui.progressbar",{options:{value:0},_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this._valueMin(),"aria-valuemax":this._valueMax(),"aria-valuenow":this._value()});this.valueDiv=b("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"); -this.valueDiv.remove();this._superApply("destroy",arguments)},value:function(a){if(a===undefined)return this._value();this._setOption("value",a);return this},_setOption:function(a,c){switch(a){case "value":this.options.value=c;this._refreshValue();this._trigger("change");break}this._superApply("_setOption",arguments)},_value:function(){var a=this.options.value;if(typeof a!=="number")a=0;if(a<this._valueMin())a=this._valueMin();if(a>this._valueMax())a=this._valueMax();return a},_valueMin:function(){return 0}, -_valueMax:function(){return 100},_refreshValue:function(){var a=this.value();this.valueDiv[a===this._valueMax()?"addClass":"removeClass"]("ui-corner-right").width(a+"%");this.element.attr("aria-valuenow",a)}});b.extend(b.ui.progressbar,{version:"1.9m2"})})(jQuery); -(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");b.disabled&&this.element.addClass("ui-slider-disabled ui-disabled"); -this.range=d([]);if(b.range){if(b.range===true){this.range=d("<div></div>");if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(b.range==="min"||b.range==="max")this.range.addClass("ui-slider-range-"+b.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle"); -if(b.values&&b.values.length)for(;d(".ui-slider-handle",this.element).length<b.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(b.disabled)d(this).blur(); -else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),g,h,i;if(!a.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e= -false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");g=a._start(c,f);if(g===false)return}break}i=a.options.step;g=a.options.values&&a.options.values.length?(h=a.values(f)):(h=a.value());switch(c.keyCode){case d.ui.keyCode.HOME:h=a._valueMin();break;case d.ui.keyCode.END:h=a._valueMax();break;case d.ui.keyCode.PAGE_UP:h=a._trimAlignValue(g+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:h=a._trimAlignValue(g-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(g=== -a._valueMax())return;h=a._trimAlignValue(g+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(g===a._valueMin())return;h=a._trimAlignValue(g-i);break}a._slide(c,f,h);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(c,e);a._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"); -this._mouseDestroy();return this},_mouseCapture:function(a){var b=this.options,c,e,f,g,h,i;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c={x:a.pageX,y:a.pageY};e=this._normValueFromMouse(c);f=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(j){var k=Math.abs(e-h.values(j));if(f>k){f=k;g=d(this);i=j}});if(b.range===true&&this.values(1)===b.min){i+=1;g=d(this.handles[i])}if(this._start(a, -i)===false)return false;this._mouseSliding=true;h._handleIndex=i;g.addClass("ui-state-active").focus();b=g.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-g.width()/2,top:a.pageY-b.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)};e=this._normValueFromMouse(c);this._slide(a,i,e);return this._animateOff=true},_mouseStart:function(){return true}, -_mouseDrag:function(a){var b=this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b; -if(this.orientation==="horizontal"){b=this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value= -this.values(b);c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var e;if(this.options.values&&this.options.values.length){e=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>e||b===1&&c<e))c=e;if(c!==this.values(b)){e=this.values();e[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e});this.values(b?0:1);a!==false&&this.values(b,c,true)}}else if(c!==this.value()){a=this._trigger("slide",a,{handle:this.handles[b], -value:c});a!==false&&this.value(c)}},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value= -this._trimAlignValue(a);this._refreshValue();this._change(null,0)}return this._value()},values:function(a,b){var c,e,f;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):this.value(); -else return this._values()},_setOption:function(a,b){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;this._superApply("_setOption",arguments);switch(a){case "disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+ -this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,c;if(arguments.length){b=this.options.values[a];return b=this._trimAlignValue(b)}else{b=this.options.values.slice();for(c= -0;c<b.length;c+=1)b[c]=this._trimAlignValue(b[c]);return b}},_trimAlignValue:function(a){if(a<this._valueMin())return this._valueMin();if(a>this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=a%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=this.options.range,b=this.options,c=this,e=!this._animateOff?b.animate:false, -f,g={},h,i,j,k;if(this.options.values&&this.options.values.length)this.handles.each(function(l){f=(c.values(l)-c._valueMin())/(c._valueMax()-c._valueMin())*100;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](g,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(l===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({width:f-h+"%"},{queue:false,duration:b.animate})}else{if(l===0)c.range.stop(1, -1)[e?"animate":"css"]({bottom:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({height:f-h+"%"},{queue:false,duration:b.animate})}h=f});else{i=this.value();j=this._valueMin();k=this._valueMax();f=k!==j?(i-j)/(k-j)*100:0;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](g,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[e? -"animate":"css"]({width:100-f+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.9m2"})})(jQuery); -(function(d){function s(){return++u}function v(){return++w}var u=0,w=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c=="selected")this.options.collapsible&& -e==this.options.selected||this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+s()},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+v());return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c= -d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString().split("#")[0]|| -(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"); -this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-selected").length)b.selected= -this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active"); -if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsible?"addClass": -"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bind("mouseover.tabs", -function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show", -null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.event+".tabs", -function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){r(g, -j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind("click.tabs", -function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this, -"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs", -true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("ui-tabs-hide"); -this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify();this._trigger("remove", -null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this}, -select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing"); -if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue("tabs");return this}}, -abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.9m2"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rotate||(a._rotate= -function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery); -(function(b){b(document.body).is("[role]")||b(document.body).attr("role","application");var f=0;b.widget("ui.tooltip",{options:{tooltipClass:"ui-widget-content",content:function(){return b(this).attr("title")},position:{my:"left center",at:"right center",offset:"15 0"}},_init:function(){var c=this;this.tooltip=b("<div></div>").attr("id","ui-tooltip-"+f++).attr("role","tooltip").attr("aria-hidden","true").addClass("ui-tooltip ui-widget ui-corner-all").addClass(this.options.tooltipClass).appendTo(document.body).hide(); -this.tooltipContent=b("<div></div>").addClass("ui-tooltip-content").appendTo(this.tooltip);this.opacity=this.tooltip.css("opacity");this.element.bind("focus.tooltip mouseenter.tooltip",function(a){c.open(a)}).bind("blur.tooltip mouseleave.tooltip",function(a){c.close(a)})},enable:function(){this.options.disabled=false},disable:function(){this.options.disabled=true},destroy:function(){this.tooltip.remove();b.Widget.prototype.destroy.apply(this,arguments)},widget:function(){return this.tooltip},open:function(c){var a= -this.element;if(!(this.current&&this.current[0]==a[0])){var d=this;this.current=a;this.currentTitle=a.attr("title");var e=this.options.content.call(a[0],function(g){d.current==a&&d._show(c,a,g)});e&&d._show(c,a,e)}},_show:function(c,a,d){if(d){a.attr("title","");if(!this.options.disabled){this.tooltipContent.html(d);this.tooltip.css({top:0,left:0}).show().position(b.extend(this.options.position,{of:a})).hide();this.tooltip.attr("aria-hidden","false");a.attr("aria-describedby",this.tooltip.attr("id")); -if(this.tooltip.is(":animated"))this.tooltip.stop().show().fadeTo("normal",this.opacity);else this.tooltip.is(":visible")?this.tooltip.fadeTo("normal",this.opacity):this.tooltip.fadeIn();this._trigger("open",c)}}},close:function(c){if(this.current){var a=this.current.attr("title",this.currentTitle);this.current=null;if(!this.options.disabled){a.removeAttr("aria-describedby");this.tooltip.attr("aria-hidden","true");this.tooltip.is(":animated")?this.tooltip.stop().fadeTo("normal",0,function(){b(this).hide().css("opacity", -"")}):this.tooltip.stop().fadeOut();this._trigger("close",c)}}}})})(jQuery); + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { display: none; } +.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } +.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } +.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; } +.ui-helper-clearfix:after { clear: both; } +.ui-helper-clearfix { zoom: 1; } +.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { cursor: default !important; } + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } + + +/*! + * jQuery UI CSS Framework 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + * + * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS,%20Tahoma,%20Verdana,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=03_highlight_soft.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=08_diagonals_thick.png&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=01_flat.png&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px + */ + + +/* Component containers +----------------------------------*/ +.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; } +.ui-widget .ui-widget { font-size: 1em; } +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; } +.ui-widget-content { border: 1px solid #dddddd; background: #eeeeee url(images/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x; color: #333333; } +.ui-widget-content a { color: #333333; } +.ui-widget-header { border: 1px solid #e78f08; background: #f6a828 url(images/ui-bg_gloss-wave_35_f6a828_500x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; } +.ui-widget-header a { color: #ffffff; } + +/* Interaction states +----------------------------------*/ +.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6 url(images/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #1c94c4; } +.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; } +.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce url(images/ui-bg_glass_100_fdf5ce_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #c77405; } +.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; } +.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #fbd850; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #eb8f00; } +.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; } +.ui-widget :active { outline: none; } + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fed22f; background: #ffe45c url(images/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; } +.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; } +.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #b81900 url(images/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; } +.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; } +.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; } +.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } +.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } +.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); } +.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); } +.ui-widget-header .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); } +.ui-state-default .ui-icon { background-image: url(images/ui-icons_ef8c08_256x240.png); } +.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); } +.ui-state-active .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); } +.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_228ef1_256x240.png); } +.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ffd27a_256x240.png); } + +/* positioning */ +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-off { background-position: -96px -144px; } +.ui-icon-radio-on { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; } +.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; } + +/* Overlays */ +.ui-widget-overlay { background: #666666 url(images/ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat; opacity: .50;filter:Alpha(Opacity=50); } +.ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background: #000000 url(images/ui-bg_flat_10_000000_40x100.png) 50% 50% repeat-x; opacity: .20;filter:Alpha(Opacity=20); -moz-border-radius: 5px; -khtml-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; }/*! + * jQuery UI Resizable 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Resizable#theming + */ +.ui-resizable { position: relative;} +.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; } +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } +.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } +.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } +.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } +.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } +.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } +.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } +.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } +.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/*! + * jQuery UI Selectable 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Selectable#theming + */ +.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } +/*! + * jQuery UI Accordion 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Accordion#theming + */ +/* IE/Win - Fix animation bug - #4615 */ +.ui-accordion { width: 100%; } +.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; } +.ui-accordion .ui-accordion-li-fix { display: inline; } +.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; } +.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; } +.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; } +.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } +.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; } +.ui-accordion .ui-accordion-content-active { display: block; } +/*! + * jQuery UI Autocomplete 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Autocomplete#theming + */ +.ui-autocomplete { position: absolute; cursor: default; } + +/* workarounds */ +* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ + +/* + * jQuery UI Menu 1.8.24 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu#theming + */ +.ui-menu { + list-style:none; + padding: 2px; + margin: 0; + display:block; + float: left; +} +.ui-menu .ui-menu { + margin-top: -3px; +} +.ui-menu .ui-menu-item { + margin:0; + padding: 0; + zoom: 1; + float: left; + clear: left; + width: 100%; +} +.ui-menu .ui-menu-item a { + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + zoom:1; +} +.ui-menu .ui-menu-item a.ui-state-hover, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} +/*! + * jQuery UI Button 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Button#theming + */ +.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ +.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ +button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ +.ui-button-icons-only { width: 3.4em; } +button.ui-button-icons-only { width: 3.7em; } + +/*button text element */ +.ui-button .ui-button-text { display: block; line-height: 1.4; } +.ui-button-text-only .ui-button-text { padding: .4em 1em; } +.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } +.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } +.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } +.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } +/* no icon support for input elements, provide padding by default */ +input.ui-button { padding: .4em 1em; } + +/*button icon element(s) */ +.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } +.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } +.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } +.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } +.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } + +/*button sets*/ +.ui-buttonset { margin-right: 7px; } +.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } + +/* workarounds */ +button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ +/*! + * jQuery UI Dialog 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Dialog#theming + */ +.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } +.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } +.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } +.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } +.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } +.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } +.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } +.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } +.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } +.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } +.ui-draggable .ui-dialog-titlebar { cursor: move; } +/*! + * jQuery UI Slider 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Slider#theming + */ +.ui-slider { position: relative; text-align: left; } +.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } +.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } + +.ui-slider-horizontal { height: .8em; } +.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } +.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } +.ui-slider-horizontal .ui-slider-range-min { left: 0; } +.ui-slider-horizontal .ui-slider-range-max { right: 0; } + +.ui-slider-vertical { width: .8em; height: 100px; } +.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } +.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } +.ui-slider-vertical .ui-slider-range-min { bottom: 0; } +.ui-slider-vertical .ui-slider-range-max { top: 0; }/*! + * jQuery UI Tabs 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Tabs#theming + */ +.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ +.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } +.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; } +.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; } +.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } +.ui-tabs .ui-tabs-hide { display: none !important; } +/*! + * jQuery UI Datepicker 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Datepicker#theming + */ +.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } +.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } +.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } +.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } +.ui-datepicker .ui-datepicker-prev { left:2px; } +.ui-datepicker .ui-datepicker-next { right:2px; } +.ui-datepicker .ui-datepicker-prev-hover { left:1px; } +.ui-datepicker .ui-datepicker-next-hover { right:1px; } +.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } +.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } +.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } +.ui-datepicker select.ui-datepicker-month-year {width: 100%;} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { width: 49%;} +.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } +.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } +.ui-datepicker td { border: 0; padding: 1px; } +.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } +.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } +.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { width:auto; } +.ui-datepicker-multi .ui-datepicker-group { float:left; } +.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } +.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } +.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } +.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } +.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } + +/* RTL support */ +.ui-datepicker-rtl { direction: rtl; } +.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } +.ui-datepicker-rtl .ui-datepicker-group { float:right; } +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } + +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-datepicker-cover { + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ +}/*! + * jQuery UI Progressbar 1.8.24 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Progressbar#theming + */ +.ui-progressbar { height:2em; text-align: left; overflow: hidden; } +.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js index 16ad06c5ac..bc3fbc81b2 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js @@ -1,4 +1,2 @@ -/*! jQuery v1.7.2 jquery.com | jquery.org/license */ -(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( -a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f -.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
\ No newline at end of file +/*! jQuery v1.8.2 jquery.com | jquery.org/license */ +(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js index 4e0c9d75c7..4dd48675b7 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js @@ -1,7 +1,7 @@ /** - * @preserve jquery.layout 1.3.0 - Release Candidate 30.5 - * $Date: 2012-04-14 08:00:00 (Sat, 14 Apr 2012) $ - * $Rev: 303005 $ + * @preserve jquery.layout 1.3.0 - Release Candidate 30.62 + * $Date: 2012-08-04 08:00:00 (Thu, 23 Aug 2012) $ + * $Rev: 303006 $ * * Copyright (c) 2012 * Fabrizio Balliano (http://www.fabrizioballiano.net) @@ -10,7 +10,9 @@ * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * - * Changelog: http://layout.jquery-dev.net/changelog.cfm#1.3.0.rc30.5 + * Changelog: http://layout.jquery-dev.net/changelog.cfm#1.3.0.rc30.62 + * NOTE: This is a short-term release to patch a couple of bugs. + * These bugs are listed as officially fixed in RC30.7, which will be released shortly. * * Docs: http://layout.jquery-dev.net/documentation.html * Tips: http://layout.jquery-dev.net/tips.html @@ -32,22 +34,23 @@ var min = Math.min , max = Math.max , round = Math.floor -; -function isStr (v) { return $.type(v) === "string"; } -function runPluginCallbacks (Instance, a_fn) { - if ($.isArray(a_fn)) - for (var i=0, c=a_fn.length; i<c; i++) { - var fn = a_fn[i]; - try { - if (isStr(fn)) // 'name' of a function - fn = eval(fn); - if ($.isFunction(fn)) - fn( Instance ); - } catch (ex) {} - } -}; +, isStr = function (v) { return $.type(v) === "string"; } + +, runPluginCallbacks = function (Instance, a_fn) { + if ($.isArray(a_fn)) + for (var i=0, c=a_fn.length; i<c; i++) { + var fn = a_fn[i]; + try { + if (isStr(fn)) // 'name' of a function + fn = eval(fn); + if ($.isFunction(fn)) + fn( Instance ); + } catch (ex) {} + } + } +; /* @@ -55,36 +58,16 @@ function runPluginCallbacks (Instance, a_fn) { */ $.layout = { - version: "1.3.rc30.5" -, revision: 0.033005 // 1.3.0 final = 1.0300 - major(n+).minor(nn)+patch(nn+) - - // LANGUAGE CUSTOMIZATION -, language: { - // Tips and messages for resizers, togglers, custom buttons, etc. - Open: "Open" // eg: "Open Pane" - , Close: "Close" - , Resize: "Resize" - , Slide: "Slide Open" - , Pin: "Pin" - , Unpin: "Un-Pin" - , noRoomToOpenTip: "Not enough room to show this pane." - , minSizeWarning: "Panel has reached its minimum size" - , maxSizeWarning: "Panel has reached its maximum size" - // Developer error messages - , pane: "pane" // description of "layout pane element" - , selector: "selector" // description of "jQuery-selector" - , errButton: "Error Adding Button \n\nInvalid " - , errContainerMissing: "UI Layout Initialization Error\n\nThe specified layout-container does not exist." - , errCenterPaneMissing: "UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element." - , errContainerHeight: "UI Layout Initialization Warning\n\nThe layout-container \"CONTAINER\" has no height.\n\nTherefore the layout is 0-height and hence 'invisible'!" - } + version: "1.3.rc30.62" +, revision: 0.033006 // 1.3.0 final = 1.0300 - major(n+).minor(nn)+patch(nn+) // can update code here if $.browser is phased out , browser: { mozilla: !!$.browser.mozilla , webkit: !!$.browser.webkit || !!$.browser.safari // webkit = jQ 1.4 , msie: !!$.browser.msie - , isIE6: !!$.browser.msie && $.browser.version == 6 + , isIE6: $.browser.msie && $.browser.version == 6 + , boxModel: $.support.boxModel !== false || !$.browser.msie // ONLY IE reverts to old box-model - update for older jQ onReady , version: $.browser.version // not used in Layout core, but may be used by plugins } @@ -352,17 +335,15 @@ $.layout = { * @see $.swap() - swaps CSS, runs callback, resets CSS */ , showInvisibly: function ($E, force) { - if (!$E) return {}; - if (!$E.jquery) $E = $($E); - var CSS = { - display: $E.css('display') - , visibility: $E.css('visibility') - }; - if (force || CSS.display === "none") { // only if not *already hidden* - $E.css({ display: "block", visibility: "hidden" }); // show element 'invisibly' so can be measured + if ($E && $E.length && (force || $E.css('display') === "none")) { // only if not *already hidden* + var s = $E[0].style + // save ONLY the 'style' props because that is what we must restore + , CSS = { display: s.display || '', visibility: s.visibility || '' }; + // show element 'invisibly' so can be measured + $E.css({ display: "block", visibility: "hidden" }); return CSS; } - else return {}; + return {}; } /** @@ -387,7 +368,7 @@ $.layout = { b = x["border" + e] = $.layout.borderWidth($E, e); p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e); i[e] = b + p; // total offset of content from outer side - d["inset"+ e] = p; + d["inset"+ e] = p; // eg: insetLeft = paddingLeft }); d.offsetWidth = $E.innerWidth(); // offsetWidth is used in calc when doing manual resize @@ -446,22 +427,19 @@ $.layout = { * @return {number} Returns the innerWidth of the elem by subtracting padding and borders */ , cssWidth: function ($E, outerWidth) { - var - b = $.layout.borderWidth - , n = $.layout.cssNum - ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerWidth <= 0) return 0; - if (!$.support.boxModel) return outerWidth; + if (!$.layout.browser.boxModel) return outerWidth; // strip border and padding from outerWidth to get CSS Width - var W = outerWidth - - b($E, "Left") - - b($E, "Right") - - n($E, "paddingLeft") - - n($E, "paddingRight") - ; + var b = $.layout.borderWidth + , n = $.layout.cssNum + , W = outerWidth + - b($E, "Left") + - b($E, "Right") + - n($E, "paddingLeft") + - n($E, "paddingRight"); return max(0,W); } @@ -475,22 +453,19 @@ $.layout = { * @return {number} Returns the innerHeight of the elem by subtracting padding and borders */ , cssHeight: function ($E, outerHeight) { - var - b = $.layout.borderWidth - , n = $.layout.cssNum - ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerHeight <= 0) return 0; - if (!$.support.boxModel) return outerHeight; + if (!$.layout.browser.boxModel) return outerHeight; // strip border and padding from outerHeight to get CSS Height - var H = outerHeight + var b = $.layout.borderWidth + , n = $.layout.cssNum + , H = outerHeight - b($E, "Top") - b($E, "Bottom") - n($E, "paddingTop") - - n($E, "paddingBottom") - ; + - n($E, "paddingBottom"); return max(0,H); } @@ -507,7 +482,7 @@ $.layout = { , cssNum: function ($E, prop, allowAuto) { if (!$E.jquery) $E = $($E); var CSS = $.layout.showInvisibly($E) - , p = $.curCSS($E[0], prop, true) + , p = $.css($E[0], prop, true) , v = allowAuto && p=="auto" ? p : (parseInt(p, 10) || 0); $E.css( CSS ); // RESET return v; @@ -516,7 +491,7 @@ $.layout = { , borderWidth: function (el, side) { if (el.jquery) el = el[0]; var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left - return $.curCSS(el, b+"Style", true) === "none" ? 0 : (parseInt($.curCSS(el, b+"Width", true), 10) || 0); + return $.css(el, b+"Style", true) === "none" ? 0 : (parseInt($.css(el, b+"Width", true), 10) || 0); } /** @@ -567,7 +542,7 @@ $.layout = { * @param {(Object|string)} info String message OR Hash/Array * @param {(Boolean|string|Object)=} [popup=false] True means alert-box - can be skipped * @param {(Object|string)=} [debugTitle=""] Title for Hash data - can be skipped - * @param {Object=} [debutOpts={}] Extra options for debug output + * @param {Object=} [debugOpts] Extra options for debug output */ , msg: function (info, popup, debugTitle, debugOpts) { if ($.isPlainObject(info) && window.debugData) { @@ -614,9 +589,7 @@ $.layout = { }; -var lang = $.layout.language; // alias used in defaults... - -// DEFAULT OPTIONS - CHANGE IF DESIRED +// DEFAULT OPTIONS $.layout.defaults = { /* * LAYOUT & LAYOUT-CONTAINER OPTIONS @@ -635,7 +608,6 @@ $.layout.defaults = { , onload_end: null // CALLBACK when Layout inits - after EVERYTHING has been initialized , onunload_start: null // CALLBACK when Layout is destroyed OR onWindowUnload , onunload_end: null // CALLBACK when Layout is destroyed OR onWindowUnload -, autoBindCustomButtons: false // search for buttons with ui-layout-button class and auto-bind them , initPanes: true // false = DO NOT initialize the panes onLoad - will init later , showErrorMessages: true // enables fatal error messages to warn developers of common errors , showDebugMessages: false // display console-and-alert debug msgs - IF this Layout version _has_ debugging code! @@ -650,6 +622,15 @@ $.layout.defaults = { , pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer , resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged' } +, errors: { + pane: "pane" // description of "layout pane element" - used only in error messages + , selector: "selector" // description of "jQuery-selector" - used only in error messages + , addButtonError: "Error Adding Button \n\nInvalid " + , containerMissing: "UI Layout Initialization Error\n\nThe specified layout-container does not exist." + , centerPaneMissing: "UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element." + , noContainerHeight: "UI Layout Initialization Warning\n\nThe layout-container \"CONTAINER\" has no height.\n\nTherefore the layout is 0-height and hence 'invisible'!" + , callbackError: "UI Layout Callback Error\n\nThe EVENT callback is not a valid function." + } /* * PANE DEFAULT SETTINGS * - settings under the 'panes' key become the default settings for *all panes* @@ -682,8 +663,6 @@ $.layout.defaults = { , togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden' , togglerAlign_open: "center" // top/left, bottom/right, center, OR... , togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right - , togglerTip_open: lang.Close // Toggler tool-tip (title) - , togglerTip_closed: lang.Open // ditto , togglerContent_open: "" // text or HTML to put INSIDE the toggler , togglerContent_closed: "" // ditto // RESIZING OPTIONS @@ -699,10 +678,7 @@ $.layout.defaults = { , livePaneResizing: false // true = LIVE Resizing as resizer is dragged , liveContentResizing: false // true = re-measure header/footer heights as resizer is dragged , liveResizingTolerance: 1 // how many px change before pane resizes, to control performance - // TIPS & MESSAGES - also see lang object - , noRoomToOpenTip: lang.noRoomToOpenTip - , resizerTip: lang.Resize // Resizer tool-tip (title) - , sliderTip: lang.Slide // resizer-bar triggers 'sliding' when pane is closed + // SLIDING OPTIONS , sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding' , slideTrigger_open: "click" // click, dblclick, mouseenter , slideTrigger_close: "mouseleave"// click, mouseleave @@ -711,6 +687,18 @@ $.layout.defaults = { , hideTogglerOnSlide: false // when pane is slid-open, should the toggler show? , preventQuickSlideClose: $.layout.browser.webkit // Chrome triggers slideClosed as it is opening , preventPrematureSlideClose: false // handle incorrect mouseleave trigger, like when over a SELECT-list in IE + // PANE-SPECIFIC TIPS & MESSAGES + , tips: { + Open: "Open" // eg: "Open Pane" + , Close: "Close" + , Resize: "Resize" + , Slide: "Slide Open" + , Pin: "Pin" + , Unpin: "Un-Pin" + , noRoomToOpen: "Not enough room to show this panel." // alert if user tries to open a pane that cannot + , minSizeWarning: "Panel has reached its minimum size" // displays in browser statusbar + , maxSizeWarning: "Panel has reached its maximum size" // ditto + } // HOT-KEYS & MISC , showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver , enableCursorHotkey: true // enabled 'cursor' hotkeys @@ -723,7 +711,7 @@ $.layout.defaults = { , fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 } , fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation , animatePaneSizing: false // true = animate resizing after dragging resizer-bar OR sizePane() is called - /* NOTE: Action-specific FX options are auto-generated from the options above if not specifically set: + /* NOTE: Action-specific FX options are auto-generated from the options above if not specifically set: fxName_open: "slide" // 'Open' pane animation fnName_close: "slide" // 'Close' pane animation fxName_size: "slide" // 'Size' pane animation - when animatePaneSizing = true @@ -739,9 +727,10 @@ $.layout.defaults = { , initChildLayout: true // true = child layout will be created as soon as _this_ layout completes initialization , destroyChildLayout: true // true = destroy child-layout if this pane is destroyed , resizeChildLayout: true // true = trigger child-layout.resizeAll() when this pane is resized - // PANE CALLBACKS + // EVENT TRIGGERING , triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes , triggerEventsDuringLiveResize: true // true = trigger onresize callback REPEATEDLY if livePaneResizing==true + // PANE CALLBACKS , onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start , onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end , onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start @@ -798,10 +787,10 @@ $.layout.defaults = { $.layout.optionsMap = { // layout/global options - NOT pane-options - layout: ("stateManagement,effects,zIndexes," + layout: ("stateManagement,effects,zIndexes,errors," + "name,zIndex,scrollToBookmarkOnLoad,showErrorMessages," + "resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay," - + "onresizeall,onresizeall_start,onresizeall_end,onload,onunload,autoBindCustomButtons").split(",") + + "onresizeall,onresizeall_start,onresizeall_end,onload,onunload").split(",") // borderPanes: [ ALL options that are NOT specified as 'layout' ] // default.panes options that apply to the center-pane (most options apply _only_ to border-panes) , center: ("paneClass,contentSelector,contentIgnoreSelector,findNestedContent,applyDemoStyles,triggerEventsOnLoad," @@ -846,7 +835,7 @@ $.layout.transformData = function (hash) { } return json; -} +}; // INTERNAL CONFIG DATA - DO NOT CHANGE THIS! $.layout.backwardCompatibility = { @@ -868,19 +857,26 @@ $.layout.backwardCompatibility = { , "cookie.path": "stateManagement.cookie.path" , "cookie.expires": "stateManagement.cookie.expires" , "cookie.secure": "stateManagement.cookie.secure" + // OLD Language options + , noRoomToOpenTip: "tips.noRoomToOpen" + , togglerTip_open: "tips.Close" // open = Close + , togglerTip_closed: "tips.Open" // closed = Open + , resizerTip: "tips.Resize" + , sliderTip: "tips.Slide" } - /** - * @param {Object} opts - */ + +/** +* @param {Object} opts +*/ , renameOptions: function (opts) { var map = $.layout.backwardCompatibility.map , oldData, newData, value ; for (var itemPath in map) { oldData = getBranch( itemPath ); - value = oldData.branch[ oldData.key ] + value = oldData.branch[ oldData.key ]; if (value !== undefined) { - newData = getBranch( map[itemPath], true ) + newData = getBranch( map[itemPath], true ); newData.branch[ newData.key ] = value; delete oldData.branch[ oldData.key ]; } @@ -910,9 +906,10 @@ $.layout.backwardCompatibility = { return D; }; } - /** - * @param {Object} opts - */ + +/** +* @param {Object} opts +*/ , renameAllOptions: function (opts) { var ren = $.layout.backwardCompatibility.renameOptions; // rename root (layout) options @@ -936,6 +933,7 @@ $.layout.backwardCompatibility = { + /* ============================================================ * BEGIN WIDGET: $( selector ).layout( {options} ); * ============================================================ @@ -945,7 +943,6 @@ $.fn.layout = function (opts) { // local aliases to global data browser = $.layout.browser -, lang = $.layout.language // internal alias , _c = $.layout.config // local aliases to utlity methods @@ -1004,31 +1001,46 @@ $.fn.layout = function (opts) { , clear: function (s) { var t=timer.data; if (t[s]) {clearTimeout(t[s]); delete t[s];} } } -, _log = function (msg, popup) { - $.layout.msg( options.name +' / '+ msg, (popup && options.showErrorMessages) ); + /** + * Alert or console.log a message - IF option is enabled. + * + * @param {(string|!Object)} msg Message (or debug-data) to display + * @param {?boolean} popup True by default, means 'alert', false means use console.log + * @param {?boolean} debug True means is a widget debugging message + */ +, _log = function (msg, popup, debug) { + var o = options; + if ((o.showErrorMessages && !debug) || (debug && o.showDebugMessages)) + $.layout.msg( o.name +' / '+ msg, (popup !== false) ); + return false; } /** * Executes a Callback function after a trigger event, like resize, open or close * - * @param {?string} pane This is passed only so we can pass the 'pane object' to the callback - * @param {(string|function())} fn Accepts a function name, OR a comma-delimited array: [0]=function name, [1]=argument + * @param {string} evtName Name of the layout callback, eg "onresize_start" + * @param {?string} pane This is passed only so we can pass the 'pane object' to the callback + * @param {?string|?boolean} skipBoundEvents True = do not run events bound to the elements - only the callbacks set in options */ , _runCallbacks = function (evtName, pane, skipBoundEvents) { - var o = pane ? options[pane] : options + var paneCB = pane && isStr(pane) + , s = paneCB ? state[pane] : state + , o = paneCB ? options[pane] : options + , lName = options.name // names like onopen and onopen_end separate are interchangeable in options... - , long = evtName + (evtName.match(/_/) ? "" : "_end") - , short = long.match(/_end$/) ? long.substr(0, long.length - 4) : "" - , fn = o[long] + , lng = evtName + (evtName.match(/_/) ? "" : "_end") + , shrt = lng.match(/_end$/) ? lng.substr(0, lng.length - 4) : "" + , fn = o[lng] || o[shrt] , retVal = "NC" // NC = No Callback , args = [] + , $P ; - if (!fn && short) - fn = o[short]; + if ( !paneCB && $.type(skipBoundEvents) !== 'boolean' ) + skipBoundEvents = pane; // allow pane param to be skipped for Layout callback // first trigger the callback set in the options if (fn) { - //try { + try { // convert function name (string) to function object if (isStr( fn )) { if (fn.match(/,/)) { @@ -1044,25 +1056,33 @@ $.fn.layout = function (opts) { if ($.isFunction( fn )) { if (args.length) retVal = fn(args[1]); // pass the argument parsed from 'list' - else if (pane && $Ps[pane]) + else if ( paneCB ) // pass data: pane-name, pane-element, pane-state, pane-options, and layout-name - retVal = fn( pane, $Ps[pane], state[pane], options[pane], options.name ); + retVal = fn( pane, $Ps[pane], s, o, lName ); else // must be a layout/container callback - pass suitable info - retVal = fn( Instance, state, options, options.name ); + retVal = fn( Instance, s, o, lName ); } - //} - //catch (ex) {} + } + catch (ex) { + _log( options.errors.callbackError.replace(/EVENT/, $.trim(pane +" "+ lng)), false ); + } } // trigger additional events bound directly to the pane if (!skipBoundEvents && retVal !== false) { - if (pane) { // PANE events can be bound to each pane-elements - $Ps[pane].triggerHandler('layoutpane'+ long, [ pane, $Ps[pane], state[pane], options[pane], options.name ]); - if (short) - $Ps[pane].triggerHandler('layoutpane'+ short, [ pane, $Ps[pane], state[pane], options[pane], options.name ]); + if ( paneCB ) { // PANE events can be bound to each pane-elements + $P = $Ps[pane]; + o = options[pane]; + s = state[pane]; + $P.triggerHandler('layoutpane'+ lng, [ pane, $P, s, o, lName ]); + if (shrt) + $P.triggerHandler('layoutpane'+ shrt, [ pane, $P, s, o, lName ]); + } + else { // LAYOUT events can be bound to the container-element + $N.triggerHandler('layout'+ lng, [ Instance, s, o, lName ]); + if (shrt) + $N.triggerHandler('layout'+ shrt, [ Instance, s, o, lName ]); } - else // LAYOUT events can be bound to the container-element - $N.triggerHandler('layout'+ long, [ pane, $Ps[pane], state[pane], options[pane], options.name ]); } // ALWAYS resizeChildLayout after a resize event - even during initialization @@ -1231,7 +1251,7 @@ $.fn.layout = function (opts) { * * @param {(string|!Object)} pane * @param {boolean=} [inclSpace=false] - * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes - adjusted for boxModel & browser + * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes */ , getPaneSize = function (pane, inclSpace) { var @@ -1478,9 +1498,7 @@ $.fn.layout = function (opts) { // a center pane is required, so make sure it exists if (!getPane("center").length) { - if (options.showErrorMessages) - _log( lang.errCenterPaneMissing, true ); - return false; + return _log( o.errors.centerPaneMissing ); } // TEMP state so isInitialized returns true during init process @@ -1535,8 +1553,8 @@ $.fn.layout = function (opts) { * Initialize nested layouts for a specific pane - can optionally pass layout-options * * @see _initChildLayouts - * @param {string} pane The pane being opened, ie: north, south, east, or west - * @param {Object=} [opts] Layout-options - if passed, will OVERRRIDE options[pane].childOptions + * @param {string|Object} evt_or_pane The pane being opened, ie: north, south, east, or west + * @param {Object=} [opts] Layout-options - if passed, will OVERRRIDE options[pane].childOptions * @return An object pointer to the layout instance created - or null */ , createChildLayout = function (evt_or_pane, opts) { @@ -1632,12 +1650,11 @@ $.fn.layout = function (opts) { .addClass(o.containerClass) ; var layoutMethods = { - destroy: '' - , initPanes: '' - , resizeAll: 'resizeAll' - , resize: 'resizeAll' - } - , name; + destroy: '' + , initPanes: '' + , resizeAll: 'resizeAll' + , resize: 'resizeAll' + }; // loop hash and bind all methods - include layoutID namespacing for (name in layoutMethods) { $N.bind("layout"+ name.toLowerCase() +"."+ sID, Instance[ layoutMethods[name] || name ]); @@ -1720,8 +1737,8 @@ $.fn.layout = function (opts) { // set current layout-container dimensions if ( $N.is(":visible") ) { $.extend(sC, elDims( $N )); - if (o.showErrorMessages && sC.innerHeight < 1) - _log( lang.errContainerHeight.replace(/CONTAINER/, sC.ref), true ); + if (sC.innerHeight < 1) + _log( o.errors.noContainerHeight.replace(/CONTAINER/, sC.ref) ); } } } catch (ex) {} @@ -1759,7 +1776,7 @@ $.fn.layout = function (opts) { // auto-rename old options for backward compatibility opts = $.layout.backwardCompatibility.renameAllOptions( opts ); - // if user-options has 'panes' key (pane-defaults), process it... + // if user-options has 'panes' key (pane-defaults), clean it... if (!$.isEmptyObject(opts.panes)) { // REMOVE any pane-defaults that MUST be set per-pane data = $.layout.optionsMap.noDefault; @@ -1775,7 +1792,7 @@ $.fn.layout = function (opts) { } } - // MOVE any NON-layout-options to opts.panes + // MOVE any NON-layout-options from opts-root to opts.panes data = $.layout.optionsMap.layout; var rootKeys = $.layout.config.optionRootKeys; for (key in opts) { @@ -1794,7 +1811,7 @@ $.fn.layout = function (opts) { $.each(_c.allPanes, function (i, pane) { // apply 'pane-defaults' to CONFIG.[PANE] - _c[pane] = $.extend( true, {}, _c.panes, _c[pane] ); + _c[pane] = $.extend(true, {}, _c.panes, _c[pane]); d = options.panes; o = options[pane]; @@ -1812,7 +1829,7 @@ $.fn.layout = function (opts) { } else { // border-panes use ALL keys in defaults.panes branch - o = options[pane] = $.extend({}, d, o); // re-apply pane-specific opts AFTER pane-defaults + o = options[pane] = $.extend(true, {}, d, o); // re-apply pane-specific opts AFTER pane-defaults createFxOptions( pane ); // ensure all border-pane-specific base-classes exist if (!o.resizerClass) o.resizerClass = "ui-layout-resizer"; @@ -1831,6 +1848,10 @@ $.fn.layout = function (opts) { z.resizer_normal = max(zo+2, z.resizer_normal); // MIN = +2 } + // DELETE 'panes' key now that we are done - values were copied to EACH pane + delete options.panes; + + function createFxOptions ( pane ) { var o = options[pane] , d = options.panes; @@ -1870,7 +1891,8 @@ $.fn.layout = function (opts) { ; // create fxSettings[_open|_close|_size] o[sSettings] = $.extend( - {} + true + , {} , fx_all // effects.slide.all , fx_pane // effects.slide.west , d.fxSettings // options.panes.fxSettings @@ -1886,9 +1908,6 @@ $.fn.layout = function (opts) { delete o.fxSpeed; delete o.fxSettings; } - - // DELETE 'panes' key now that we are done - values were copied to EACH pane - delete options.panes; } /** @@ -1909,7 +1928,10 @@ $.fn.layout = function (opts) { } } -, initPanes = function () { +, initPanes = function (evt) { + // stopPropagation if called by trigger("layoutinitpanes") - use evtPane utility + evtPane(evt); + // NOTE: do north & south FIRST so we can measure their height - do center LAST $.each(_c.allPanes, function (idx, pane) { addPane( pane, true ); @@ -2017,8 +2039,8 @@ $.fn.layout = function (opts) { , slideOpen: '' , slideClose: '' , slideToggle: '' - , size: 'manualSizePane' - , sizePane: 'manualSizePane' + , size: 'sizePane' + , sizePane: 'sizePane' , sizeContent: '' , sizeHandles: '' , enableClosable: '' @@ -2149,6 +2171,7 @@ $.fn.layout = function (opts) { o = options[pane] , s = state[pane] , c = _c[pane] + , paneId = o.paneSelector.substr(0,1) === "#" ? o.paneSelector.substr(1) : "" , rClass = o.resizerClass , tClass = o.togglerClass , side = c.side.toLowerCase() @@ -2164,10 +2187,10 @@ $.fn.layout = function (opts) { //if (s.isVisible && o.resizable) ... handled by initResizable if (!s.isVisible && o.slidable) - $R.attr("title", o.sliderTip).css("cursor", o.sliderCursor); + $R.attr("title", o.tips.Slide).css("cursor", o.sliderCursor); $R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer" - .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-resizer" : "")) + .attr("id", paneId ? paneId +"-resizer" : "" ) .data({ parentLayout: Instance , layoutPane: Instance[pane] // NEW pointer to pane-alias-object @@ -2184,7 +2207,7 @@ $.fn.layout = function (opts) { if ($T) { $T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler" - .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-toggler" : "")) + .attr("id", paneId ? paneId +"-toggler" : "" ) .data({ parentLayout: Instance , layoutPane: Instance[pane] // NEW pointer to pane-alias-object @@ -2327,7 +2350,7 @@ $.fn.layout = function (opts) { ; if (!s.isClosed) - $R.attr("title", o.resizerTip) + $R.attr("title", o.tips.Resize) .css("cursor", o.resizerCursor); // n-resize, s-resize, etc $R.draggable({ @@ -2397,7 +2420,7 @@ $.fn.layout = function (opts) { // ADD/REMOVE dragging-limit CLASS if (limit) { ui.helper.addClass( helperLimitClass +" "+ helperPaneLimitClass ); // at dragging-limit - window.defaultStatus = (limit>0 && pane.match(/north|west/)) || (limit<0 && pane.match(/south|east/)) ? lang.maxSizeWarning : lang.minSizeWarning; + window.defaultStatus = (limit>0 && pane.match(/(north|west)/)) || (limit<0 && pane.match(/(south|east)/)) ? o.tips.maxSizeWarning : o.tips.minSizeWarning; } else { ui.helper.removeClass( helperLimitClass +" "+ helperPaneLimitClass ); // not at dragging-limit @@ -2605,11 +2628,17 @@ $.fn.layout = function (opts) { * * @param {boolean=} [destroyChildren=false] Destory Child-Layouts first? */ -, destroy = function (destroyChildren) { +, destroy = function (evt_or_destroyChildren, destroyChildren) { // UNBIND layout events and remove global object $(window).unbind("."+ sID); // resize & unload $(document).unbind("."+ sID); // keyDown (hotkeys) + if (typeof evt_or_destroyChildren === "object") + // stopPropagation if called by trigger("layoutdestroy") - use evtPane utility + evtPane(evt_or_destroyChildren); + else // no event, so transfer 1st param to destroyChildren param + destroyChildren = evt_or_destroyChildren; + // need to look for parent layout BEFORE we remove the container data, else skips a level //var parentPane = Instance.hasParentLayout ? $.layout.getParentPaneInstance( $N ) : null; @@ -2666,9 +2695,10 @@ $.fn.layout = function (opts) { * Remove a pane from the layout - subroutine of destroy() * * @see destroy() - * @param {string} pane The pane to process - * @param {boolean=} [remove=false] Remove the DOM element? - * @param {boolean=} [skipResize=false] Skip calling resizeAll()? + * @param {string|Object} evt_or_pane The pane to process + * @param {boolean=} [remove=false] Remove the DOM element? + * @param {boolean=} [skipResize=false] Skip calling resizeAll()? + * @param {boolean=} [destroyChild=true] Destroy Child-layouts? If not passed, obeys options setting */ , removePane = function (evt_or_pane, remove, skipResize, destroyChild) { if (!isInitialized()) return; @@ -2678,7 +2708,6 @@ $.fn.layout = function (opts) { , $R = $Rs[pane] , $T = $Ts[pane] ; - //alert( '$P.length = '+ $P.length ); // NOTE: elements can still exist even after remove() // so check for missing data(), which is cleared by removed() if ($P && $.isEmptyObject( $P.data() )) $P = false; @@ -2798,8 +2827,8 @@ $.fn.layout = function (opts) { * Completely 'hides' a pane, including its spacing - as if it does not exist * The pane is not actually 'removed' from the source, so can use 'show' to un-hide it * - * @param {string} pane The pane being hidden, ie: north, south, east, or west - * @param {boolean=} [noAnimation=false] + * @param {string|Object} evt_or_pane The pane being hidden, ie: north, south, east, or west + * @param {boolean=} [noAnimation=false] */ , hide = function (evt_or_pane, noAnimation) { if (!isInitialized()) return; @@ -2837,10 +2866,10 @@ $.fn.layout = function (opts) { /** * Show a hidden pane - show as 'closed' by default unless openPane = true * - * @param {string} pane The pane being opened, ie: north, south, east, or west - * @param {boolean=} [openPane=false] - * @param {boolean=} [noAnimation=false] - * @param {boolean=} [noAlert=false] + * @param {string|Object} evt_or_pane The pane being opened, ie: north, south, east, or west + * @param {boolean=} [openPane=false] + * @param {boolean=} [noAnimation=false] + * @param {boolean=} [noAlert=false] */ , show = function (evt_or_pane, openPane, noAnimation, noAlert) { if (!isInitialized()) return; @@ -2871,8 +2900,8 @@ $.fn.layout = function (opts) { /** * Toggles a pane open/closed by calling either open or close * - * @param {string} pane The pane being toggled, ie: north, south, east, or west - * @param {boolean=} [slide=false] + * @param {string|Object} evt_or_pane The pane being toggled, ie: north, south, east, or west + * @param {boolean=} [slide=false] */ , toggle = function (evt_or_pane, slide) { if (!isInitialized()) return; @@ -2911,10 +2940,10 @@ $.fn.layout = function (opts) { /** * Close the specified pane (animation optional), and resize all other panes as needed * - * @param {string} pane The pane being closed, ie: north, south, east, or west - * @param {boolean=} [force=false] - * @param {boolean=} [noAnimation=false] - * @param {boolean=} [skipCallback=false] + * @param {string|Object} evt_or_pane The pane being closed, ie: north, south, east, or west + * @param {boolean=} [force=false] + * @param {boolean=} [noAnimation=false] + * @param {boolean=} [skipCallback=false] */ , close = function (evt_or_pane, force, noAnimation, skipCallback) { var pane = evtPane.call(this, evt_or_pane); @@ -3056,7 +3085,7 @@ $.fn.layout = function (opts) { $T .removeClass( tClass+_open +" "+ tClass+_pane+_open ) .addClass( tClass+_closed +" "+ tClass+_pane+_closed ) - .attr("title", o.togglerTip_closed) // may be blank + .attr("title", o.tips.Open) // may be blank ; // toggler-content - if exists $T.children(".content-open").hide(); @@ -3075,10 +3104,10 @@ $.fn.layout = function (opts) { /** * Open the specified pane (animation optional), and resize all other panes as needed * - * @param {string} pane The pane being opened, ie: north, south, east, or west - * @param {boolean=} [slide=false] - * @param {boolean=} [noAnimation=false] - * @param {boolean=} [noAlert=false] + * @param {string|Object} evt_or_pane The pane being opened, ie: north, south, east, or west + * @param {boolean=} [slide=false] + * @param {boolean=} [noAnimation=false] + * @param {boolean=} [noAlert=false] */ , open = function (evt_or_pane, slide, noAnimation, noAlert) { if (!isInitialized()) return; @@ -3124,8 +3153,8 @@ $.fn.layout = function (opts) { if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN! syncPinBtns(pane, false); // make sure pin-buttons are reset - if (!noAlert && o.noRoomToOpenTip) - alert(o.noRoomToOpenTip); + if (!noAlert && o.tips.noRoomToOpen) + alert(o.tips.noRoomToOpen); return queueNext(); // ABORT } @@ -3225,7 +3254,7 @@ $.fn.layout = function (opts) { if (o.resizable && $.layout.plugins.draggable) $R .draggable("enable") .css("cursor", o.resizerCursor) - .attr("title", o.resizerTip); + .attr("title", o.tips.Resize); else if (!s.isSliding) $R.css("cursor", "default"); // n-resize, s-resize, etc @@ -3233,7 +3262,7 @@ $.fn.layout = function (opts) { if ($T) { $T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed ) .addClass( tClass+_open +" "+ tClass+_pane+_open ) - .attr("title", o.togglerTip_open); // may be blank + .attr("title", o.tips.Close); // may be blank removeHover( 0, $T ); // remove hover classes // toggler-content - if exists $T.children(".content-closed").hide(); @@ -3334,7 +3363,7 @@ $.fn.layout = function (opts) { } /** - * @param {string} pane The pane being opened, ie: north, south, east, or west + * @param {string|Object} evt_or_pane The pane being opened, ie: north, south, east, or west */ , slideToggle = function (evt_or_pane) { var pane = evtPane.call(this, evt_or_pane); @@ -3394,7 +3423,7 @@ $.fn.layout = function (opts) { // make sure we have a valid event if (evtName.match(/mouseover/)) evtName = o.slideTrigger_open = "mouseenter"; - else if (!evtName.match(/click|dblclick|mouseenter/)) + else if (!evtName.match(/(click|dblclick|mouseenter)/)) evtName = o.slideTrigger_open = "click"; $R @@ -3402,7 +3431,7 @@ $.fn.layout = function (opts) { [enable ? "bind" : "unbind"](evtName +'.'+ sID, slideOpen) // set the appropriate cursor & title/tip .css("cursor", enable ? o.sliderCursor : "default") - .attr("title", enable ? o.sliderTip : "") + .attr("title", enable ? o.tips.Slide : "") ; } @@ -3437,7 +3466,7 @@ $.fn.layout = function (opts) { $R.css("zIndex", enable ? z.pane_sliding+2 : z.resizer_normal); // NOTE: mask = pane_sliding+1 // make sure we have a valid event - if (!evtName.match(/click|mouseleave/)) + if (!evtName.match(/(click|mouseleave)/)) evtName = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout' // add/remove slide triggers @@ -3457,7 +3486,7 @@ $.fn.layout = function (opts) { // IF pane is not resizable (which already has a cursor and tip) // then set the a cursor & title/tip on resizer when sliding $R.css("cursor", enable ? o.sliderCursor : "default"); - $R.attr("title", enable ? o.togglerTip_open : ""); // use Toggler-tip, eg: "Close Pane" + $R.attr("title", enable ? o.tips.Close : ""); // use Toggler-tip, eg: "Close Pane" } // SUBROUTINE for mouseleave timer clearing @@ -3560,10 +3589,10 @@ $.fn.layout = function (opts) { * sizePane is called only by internal methods whenever a pane needs to be resized * manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized' * - * @param {string} pane The pane being resized - * @param {number} size The *desired* new size for this pane - will be validated - * @param {boolean=} [skipCallback=false] Should the onresize callback be run? - * @param {boolean=} [noAnimation=false] + * @param {string|Object} evt_or_pane The pane being resized + * @param {number} size The *desired* new size for this pane - will be validated + * @param {boolean=} [skipCallback=false] Should the onresize callback be run? + * @param {boolean=} [noAnimation=false] */ , manualSizePane = function (evt_or_pane, size, skipCallback, noAnimation) { if (!isInitialized()) return; @@ -3580,11 +3609,11 @@ $.fn.layout = function (opts) { } /** - * @param {string} pane The pane being resized - * @param {number} size The *desired* new size for this pane - will be validated - * @param {boolean=} [skipCallback=false] Should the onresize callback be run? - * @param {boolean=} [force=false] Force resizing even if does not seem necessary - * @param {boolean=} [noAnimation=false] + * @param {string|Object} evt_or_pane The pane being resized + * @param {number} size The *desired* new size for this pane - will be validated + * @param {boolean=} [skipCallback=false] Should the onresize callback be run? + * @param {boolean=} [force=false] Force resizing even if does not seem necessary + * @param {boolean=} [noAnimation=false] */ , sizePane = function (evt_or_pane, size, skipCallback, force, noAnimation) { if (!isInitialized()) return; @@ -3674,6 +3703,7 @@ $.fn.layout = function (opts) { , cssSize: newSize }] , lastTry = tries[0] + , thisTry = {} , msg = 'Inaccurate size after resizing the '+ pane +'-pane.' ; while ( !lastTry.correct ) { @@ -3690,15 +3720,12 @@ $.fn.layout = function (opts) { thisTry.actual = dimName=='width' ? $P.outerWidth() : $P.outerHeight(); thisTry.correct = (size === thisTry.actual); - // if showDebugMessages, log attempts and alert the user of this *non-fatal error* - if (options.showDebugMessages) { - if ( tries.length === 1) { - _log(msg, false); - _log(lastTry, false); - } - _log(thisTry, false); + // log attempts and alert the user of this *non-fatal error* (if showDebugMessages) + if ( tries.length === 1) { + _log(msg, false, true); + _log(lastTry, false, true); } - + _log(thisTry, false, true); // after 4 tries, is as close as its gonna get! if (tries.length > 3) break; @@ -3737,16 +3764,16 @@ $.fn.layout = function (opts) { } // DEBUG - ALERT user/developer so they know there was a sizing problem - if (options.showDebugMessages && tries.length > 1) - _log(msg +'\nSee the Error Console for details.', true); + if (tries.length > 1) + _log(msg +'\nSee the Error Console for details.', true, true); } } /** * @see initPanes(), sizePane(), resizeAll(), open(), close(), hide() - * @param {string} panes The pane(s) being resized, comma-delmited string - * @param {boolean=} [skipCallback=false] Should the onresize callback be run? - * @param {boolean=} [force=false] + * @param {Array.<string>|string} panes The pane(s) being resized, comma-delmited string + * @param {boolean=} [skipCallback=false] Should the onresize callback be run? + * @param {boolean=} [force=false] */ , sizeMidPanes = function (panes, skipCallback, force) { panes = (panes ? panes : "east,west,center").split(","); @@ -3801,9 +3828,9 @@ $.fn.layout = function (opts) { } // IF we found enough extra space, then resize the border panes as calculated if (reqPx === 0) { - if (sizeE != minE) + if (sizeE && sizeE != minE) sizePane('east', newE, true, force, true); // true = skipCallback/noAnimation - initPanes will handle when done - if (sizeW != minW) + if (sizeW && sizeW != minW) sizePane('west', newW, true, force, true); // now start over! sizeMidPanes('center', skipCallback, force); @@ -3833,7 +3860,8 @@ $.fn.layout = function (opts) { _runCallbacks("onresize_start", pane); $P.css(CSS); // apply the CSS to pane - sizeHandles(pane); // also update resizer length + if (pane !== "center") + sizeHandles(pane); // also update resizer length if (s.noRoom && !s.isClosed && !s.isHidden) makePaneFit(pane); // will re-open/show auto-closed/hidden pane if (s.isVisible) { @@ -3851,10 +3879,11 @@ $.fn.layout = function (opts) { * Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes * Normally these panes have only 'left' & 'right' positions so pane auto-sizes * ALSO required when pane is an IFRAME because will NOT default to 'full width' + * TODO: Can I use width:100% for a north/south iframe? + * TODO: Sounds like a job for $P.outerWidth( sC.innerWidth ) SETTER METHOD */ if (pane === "center") { // finished processing midPanes - var b = $.layout.browser; - var fix = b.isIE6 || (b.msie && !$.support.boxModel); + var fix = browser.isIE6 || !browser.boxModel; if ($Ps.north && (fix || state.north.tagName=="IFRAME")) $Ps.north.css("width", cssW($Ps.north, sC.innerWidth)); if ($Ps.south && (fix || state.south.tagName=="IFRAME")) @@ -3871,7 +3900,10 @@ $.fn.layout = function (opts) { /** * @see window.onresize(), callbacks or custom code */ -, resizeAll = function () { +, resizeAll = function (evt) { + // stopPropagation if called by trigger("layoutdestroy") - use evtPane utility + evtPane(evt); + if (!state.initialized) { _initLayoutElements(); return; // no need to resize since we just initialized! @@ -3880,8 +3912,8 @@ $.fn.layout = function (opts) { , oldH = sC.innerHeight ; // cannot size layout when 'container' is hidden or collapsed - if (!$N.is(":visible:") ) return; - $.extend( state.container, elDims( $N ) ); // UPDATE container dimensions + if (!$N.is(":visible") ) return; + $.extend(state.container, elDims( $N )); // UPDATE container dimensions if (!sC.outerHeight) return; // onresizeall_start will CANCEL resizing if returns false @@ -3927,7 +3959,7 @@ $.fn.layout = function (opts) { /** * Whenever a pane resizes or opens that has a nested layout, trigger resizeAll * - * @param {string} pane The pane just resized or opened + * @param {string|Object} evt_or_pane The pane just resized or opened */ , resizeChildLayout = function (evt_or_pane) { var pane = evtPane.call(this, evt_or_pane); @@ -3961,8 +3993,8 @@ $.fn.layout = function (opts) { /** * IF pane has a content-div, then resize all elements inside pane to fit pane-height * - * @param {string=} [panes=""] The pane(s) being resized - * @param {boolean=} [remeasure=false] Should the content (header/footer) be remeasured? + * @param {string|Object} evt_or_panes The pane(s) being resized + * @param {boolean=} [remeasure=false] Should the content (header/footer) be remeasured? */ , sizeContent = function (evt_or_panes, remeasure) { if (!isInitialized()) return; @@ -4046,7 +4078,7 @@ $.fn.layout = function (opts) { * Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary * * @see initHandles(), open(), close(), resizeAll() - * @param {string=} [panes=""] The pane(s) being resized + * @param {string|Object} evt_or_panes The pane(s) being resized */ , sizeHandles = function (evt_or_panes) { var panes = evtPane.call(this, evt_or_panes) @@ -4184,7 +4216,7 @@ $.fn.layout = function (opts) { /** - * @param {string} pane + * @param {string|Object} evt_or_pane */ , enableClosable = function (evt_or_pane) { if (!isInitialized()) return; @@ -4197,12 +4229,12 @@ $.fn.layout = function (opts) { $T .bind("click."+ sID, function(evt){ evt.stopPropagation(); toggle(pane); }) .css("visibility", "visible") .css("cursor", "pointer") - .attr("title", state[pane].isClosed ? o.togglerTip_closed : o.togglerTip_open) // may be blank + .attr("title", state[pane].isClosed ? o.tips.Open : o.tips.Close) // may be blank .show(); } /** - * @param {string} pane - * @param {boolean=} [hide=false] + * @param {string|Object} evt_or_pane + * @param {boolean=} [hide=false] */ , disableClosable = function (evt_or_pane, hide) { if (!isInitialized()) return; @@ -4221,7 +4253,7 @@ $.fn.layout = function (opts) { /** - * @param {string} pane + * @param {string|Object} evt_or_pane */ , enableSlidable = function (evt_or_pane) { if (!isInitialized()) return; @@ -4230,11 +4262,11 @@ $.fn.layout = function (opts) { ; if (!$R || !$R.data('draggable')) return; options[pane].slidable = true; - if (s.isClosed) + if (state[pane].isClosed) bindStartSlidingEvent(pane, true); } /** - * @param {string} pane + * @param {string|Object} evt_or_pane */ , disableSlidable = function (evt_or_pane) { if (!isInitialized()) return; @@ -4255,7 +4287,7 @@ $.fn.layout = function (opts) { /** - * @param {string} pane + * @param {string|Object} evt_or_pane */ , enableResizable = function (evt_or_pane) { if (!isInitialized()) return; @@ -4268,10 +4300,10 @@ $.fn.layout = function (opts) { $R.draggable("enable"); if (!state[pane].isClosed) $R .css("cursor", o.resizerCursor) - .attr("title", o.resizerTip); + .attr("title", o.tips.Resize); } /** - * @param {string} pane + * @param {string|Object} evt_or_pane */ , disableResizable = function (evt_or_pane) { if (!isInitialized()) return; @@ -4291,8 +4323,8 @@ $.fn.layout = function (opts) { * Move a pane from source-side (eg, west) to target-side (eg, east) * If pane exists on target-side, move that to source-side, ie, 'swap' the panes * - * @param {string} pane1 The pane/edge being swapped - * @param {string} pane2 ditto + * @param {string|Object} evt_or_pane1 The pane/edge being swapped + * @param {string} pane2 ditto */ , swapPanes = function (evt_or_pane1, pane2) { if (!isInitialized()) return; @@ -4374,7 +4406,7 @@ $.fn.layout = function (opts) { , side = c.side.toLowerCase() , inset = "inset"+ c.side // save pane-options that should be retained - , s = $.extend({}, state[pane]) + , s = $.extend(true, {}, state[pane]) , o = options[pane] // RETAIN side-specific FX Settings - more below , fx = { resizerCursor: o.resizerCursor } @@ -4398,8 +4430,8 @@ $.fn.layout = function (opts) { $Cs[pane] = C ? $(C) : false; // set options and state - options[pane] = $.extend({}, oPane.options, fx); - state[pane] = $.extend({}, oPane.state); + options[pane] = $.extend(true, {}, oPane.options, fx); + state[pane] = $.extend(true, {}, oPane.state); // change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west re = new RegExp(o.paneClass +"-"+ oldPane, "g"); @@ -4559,11 +4591,11 @@ $.fn.layout = function (opts) { curCSS.overflow = of; newCSS.overflow = "visible"; } - if (ofX && !ofX.match(/visible|auto/)) { + if (ofX && !ofX.match(/(visible|auto)/)) { curCSS.overflowX = ofX; newCSS.overflowX = "visible"; } - if (ofY && !ofY.match(/visible|auto/)) { + if (ofY && !ofY.match(/(visible|auto)/)) { curCSS.overflowY = ofX; newCSS.overflowY = "visible"; } @@ -4625,9 +4657,7 @@ $.fn.layout = function (opts) { // validate that container exists var $N = $(this).eq(0); // FIRST matching Container element if (!$N.length) { - if (options.showErrorMessages) - _log( lang.errContainerMissing, true ); - return null; + return _log( options.errors.containerMissing ); }; // Users retrieve Instance of a layout with: $N.layout() OR $N.data("layout") @@ -4673,6 +4703,8 @@ $.fn.layout = function (opts) { , sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto' , sizeContent: sizeContent // method - pass a 'pane' , swapPanes: swapPanes // method - pass TWO 'panes' - will swap them + , showMasks: showMasks // method - pass a 'pane' OR list of panes - default = all panes with mask option set + , hideMasks: hideMasks // method - ditto' // pane element methods , initContent: initContent // method - ditto , addPane: addPane // method - pass a 'pane' @@ -4713,6 +4745,13 @@ $.fn.layout = function (opts) { } +/* OLD versions of jQuery only set $.support.boxModel after page is loaded + * so if this is IE, use support.boxModel to test for quirks-mode (ONLY IE changes boxModel). + */ +$(function(){ + var b = $.layout.browser; + if (b.msie) b.boxModel = $.support.boxModel; +}); /** @@ -4869,7 +4908,7 @@ $.layout.state = { * * @param {Object} inst * @param {(string|Array)=} keys - * @param {Object=} opts + * @param {Object=} cookieOpts */ saveCookie: function (inst, keys, cookieOpts) { var o = inst.options @@ -5097,8 +5136,6 @@ $.layout.defaults.autoBindCustomButtons = false; // Specify autoBindCustomButtons as a layout-option, NOT a pane-option $.layout.optionsMap.layout.push("autoBindCustomButtons"); -var lang = $.layout.language; - /* * Button methods */ @@ -5147,13 +5184,13 @@ $.layout.buttons = { , get: function (inst, selector, pane, action) { var $E = $(selector) , o = inst.options - , err = o.showErrorMessages + , err = o.errors.addButtonError ; if (!$E.length) { // element not found - if (err) $.layout.msg(lang.errButton + lang.selector +": "+ selector, true); + $.layout.msg(err +" "+ o.errors.selector +": "+ selector, true); } else if ($.inArray(pane, $.layout.config.borderPanes) < 0) { // invalid 'pane' sepecified - if (err) $.layout.msg(lang.errButton + lang.pane +": "+ pane, true); + $.layout.msg(err +" "+ o.errors.pane +": "+ pane, true); $E = $(""); // NO BUTTON } else { // VALID @@ -5213,7 +5250,7 @@ $.layout.buttons = { */ , addOpen: function (inst, selector, pane, slide) { $.layout.buttons.get(inst, selector, pane, "open") - .attr("title", lang.Open) + .attr("title", inst.options[pane].tips.Open) .click(function (evt) { inst.open(pane, !!slide); evt.stopPropagation(); @@ -5230,7 +5267,7 @@ $.layout.buttons = { */ , addClose: function (inst, selector, pane) { $.layout.buttons.get(inst, selector, pane, "close") - .attr("title", lang.Close) + .attr("title", inst.options[pane].tips.Close) .click(function (evt) { inst.close(pane); evt.stopPropagation(); @@ -5286,14 +5323,15 @@ $.layout.buttons = { var updown = $Pin.attr("pin"); if (updown && doPin === (updown=="down")) return; // already in correct state var - pin = inst.options[pane].buttonClass +"-pin" + o = inst.options[pane] + , pin = o.buttonClass +"-pin" , side = pin +"-"+ pane , UP = pin +"-up "+ side +"-up" , DN = pin +"-down "+side +"-down" ; $Pin .attr("pin", doPin ? "down" : "up") // logic - .attr("title", doPin ? lang.Unpin : lang.Pin) + .attr("title", doPin ? o.tips.Unpin : o.tips.Pin) .removeClass( doPin ? UP : DN ) .addClass( doPin ? DN : UP ) ; @@ -5311,7 +5349,7 @@ $.layout.buttons = { */ , syncPinBtns: function (inst, pane, doPin) { // REAL METHOD IS _INSIDE_ LAYOUT - THIS IS HERE JUST FOR REFERENCE - $.each(state[pane].pins, function (i, selector) { + $.each(inst.state[pane].pins, function (i, selector) { $.layout.buttons.setPinState(inst, $(selector), pane, doPin); }); } diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js index 5920fdfdb2..6d1caf6d50 100644 --- a/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js +++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js @@ -2,6 +2,22 @@ // code by Gilles Dubochet with contributions by Pedro Furlanetto $(document).ready(function(){ + + // Escapes special characters and returns a valid jQuery selector + function escapeJquery(str){ + return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); + } + + // highlight and jump to selected member + if (window.location.hash) { + var temp = window.location.hash.replace('#', ''); + var elem = '#'+escapeJquery(temp); + + window.scrollTo(0, 0); + $(elem).parent().effect("highlight", {color: "#FFCC85"}, 3000); + $('html,body').animate({scrollTop:$(elem).parent().offset().top}, 1000); + } + var isHiddenClass = function (name) { return name == 'scala.Any' || name == 'scala.AnyRef'; @@ -101,6 +117,12 @@ $(document).ready(function(){ $("#linearization li.in").removeClass("in").addClass("out"); $("#linearization li:first").removeClass("out").addClass("in"); $("#implicits li.in").removeClass("in").addClass("out"); + + if ($(this).hasClass("out") && $("#mbrsel > div[id=ancestors] > ol > li.showall").hasClass("in")) { + $(this).removeClass("out").addClass("in"); + $("#mbrsel > div[id=ancestors] > ol > li.showall").removeClass("in").addClass("out"); + } + filter(); }) $("#mbrsel > div[id=ancestors] > ol > li.showall").click(function() { @@ -116,6 +138,11 @@ $(document).ready(function(){ }); filteredImplicits.removeClass("out").addClass("in"); + if ($(this).hasClass("out") && $("#mbrsel > div[id=ancestors] > ol > li.hideall").hasClass("in")) { + $(this).removeClass("out").addClass("in"); + $("#mbrsel > div[id=ancestors] > ol > li.hideall").removeClass("in").addClass("out"); + } + filter(); }); $("#visbl > ol > li.public").click(function() { diff --git a/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala b/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala index 21fd086231..5257db1610 100644 --- a/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala +++ b/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala @@ -120,19 +120,17 @@ trait MemberLookup { private object OnlyTerm extends SearchStrategy private def lookupInRootPackage(pos: Position, members: List[String]) = - if (members.length == 1) - lookupInTemplate(pos, members, EmptyPackage) ::: lookupInTemplate(pos, members, RootPackage) - else - lookupInTemplate(pos, members, RootPackage) + lookupInTemplate(pos, members, EmptyPackage) ::: lookupInTemplate(pos, members, RootPackage) private def createLinks(syms: List[(Symbol, Symbol)]): List[LinkTo] = syms.flatMap { case (sym, owner) => - if (sym.isClass || sym.isModule || sym.isTrait || sym.isPackage) - findTemplateMaybe(sym) map (LinkToTpl(_)) - else - findTemplateMaybe(owner) flatMap { inTpl => - inTpl.members find (_.asInstanceOf[EntityImpl].sym == sym) map (LinkToMember(_, inTpl)) - } + findTemplateMaybe(sym) match { + case Some(tpl) => LinkToTpl(tpl) :: Nil + case None => + findTemplateMaybe(owner) flatMap { inTpl => + inTpl.members find (_.asInstanceOf[EntityImpl].sym == sym) map (LinkToMember(_, inTpl)) + } + } } private def lookupInTemplate(pos: Position, members: List[String], container: Symbol): List[(Symbol, Symbol)] = { @@ -153,7 +151,7 @@ trait MemberLookup { case tplName::rest => def completeSearch(syms: List[Symbol]) = - syms filter {sym => sym.isPackage || sym.isClass || sym.isModule} flatMap (lookupInTemplate(pos, rest, _)) + syms flatMap (lookupInTemplate(pos, rest, _)) completeSearch(lookupInTemplate(pos, tplName, container, OnlyTerm)) match { case Nil => completeSearch(lookupInTemplate(pos, tplName, container, OnlyType)) diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala index 44e10d1c75..496aeb4aa1 100644 --- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala @@ -31,6 +31,12 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { import definitions.{ ObjectClass, NothingClass, AnyClass, AnyValClass, AnyRefClass, ListClass } import rootMirror.{ RootPackage, RootClass, EmptyPackage } + // Defaults for member grouping, that may be overridden by the template + val defaultGroup = "Ungrouped" + val defaultGroupName = "Ungrouped" + val defaultGroupDesc = None + val defaultGroupPriority = 1000 + def templatesCount = docTemplatesCache.count(_._2.isDocTemplate) - droppedPackages.size private var _modelFinished = false @@ -121,7 +127,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { } if (inTpl != null) thisFactory.comment(sym, thisTpl, inTpl) else None } - def group = if (comment.isDefined) comment.get.group.getOrElse("No Group") else "No Group" + def group = if (comment.isDefined) comment.get.group.getOrElse(defaultGroup) else defaultGroup override def inTemplate = inTpl override def toRoot: List[MemberImpl] = this :: inTpl.toRoot def inDefinitionTemplates = this match { @@ -286,7 +292,8 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { val tps = (this match { case a: AliasType => sym.tpe.dealias.parents case a: AbstractType => sym.info.bounds match { - case TypeBounds(lo, hi) => List(hi) + case TypeBounds(lo, RefinedType(parents, decls)) => parents + case TypeBounds(lo, hi) => hi :: Nil case _ => Nil } case _ => sym.tpe.parents @@ -403,7 +410,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { * This is the final point in the core model creation: no DocTemplates are created after the model has finished, but * inherited templates and implicit members are added to the members at this point. */ - def completeModel: Unit = { + def completeModel(): Unit = { // DFS completion // since alias types and abstract types have no own members, there's no reason for them to call completeModel if (!sym.isAliasType && !sym.isAbstractType) @@ -493,16 +500,21 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { if (entity != default) return entity } // query linearization - for (tpl <- linearizationTemplates.collect{ case dtpl: DocTemplateImpl if dtpl!=this => dtpl}) { - val entity = tpl.groupSearch(extractor, default) - if (entity != default) return entity - } - default + if (!sym.isPackage) + for (tpl <- linearizationTemplates.collect{ case dtpl: DocTemplateImpl if dtpl!=this => dtpl}) { + val entity = tpl.groupSearch(extractor, default) + if (entity != default) return entity + } + // query inTpl, going up the ownerChain + if (inTpl != null) + inTpl.groupSearch(extractor, default) + else + default } - def groupDescription(group: String): Option[Body] = groupSearch(_.groupDesc.get(group), None) - def groupPriority(group: String): Int = groupSearch(_.groupPrio.get(group) match { case Some(prio) => prio; case _ => 0 }, 0) - def groupName(group: String): String = groupSearch(_.groupNames.get(group) match { case Some(name) => name; case _ => group }, group) + def groupDescription(group: String): Option[Body] = groupSearch(_.groupDesc.get(group), if (group == defaultGroup) defaultGroupDesc else None) + def groupPriority(group: String): Int = groupSearch(_.groupPrio.get(group) match { case Some(prio) => prio; case _ => 0 }, if (group == defaultGroup) defaultGroupPriority else 0) + def groupName(group: String): String = groupSearch(_.groupNames.get(group) match { case Some(name) => name; case _ => group }, if (group == defaultGroup) defaultGroupName else group) } abstract class PackageImpl(sym: Symbol, inTpl: PackageImpl) extends DocTemplateImpl(sym, inTpl) with Package { @@ -736,7 +748,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { } else { // no class inheritance at this point - assert(inOriginalOwner(bSym, inTpl) || bSym.isAbstractType || bSym.isAliasType, bSym + " in " + inTpl) + assert(inOriginalOwner(bSym, inTpl), bSym + " in " + inTpl) Some(createDocTemplate(bSym, inTpl)) } } @@ -833,7 +845,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { Some(new MemberTemplateImpl(bSym, inTpl) with AliasImpl with AliasType { override def isAliasType = true }) - else if (!modelFinished && (bSym.isPackage || bSym.isAliasType || bSym.isAbstractType || templateShouldDocument(bSym, inTpl))) + else if (!modelFinished && (bSym.isPackage || templateShouldDocument(bSym, inTpl))) modelCreation.createTemplate(bSym, inTpl) else None @@ -861,7 +873,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { inTpl.members.find(_.sym == aSym) } - @deprecated("2.10", "Use findLinkTarget instead!") + @deprecated("Use `findLinkTarget` instead.", "2.10.0") def findTemplate(query: String): Option[DocTemplateImpl] = { assert(modelFinished) docTemplatesCache.values find { (tpl: DocTemplateImpl) => tpl.qualifiedName == query && !packageDropped(tpl) && !tpl.isObject } @@ -1040,8 +1052,8 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { def inOriginalOwner(aSym: Symbol, inTpl: TemplateImpl): Boolean = normalizeTemplate(aSym.owner) == normalizeTemplate(inTpl.sym) - def templateShouldDocument(aSym: Symbol, inTpl: TemplateImpl): Boolean = - (aSym.isTrait || aSym.isClass || aSym.isModule) && + def templateShouldDocument(aSym: Symbol, inTpl: DocTemplateImpl): Boolean = + (aSym.isTrait || aSym.isClass || aSym.isModule || typeShouldDocument(aSym, inTpl)) && localShouldDocument(aSym) && !isEmptyJavaObject(aSym) && // either it's inside the original owner or we can document it later: @@ -1081,6 +1093,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { // whether or not to create a page for an {abstract,alias} type def typeShouldDocument(bSym: Symbol, inTpl: DocTemplateImpl) = (settings.docExpandAllTypes.value && (bSym.sourceFile != null)) || + (bSym.isAliasType || bSym.isAbstractType) && { val rawComment = global.expandedDocComment(bSym, inTpl.sym) rawComment.contains("@template") || rawComment.contains("@documentable") } diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala index 1baa7f9831..924ebb8a3b 100644 --- a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala +++ b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala @@ -147,7 +147,7 @@ trait CommentFactory { thisFactory: ModelFactory with CommentFactory with Member case (group, body) => try { body match { - case Body(List(Paragraph(Chain(List(Summary(Text(prio))))))) => List(group -> prio.toInt) + case Body(List(Paragraph(Chain(List(Summary(Text(prio))))))) => List(group -> prio.trim.toInt) case _ => List() } } catch { diff --git a/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala b/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala index 3de2359ce3..b528948716 100644 --- a/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala +++ b/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala @@ -13,6 +13,7 @@ import scala.tools.nsc.util.FailedInterrupt import scala.tools.nsc.util.EmptyAction import scala.tools.nsc.util.WorkScheduler import scala.reflect.internal.util.{SourceFile, Position} +import scala.tools.nsc.util.InterruptReq /** Interface of interactive compiler to a client such as an IDE * The model the presentation compiler consists of the following parts: @@ -69,11 +70,11 @@ trait CompilerControl { self: Global => * if it does not yet exist create a new one atomically * Note: We want to get roid of this operation as it messes compiler invariants. */ - @deprecated("use getUnitOf(s) or onUnitOf(s) instead") + @deprecated("use getUnitOf(s) or onUnitOf(s) instead", "2.10.0") def unitOf(s: SourceFile): RichCompilationUnit = getOrCreateUnitOf(s) /** The compilation unit corresponding to a position */ - @deprecated("use getUnitOf(pos.source) or onUnitOf(pos.source) instead") + @deprecated("use getUnitOf(pos.source) or onUnitOf(pos.source) instead", "2.10.0") def unitOf(pos: Position): RichCompilationUnit = getOrCreateUnitOf(pos.source) /** Removes the CompilationUnit corresponding to the given SourceFile @@ -221,6 +222,7 @@ trait CompilerControl { self: Global => * everything is brought up to date in a regular type checker run. * @param response The response. */ + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") def askInstrumented(source: SourceFile, line: Int, response: Response[(String, Array[Char])]) = postWorkItem(new AskInstrumentedItem(source, line, response)) @@ -232,7 +234,7 @@ trait CompilerControl { self: Global => /** Tells the compile server to shutdown, and not to restart again */ def askShutdown() = scheduler raise ShutdownReq - @deprecated("use parseTree(source) instead") // deleted 2nd parameter, as this has to run on 2.8 also. + @deprecated("use parseTree(source) instead", "2.10.0") // deleted 2nd parameter, as this has to run on 2.8 also. def askParse(source: SourceFile, response: Response[Tree]) = respond(response) { parseTree(source) } @@ -388,6 +390,7 @@ trait CompilerControl { self: Global => response raise new MissingResponse } + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") case class AskInstrumentedItem(val source: SourceFile, line: Int, response: Response[(String, Array[Char])]) extends WorkItem { def apply() = self.getInstrumented(source, line, response) override def toString = "getInstrumented "+source @@ -413,6 +416,16 @@ trait CompilerControl { self: Global => override def doQuickly[A](op: () => A): A = { throw new FailedInterrupt(new Exception("Posted a work item to a compiler that's shutting down")) } + + override def askDoQuickly[A](op: () => A): InterruptReq { type R = A } = { + val ir = new InterruptReq { + type R = A + val todo = () => throw new MissingResponse + } + ir.execute() + ir + } + } } diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala index 5514983d98..01889f4f98 100644 --- a/src/compiler/scala/tools/nsc/interactive/Global.scala +++ b/src/compiler/scala/tools/nsc/interactive/Global.scala @@ -205,7 +205,7 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") protected[interactive] var minRunId = 1 - private var interruptsEnabled = true + private[interactive] var interruptsEnabled = true private val NoResponse: Response[_] = new Response[Any] @@ -1041,6 +1041,7 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") } } + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") def getInstrumented(source: SourceFile, line: Int, response: Response[(String, Array[Char])]) = try { interruptsEnabled = false diff --git a/src/compiler/scala/tools/nsc/interactive/REPL.scala b/src/compiler/scala/tools/nsc/interactive/REPL.scala index afac5828e5..be837b32f3 100644 --- a/src/compiler/scala/tools/nsc/interactive/REPL.scala +++ b/src/compiler/scala/tools/nsc/interactive/REPL.scala @@ -92,6 +92,7 @@ object REPL { val completeResult = new Response[List[comp.Member]] val typedResult = new Response[comp.Tree] val structureResult = new Response[comp.Tree] + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") val instrumentedResult = new Response[(String, Array[Char])] def makePos(file: String, off1: String, off2: String) = { @@ -124,6 +125,7 @@ object REPL { * @param iContents An Array[Char] containing the instrumented source * @return The name of the instrumented source file */ + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") def writeInstrumented(iFullName: String, suffix: String, iContents: Array[Char]): String = { val iSimpleName = iFullName drop ((iFullName lastIndexOf '.') + 1) val iSourceName = iSimpleName + suffix @@ -142,6 +144,7 @@ object REPL { * and outputs in the right column, or None if the presentation compiler * does not respond to askInstrumented. */ + @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") def instrument(arguments: List[String], line: Int): Option[(String, String)] = { val source = toSourceFile(arguments.head) // strip right hand side comment column and any trailing spaces from all lines diff --git a/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala b/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala index dfbbb6ff88..7f0265bf4f 100644 --- a/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala +++ b/src/compiler/scala/tools/nsc/interactive/ScratchPadMaker.scala @@ -6,6 +6,7 @@ import scala.collection.mutable.ArrayBuffer import scala.reflect.internal.Chars.{isLineBreakChar, isWhitespace} import ast.parser.Tokens._ +@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") trait ScratchPadMaker { self: Global => import definitions._ @@ -35,7 +36,7 @@ trait ScratchPadMaker { self: Global => private def literal(str: String) = "\"\"\""+str+"\"\"\"" - private val prologue = "import scala.runtime.WorksheetSupport._; def main(args: Array[String])=$execute{" + private val prologue = ";import scala.runtime.WorksheetSupport._; def main(args: Array[String])=$execute{" private val epilogue = "}" @@ -117,12 +118,13 @@ trait ScratchPadMaker { self: Global => super.traverse(tree) case ModuleDef(_, name, Template(_, _, body)) => val topLevel = objectName.isEmpty - if (topLevel) objectName = tree.symbol.fullName - body foreach traverseStat - if (skipped != 0) { // don't issue prologue and epilogue if there are no instrumented statements - applyPendingPatches(skipped) - if (topLevel) + if (topLevel) { + objectName = tree.symbol.fullName + body foreach traverseStat + if (skipped != 0) { // don't issue prologue and epilogue if there are no instrumented statements + applyPendingPatches(skipped) patches += Patch(skipped, epilogue) + } } case _ => } diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala index af77d3fe3f..40e520076a 100644 --- a/src/compiler/scala/tools/nsc/matching/Patterns.scala +++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala @@ -21,7 +21,7 @@ trait Patterns extends ast.TreeDSL { import definitions._ import CODE._ import Debug._ - import treeInfo.{ unbind, isStar, isVarPattern, isVariableName } + import treeInfo.{ unbind, isStar, isVarPattern } type PatternMatch = MatchMatrix#PatternMatch private type PatternVar = MatrixContext#PatternVar @@ -366,7 +366,7 @@ trait Patterns extends ast.TreeDSL { lazy val Select(qualifier, name) = select def pathSegments = getPathSegments(tree) def backticked: Option[String] = qualifier match { - case _: This if isVariableName(name) => Some("`%s`".format(name)) + case _: This if nme.isVariableName(name) => Some("`%s`".format(name)) case _ => None } override def covers(sym: Symbol) = newMatchesPattern(sym, tree.tpe) @@ -388,11 +388,11 @@ trait Patterns extends ast.TreeDSL { lazy val UnApply(unfn, args) = tree lazy val Apply(fn, _) = unfn lazy val MethodType(List(arg, _*), _) = fn.tpe - + // Covers if the symbol matches the unapply method's argument type, // and the return type of the unapply is Some. override def covers(sym: Symbol) = newMatchesPattern(sym, arg.tpe) - + // TODO: for alwaysCovers: // fn.tpe.finalResultType.typeSymbol == SomeClass @@ -451,7 +451,7 @@ trait Patterns extends ast.TreeDSL { (sym.tpe.baseTypeSeq exists (_ matchesPattern pattp)) } } - + def sym = tree.symbol def tpe = tree.tpe def isEmpty = tree.isEmpty @@ -496,4 +496,4 @@ trait Patterns extends ast.TreeDSL { } } } -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala b/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala index f7ad39bd95..10e9982594 100644 --- a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala +++ b/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala @@ -7,6 +7,7 @@ import java.lang.reflect.InvocationTargetException import scala.reflect.runtime.ReflectionUtils._ import scala.collection.mutable.ArrayBuffer +@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") class Mixer { protected val stdSeparator = "//> " diff --git a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala b/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala index 5eeab53fca..01dccd7521 100644 --- a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala +++ b/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala @@ -5,6 +5,7 @@ import java.io.Writer import scala.reflect.internal.util.SourceFile import scala.reflect.internal.Chars._ +@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") object SourceInserter { def stripRight(cs: Array[Char]): Array[Char] = { val lines = diff --git a/src/compiler/scala/tools/nsc/settings/Warnings.scala b/src/compiler/scala/tools/nsc/settings/Warnings.scala index 16f8685a87..72284cc940 100644 --- a/src/compiler/scala/tools/nsc/settings/Warnings.scala +++ b/src/compiler/scala/tools/nsc/settings/Warnings.scala @@ -18,6 +18,7 @@ trait Warnings { // These warnings are all so noisy as to be useless in their // present form, but have the potential to offer useful info. protected def allWarnings = lintWarnings ++ List( + warnDeadCode, warnSelectNullable, warnValueDiscard, warnNumericWiden @@ -25,7 +26,7 @@ trait Warnings { // These warnings should be pretty quiet unless you're doing // something inadvisable. protected def lintWarnings = List( - warnDeadCode, + // warnDeadCode, warnInaccessible, warnNullaryOverride, warnNullaryUnit, diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala index f7c3a55954..369b6aa77d 100644 --- a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala +++ b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala @@ -219,7 +219,7 @@ abstract class SymbolLoaders { /** * Load contents of a package */ - class PackageLoader(classpath: ClassPath[platform.BinaryRepr]) extends SymbolLoader { + class PackageLoader(classpath: ClassPath[platform.BinaryRepr]) extends SymbolLoader with FlagAgnosticCompleter { protected def description = "package loader "+ classpath.name protected def doComplete(root: Symbol) { @@ -242,7 +242,7 @@ abstract class SymbolLoaders { } } - class ClassfileLoader(val classfile: AbstractFile) extends SymbolLoader { + class ClassfileLoader(val classfile: AbstractFile) extends SymbolLoader with FlagAssigningCompleter { private object classfileParser extends ClassfileParser { val global: SymbolLoaders.this.global.type = SymbolLoaders.this.global } @@ -267,7 +267,7 @@ abstract class SymbolLoaders { override def sourcefile: Option[AbstractFile] = classfileParser.srcfile } - class MsilFileLoader(msilFile: MsilFile) extends SymbolLoader { + class MsilFileLoader(msilFile: MsilFile) extends SymbolLoader with FlagAssigningCompleter { private def typ = msilFile.msilType private object typeParser extends clr.TypeParser { val global: SymbolLoaders.this.global.type = SymbolLoaders.this.global @@ -277,14 +277,14 @@ abstract class SymbolLoaders { protected def doComplete(root: Symbol) { typeParser.parse(typ, root) } } - class SourcefileLoader(val srcfile: AbstractFile) extends SymbolLoader { + class SourcefileLoader(val srcfile: AbstractFile) extends SymbolLoader with FlagAssigningCompleter { protected def description = "source file "+ srcfile.toString override def fromSource = true override def sourcefile = Some(srcfile) protected def doComplete(root: Symbol): Unit = global.currentRun.compileLate(srcfile) } - object moduleClassLoader extends SymbolLoader { + object moduleClassLoader extends SymbolLoader with FlagAssigningCompleter { protected def description = "module class loader" protected def doComplete(root: Symbol) { root.sourceModule.initialize } } diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index a356b70e62..8fd8dfaf83 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -844,7 +844,7 @@ abstract class ClassfileParser { GenPolyType(ownTypeParams, tpe) } // sigToType - class TypeParamsType(override val typeParams: List[Symbol]) extends LazyType { + class TypeParamsType(override val typeParams: List[Symbol]) extends LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) { throw new AssertionError("cyclic type dereferencing") } } @@ -1228,7 +1228,7 @@ abstract class ClassfileParser { } } - class LazyAliasType(alias: Symbol) extends LazyType { + class LazyAliasType(alias: Symbol) extends LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) { sym setInfo createFromClonedSymbols(alias.initialize.typeParams, alias.tpe)(typeFun) } diff --git a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala index 18b95ba191..1d2ffd2a73 100644 --- a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala @@ -64,7 +64,7 @@ abstract class TypeParser { busy = false } - class TypeParamsType(override val typeParams: List[Symbol]) extends LazyType { + class TypeParamsType(override val typeParams: List[Symbol]) extends LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) { throw new AssertionError("cyclic type dereferencing") } } diff --git a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala index ab0a8756a4..143dcaa8be 100644 --- a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala +++ b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala @@ -132,7 +132,7 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => * - for every interface member of iface: its implementation method, if one is needed * - every former member of iface that is implementation only */ - private class LazyImplClassType(iface: Symbol) extends LazyType { + private class LazyImplClassType(iface: Symbol) extends LazyType with FlagAgnosticCompleter { /** Compute the decls of implementation class implClass, * given the decls ifaceDecls of its interface. */ @@ -231,9 +231,8 @@ abstract class AddInterfaces extends InfoTransform { self: Erasure => extends ChangeOwnerTraverser(oldowner, newowner) { override def traverse(tree: Tree) { tree match { - case Return(expr) => - if (tree.symbol == oldowner) tree.symbol = newowner - case _ => + case _: Return => change(tree.symbol) + case _ => } super.traverse(tree) } diff --git a/src/compiler/scala/tools/nsc/transform/Constructors.scala b/src/compiler/scala/tools/nsc/transform/Constructors.scala index 23b15a9033..4b9585bb93 100644 --- a/src/compiler/scala/tools/nsc/transform/Constructors.scala +++ b/src/compiler/scala/tools/nsc/transform/Constructors.scala @@ -127,7 +127,8 @@ abstract class Constructors extends Transform with ast.TreeDSL { import CODE._ val result = mkAssign(to, Ident(from)) - if (from.name != nme.OUTER) result + if (from.name != nme.OUTER || + from.tpe.typeSymbol.isPrimitiveValueClass) result else localTyper.typedPos(to.pos) { IF (from OBJ_EQ NULL) THEN Throw(NullPointerExceptionClass.tpe) ELSE result } diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala index 5d5e150662..3ac7dd2a8f 100644 --- a/src/compiler/scala/tools/nsc/transform/Erasure.scala +++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala @@ -663,7 +663,7 @@ abstract class Erasure extends AddInterfaces /** Generate a synthetic cast operation from tree.tpe to pt. * @pre pt eq pt.normalize */ - private def cast(tree: Tree, pt: Type): Tree = { + private def cast(tree: Tree, pt: Type): Tree = logResult(s"cast($tree, $pt)") { if (pt.typeSymbol == UnitClass) { // See SI-4731 for one example of how this occurs. log("Attempted to cast to Unit: " + tree) diff --git a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala index 8a9d0e58ec..6dd937c0ad 100644 --- a/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala +++ b/src/compiler/scala/tools/nsc/transform/ExtensionMethods.scala @@ -56,11 +56,11 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { case OverloadedType(_, alts) => val index = alts indexOf imeth assert(index >= 0, alts+" does not contain "+imeth) - def altName(index: Int) = newTermName("extension"+index+"$"+imeth.name) + def altName(index: Int) = newTermName(imeth.name+"$extension"+index) altName(index) #:: ((0 until alts.length).toStream filter (index != _) map altName) case tpe => assert(tpe != NoType, imeth.name+" not found in "+imeth.owner+"'s decls: "+imeth.owner.info.decls) - Stream(newTermName("extension$"+imeth.name)) + Stream(newTermName(imeth.name+"$extension")) } } @@ -68,10 +68,10 @@ abstract class ExtensionMethods extends Transform with TypingTransformers { */ def extensionMethod(imeth: Symbol): Symbol = atPhase(currentRun.refchecksPhase) { val companionInfo = imeth.owner.companionModule.info - val candidates = extensionNames(imeth) map (companionInfo.decl(_)) + val candidates = extensionNames(imeth) map (companionInfo.decl(_)) filter (_.exists) val matching = candidates filter (alt => normalize(alt.tpe, imeth.owner) matches imeth.tpe) assert(matching.nonEmpty, - s"no extension method found for $imeth:${imeth.tpe}+among ${candidates map (c => c.name+":"+c.tpe)} / ${extensionNames(imeth)}") + s"no extension method found for $imeth:${imeth.tpe} among ${candidates map (c => c.name+":"+c.tpe)} / ${extensionNames(imeth)}") matching.head } diff --git a/src/compiler/scala/tools/nsc/transform/LazyVals.scala b/src/compiler/scala/tools/nsc/transform/LazyVals.scala index 12e2433e0d..21213cf9d9 100644 --- a/src/compiler/scala/tools/nsc/transform/LazyVals.scala +++ b/src/compiler/scala/tools/nsc/transform/LazyVals.scala @@ -94,6 +94,7 @@ abstract class LazyVals extends Transform with TypingTransformers with ast.TreeD } else sym.owner } + debuglog(s"determined enclosing class/dummy/method for lazy val as $enclosingClassOrDummyOrMethod given symbol $sym") val idx = lazyVals(enclosingClassOrDummyOrMethod) lazyVals(enclosingClassOrDummyOrMethod) = idx + 1 val (rhs1, sDef) = mkLazyDef(enclosingClassOrDummyOrMethod, transform(rhs), idx, sym) @@ -194,6 +195,7 @@ abstract class LazyVals extends Transform with TypingTransformers with ast.TreeD val defSym = clazz.newMethod(nme.newLazyValSlowComputeName(lzyVal.name), lzyVal.pos, STABLE | PRIVATE) defSym setInfo MethodType(List(), lzyVal.tpe.resultType) defSym.owner = lzyVal.owner + debuglog(s"crete slow compute path $defSym with owner ${defSym.owner} for lazy val $lzyVal") if (bitmaps.contains(lzyVal)) bitmaps(lzyVal).map(_.owner = defSym) val rhs: Tree = (gen.mkSynchronizedCheck(clazz, cond, syncBody, stats)).changeOwner(currentOwner -> defSym) @@ -248,6 +250,7 @@ abstract class LazyVals extends Transform with TypingTransformers with ast.TreeD def mkBlock(stmt: Tree) = BLOCK(stmt, mkSetFlag(bitmapSym, mask, bitmapRef), UNIT) + debuglog(s"create complete lazy def in $methOrClass for $lazyVal") val (block, res) = tree match { case Block(List(assignment), res) if !lazyUnit(lazyVal) => (mkBlock(assignment), res) diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 5a3db26e30..d3a5cebea0 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -185,7 +185,7 @@ abstract class UnCurry extends InfoTransform * try { * body * } catch { - * case ex: NonLocalReturnControl[_] => + * case ex: NonLocalReturnControl[T @unchecked] => * if (ex.key().eq(key)) ex.value() * else throw ex * } @@ -195,7 +195,8 @@ abstract class UnCurry extends InfoTransform localTyper typed { val extpe = nonLocalReturnExceptionType(meth.tpe.finalResultType) val ex = meth.newValue(nme.ex, body.pos) setInfo extpe - val pat = gen.mkBindForCase(ex, NonLocalReturnControlClass, List(meth.tpe.finalResultType)) + val argType = meth.tpe.finalResultType withAnnotation (AnnotationInfo marker UncheckedClass.tpe) + val pat = gen.mkBindForCase(ex, NonLocalReturnControlClass, List(argType)) val rhs = ( IF ((ex DOT nme.key)() OBJ_EQ Ident(key)) THEN ((ex DOT nme.value)()) diff --git a/src/compiler/scala/tools/nsc/typechecker/Checkable.scala b/src/compiler/scala/tools/nsc/typechecker/Checkable.scala new file mode 100644 index 0000000000..7e15cf91a7 --- /dev/null +++ b/src/compiler/scala/tools/nsc/typechecker/Checkable.scala @@ -0,0 +1,284 @@ +/* NSC -- new Scala compiler + * Copyright 2005-2012 LAMP/EPFL + * @author Paul Phillips + */ + +package scala.tools.nsc +package typechecker + +import scala.collection.{ mutable, immutable } +import scala.collection.mutable.ListBuffer +import scala.util.control.ControlThrowable +import symtab.Flags._ +import scala.annotation.tailrec +import Checkability._ + +/** On pattern matcher checkability: + * + * Consider a pattern match of this form: (x: X) match { case _: P => } + * + * There are four possibilities to consider: + * [P1] X will always conform to P + * [P2] x will never conform to P + * [P3] X <: P if some runtime test is true + * [P4] X cannot be checked against P + * + * The first two cases correspond to those when there is enough + * static information to say X <: P or that (x ∈ X) ⇒ (x ∉ P). + * The fourth case includes unknown abstract types or structural + * refinements appearing within a pattern. + * + * The third case is the interesting one. We designate another type, XR, + * which is essentially the intersection of X and |P|, where |P| is + * the erasure of P. If XR <: P, then no warning is emitted. + * + * Examples of how this info is put to use: + * sealed trait A[T] ; class B[T] extends A[T] + * def f(x: B[Int]) = x match { case _: A[Int] if true => } + * def g(x: A[Int]) = x match { case _: B[Int] => } + * + * `f` requires no warning because X=B[Int], P=A[Int], and B[Int] <:< A[Int]. + * `g` requires no warning because X=A[Int], P=B[Int], XR=B[Int], and B[Int] <:< B[Int]. + * XR=B[Int] because a value of type A[Int] which is tested to be a B can + * only be a B[Int], due to the definition of B (B[T] extends A[T].) + * + * This is something like asSeenFrom, only rather than asking what a type looks + * like from the point of view of one of its base classes, we ask what it looks + * like from the point of view of one of its subclasses. + */ +trait Checkable { + self: Analyzer => + + import global._ + import definitions._ + import CheckabilityChecker.{ isNeverSubType, isNeverSubClass } + + /** The applied type of class 'to' after inferring anything + * possible from the knowledge that 'to' must also be of the + * type given in 'from'. + */ + def propagateKnownTypes(from: Type, to: Symbol): Type = { + def tparams = to.typeParams + val tvars = tparams map (p => TypeVar(p)) + val tvarType = appliedType(to, tvars: _*) + val bases = from.baseClasses filter (to.baseClasses contains _) + + bases foreach { bc => + val tps1 = (from baseType bc).typeArgs + val tps2 = (tvarType baseType bc).typeArgs + (tps1, tps2).zipped foreach (_ =:= _) + // Alternate, variance respecting formulation causes + // neg/unchecked3.scala to fail (abstract types). TODO - + // figure it out. It seems there is more work to do if I + // allow for variance, because the constraints accumulate + // as bounds and "tvar.instValid" is false. + // + // foreach3(tps1, tps2, bc.typeParams)((tp1, tp2, tparam) => + // if (tparam.initialize.isCovariant) tp1 <:< tp2 + // else if (tparam.isContravariant) tp2 <:< tp1 + // else tp1 =:= tp2 + // ) + } + + val resArgs = tparams zip tvars map { + case (_, tvar) if tvar.instValid => tvar.constr.inst + case (tparam, _) => tparam.tpe + } + appliedType(to, resArgs: _*) + } + + private def isUnwarnableTypeArgSymbol(sym: Symbol) = ( + sym.isTypeParameter // dummy + || (sym.name.toTermName == nme.WILDCARD) // _ + || nme.isVariableName(sym.name) // type variable + ) + private def isUnwarnableTypeArg(arg: Type) = ( + uncheckedOk(arg) // @unchecked T + || isUnwarnableTypeArgSymbol(arg.typeSymbolDirect) // has to be direct: see pos/t1439 + ) + private def uncheckedOk(tp: Type) = tp hasAnnotation UncheckedClass + + private def typeArgsInTopLevelType(tp: Type): List[Type] = { + val tps = tp match { + case RefinedType(parents, _) => parents flatMap typeArgsInTopLevelType + case TypeRef(_, ArrayClass, arg :: Nil) => typeArgsInTopLevelType(arg) + case TypeRef(pre, sym, args) => typeArgsInTopLevelType(pre) ++ args + case ExistentialType(tparams, underlying) => tparams.map(_.tpe) ++ typeArgsInTopLevelType(underlying) + case _ => Nil + } + tps filterNot isUnwarnableTypeArg + } + + private class CheckabilityChecker(val X: Type, val P: Type) { + def Xsym = X.typeSymbol + def Psym = P.typeSymbol + def XR = propagateKnownTypes(X, Psym) + // sadly the spec says (new java.lang.Boolean(true)).isInstanceOf[scala.Boolean] + def P1 = X matchesPattern P + def P2 = !Psym.isPrimitiveValueClass && isNeverSubType(X, P) + def P3 = isNonRefinementClassType(P) && (XR matchesPattern P) + def P4 = !(P1 || P2 || P3) + + def summaryString = f""" + |Checking checkability of (x: $X) against pattern $P + |[P1] $P1%-6s X <: P // $X <: $P + |[P2] $P2%-6s x ∉ P // (x ∈ $X) ⇒ (x ∉ $P) + |[P3] $P3%-6s XR <: P // $XR <: $P + |[P4] $P4%-6s None of the above // !(P1 || P2 || P3) + """.stripMargin.trim + + val result = ( + if (X.isErroneous || P.isErroneous) CheckabilityError + else if (P1) StaticallyTrue + else if (P2) StaticallyFalse + else if (P3) RuntimeCheckable + else if (uncheckableType == NoType) { + // Avoid warning (except ourselves) if we can't pinpoint the uncheckable type + debugwarn("Checkability checker says 'Uncheckable', but uncheckable type cannot be found:\n" + summaryString) + CheckabilityError + } + else Uncheckable + ) + lazy val uncheckableType = if (Psym.isAbstractType) P else { + val possibles = typeArgsInTopLevelType(P).toSet + val opt = possibles find { targ => + // Create a derived type with every possibly uncheckable type replaced + // with a WildcardType, except for 'targ'. If !(XR <: derived) then + // 'targ' is uncheckable. + val derived = P map (tp => if (possibles(tp) && !(tp =:= targ)) WildcardType else tp) + !(XR <:< derived) + } + opt getOrElse NoType + } + + def neverSubClass = isNeverSubClass(Xsym, Psym) + def neverMatches = result == StaticallyFalse + def isUncheckable = result == Uncheckable + def uncheckableMessage = uncheckableType match { + case NoType => "something" + case tp @ RefinedType(_, _) => "refinement " + tp + case TypeRef(_, sym, _) if sym.isAbstractType => "abstract type " + sym.name + case tp => "non-variable type argument " + tp + } + } + + /** X, P, [P1], etc. are all explained at the top of the file. + */ + private object CheckabilityChecker { + /** A knowable class is one which is either effectively final + * itself, or sealed with only knowable children. + */ + def isKnowable(sym: Symbol): Boolean = /*logResult(s"isKnowable($sym)")*/( + sym.initialize.isEffectivelyFinal // pesky .initialize requirement, or we receive lies about isSealed + || sym.isSealed && (sym.children forall isKnowable) + ) + def knownSubclasses(sym: Symbol): List[Symbol] = /*logResult(s"knownSubclasses($sym)")*/(sym :: { + if (sym.isSealed) sym.children.toList flatMap knownSubclasses + else Nil + }) + def excludable(s1: Symbol, s2: Symbol) = /*logResult(s"excludable($s1, $s2)")*/( + isKnowable(s1) + && !(s2 isSubClass s1) + && knownSubclasses(s1).forall(child => !(child isSubClass s2)) + ) + + /** Given classes A and B, can it be shown that nothing which is + * an A will ever be a subclass of something which is a B? This + * entails not only showing that !(A isSubClass B) but that the + * same is true of all their subclasses. Restated for symmetry: + * the same value cannot be a member of both A and B. + * + * 1) A must not be a subclass of B, nor B of A (the trivial check) + * 2) One of A or B must be completely knowable (see isKnowable) + * 3) Assuming A is knowable, the proposition is true if + * !(A' isSubClass B) for all A', where A' is a subclass of A. + * + * Due to symmetry, the last condition applies as well in reverse. + */ + def isNeverSubClass(sym1: Symbol, sym2: Symbol) = /*logResult(s"isNeverSubClass($sym1, $sym2)")*/( + sym1.isClass + && sym2.isClass + && (excludable(sym1, sym2) || excludable(sym2, sym1)) + ) + private def isNeverSubArgs(tps1: List[Type], tps2: List[Type], tparams: List[Symbol]): Boolean = /*logResult(s"isNeverSubArgs($tps1, $tps2, $tparams)")*/ { + def isNeverSubArg(t1: Type, t2: Type, variance: Int) = { + if (variance > 0) isNeverSubType(t2, t1) + else if (variance < 0) isNeverSubType(t1, t2) + else isNeverSameType(t1, t2) + } + exists3(tps1, tps2, tparams map (_.variance))(isNeverSubArg) + } + private def isNeverSameType(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match { + case (TypeRef(_, sym1, args1), TypeRef(_, sym2, args2)) => + ( isNeverSubClass(sym1, sym2) + || isNeverSubClass(sym2, sym1) + || ((sym1 == sym2) && isNeverSubArgs(args1, args2, sym1.typeParams)) + ) + case _ => + false + } + // Important to dealias at any entry point (this is the only one at this writing.) + def isNeverSubType(tp1: Type, tp2: Type): Boolean = /*logResult(s"isNeverSubType($tp1, $tp2)")*/((tp1.dealias, tp2.dealias) match { + case (TypeRef(_, sym1, args1), TypeRef(_, sym2, args2)) => + isNeverSubClass(sym1, sym2) || { + (sym1 isSubClass sym2) && { + val tp1seen = tp1 baseType sym2 + isNeverSubArgs(tp1seen.typeArgs, args2, sym2.typeParams) + } + } + case _ => false + }) + } + + trait InferCheckable { + self: Inferencer => + + /** TODO: much better error positions. + * Kind of stuck right now because they just pass us the one tree. + * TODO: Eliminate inPattern, canRemedy, which have no place here. + */ + def checkCheckable(tree: Tree, P0: Type, X0: Type, inPattern: Boolean, canRemedy: Boolean = false) { + if (uncheckedOk(P0)) return + def where = if (inPattern) "pattern " else "" + + // singleton types not considered here + val P = P0.widen + val X = X0.widen + + P match { + // Prohibit top-level type tests for these, but they are ok nested (e.g. case Foldable[Nothing] => ... ) + case TypeRef(_, NothingClass | NullClass | AnyValClass, _) => + InferErrorGen.TypePatternOrIsInstanceTestError(tree, P) + // If top-level abstract types can be checked using a classtag extractor, don't warn about them + case TypeRef(_, sym, _) if sym.isAbstractType && canRemedy => + ; + // Matching on types like case _: AnyRef { def bippy: Int } => doesn't work -- yet. + case RefinedType(_, decls) if !decls.isEmpty => + getContext.unit.warning(tree.pos, s"a pattern match on a refinement type is unchecked") + case _ => + val checker = new CheckabilityChecker(X, P) + log(checker.summaryString) + if (checker.neverMatches) { + val addendum = if (checker.neverSubClass) "" else " (but still might match its erasure)" + getContext.unit.warning(tree.pos, s"fruitless type test: a value of type $X cannot also be a $P$addendum") + } + else if (checker.isUncheckable) { + val msg = ( + if (checker.uncheckableType =:= P) s"abstract type $where$P" + else s"${checker.uncheckableMessage} in type $where$P" + ) + getContext.unit.warning(tree.pos, s"$msg is unchecked since it is eliminated by erasure") + } + } + } + } +} + +private[typechecker] final class Checkability(val value: Int) extends AnyVal { } +private[typechecker] object Checkability { + val StaticallyTrue = new Checkability(0) + val StaticallyFalse = new Checkability(1) + val RuntimeCheckable = new Checkability(2) + val Uncheckable = new Checkability(3) + val CheckabilityError = new Checkability(4) +} diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala index 22077303a4..cb5fc8df5a 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala @@ -17,7 +17,7 @@ import scala.annotation.tailrec * @author Martin Odersky * @version 1.0 */ -trait Infer { +trait Infer extends Checkable { self: Analyzer => import global._ @@ -254,7 +254,7 @@ trait Infer { private val stdErrorValue = stdErrorClass.newErrorValue(nme.ERROR) /** The context-dependent inferencer part */ - class Inferencer(context: Context) extends InferencerContextErrors { + class Inferencer(context: Context) extends InferencerContextErrors with InferCheckable { import InferErrorGen._ /* -- Error Messages --------------------------------------------------- */ @@ -517,7 +517,7 @@ trait Infer { val tvars = tparams map freshVar if (isConservativelyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt)) map2(tparams, tvars)((tparam, tvar) => - instantiateToBound(tvar, inferVariance(formals, restpe)(tparam))) + instantiateToBound(tvar, varianceInTypes(formals)(tparam))) else tvars map (tvar => WildcardType) } @@ -647,24 +647,13 @@ trait Infer { "argument expression's type is not compatible with formal parameter type" + foundReqMsg(tp1, pt1)) } } - val targs = solvedTypes( - tvars, tparams, tparams map inferVariance(formals, restpe), + tvars, tparams, tparams map varianceInTypes(formals), false, lubDepth(formals) max lubDepth(argtpes) ) adjustTypeArgs(tparams, tvars, targs, restpe) } - /** Determine which variance to assume for the type paraneter. We first chose the variance - * that minimizes any formal parameters. If that is still undetermined, because the type parameter - * does not appear as a formal parameter type, then we pick the variance so that it minimizes the - * method's result type instead. - */ - private def inferVariance(formals: List[Type], restpe: Type)(tparam: Symbol): Int = { - val v = varianceInTypes(formals)(tparam) - if (v != VarianceFlags) v else varianceInType(restpe)(tparam) - } - private[typechecker] def followApply(tp: Type): Type = tp match { case NullaryMethodType(restp) => val restp1 = followApply(restp) @@ -1341,99 +1330,6 @@ trait Infer { check(tp, Nil) } - // if top-level abstract types can be checked using a classtag extractor, don't warn about them - def checkCheckable(tree: Tree, typeToTest: Type, typeEnsured: Type, inPattern: Boolean, canRemedy: Boolean = false) = { - log(s"checkCheckable($tree, $typeToTest, $typeEnsured, inPattern = $inPattern, canRemedy = $canRemedy") - - sealed abstract class TypeConformance(check: (Type, Type) => Boolean) { - def apply(t1: Type, t2: Type): Boolean = check(t1, t2) && { - log(s"Skipping unchecked for statically verifiable condition $t1 ${this} $t2") - true - } - } - // I tried to use varianceInType to track the variance implications - // but I could not make it work. - case object =:= extends TypeConformance(_ =:= _) - case object <:< extends TypeConformance(_ <:< _) - case object >:> extends TypeConformance((t1, t2) => t2 <:< t1) - case object =!= extends TypeConformance((t1, t2) => false) - - var bound: List[Symbol] = Nil - var warningMessages: List[String] = Nil - - def isLocalBinding(sym: Symbol) = ( - sym.isAbstractType && ( - (bound contains sym) - || (sym.name == tpnme.WILDCARD) - || { - val e = context.scope.lookupEntry(sym.name) - (e ne null) && e.sym == sym && !e.sym.isTypeParameterOrSkolem && e.owner == context.scope - } - ) - ) - def check(tp0: Type, pt: Type, conformance: TypeConformance): Boolean = { - val tp = tp0.normalize - // Set the warning message to be issued when the top-level call fails. - def warn(what: String): Boolean = { - warningMessages ::= what - false - } - def checkArg(param: Symbol, arg: Type) = { - def conforms = ( - if (param.isCovariant) <:< - else if (param.isContravariant) >:> - else =:= - ) - (arg hasAnnotation UncheckedClass) || { - arg.withoutAnnotations match { - case TypeRef(_, sym, args) => - ( isLocalBinding(sym) - || arg.typeSymbol.isTypeParameterOrSkolem - || (sym.name == tpnme.WILDCARD) // avoid spurious warnings on HK types - || check(arg, param.tpeHK, conforms) - || warn("non-variable type argument " + arg) - ) - case _ => - warn("non-variable type argument " + arg) - } - } - } - - // Checking if pt (the expected type of the pattern, and the type - // we are guaranteed) conforms to tp (the type expressed in the pattern's - // type test.) If it does, then even if the type being checked for appears - // to be uncheckable, it is not a warning situation, because it is indeed - // checked: not at runtime, but statically. - conformance.apply(pt, tp) || (tp match { - case SingleType(pre, _) => check(pre, pt, =:=) - case ExistentialType(quantified, tp1) => bound :::= quantified ; check(tp1, pt, <:<) - case ThisType(_) | NoPrefix => true - case RefinedType(parents, decls) if decls.isEmpty => parents forall (p => check(p, pt, <:<)) - case RefinedType(_, _) => warn("refinement " + tp) - case TypeRef(_, ArrayClass, arg :: Nil) => check(arg, NoType, =!=) - case TypeRef(_, NonLocalReturnControlClass, _) => true // no way to suppress unchecked warnings on try/catch - // we only use the extractor for top-level type tests, type arguments remain unchecked - case TypeRef(_, sym, _) if sym.isAbstractType => isLocalBinding(sym) || canRemedy || warn("abstract type " + tp) - case TypeRef(_, _, Nil) => false // leaf node - case TypeRef(pre, sym, args) => forall2(sym.typeParams, args)(checkArg) && check(pre, pt.prefix, =:=) - case _ => warn("type " + tp) - }) - } - typeToTest match { - // Prohibit top-level type tests for these, but they are - // acceptable nested (e.g. case Foldable[Nothing] => ... ) - case TypeRef(_, NothingClass | NullClass | AnyValClass, _) => - TypePatternOrIsInstanceTestError(tree, typeToTest) - case _ => - def where = ( if (inPattern) "pattern " else "" ) + typeToTest - if (check(typeToTest, typeEnsured, =:=)) () - // Note that this is a regular warning, not an uncheckedWarning, - // which is now the province of such notifications as "pattern matcher - // exceeded its analysis budget." - else warningMessages foreach (m => - context.unit.warning(tree.pos, s"$m in type $where is unchecked since it is eliminated by erasure")) - } - } /** Type intersection of simple type tp1 with general type tp2. * The result eliminates some redundancies. diff --git a/src/compiler/scala/tools/nsc/typechecker/Macros.scala b/src/compiler/scala/tools/nsc/typechecker/Macros.scala index f9a35ba9a0..bcc37e8b37 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Macros.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Macros.scala @@ -354,7 +354,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces { macroTraceVerbose("tparams are: ")(tparams) macroTraceVerbose("vparamss are: ")(vparamss) macroTraceVerbose("retTpe is: ")(retTpe) - macroTraceVerbose("macroImplSig is: ")(paramss, implRetTpe) + macroTraceVerbose("macroImplSig is: ")((paramss, implRetTpe)) } /** Verifies that the body of a macro def typechecks to a reference to a static public non-overloaded method, diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala index 91dcd90962..c95951e608 100644 --- a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala +++ b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala @@ -198,13 +198,14 @@ trait MethodSynthesis { if (nme.isSetterName(name)) ValOrValWithSetterSuffixError(tree) - val getter = Getter(tree).createAndEnterSymbol() - tree.symbol = ( - if (mods.isLazy) enterLazyVal(tree, getter) - else { + if (mods.isLazy) { + val lazyValGetter = LazyValGetter(tree).createAndEnterSymbol() + enterLazyVal(tree, lazyValGetter) + } else { if (mods.isPrivateLocal) PrivateThisCaseClassParameterError(tree) + val getter = Getter(tree).createAndEnterSymbol() // Create the setter if necessary. if (mods.isMutable) Setter(tree).createAndEnterSymbol() @@ -219,7 +220,7 @@ trait MethodSynthesis { } def addDerivedTrees(typer: Typer, stat: Tree): List[Tree] = stat match { - case vd @ ValDef(mods, name, tpt, rhs) if !noFinishGetterSetter(vd) && !vd.symbol.isLazy => + case vd @ ValDef(mods, name, tpt, rhs) if !noFinishGetterSetter(vd) => // If we don't save the annotations, they seem to wander off. val annotations = stat.symbol.initialize.annotations ( allValDefDerived(vd) @@ -247,6 +248,7 @@ trait MethodSynthesis { def standardAccessors(vd: ValDef): List[DerivedFromValDef] = ( if (vd.mods.isMutable && !vd.mods.isLazy) List(Getter(vd), Setter(vd)) + else if (vd.mods.isLazy) List(LazyValGetter(vd)) else List(Getter(vd)) ) def beanAccessors(vd: ValDef): List[DerivedFromValDef] = { @@ -259,10 +261,15 @@ trait MethodSynthesis { else Nil } def allValDefDerived(vd: ValDef) = { - val field = if (vd.mods.isDeferred) Nil else List(Field(vd)) + val field = if (vd.mods.isDeferred || (vd.mods.isLazy && hasUnitType(vd.symbol))) Nil + else List(Field(vd)) field ::: standardAccessors(vd) ::: beanAccessors(vd) } + // Take into account annotations so that we keep annotated unit lazy val + // to get better error message already from the cps plugin itself + def hasUnitType(sym: Symbol) = (sym.tpe.typeSymbol == UnitClass) && sym.tpe.annotations.isEmpty + /** This trait assembles what's needed for synthesizing derived methods. * Important: Typically, instances of this trait are created TWICE for each derived * symbol; once form Namers in an enter method, and once from Typers in addDerivedTrees. @@ -388,16 +395,12 @@ trait MethodSynthesis { def name: TermName = tree.name.toTermName } - case class Getter(tree: ValDef) extends DerivedGetter { + abstract class BaseGetter(tree: ValDef) extends DerivedGetter { def name = tree.name def category = GetterTargetClass def flagsMask = GetterFlags def flagsExtra = ACCESSOR | ( if (tree.mods.isMutable) 0 else STABLE ) - override def derivedSym = ( - if (mods.isDeferred) basisSym - else basisSym.getter(enclClass) - ) override def validate() { assert(derivedSym != NoSymbol, tree) if (derivedSym.isOverloaded) @@ -405,6 +408,13 @@ trait MethodSynthesis { super.validate() } + } + case class Getter(tree: ValDef) extends BaseGetter(tree) { + override def derivedSym = ( + if (mods.isDeferred) basisSym + else basisSym.getter(enclClass) + ) + override def derivedTree: DefDef = { // For existentials, don't specify a type for the getter, even one derived // from the symbol! This leads to incompatible existentials for the field and @@ -437,6 +447,45 @@ trait MethodSynthesis { } } } + /** Implements lazy value accessors: + * - for lazy values of type Unit and all lazy fields inside traits, + * the rhs is the initializer itself + * - for all other lazy values z the accessor is a block of this form: + * { z = <rhs>; z } where z can be an identifier or a field. + */ + case class LazyValGetter(tree: ValDef) extends BaseGetter(tree) { + class ChangeOwnerAndModuleClassTraverser(oldowner: Symbol, newowner: Symbol) + extends ChangeOwnerTraverser(oldowner, newowner) { + + override def traverse(tree: Tree) { + tree match { + case _: DefTree => change(tree.symbol.moduleClass) + case _ => + } + super.traverse(tree) + } + } + + // todo: in future this should be enabled but now other phases still depend on the flag for various reasons + //override def flagsMask = (super.flagsMask & ~LAZY) + override def derivedSym = basisSym.lazyAccessor + override def derivedTree: DefDef = { + val ValDef(_, _, tpt0, rhs0) = tree + val rhs1 = transformed.getOrElse(rhs0, rhs0) + val body = ( + if (tree.symbol.owner.isTrait || hasUnitType(basisSym)) rhs1 + else gen.mkAssignAndReturn(basisSym, rhs1) + ) + derivedSym.setPos(tree.pos) // cannot set it at createAndEnterSymbol because basisSym can possible stil have NoPosition + val ddefRes = atPos(tree.pos)(DefDef(derivedSym, new ChangeOwnerAndModuleClassTraverser(basisSym, derivedSym)(body))) + // ValDef will have its position focused whereas DefDef will have original correct rangepos + // ideally positions would be correct at the creation time but lazy vals are really a special case + // here so for the sake of keeping api clean we fix positions manually in LazyValGetter + ddefRes.tpt.setPos(tpt0.pos) + tpt0.setPos(tpt0.pos.focus) + ddefRes + } + } case class Setter(tree: ValDef) extends DerivedSetter { def name = nme.getterToSetter(tree.name) def category = SetterTargetClass @@ -455,6 +504,7 @@ trait MethodSynthesis { override def keepClean = !mods.isParamAccessor override def derivedTree = ( if (mods.isDeferred) EmptyTree + else if (mods.isLazy) copyValDef(tree)(mods = mods | flagsExtra, name = this.name, rhs = EmptyTree).setPos(tree.pos.focus) else copyValDef(tree)(mods = mods | flagsExtra, name = this.name) ) } diff --git a/src/compiler/scala/tools/nsc/typechecker/Modes.scala b/src/compiler/scala/tools/nsc/typechecker/Modes.scala index e9ea99faab..d942d080cb 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Modes.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Modes.scala @@ -86,6 +86,10 @@ trait Modes { */ final val TYPEPATmode = 0x10000 + /** RETmode is set when we are typing a return expression. + */ + final val RETmode = 0x20000 + final private val StickyModes = EXPRmode | PATTERNmode | TYPEmode | ALTmode final def onlyStickyModes(mode: Int) = @@ -133,4 +137,4 @@ trait Modes { def modeString(mode: Int): String = if (mode == 0) "NOmode" else (modeNameMap filterKeys (bit => inAllModes(mode, bit))).values mkString " " -}
\ No newline at end of file +} diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index 9e66d696cb..9e9a22d4d1 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -113,10 +113,8 @@ trait Namers extends MethodSynthesis { || (context.unit.isJava) ) def noFinishGetterSetter(vd: ValDef) = ( - vd.mods.isPrivateLocal - || vd.symbol.isModuleVar - || vd.symbol.isLazy - ) + (vd.mods.isPrivateLocal && !vd.mods.isLazy) // all lazy vals need accessors, even private[this] + || vd.symbol.isModuleVar) def setPrivateWithin[T <: Symbol](tree: Tree, sym: T, mods: Modifiers): T = if (sym.isPrivateLocal || !mods.hasAccessBoundary) sym @@ -377,6 +375,8 @@ trait Namers extends MethodSynthesis { && (clazz.sourceFile ne null) && (module.sourceFile ne null) && !(module isCoDefinedWith clazz) + && module.exists + && clazz.exists ) if (fails) { context.unit.error(tree.pos, ( @@ -1506,7 +1506,7 @@ trait Namers extends MethodSynthesis { /** A class representing a lazy type with known type parameters. */ - class PolyTypeCompleter(tparams: List[TypeDef], restp: TypeCompleter, owner: Tree, ctx: Context) extends LockingTypeCompleter { + class PolyTypeCompleter(tparams: List[TypeDef], restp: TypeCompleter, owner: Tree, ctx: Context) extends LockingTypeCompleter with FlagAgnosticCompleter { private val ownerSym = owner.symbol override val typeParams = tparams map (_.symbol) //@M override val tree = restp.tree diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala index d0b715d502..de8685ab78 100644 --- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala +++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala @@ -1376,10 +1376,6 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL t.symbol.owner = currentOwner case d : DefTree if (d.symbol != NoSymbol) && ((d.symbol.owner == NoSymbol) || (d.symbol.owner == origOwner)) => // don't indiscriminately change existing owners! (see e.g., pos/t3440, pos/t3534, pos/unapplyContexts2) patmatDebug("def: "+ (d, d.symbol.ownerChain, currentOwner.ownerChain)) - if(d.symbol.isLazy) { // for lazy val's accessor -- is there no tree?? - assert(d.symbol.lazyAccessor != NoSymbol && d.symbol.lazyAccessor.owner == d.symbol.owner, d.symbol.lazyAccessor) - d.symbol.lazyAccessor.owner = currentOwner - } if(d.symbol.moduleClass ne NoSymbol) d.symbol.moduleClass.owner = currentOwner @@ -1589,7 +1585,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL object EqualityCond { private val uniques = new scala.collection.mutable.HashMap[(Tree, Tree), EqualityCond] def apply(testedPath: Tree, rhs: Tree): EqualityCond = uniques getOrElseUpdate((testedPath, rhs), new EqualityCond(testedPath, rhs)) - def unapply(c: EqualityCond) = Some(c.testedPath, c.rhs) + def unapply(c: EqualityCond) = Some((c.testedPath, c.rhs)) } class EqualityCond(val testedPath: Tree, val rhs: Tree) extends Cond { override def toString = testedPath +" == "+ rhs +"#"+ id @@ -1607,7 +1603,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL object TypeCond { private val uniques = new scala.collection.mutable.HashMap[(Tree, Type), TypeCond] def apply(testedPath: Tree, pt: Type): TypeCond = uniques getOrElseUpdate((testedPath, pt), new TypeCond(testedPath, pt)) - def unapply(c: TypeCond) = Some(c.testedPath, c.pt) + def unapply(c: TypeCond) = Some((c.testedPath, c.pt)) } class TypeCond(val testedPath: Tree, val pt: Type) extends Cond { override def toString = testedPath +" : "+ pt +"#"+ id @@ -1645,7 +1641,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL def unapply(xtm: ExtractorTreeMaker): Option[(Tree, Symbol)] = xtm match { case ExtractorTreeMaker(extractor, None, nextBinder) if irrefutableExtractorType(extractor.tpe) => - Some(extractor, nextBinder) + Some((extractor, nextBinder)) case _ => None } @@ -1864,7 +1860,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL def registerEquality(c: Const): Unit // call this to indicate null is part of the domain - def registerNull: Unit + def registerNull(): Unit // can this variable be null? def mayBeNull: Boolean @@ -2279,7 +2275,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL val staticTpCheckable: Type = checkableType(staticTp) private[this] var _mayBeNull = false - def registerNull: Unit = { ensureCanModify; if (NullTp <:< staticTpCheckable) _mayBeNull = true } + def registerNull(): Unit = { ensureCanModify; if (NullTp <:< staticTpCheckable) _mayBeNull = true } def mayBeNull: Boolean = _mayBeNull // case None => domain is unknown, @@ -2676,7 +2672,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL case UnitClass => Some(List(UnitClass.tpe)) case BooleanClass => - Some(List(ConstantType(Constant(true)), ConstantType(Constant(false)))) + Some((List(ConstantType(Constant(true)), ConstantType(Constant(false))))) // TODO case _ if tp.isTupleType => // recurse into component types case modSym: ModuleClassSymbol => Some(List(tp)) diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala index 84ec86b194..e3f694f724 100644 --- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala +++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala @@ -1024,15 +1024,18 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans private def enterSyms(stats: List[Tree]) { var index = -1 for (stat <- stats) { - index = index + 1; + index = index + 1 + def enterSym(sym: Symbol) = if (sym.isLocal) { + currentLevel.scope.enter(sym) + symIndex(sym) = index + } + stat match { + case DefDef(_, _, _, _, _, _) if stat.symbol.isLazy => + enterSym(stat.symbol) case ClassDef(_, _, _, _) | DefDef(_, _, _, _, _, _) | ModuleDef(_, _, _) | ValDef(_, _, _, _) => //assert(stat.symbol != NoSymbol, stat);//debug - val sym = stat.symbol.lazyAccessorOrSelf - if (sym.isLocal) { - currentLevel.scope.enter(sym) - symIndex(sym) = index; - } + enterSym(stat.symbol.lazyAccessorOrSelf) case _ => } } @@ -1297,34 +1300,6 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans }) } - /** Implements lazy value accessors: - * - for lazy values of type Unit and all lazy fields inside traits, - * the rhs is the initializer itself - * - for all other lazy values z the accessor is a block of this form: - * { z = <rhs>; z } where z can be an identifier or a field. - */ - private def makeLazyAccessor(tree: Tree, rhs: Tree): List[Tree] = { - val vsym = tree.symbol - assert(vsym.isTerm, vsym) - val hasUnitType = vsym.tpe.typeSymbol == UnitClass - val lazySym = vsym.lazyAccessor - assert(lazySym != NoSymbol, vsym) - - // for traits, this is further transformed in mixins - val body = ( - if (tree.symbol.owner.isTrait || hasUnitType) rhs - else gen.mkAssignAndReturn(vsym, rhs) - ) - val lazyDef = atPos(tree.pos)(DefDef(lazySym, body.changeOwner(vsym -> lazySym))) - debuglog("Created lazy accessor: " + lazyDef) - - if (hasUnitType) List(typed(lazyDef)) - else List( - typed(ValDef(vsym)), - afterRefchecks(typed(lazyDef)) - ) - } - def transformStat(tree: Tree, index: Int): List[Tree] = tree match { case t if treeInfo.isSelfConstrCall(t) => assert(index == 0, index) @@ -1337,8 +1312,7 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans case ModuleDef(_, _, _) => eliminateModuleDefs(tree) case ValDef(_, _, _, _) => val tree1 @ ValDef(_, _, _, rhs) = transform(tree) // important to do before forward reference check - if (tree.symbol.isLazy) - makeLazyAccessor(tree, rhs) + if (tree1.symbol.isLazy) tree1 :: Nil else { val lazySym = tree.symbol.lazyAccessorOrSelf if (lazySym.isLocal && index <= currentLevel.maxindex) { @@ -1631,12 +1605,14 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans case NullaryMethodType(restpe) if restpe.typeSymbol == UnitClass => // this may be the implementation of e.g. a generic method being parameterized // on Unit, in which case we had better let it slide. - if (sym.isGetter || sym.allOverriddenSymbols.exists(over => !(over.tpe.resultType =:= sym.tpe.resultType))) () - else unit.warning(sym.pos, - "side-effecting nullary methods are discouraged: suggest defining as `def %s()` instead".format( - sym.name.decode) + val isOk = ( + sym.isGetter + || sym.allOverriddenSymbols.exists(over => !(over.tpe.resultType =:= sym.tpe.resultType)) + || (sym.name containsName nme.DEFAULT_GETTER_STRING) ) - case _ => () + if (!isOk) + unit.warning(sym.pos, s"side-effecting nullary methods are discouraged: suggest defining as `def ${sym.name.decode}()` instead") + case _ => () } // Verify classes extending AnyVal meet the requirements diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index af89af74d0..2dbf715bda 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -253,12 +253,6 @@ trait Typers extends Modes with Adaptations with Tags { result } } - def isNonRefinementClassType(tpe: Type) = tpe match { - case SingleType(_, sym) => sym.isModuleClass - case TypeRef(_, sym, _) => sym.isClass && !sym.isRefinementClass - case ErrorType => true - case _ => false - } private def errorNotClass(tpt: Tree, found: Type) = { ClassTypeRequiredError(tpt, found); false } private def errorNotStable(tpt: Tree, found: Type) = { TypeNotAStablePrefixError(tpt, found); false } @@ -1394,6 +1388,70 @@ trait Typers extends Modes with Adaptations with Tags { } } + private def checkEphemeral(clazz: Symbol, body: List[Tree]) = { + // NOTE: Code appears to be messy in this method for good reason: it clearly + // communicates the fact that it implements rather ad-hoc, arbitrary and + // non-regular set of rules that identify features that interact badly with + // value classes. This code can be cleaned up a lot once implementation + // restrictions are addressed. + val isValueClass = !clazz.isTrait + def where = if (isValueClass) "value class" else "universal trait extending from class Any" + def implRestriction(tree: Tree, what: String) = + unit.error(tree.pos, s"implementation restriction: $what is not allowed in $where" + + "\nThis restriction is planned to be removed in subsequent releases.") + /** + * Deeply traverses the tree in search of constructs that are not allowed + * in value classes (at any nesting level). + * + * All restrictions this object imposes are probably not fundamental but require + * fair amount of work and testing. We are conservative for now when it comes + * to allowing language features to interact with value classes. + * */ + object checkEphemeralDeep extends Traverser { + override def traverse(tree: Tree): Unit = if (isValueClass) { + tree match { + case _: ModuleDef => + //see https://issues.scala-lang.org/browse/SI-6359 + implRestriction(tree, "nested object") + //see https://issues.scala-lang.org/browse/SI-6444 + //see https://issues.scala-lang.org/browse/SI-6463 + case _: ClassDef => + implRestriction(tree, "nested class") + case Select(sup @ Super(qual, mix), selector) if selector != nme.CONSTRUCTOR && qual.symbol == clazz && mix != tpnme.EMPTY => + //see https://issues.scala-lang.org/browse/SI-6483 + implRestriction(sup, "qualified super reference") + case _ => + } + super.traverse(tree) + } + } + for (stat <- body) { + def notAllowed(what: String) = unit.error(stat.pos, s"$what is not allowed in $where") + stat match { + // see https://issues.scala-lang.org/browse/SI-6444 + // see https://issues.scala-lang.org/browse/SI-6463 + case ClassDef(mods, _, _, _) if isValueClass => + implRestriction(stat, s"nested ${ if (mods.isTrait) "trait" else "class" }") + case _: Import | _: ClassDef | _: TypeDef | EmptyTree => // OK + case DefDef(_, name, _, _, _, rhs) => + if (stat.symbol.isAuxiliaryConstructor) + notAllowed("secondary constructor") + else if (isValueClass && (name == nme.equals_ || name == nme.hashCode_)) + notAllowed(s"redefinition of $name method. See SIP-15, criterion 4.") + else if (stat.symbol != null && stat.symbol.isParamAccessor) + notAllowed("additional parameter") + checkEphemeralDeep.traverse(rhs) + case _: ValDef => + notAllowed("field definition") + case _: ModuleDef => + //see https://issues.scala-lang.org/browse/SI-6359 + implRestriction(stat, "nested object") + case _ => + notAllowed("this statement") + } + } + } + private def validateDerivedValueClass(clazz: Symbol, body: List[Tree]) = { if (clazz.isTrait) unit.error(clazz.pos, "only classes (not traits) are allowed to extend AnyVal") @@ -1401,7 +1459,7 @@ trait Typers extends Modes with Adaptations with Tags { unit.error(clazz.pos, "value class may not be a "+ (if (clazz.owner.isTerm) "local class" else "member of another class")) if (!clazz.isPrimitiveValueClass) { - clazz.info.decls.toList.filter(acc => acc.isMethod && (acc hasFlag PARAMACCESSOR)) match { + clazz.info.decls.toList.filter(acc => acc.isMethod && acc.isParamAccessor) match { case List(acc) => def isUnderlyingAcc(sym: Symbol) = sym == acc || acc.hasAccessorFlag && sym == acc.accessed @@ -1409,25 +1467,12 @@ trait Typers extends Modes with Adaptations with Tags { unit.error(acc.pos, "value class needs to have a publicly accessible val parameter") else if (acc.tpe.typeSymbol.isDerivedValueClass) unit.error(acc.pos, "value class may not wrap another user-defined value class") - for (stat <- body) - if (!treeInfo.isAllowedInUniversalTrait(stat) && !isUnderlyingAcc(stat.symbol)) - unit.error(stat.pos, - if (stat.symbol != null && (stat.symbol hasFlag PARAMACCESSOR)) "illegal parameter for value class" - else "this statement is not allowed in value class: " + stat) + checkEphemeral(clazz, body filterNot (stat => isUnderlyingAcc(stat.symbol))) case x => unit.error(clazz.pos, "value class needs to have exactly one public val parameter") } } - def valueClassMayNotHave(at: Tree, what: String) = unit.error(at.pos, s"value class may not have $what") - body.foreach { - case dd: DefDef if dd.symbol.isAuxiliaryConstructor => valueClassMayNotHave(dd, "secondary constructors") - case t => t.foreach { - case md: ModuleDef => valueClassMayNotHave(md, "nested module definitions") - case cd: ClassDef => valueClassMayNotHave(cd, "nested class definitions") - case _ => - } - } for (tparam <- clazz.typeParams) if (tparam hasAnnotation definitions.SpecializedClass) unit.error(tparam.pos, "type parameter of value class may not be specialized") @@ -1674,9 +1719,7 @@ trait Typers extends Modes with Adaptations with Tags { } val impl2 = finishMethodSynthesis(impl1, clazz, context) if (clazz.isTrait && clazz.info.parents.nonEmpty && clazz.info.firstParent.normalize.typeSymbol == AnyClass) - for (stat <- impl2.body) - if (!treeInfo.isAllowedInUniversalTrait(stat)) - unit.error(stat.pos, "this statement is not allowed in universal trait extending from class Any: "+stat) + checkEphemeral(clazz, impl2.body) if ((clazz != ClassfileAnnotationClass) && (clazz isNonBottomSubClass ClassfileAnnotationClass)) restrictionWarning(cdef.pos, unit, @@ -1859,7 +1902,7 @@ trait Typers extends Modes with Adaptations with Tags { } val rhs1 = if (vdef.rhs.isEmpty) { - if (sym.isVariable && sym.owner.isTerm && !isPastTyper) + if (sym.isVariable && sym.owner.isTerm && !sym.isLazy && !isPastTyper) LocalVarUninitializedError(vdef) vdef.rhs } else { @@ -2285,9 +2328,15 @@ trait Typers extends Modes with Adaptations with Tags { case _ => } } - val stats1 = typedStats(block.stats, context.owner) + val stats1 = if (isPastTyper) block.stats else + block.stats.flatMap(stat => stat match { + case vd@ValDef(_, _, _, _) if vd.symbol.isLazy => + namer.addDerivedTrees(Typer.this, vd) + case _ => stat::Nil + }) + val stats2 = typedStats(stats1, context.owner) val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt) - treeCopy.Block(block, stats1, expr1) + treeCopy.Block(block, stats2, expr1) .setType(if (treeInfo.isExprSafeToInline(block)) expr1.tpe else expr1.tpe.deconst) } finally { // enable escaping privates checking from the outside and recycle @@ -3768,9 +3817,13 @@ trait Typers extends Modes with Adaptations with Tags { if (fun.symbol == Predef_classOf) typedClassOf(tree, args.head, true) else { - if (!isPastTyper && fun.symbol == Any_isInstanceOf && !targs.isEmpty) - checkCheckable(tree, targs.head, AnyClass.tpe, inPattern = false) - + if (!isPastTyper && fun.symbol == Any_isInstanceOf && targs.nonEmpty) { + val scrutineeType = fun match { + case Select(qual, _) => qual.tpe + case _ => AnyClass.tpe + } + checkCheckable(tree, targs.head, scrutineeType, inPattern = false) + } val resultpe = restpe.instantiateTypeParams(tparams, targs) //@M substitution in instantiateParams needs to be careful! //@M example: class Foo[a] { def foo[m[x]]: m[a] = error("") } (new Foo[Int]).foo[List] : List[Int] @@ -3780,7 +3833,8 @@ trait Typers extends Modes with Adaptations with Tags { //println("instantiating type params "+restpe+" "+tparams+" "+targs+" = "+resultpe) treeCopy.TypeApply(tree, fun, args) setType resultpe } - } else { + } + else { TypedApplyWrongNumberOfTpeParametersError(tree, fun) } case ErrorType => @@ -4177,7 +4231,7 @@ trait Typers extends Modes with Adaptations with Tags { ReturnWithoutTypeError(tree, enclMethod.owner) } else { context.enclMethod.returnsSeen = true - val expr1: Tree = typed(expr, EXPRmode | BYVALmode, restpt.tpe) + val expr1: Tree = typed(expr, EXPRmode | BYVALmode | RETmode, restpt.tpe) // Warn about returning a value if no value can be returned. if (restpt.tpe.typeSymbol == UnitClass) { // The typing in expr1 says expr is Unit (it has already been coerced if @@ -4186,7 +4240,8 @@ trait Typers extends Modes with Adaptations with Tags { if (typed(expr).tpe.typeSymbol != UnitClass) unit.warning(tree.pos, "enclosing method " + name + " has result type Unit: return value discarded") } - treeCopy.Return(tree, checkDead(expr1)) setSymbol enclMethod.owner setType NothingClass.tpe + treeCopy.Return(tree, checkDead(expr1)).setSymbol(enclMethod.owner) + .setType(adaptTypeOfReturn(expr1, restpt.tpe, NothingClass.tpe)) } } } @@ -4578,7 +4633,7 @@ trait Typers extends Modes with Adaptations with Tags { // xml member to StringContext, which in turn has an unapply[Seq] method) if (name != nme.CONSTRUCTOR && inExprModeOr(mode, PATTERNmode)) { val qual1 = adaptToMemberWithArgs(tree, qual, name, mode, true, true) - if (qual1 ne qual) + if ((qual1 ne qual) && !qual1.isErrorTyped) return typed(treeCopy.Select(tree, qual1, name), mode, pt) } NoSymbol diff --git a/src/compiler/scala/tools/nsc/util/DocStrings.scala b/src/compiler/scala/tools/nsc/util/DocStrings.scala index b096e1bc03..6113b54403 100755 --- a/src/compiler/scala/tools/nsc/util/DocStrings.scala +++ b/src/compiler/scala/tools/nsc/util/DocStrings.scala @@ -100,10 +100,10 @@ object DocStrings { * can override the parent symbol's sections */ def mergeUsecaseSections(str: String, idxs: List[Int]): List[Int] = { - idxs.indexWhere(str.substring(_).startsWith("@usecase")) match { + idxs.indexWhere(str.startsWith("@usecase", _)) match { case firstUCIndex if firstUCIndex != -1 => val commentSections = idxs.take(firstUCIndex) - val usecaseSections = idxs.drop(firstUCIndex).filter(str.substring(_).startsWith("@usecase")) + val usecaseSections = idxs.drop(firstUCIndex).filter(str.startsWith("@usecase", _)) commentSections ::: usecaseSections case _ => idxs @@ -114,7 +114,7 @@ object DocStrings { * Merge the inheritdoc sections, as they never make sense on their own */ def mergeInheritdocSections(str: String, idxs: List[Int]): List[Int] = - idxs.filterNot(str.substring(_).startsWith("@inheritdoc")) + idxs.filterNot(str.startsWith("@inheritdoc", _)) /** Does interval `iv` start with given `tag`? */ @@ -190,11 +190,12 @@ object DocStrings { /** Extract the section parameter */ def extractSectionParam(str: String, section: (Int, Int)): String = { - assert(str.substring(section._1).startsWith("@param") || - str.substring(section._1).startsWith("@tparam") || - str.substring(section._1).startsWith("@throws")) + val (beg, _) = section + assert(str.startsWith("@param", beg) || + str.startsWith("@tparam", beg) || + str.startsWith("@throws", beg)) - val start = skipWhitespace(str, skipTag(str, section._1)) + val start = skipWhitespace(str, skipTag(str, beg)) val finish = skipIdent(str, start) str.substring(start, finish) @@ -202,12 +203,13 @@ object DocStrings { /** Extract the section text, except for the tag and comment newlines */ def extractSectionText(str: String, section: (Int, Int)): (Int, Int) = { - if (str.substring(section._1).startsWith("@param") || - str.substring(section._1).startsWith("@tparam") || - str.substring(section._1).startsWith("@throws")) - (skipWhitespace(str, skipIdent(str, skipWhitespace(str, skipTag(str, section._1)))), section._2) + val (beg, end) = section + if (str.startsWith("@param", beg) || + str.startsWith("@tparam", beg) || + str.startsWith("@throws", beg)) + (skipWhitespace(str, skipIdent(str, skipWhitespace(str, skipTag(str, beg)))), end) else - (skipWhitespace(str, skipTag(str, section._1)), section._2) + (skipWhitespace(str, skipTag(str, beg)), end) } /** Cleanup section text */ diff --git a/src/compiler/scala/tools/nsc/util/InterruptReq.scala b/src/compiler/scala/tools/nsc/util/InterruptReq.scala index 816d16f767..b1b81d0952 100644 --- a/src/compiler/scala/tools/nsc/util/InterruptReq.scala +++ b/src/compiler/scala/tools/nsc/util/InterruptReq.scala @@ -47,7 +47,10 @@ abstract class InterruptReq { } def onComplete(k: Continuation) = synchronized { - waiting = k :: waiting + if (result.isDefined) + k(result.get) + else + waiting = k :: waiting } } diff --git a/src/compiler/scala/tools/reflect/FrontEnd.scala b/src/compiler/scala/tools/reflect/FrontEnd.scala new file mode 100644 index 0000000000..f0d3d5973d --- /dev/null +++ b/src/compiler/scala/tools/reflect/FrontEnd.scala @@ -0,0 +1,50 @@ +package scala.tools +package reflect + +import scala.reflect.internal.util.Position + +trait FrontEnd { + object severity extends Enumeration + class Severity(val id: Int) extends severity.Value { + var count: Int = 0 + override def toString() = this match { + case INFO => "INFO" + case WARNING => "WARNING" + case ERROR => "ERROR" + case _ => "<unknown>" + } + } + val INFO = new Severity(0) + val WARNING = new Severity(1) + val ERROR = new Severity(2) + + def hasErrors = ERROR.count > 0 + def hasWarnings = WARNING.count > 0 + + case class Info(val pos: Position, val msg: String, val severity: Severity) + val infos = new scala.collection.mutable.LinkedHashSet[Info] + + /** Handles incoming info */ + def log(pos: Position, msg: String, severity: Severity) { + infos += new Info(pos, msg, severity) + severity.count += 1 + display(infos.last) + } + + /** Displays incoming info */ + def display(info: Info): Unit + + /** Services a request to drop into interactive mode */ + def interactive(): Unit + + /** Refreshes the UI */ + def flush(): Unit = {} + + /** Resets the reporter */ + def reset(): Unit = { + INFO.count = 0 + WARNING.count = 0 + ERROR.count = 0 + infos.clear() + } +} diff --git a/src/compiler/scala/tools/reflect/FrontEnds.scala b/src/compiler/scala/tools/reflect/FrontEnds.scala deleted file mode 100644 index d0c3c1c774..0000000000 --- a/src/compiler/scala/tools/reflect/FrontEnds.scala +++ /dev/null @@ -1,88 +0,0 @@ -package scala.tools -package reflect - -import scala.tools.nsc.reporters._ -import scala.tools.nsc.Settings -import scala.reflect.ClassTag - -trait FrontEnds extends scala.reflect.api.FrontEnds { - - type Position = scala.reflect.internal.util.Position - - def mkConsoleFrontEnd(minSeverity: Int = 1): FrontEnd = { - val settings = new Settings() - if (minSeverity <= 0) settings.verbose.value = true - if (minSeverity > 1) settings.nowarn.value = true - wrapReporter(new ConsoleReporter(settings)) - } - - abstract class FrontEndToReporterProxy(val frontEnd: FrontEnd) extends AbstractReporter { - import frontEnd.{Severity => ApiSeverity} - val API_INFO = frontEnd.INFO - val API_WARNING = frontEnd.WARNING - val API_ERROR = frontEnd.ERROR - - type NscSeverity = Severity - val NSC_INFO = INFO - val NSC_WARNING = WARNING - val NSC_ERROR = ERROR - - def display(pos: Position, msg: String, nscSeverity: NscSeverity): Unit = - frontEnd.log(pos, msg, nscSeverity match { - case NSC_INFO => API_INFO - case NSC_WARNING => API_WARNING - case NSC_ERROR => API_ERROR - }) - - def displayPrompt(): Unit = - frontEnd.interactive() - - override def flush(): Unit = { - super.flush() - frontEnd.flush() - } - - override def reset(): Unit = { - super.reset() - frontEnd.reset() - } - } - - def wrapFrontEnd(frontEnd: FrontEnd): Reporter = new FrontEndToReporterProxy(frontEnd) { - val settings = new Settings() - settings.verbose.value = true - settings.nowarn.value = false - } - - class ReporterToFrontEndProxy(val reporter: Reporter) extends FrontEnd { - val API_INFO = INFO - val API_WARNING = WARNING - val API_ERROR = ERROR - - override def hasErrors = reporter.hasErrors - override def hasWarnings = reporter.hasWarnings - - def display(info: Info): Unit = info.severity match { - case API_INFO => reporter.info(info.pos, info.msg, false) - case API_WARNING => reporter.warning(info.pos, info.msg) - case API_ERROR => reporter.error(info.pos, info.msg) - } - - def interactive(): Unit = reporter match { - case reporter: AbstractReporter => reporter.displayPrompt() - case _ => // do nothing - } - - override def flush(): Unit = { - super.flush() - reporter.flush() - } - - override def reset(): Unit = { - super.reset() - reporter.reset() - } - } - - def wrapReporter(reporter: Reporter): FrontEnd = new ReporterToFrontEndProxy(reporter) -} diff --git a/src/compiler/scala/tools/reflect/MacroImplementations.scala b/src/compiler/scala/tools/reflect/MacroImplementations.scala index 48a4811744..86cd845c54 100644 --- a/src/compiler/scala/tools/reflect/MacroImplementations.scala +++ b/src/compiler/scala/tools/reflect/MacroImplementations.scala @@ -1,6 +1,6 @@ package scala.tools.reflect -import scala.reflect.macros.{ReificationError, UnexpectedReificationError} +import scala.reflect.macros.{ReificationException, UnexpectedReificationException} import scala.reflect.macros.runtime.Context import scala.collection.mutable.ListBuffer import scala.collection.mutable.Stack diff --git a/src/compiler/scala/tools/reflect/StdTags.scala b/src/compiler/scala/tools/reflect/StdTags.scala index 94fd8e1fe8..a3bc9b9bd1 100644 --- a/src/compiler/scala/tools/reflect/StdTags.scala +++ b/src/compiler/scala/tools/reflect/StdTags.scala @@ -3,7 +3,7 @@ package reflect import java.lang.{Class => jClass} import scala.reflect.{ClassTag, classTag} -import scala.reflect.api.{MirrorOf, TypeCreator, Universe => ApiUniverse} +import scala.reflect.api.{Mirror, TypeCreator, Universe => ApiUniverse} // [Eugene++] Before 2.10 is released, I suggest we don't rely on automated type tag generation // sure, it's convenient, but then refactoring reflection / reification becomes a pain @@ -11,13 +11,13 @@ import scala.reflect.api.{MirrorOf, TypeCreator, Universe => ApiUniverse} trait StdTags { val u: ApiUniverse with Singleton - val m: MirrorOf[u.type] + val m: Mirror[u.type] lazy val tagOfListOfString: u.TypeTag[List[String]] = u.TypeTag[List[String]]( m, new TypeCreator { - def apply[U <: ApiUniverse with Singleton](m: MirrorOf[U]): U # Type = { + def apply[U <: ApiUniverse with Singleton](m: Mirror[U]): U # Type = { val u = m.universe val pre = u.ThisType(m.staticPackage("scala.collection.immutable").moduleClass.asInstanceOf[u.Symbol]) u.TypeRef(pre, u.definitions.ListClass, List(u.definitions.StringClass.toTypeConstructor)) @@ -28,7 +28,7 @@ trait StdTags { u.TypeTag[T]( m, new TypeCreator { - def apply[U <: ApiUniverse with Singleton](m: MirrorOf[U]): U # Type = + def apply[U <: ApiUniverse with Singleton](m: Mirror[U]): U # Type = m.staticClass(classTag[T].runtimeClass.getName).toTypeConstructor.asInstanceOf[U # Type] }) lazy val tagOfInt = u.TypeTag.Int diff --git a/src/compiler/scala/tools/reflect/ToolBox.scala b/src/compiler/scala/tools/reflect/ToolBox.scala index f627699597..ab814b617d 100644 --- a/src/compiler/scala/tools/reflect/ToolBox.scala +++ b/src/compiler/scala/tools/reflect/ToolBox.scala @@ -15,6 +15,9 @@ trait ToolBox[U <: scala.reflect.api.Universe] { * * Accumulates and displays warnings and errors, can drop to interactive mode (if supported). * The latter can be useful to study the typechecker or to debug complex macros. + * + * [[scala.tools.reflect]] provides two predefined front ends that can be created using + * [[scala.tools.reflect.mkSilentFrontEnd]] and [[scala.tools.reflect.mkConsoleFrontEnd]]. */ def frontEnd: FrontEnd diff --git a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala index f985eedf99..95135b84e0 100644 --- a/src/compiler/scala/tools/reflect/ToolBoxFactory.scala +++ b/src/compiler/scala/tools/reflect/ToolBoxFactory.scala @@ -46,6 +46,20 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => newTermName("__wrapper$" + wrapCount + "$" + java.util.UUID.randomUUID.toString.replace("-", "")) } + // should be called after every use of ToolBoxGlobal in order to prevent leaks + // there's the `withCleanupCaches` method defined below, which provides a convenient interface for that + def cleanupCaches(): Unit = { + perRunCaches.clearAll() + undoLog.clear() + analyzer.lastTreeToTyper = EmptyTree + lastSeenSourceFile = NoSourceFile + lastSeenContext = null + } + + def withCleanupCaches[T](body: => T): T = + try body + finally cleanupCaches() + def verify(expr: Tree): Unit = { // Previously toolboxes used to typecheck their inputs before compiling. // Actually, the initial demo by Martin first typechecked the reified tree, @@ -320,7 +334,7 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => val errorFn: String => Unit = msg => frontEnd.log(scala.reflect.internal.util.NoPosition, msg, frontEnd.ERROR) val command = new CompilerCommand(arguments.toList, errorFn) command.settings.outputDirs setSingleOutput virtualDirectory - val instance = new ToolBoxGlobal(command.settings, new FrontEndToReporterProxy(frontEnd) { val settings = command.settings }) + val instance = new ToolBoxGlobal(command.settings, frontEndToReporter(frontEnd, command.settings)) if (frontEnd.hasErrors) { var msg = "reflective compilation has failed: cannot initialize the compiler: " + EOL + EOL msg += frontEnd.infos map (_.msg) mkString EOL @@ -337,7 +351,7 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => lazy val importer = compiler.mkImporter(u) lazy val exporter = importer.reverse - def typeCheck(tree: u.Tree, expectedType: u.Type, silent: Boolean = false, withImplicitViewsDisabled: Boolean = false, withMacrosDisabled: Boolean = false): u.Tree = { + def typeCheck(tree: u.Tree, expectedType: u.Type, silent: Boolean = false, withImplicitViewsDisabled: Boolean = false, withMacrosDisabled: Boolean = false): u.Tree = compiler.withCleanupCaches { if (compiler.settings.verbose.value) println("importing "+tree+", expectedType = "+expectedType) var ctree: compiler.Tree = importer.importTree(tree) var cexpectedType: compiler.Type = importer.importType(expectedType) @@ -357,7 +371,7 @@ abstract class ToolBoxFactory[U <: JavaUniverse](val u: U) { factorySelf => inferImplicit(tree, viewTpe, isView = true, silent = silent, withMacrosDisabled = withMacrosDisabled, pos = pos) } - private def inferImplicit(tree: u.Tree, pt: u.Type, isView: Boolean, silent: Boolean, withMacrosDisabled: Boolean, pos: u.Position): u.Tree = { + private def inferImplicit(tree: u.Tree, pt: u.Type, isView: Boolean, silent: Boolean, withMacrosDisabled: Boolean, pos: u.Position): u.Tree = compiler.withCleanupCaches { if (compiler.settings.verbose.value) println("importing "+pt, ", tree = "+tree+", pos = "+pos) var ctree: compiler.Tree = importer.importTree(tree) var cpt: compiler.Type = importer.importType(pt) diff --git a/src/compiler/scala/tools/reflect/package.scala b/src/compiler/scala/tools/reflect/package.scala index 901071d91a..8a1e3628e2 100644 --- a/src/compiler/scala/tools/reflect/package.scala +++ b/src/compiler/scala/tools/reflect/package.scala @@ -6,9 +6,12 @@ package scala.tools import scala.reflect.api.JavaUniverse +import scala.reflect.internal.util.Position import scala.language.implicitConversions +import scala.tools.nsc.reporters._ +import scala.tools.nsc.Settings -package object reflect extends FrontEnds { +package object reflect { // [todo: can we generalize this? import scala.reflect.runtime.{universe => ru} implicit def ToolBox(mirror0: ru.Mirror): ToolBoxFactory[ru.type] = @@ -17,9 +20,92 @@ package object reflect extends FrontEnds { } // todo. replace this with an implicit class, once the pesky warning is gone + // we don't provide `Eval` for trees, because it's unclear where to get an evaluation mirror from implicit def Eval[T](expr: JavaUniverse # Expr[T]): Eval[T] = new Eval[T](expr) - // we don't provide `Eval` for trees, because it's unclear where to get an evaluation mirror from + /** Creates a UI-less reporter that simply accumulates all the messages + */ + def mkSilentFrontEnd(): FrontEnd = new FrontEnd { + def display(info: Info) {} + def interactive() {} + } + + /** Creates a reporter that prints messages to the console according to the settings. + * + * ``minSeverity'' determines minimum severity of the messages to be printed. + * 0 stands for INFO, 1 stands for WARNING and 2 stands for ERROR. + */ + // todo. untangle warningsAsErrors from Reporters. I don't feel like moving this flag here! + def mkConsoleFrontEnd(minSeverity: Int = 1): FrontEnd = { + val settings = new Settings() + if (minSeverity <= 0) settings.verbose.value = true + if (minSeverity > 1) settings.nowarn.value = true + reporterToFrontEnd(new ConsoleReporter(settings)) + } + + private[reflect] def reporterToFrontEnd(reporter: Reporter): FrontEnd = new FrontEnd { + val API_INFO = INFO + val API_WARNING = WARNING + val API_ERROR = ERROR + + override def hasErrors = reporter.hasErrors + override def hasWarnings = reporter.hasWarnings + + def display(info: Info): Unit = info.severity match { + case API_INFO => reporter.info(info.pos, info.msg, false) + case API_WARNING => reporter.warning(info.pos, info.msg) + case API_ERROR => reporter.error(info.pos, info.msg) + } + + def interactive(): Unit = reporter match { + case reporter: AbstractReporter => reporter.displayPrompt() + case _ => // do nothing + } + + override def flush(): Unit = { + super.flush() + reporter.flush() + } + + override def reset(): Unit = { + super.reset() + reporter.reset() + } + } + + private[reflect] def frontEndToReporter(frontEnd: FrontEnd, settings0: Settings): Reporter = new AbstractReporter { + val settings = settings0 + + import frontEnd.{Severity => ApiSeverity} + val API_INFO = frontEnd.INFO + val API_WARNING = frontEnd.WARNING + val API_ERROR = frontEnd.ERROR + + type NscSeverity = Severity + val NSC_INFO = INFO + val NSC_WARNING = WARNING + val NSC_ERROR = ERROR + + def display(pos: Position, msg: String, nscSeverity: NscSeverity): Unit = + frontEnd.log(pos, msg, nscSeverity match { + case NSC_INFO => API_INFO + case NSC_WARNING => API_WARNING + case NSC_ERROR => API_ERROR + }) + + def displayPrompt(): Unit = + frontEnd.interactive() + + override def flush(): Unit = { + super.flush() + frontEnd.flush() + } + + override def reset(): Unit = { + super.reset() + frontEnd.reset() + } + } } package reflect { diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala index f6dc92f96e..7cf3586d3d 100644 --- a/src/compiler/scala/tools/util/PathResolver.scala +++ b/src/compiler/scala/tools/util/PathResolver.scala @@ -195,7 +195,7 @@ class PathResolver(settings: Settings, context: JavaContext) { def scalaExtDirs = cmdLineOrElse("extdirs", Defaults.scalaExtDirs) /** Scaladoc doesn't need any bootstrapping, otherwise will create errors such as: * [scaladoc] ../scala-trunk/src/reflect/scala/reflect/macros/Reifiers.scala:89: error: object api is not a member of package reflect - * [scaladoc] case class ReificationError(val pos: reflect.api.PositionApi, val msg: String) extends Throwable(msg) + * [scaladoc] case class ReificationException(val pos: reflect.api.PositionApi, val msg: String) extends Throwable(msg) * [scaladoc] ^ * because the bootstrapping will look at the sourcepath and create package "reflect" in "<root>" * and then when typing relative names, instead of picking <root>.scala.relect, typedIdentifier will pick up the diff --git a/src/continuations/library/scala/util/continuations/ControlContext.scala b/src/continuations/library/scala/util/continuations/ControlContext.scala index 37e3f45a4f..0ad880f26a 100644 --- a/src/continuations/library/scala/util/continuations/ControlContext.scala +++ b/src/continuations/library/scala/util/continuations/ControlContext.scala @@ -101,7 +101,7 @@ final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val @noinline final def map[A1](f: A => A1): ControlContext[A1,B,C] = { if (fun eq null) try { - new ControlContext(null, f(x)) // TODO: only alloc if f(x) != x + new ControlContext[A1,B,C](null, f(x)) // TODO: only alloc if f(x) != x } catch { case ex: Exception => new ControlContext((k: A1 => B, thr: Exception => B) => thr(ex).asInstanceOf[C], null.asInstanceOf[A1]) diff --git a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala index a20ff1667b..15025f85e3 100644 --- a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala +++ b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala @@ -150,10 +150,8 @@ abstract class CPSAnnotationChecker extends CPSUtils with Modes { if ((mode & global.analyzer.EXPRmode) != 0) { if ((annots1 corresponds annots2)(_.atp <:< _.atp)) { vprintln("already same, can't adapt further") - return false - } - - if (annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.BYVALmode) == 0)) { + false + } else if (annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.BYVALmode) == 0)) { //println("can adapt annotations? " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt) if (!hasPlusMarker(tree.tpe)) { // val base = tree.tpe <:< removeAllCPSAnnotations(pt) @@ -163,17 +161,26 @@ abstract class CPSAnnotationChecker extends CPSUtils with Modes { // TBD: use same or not? //if (same) { vprintln("yes we can!! (unit)") - return true + true //} - } - } else if (!annots1.isEmpty && ((mode & global.analyzer.BYVALmode) != 0)) { - if (!hasMinusMarker(tree.tpe)) { + } else false + } else if (!hasPlusMarker(tree.tpe) && annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.RETmode) != 0)) { + vprintln("checking enclosing method's result type without annotations") + tree.tpe <:< pt.withoutAnnotations + } else if (!hasMinusMarker(tree.tpe) && !annots1.isEmpty && ((mode & global.analyzer.BYVALmode) != 0)) { + val optCpsTypes: Option[(Type, Type)] = cpsParamTypes(tree.tpe) + val optExpectedCpsTypes: Option[(Type, Type)] = cpsParamTypes(pt) + if (optCpsTypes.isEmpty || optExpectedCpsTypes.isEmpty) { vprintln("yes we can!! (byval)") - return true + true + } else { // check cps param types + val cpsTpes = optCpsTypes.get + val cpsPts = optExpectedCpsTypes.get + // class cpsParam[-B,+C], therefore: + cpsPts._1 <:< cpsTpes._1 && cpsTpes._2 <:< cpsPts._2 } - } - } - false + } else false + } else false } override def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = { @@ -184,6 +191,7 @@ abstract class CPSAnnotationChecker extends CPSUtils with Modes { val patMode = (mode & global.analyzer.PATTERNmode) != 0 val exprMode = (mode & global.analyzer.EXPRmode) != 0 val byValMode = (mode & global.analyzer.BYVALmode) != 0 + val retMode = (mode & global.analyzer.RETmode) != 0 val annotsTree = cpsParamAnnotation(tree.tpe) val annotsExpected = cpsParamAnnotation(pt) @@ -210,9 +218,38 @@ abstract class CPSAnnotationChecker extends CPSUtils with Modes { val res = tree modifyType addMinusMarker vprintln("adapted annotations (by val) of " + tree + " to " + res.tpe) res + } else if (retMode && !hasPlusMarker(tree.tpe) && annotsTree.isEmpty && annotsExpected.nonEmpty) { + // add a marker annotation that will make tree.tpe behave as pt, subtyping wise + // tree will look like having any possible annotation + + // note 1: we are only adding a plus marker if the method's result type is a cps type + // (annotsExpected.nonEmpty == cpsParamAnnotation(pt).nonEmpty) + // note 2: we are not adding the expected cps annotations, since they will be added + // by adaptTypeOfReturn (see below). + val res = tree modifyType (_ withAnnotations List(newPlusMarker())) + vprintln("adapted annotations (return) of " + tree + " to " + res.tpe) + res } else tree } + /** Returns an adapted type for a return expression if the method's result type (pt) is a CPS type. + * Otherwise, it returns the `default` type (`typedReturn` passes `NothingClass.tpe`). + * + * A return expression in a method that has a CPS result type is an error unless the return + * is in tail position. Therefore, we are making sure that only the types of return expressions + * are adapted which will either be removed, or lead to an error. + */ + override def adaptTypeOfReturn(tree: Tree, pt: Type, default: => Type): Type = { + // only adapt if method's result type (pt) is cps type + val annots = cpsParamAnnotation(pt) + if (annots.nonEmpty) { + // return type of `tree` without plus marker, but only if it doesn't have other cps annots + if (hasPlusMarker(tree.tpe) && !hasCpsParamTypes(tree.tpe)) + tree.setType(removeAttribs(tree.tpe, MarkerCPSAdaptPlus)) + tree.tpe + } else default + } + def updateAttributesFromChildren(tpe: Type, childAnnots: List[AnnotationInfo], byName: List[Tree]): Type = { tpe match { // Would need to push annots into each alternative of overloaded type @@ -459,7 +496,11 @@ abstract class CPSAnnotationChecker extends CPSUtils with Modes { case ValDef(mods, name, tpt, rhs) => vprintln("[checker] checking valdef " + name + "/"+tpe+"/"+tpt+"/"+tree.symbol.tpe) // ValDef symbols must *not* have annotations! - if (hasAnswerTypeAnn(tree.symbol.info)) { // is it okay to modify sym here? + // lazy vals are currently not supported + // but if we erase here all annotations, compiler will complain only + // when generating bytecode. + // This way lazy vals will be reported as unsupported feature later rather than weird type error. + if (hasAnswerTypeAnn(tree.symbol.info) && !mods.isLazy) { // is it okay to modify sym here? vprintln("removing annotation from sym " + tree.symbol + "/" + tree.symbol.tpe + "/" + tpt) tpt modifyType removeAllCPSAnnotations tree.symbol modifyInfo removeAllCPSAnnotations diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala index 51760d2807..8b39bf3961 100644 --- a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala +++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala @@ -32,6 +32,55 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with implicit val _unit = unit // allow code in CPSUtils.scala to report errors var cpsAllowed: Boolean = false // detect cps code in places we do not handle (yet) + object RemoveTailReturnsTransformer extends Transformer { + override def transform(tree: Tree): Tree = tree match { + case Block(stms, r @ Return(expr)) => + treeCopy.Block(tree, stms, expr) + + case Block(stms, expr) => + treeCopy.Block(tree, stms, transform(expr)) + + case If(cond, r1 @ Return(thenExpr), r2 @ Return(elseExpr)) => + treeCopy.If(tree, cond, transform(thenExpr), transform(elseExpr)) + + case If(cond, r1 @ Return(thenExpr), elseExpr) => + treeCopy.If(tree, cond, transform(thenExpr), transform(elseExpr)) + + case If(cond, thenExpr, r2 @ Return(elseExpr)) => + treeCopy.If(tree, cond, transform(thenExpr), transform(elseExpr)) + + case If(cond, thenExpr, elseExpr) => + treeCopy.If(tree, cond, transform(thenExpr), transform(elseExpr)) + + case Try(block, catches, finalizer) => + treeCopy.Try(tree, + transform(block), + (catches map (t => transform(t))).asInstanceOf[List[CaseDef]], + transform(finalizer)) + + case CaseDef(pat, guard, r @ Return(expr)) => + treeCopy.CaseDef(tree, pat, guard, expr) + + case CaseDef(pat, guard, body) => + treeCopy.CaseDef(tree, pat, guard, transform(body)) + + case Return(_) => + unit.error(tree.pos, "return expressions in CPS code must be in tail position") + tree + + case _ => + super.transform(tree) + } + } + + def removeTailReturns(body: Tree): Tree = { + // support body with single return expression + body match { + case Return(expr) => expr + case _ => RemoveTailReturnsTransformer.transform(body) + } + } + override def transform(tree: Tree): Tree = { if (!cpsEnabled) return tree @@ -46,11 +95,14 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with // this would cause infinite recursion. But we could remove the // ValDef case here. - case dd @ DefDef(mods, name, tparams, vparamss, tpt, rhs) => + case dd @ DefDef(mods, name, tparams, vparamss, tpt, rhs0) => debuglog("transforming " + dd.symbol) atOwner(dd.symbol) { - val rhs1 = transExpr(rhs, None, getExternalAnswerTypeAnn(tpt.tpe)) + val rhs = + if (cpsParamTypes(tpt.tpe).nonEmpty) removeTailReturns(rhs0) + else rhs0 + val rhs1 = transExpr(rhs, None, getExternalAnswerTypeAnn(tpt.tpe))(getExternalAnswerTypeAnn(tpt.tpe).isDefined) debuglog("result "+rhs1) debuglog("result is of type "+rhs1.tpe) @@ -75,6 +127,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with val ext = getExternalAnswerTypeAnn(body.tpe) val pureBody = getAnswerTypeAnn(body.tpe).isEmpty + implicit val isParentImpure = ext.isDefined def transformPureMatch(tree: Tree, selector: Tree, cases: List[CaseDef]) = { val caseVals = cases map { case cd @ CaseDef(pat, guard, body) => @@ -142,9 +195,12 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with case _ => if (hasAnswerTypeAnn(tree.tpe)) { - if (!cpsAllowed) - unit.error(tree.pos, "cps code not allowed here / " + tree.getClass + " / " + tree) - + if (!cpsAllowed) { + if (tree.symbol.isLazy) + unit.error(tree.pos, "implementation restriction: cps annotations not allowed on lazy value definitions") + else + unit.error(tree.pos, "cps code not allowed here / " + tree.getClass + " / " + tree) + } log(tree) } @@ -154,8 +210,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with } - def transExpr(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): Tree = { - transTailValue(tree, cpsA, cpsR) match { + def transExpr(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo)(implicit isAnyParentImpure: Boolean = false): Tree = { + transTailValue(tree, cpsA, cpsR)(cpsR.isDefined || isAnyParentImpure) match { case (Nil, b) => b case (a, b) => treeCopy.Block(tree, a,b) @@ -163,7 +219,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with } - def transArgList(fun: Tree, args: List[Tree], cpsA: CPSInfo): (List[List[Tree]], List[Tree], CPSInfo) = { + def transArgList(fun: Tree, args: List[Tree], cpsA: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[List[Tree]], List[Tree], CPSInfo) = { val formals = fun.tpe.paramTypes val overshoot = args.length - formals.length @@ -172,7 +228,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with val (stm,expr) = (for ((a,tp) <- args.zip(formals ::: List.fill(overshoot)(NoType))) yield { tp match { case TypeRef(_, ByNameParamClass, List(elemtp)) => - (Nil, transExpr(a, None, getAnswerTypeAnn(elemtp))) + // note that we're not passing just isAnyParentImpure + (Nil, transExpr(a, None, getAnswerTypeAnn(elemtp))(getAnswerTypeAnn(elemtp).isDefined || isAnyParentImpure)) case _ => val (valStm, valExpr, valSpc) = transInlineValue(a, spc) spc = valSpc @@ -184,7 +241,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with } - def transValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree, CPSInfo) = { + // precondition: cpsR.isDefined "implies" isAnyParentImpure + def transValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[Tree], Tree, CPSInfo) = { // return value: (stms, expr, spc), where spc is CPSInfo after stms but *before* expr implicit val pos = tree.pos tree match { @@ -192,7 +250,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with val (cpsA2, cpsR2) = (cpsA, linearize(cpsA, getAnswerTypeAnn(tree.tpe))) // tbd // val (cpsA2, cpsR2) = (None, getAnswerTypeAnn(tree.tpe)) - val (a, b) = transBlock(stms, expr, cpsA2, cpsR2) + val (a, b) = transBlock(stms, expr, cpsA2, cpsR2)(cpsR2.isDefined || isAnyParentImpure) val tree1 = (treeCopy.Block(tree, a, b)) // no updateSynthFlag here!!! (Nil, tree1, cpsA) @@ -206,8 +264,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with val (cpsA2, cpsR2) = if (hasSynthMarker(tree.tpe)) (spc, linearize(spc, getAnswerTypeAnn(tree.tpe))) else (None, getAnswerTypeAnn(tree.tpe)) // if no cps in condition, branches must conform to tree.tpe directly - val thenVal = transExpr(thenp, cpsA2, cpsR2) - val elseVal = transExpr(elsep, cpsA2, cpsR2) + val thenVal = transExpr(thenp, cpsA2, cpsR2)(cpsR2.isDefined || isAnyParentImpure) + val elseVal = transExpr(elsep, cpsA2, cpsR2)(cpsR2.isDefined || isAnyParentImpure) // check that then and else parts agree (not necessary any more, but left as sanity check) if (cpsR.isDefined) { @@ -227,7 +285,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with else (None, getAnswerTypeAnn(tree.tpe)) val caseVals = cases map { case cd @ CaseDef(pat, guard, body) => - val bodyVal = transExpr(body, cpsA2, cpsR2) + val bodyVal = transExpr(body, cpsA2, cpsR2)(cpsR2.isDefined || isAnyParentImpure) treeCopy.CaseDef(cd, transform(pat), transform(guard), bodyVal) } @@ -245,7 +303,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with // currentOwner.newMethod(name, tree.pos, Flags.SYNTHETIC) setInfo ldef.symbol.info val sym = ldef.symbol resetFlag Flags.LABEL val rhs1 = rhs //new TreeSymSubstituter(List(ldef.symbol), List(sym)).transform(rhs) - val rhsVal = transExpr(rhs1, None, getAnswerTypeAnn(tree.tpe)) changeOwner (currentOwner -> sym) + val rhsVal = transExpr(rhs1, None, getAnswerTypeAnn(tree.tpe))(getAnswerTypeAnn(tree.tpe).isDefined || isAnyParentImpure) changeOwner (currentOwner -> sym) val stm1 = localTyper.typed(DefDef(sym, rhsVal)) // since virtpatmat does not rely on fall-through, don't call the labels it emits @@ -284,6 +342,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with (stms, updateSynthFlag(treeCopy.Assign(tree, transform(lhs), expr)), spc) case Return(expr0) => + if (isAnyParentImpure) + unit.error(tree.pos, "return expression not allowed, since method calls CPS method") val (stms, expr, spc) = transInlineValue(expr0, cpsA) (stms, updateSynthFlag(treeCopy.Return(tree, expr)), spc) @@ -321,7 +381,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with } } - def transTailValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree) = { + // precondition: cpsR.isDefined "implies" isAnyParentImpure + def transTailValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[Tree], Tree) = { val (stms, expr, spc) = transValue(tree, cpsA, cpsR) @@ -398,7 +459,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with (stms, expr) } - def transInlineValue(tree: Tree, cpsA: CPSInfo): (List[Tree], Tree, CPSInfo) = { + def transInlineValue(tree: Tree, cpsA: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[Tree], Tree, CPSInfo) = { val (stms, expr, spc) = transValue(tree, cpsA, None) // never required to be cps @@ -425,7 +486,7 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with - def transInlineStm(stm: Tree, cpsA: CPSInfo): (List[Tree], CPSInfo) = { + def transInlineStm(stm: Tree, cpsA: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[Tree], CPSInfo) = { stm match { // TODO: what about DefDefs? @@ -455,7 +516,8 @@ abstract class SelectiveANFTransform extends PluginComponent with Transform with } } - def transBlock(stms: List[Tree], expr: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree) = { + // precondition: cpsR.isDefined "implies" isAnyParentImpure + def transBlock(stms: List[Tree], expr: Tree, cpsA: CPSInfo, cpsR: CPSInfo)(implicit isAnyParentImpure: Boolean): (List[Tree], Tree) = { def rec(currStats: List[Tree], currAns: CPSInfo, accum: List[Tree]): (List[Tree], Tree) = currStats match { case Nil => diff --git a/src/library/rootdoc.txt b/src/library/rootdoc.txt index da27a0084b..0722d808bf 100644 --- a/src/library/rootdoc.txt +++ b/src/library/rootdoc.txt @@ -4,24 +4,25 @@ This is the documentation for the Scala standard library. The [[scala]] package contains core types. -scala.[[scala.collection]] and its subpackages contain a collections framework with higher-order functions for manipulation. Both [[scala.collection.immutable]] and [[scala.collection.mutable]] data structures are available, with immutable as the default. The [[scala.collection.parallel]] collections provide automatic parallel operation. +[[scala.collection `scala.collection`]] and its subpackages contain a collections framework with higher-order functions for manipulation. Both [[scala.collection.immutable `scala.collection.immutable`]] and [[scala.collection.mutable `scala.collection.mutable`]] data structures are available, with immutable as the default. The [[scala.collection.parallel `scala.collection.parallel`]] collections provide automatic parallel operation. Other important packages include: - - scala.[[scala.actors]] - Concurrency framework inspired by Erlang. - - scala.[[scala.io]] - Input and output. - - scala.[[scala.math]] - Basic math functions and additional numeric types. - - scala.[[scala.sys]] - Interaction with other processes and the operating system. - - scala.util.[[scala.util.matching]] - Pattern matching in text using regular expressions. - - scala.util.parsing.[[scala.util.parsing.combinator]] - Composable combinators for parsing. - - scala.[[scala.xml]] - XML parsing, manipulation, and serialization. + - [[scala.actors `scala.actors`]] - Concurrency framework inspired by Erlang. + - [[scala.io `scala.io`]] - Input and output. + - [[scala.math `scala.math`]] - Basic math functions and additional numeric types. + - [[scala.sys `scala.sys`]] - Interaction with other processes and the operating system. + - [[scala.util.matching `scala.util.matching`]] - Pattern matching in text using regular expressions. + - [[scala.util.parsing.combinator `scala.util.parsing.combinator`]] - Composable combinators for parsing. + - [[scala.xml `scala.xml`]] - XML parsing, manipulation, and serialization. Many other packages exist. See the complete list on the left. == Automatic imports == -Identifiers in the scala package and the [[scala.Predef]] object are always in scope by default. +Identifiers in the scala package and the [[scala.Predef `scala.Predef`]] object are always in scope by default. -Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, `List` is an alias for scala.collection.immutable.[[scala.collection.immutable.List]]. +Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, `List` is an alias for +[[scala.collection.immutable.List `scala.collection.immutable.List`]]. Other aliases refer to classes provided by the underlying platform. For example, on the JVM, `String` is an alias for `java.lang.String`. diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala index 4792de6bf5..f0854dd6e2 100644 --- a/src/library/scala/Predef.scala +++ b/src/library/scala/Predef.scala @@ -103,23 +103,29 @@ object Predef extends LowPriorityImplicits { @annotation.implicitNotFound(msg = "No ClassManifest available for ${T}.") @deprecated("Use scala.reflect.ClassTag instead", "2.10.0") type ClassManifest[T] = scala.reflect.ClassManifest[T] - @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") type OptManifest[T] = scala.reflect.OptManifest[T] @annotation.implicitNotFound(msg = "No Manifest available for ${T}.") - @deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") type Manifest[T] = scala.reflect.Manifest[T] @deprecated("Use scala.reflect.ClassTag instead", "2.10.0") val ClassManifest = scala.reflect.ClassManifest - @deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") val Manifest = scala.reflect.Manifest - @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") val NoManifest = scala.reflect.NoManifest - @deprecated("Use scala.reflect.classTag[T] and scala.reflect.runtime.universe.typeTag[T] instead", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("Use scala.reflect.classTag[T] and scala.reflect.runtime.universe.typeTag[T] instead", "2.10.0") def manifest[T](implicit m: Manifest[T]) = m @deprecated("Use scala.reflect.classTag[T] instead", "2.10.0") def classManifest[T](implicit m: ClassManifest[T]) = m - @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") def optManifest[T](implicit m: OptManifest[T]) = m // Minor variations on identity functions diff --git a/src/library/scala/StringContext.scala b/src/library/scala/StringContext.scala index 1201b1accd..fb43d56020 100644 --- a/src/library/scala/StringContext.scala +++ b/src/library/scala/StringContext.scala @@ -8,10 +8,43 @@ package scala -/** A class to support string interpolation. - * This class supports string interpolation as outlined in Scala SIP-11. - * It needs to be fully documented once the SIP is accepted. +/** This class provides the basic mechanism to do String Interpolation. + * String Interpolation allows users + * to embed variable references directly in *processed* string literals. + * Here's an example: + * {{{ + * val name = "James" + * println(s"Hello, $name") // Hello, James + * }}} * + * Any processed string literal is rewritten as an instantiation and + * method call against this class. For example: + * {{{ + * s"Hello, $name" + * }}} + * + * is rewritten to be: + * + * {{{ + * StringContext("Hello, ", "").s(name) + * }}} + * + * By default, this class provides the `raw`, `s` and `f` methods as + * available interpolators. + * + * To provide your own string interpolator, create an implicit class + * which adds a method to `StringContext`. Here's an example: + * {{{ + * implicit class JsonHelper(val sc: StringContext) extends AnyVal { + * def json(args: Any*): JSONObject = ... + * } + * val x: JSONObject = json"{ a: $a }" + * }}} + * + * Here the `JsonHelper` extenion class implicitly adds the `json` method to + * `StringContext` which can be used for `json` string literals. + * + * @since 2.10.0 * @param parts The parts that make up the interpolated string, * without the expressions that get inserted by interpolation. */ @@ -33,6 +66,20 @@ case class StringContext(parts: String*) { * * It inserts its arguments between corresponding parts of the string context. * It also treats standard escape sequences as defined in the Scala specification. + * Here's an example of usage: + * {{{ + * val name = "James" + * println(s"Hello, $name") // Hello, James + * }}} + * In this example, the expression $name is replaced with the `toString` of the + * variable `name`. + * The `s` interpolator can take the `toString` of any arbitrary expression within + * a `${}` block, for example: + * {{{ + * println(s"1 + 1 = ${1 + 1}") + * }}} + * will print the string `1 + 1 = 2`. + * * @param `args` The arguments to be inserted into the resulting string. * @throws An `IllegalArgumentException` * if the number of `parts` in the enclosing `StringContext` does not exceed @@ -47,6 +94,16 @@ case class StringContext(parts: String*) { * It inserts its arguments between corresponding parts of the string context. * As opposed to the simple string interpolator `s`, this one does not treat * standard escape sequences as defined in the Scala specification. + * + * For example, the raw processed string `raw"a\nb"` is equal to the scala string `"a\\nb"`. + * + * ''Note:'' Even when using the raw interpolator, Scala will preprocess unicode escapes. + * For example: + * {{{ + * scala> raw"\u0123" + * res0: String = ģ + * }}} + * * @param `args` The arguments to be inserted into the resulting string. * @throws An `IllegalArgumentException` * if the number of `parts` in the enclosing `StringContext` does not exceed @@ -77,6 +134,13 @@ case class StringContext(parts: String*) { * specifier. All specifiers allowed in Java format strings are handled, and in the same * way they are treated in Java. * + * For example: + * {{{ + * val height = 1.9d + * val name = "James" + * println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall + * }}} + * * @param `args` The arguments to be inserted into the resulting string. * @throws An `IllegalArgumentException` * if the number of `parts` in the enclosing `StringContext` does not exceed diff --git a/src/library/scala/annotation/migration.scala b/src/library/scala/annotation/migration.scala index f60c827620..a55c7006a1 100644 --- a/src/library/scala/annotation/migration.scala +++ b/src/library/scala/annotation/migration.scala @@ -25,6 +25,6 @@ package scala.annotation * @since 2.8 */ private[scala] final class migration(message: String, changedIn: String) extends scala.annotation.StaticAnnotation { - @deprecated("Use the constructor taking two Strings instead.", "2.10") + @deprecated("Use the constructor taking two Strings instead.", "2.10.0") def this(majorVersion: Int, minorVersion: Int, message: String) = this(message, majorVersion + "." + minorVersion) } diff --git a/src/library/scala/annotation/switch.scala b/src/library/scala/annotation/switch.scala index a867783455..20056bc03c 100644 --- a/src/library/scala/annotation/switch.scala +++ b/src/library/scala/annotation/switch.scala @@ -9,8 +9,7 @@ package scala.annotation /** An annotation to be applied to a match expression. If present, * the compiler will verify that the match has been compiled to a - * [[http://docs.oracle.com/javase/specs/jvms/se5.0/html/Instructions2.doc14.html tableswitch]] - * or [[http://docs.oracle.com/javase/specs/jvms/se5.0/html/Instructions2.doc8.html#lookupswitch lookupswitch]] + * [[http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10 tableswitch or lookupswitch]] * and issue an error if it instead compiles into a series of conditional expressions. * Example usage: {{{ diff --git a/src/library/scala/collection/SeqExtractors.scala b/src/library/scala/collection/SeqExtractors.scala index de9ff93521..20ea7f54b7 100644 --- a/src/library/scala/collection/SeqExtractors.scala +++ b/src/library/scala/collection/SeqExtractors.scala @@ -11,7 +11,7 @@ object +: { /** An extractor used to init/last deconstruct sequences. */ object :+ { /** Splits a sequence into init :+ tail. - * @return Some(init, tail) if sequence is non-empty. None otherwise. + * @return Some((init, tail)) if sequence is non-empty. None otherwise. */ def unapply[T,Coll <: SeqLike[T, Coll]]( t: Coll with SeqLike[T, Coll]): Option[(Coll, T)] = diff --git a/src/library/scala/collection/TraversableLike.scala b/src/library/scala/collection/TraversableLike.scala index ce0b130b86..7849f1c544 100644 --- a/src/library/scala/collection/TraversableLike.scala +++ b/src/library/scala/collection/TraversableLike.scala @@ -271,12 +271,7 @@ trait TraversableLike[+A, +Repr] extends Any * @return a new $coll consisting of all elements of this $coll that do not satisfy the given * predicate `p`. The order of the elements is preserved. */ - def filterNot(p: A => Boolean): Repr = { - val b = newBuilder - for (x <- this) - if (!p(x)) b += x - b.result - } + def filterNot(p: A => Boolean): Repr = filter(!p(_)) def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) diff --git a/src/library/scala/collection/TraversableOnce.scala b/src/library/scala/collection/TraversableOnce.scala index d77d278fca..f912304680 100644 --- a/src/library/scala/collection/TraversableOnce.scala +++ b/src/library/scala/collection/TraversableOnce.scala @@ -366,9 +366,9 @@ trait TraversableOnce[+A] extends Any with GenTraversableOnce[A] { object TraversableOnce { - @deprecated("use OnceCanBuildFrom instead") + @deprecated("use OnceCanBuildFrom instead", "2.10.0") def traversableOnceCanBuildFrom[T] = new OnceCanBuildFrom[T] - @deprecated("use MonadOps instead") + @deprecated("use MonadOps instead", "2.10.0") def wrapTraversableOnce[A](trav: TraversableOnce[A]) = new MonadOps(trav) implicit def alternateImplicit[A](trav: TraversableOnce[A]) = new ForceImplicitAmbiguity diff --git a/src/library/scala/collection/concurrent/TrieMap.scala b/src/library/scala/collection/concurrent/TrieMap.scala index 4f9f13c794..82f62f3c85 100644 --- a/src/library/scala/collection/concurrent/TrieMap.scala +++ b/src/library/scala/collection/concurrent/TrieMap.scala @@ -920,11 +920,11 @@ object TrieMap extends MutableMapFactory[TrieMap] { private[collection] class TrieMapIterator[K, V](var level: Int, private var ct: TrieMap[K, V], mustInit: Boolean = true) extends Iterator[(K, V)] { - var stack = new Array[Array[BasicNode]](7) - var stackpos = new Array[Int](7) - var depth = -1 - var subiter: Iterator[(K, V)] = null - var current: KVNode[K, V] = null + private var stack = new Array[Array[BasicNode]](7) + private var stackpos = new Array[Int](7) + private var depth = -1 + private var subiter: Iterator[(K, V)] = null + private var current: KVNode[K, V] = null if (mustInit) initialize() diff --git a/src/library/scala/collection/convert/DecorateAsJava.scala b/src/library/scala/collection/convert/DecorateAsJava.scala index e14769739d..f999d2fee8 100644 --- a/src/library/scala/collection/convert/DecorateAsJava.scala +++ b/src/library/scala/collection/convert/DecorateAsJava.scala @@ -313,6 +313,6 @@ trait DecorateAsJava { * @return An object with an `asJava` method that returns a Java * `ConcurrentMap` view of the argument. */ - implicit def asJavaConcurrentMapConverter[A, B](m: concurrent.Map[A, B]): AsJava[juc.ConcurrentMap[A, B]] = - new AsJava(asJavaConcurrentMap(m)) + implicit def mapAsJavaConcurrentMapConverter[A, B](m: concurrent.Map[A, B]): AsJava[juc.ConcurrentMap[A, B]] = + new AsJava(mapAsJavaConcurrentMap(m)) } diff --git a/src/library/scala/collection/convert/WrapAsJava.scala b/src/library/scala/collection/convert/WrapAsJava.scala index c79c651e96..e427afbb33 100644 --- a/src/library/scala/collection/convert/WrapAsJava.scala +++ b/src/library/scala/collection/convert/WrapAsJava.scala @@ -269,7 +269,7 @@ trait WrapAsJava { * @param m The Scala `concurrent.Map` to be converted. * @return A Java `ConcurrentMap` view of the argument. */ - implicit def asJavaConcurrentMap[A, B](m: concurrent.Map[A, B]): juc.ConcurrentMap[A, B] = m match { + implicit def mapAsJavaConcurrentMap[A, B](m: concurrent.Map[A, B]): juc.ConcurrentMap[A, B] = m match { case JConcurrentMapWrapper(wrapped) => wrapped case _ => new ConcurrentMapWrapper(m) } diff --git a/src/library/scala/collection/immutable/BitSet.scala b/src/library/scala/collection/immutable/BitSet.scala index 1b676e2d2f..d79e2adbda 100644 --- a/src/library/scala/collection/immutable/BitSet.scala +++ b/src/library/scala/collection/immutable/BitSet.scala @@ -31,7 +31,7 @@ abstract class BitSet extends scala.collection.AbstractSet[Int] with Serializable { override def empty = BitSet.empty - @deprecated("Use BitSet.fromBitMask[NoCopy] instead of fromArray", "2.10") + @deprecated("Use BitSet.fromBitMask[NoCopy] instead of fromArray", "2.10.0") def fromArray(elems: Array[Long]): BitSet = fromBitMaskNoCopy(elems) protected def fromBitMaskNoCopy(elems: Array[Long]): BitSet = BitSet.fromBitMaskNoCopy(elems) @@ -82,7 +82,7 @@ object BitSet extends BitSetFactory[BitSet] { implicit def canBuildFrom: CanBuildFrom[BitSet, Int, BitSet] = bitsetCanBuildFrom /** A bitset containing all the bits in an array */ - @deprecated("Use fromBitMask[NoCopy] instead of fromArray", "2.10") + @deprecated("Use fromBitMask[NoCopy] instead of fromArray", "2.10.0") def fromArray(elems: Array[Long]): BitSet = fromBitMaskNoCopy(elems) /** A bitset containing all the bits in an array */ diff --git a/src/library/scala/collection/immutable/HashMap.scala b/src/library/scala/collection/immutable/HashMap.scala index a6e750e7ee..ee41e2aa3c 100644 --- a/src/library/scala/collection/immutable/HashMap.scala +++ b/src/library/scala/collection/immutable/HashMap.scala @@ -120,7 +120,7 @@ class HashMap[A, +B] extends AbstractMap[A, B] */ object HashMap extends ImmutableMapFactory[HashMap] with BitOperations.Int { - private abstract class Merger[A, B] { + private[collection] abstract class Merger[A, B] { def apply(kv1: (A, B), kv2: (A, B)): (A, B) def invert: Merger[A, B] } @@ -197,7 +197,7 @@ object HashMap extends ImmutableMapFactory[HashMap] with BitOperations.Int { // } // } - override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = + private[collection] override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = if (hash == this.hash && key == this.key ) { if (merger eq null) { if (this.value.asInstanceOf[AnyRef] eq value.asInstanceOf[AnyRef]) this @@ -238,7 +238,7 @@ object HashMap extends ImmutableMapFactory[HashMap] with BitOperations.Int { override def get0(key: A, hash: Int, level: Int): Option[B] = if (hash == this.hash) kvs.get(key) else None - override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = + private[collection] override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = if (hash == this.hash) { if ((merger eq null) || !kvs.contains(key)) new HashMapCollision1(hash, kvs.updated(key, value)) else new HashMapCollision1(hash, kvs + merger((key, kvs(key)), kv)) @@ -316,7 +316,7 @@ object HashMap extends ImmutableMapFactory[HashMap] with BitOperations.Int { None } - override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = { + private[collection] override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1), merger: Merger[A, B1]): HashMap[A, B1] = { val index = (hash >>> level) & 0x1f val mask = (1 << index) val offset = Integer.bitCount(bitmap & (mask-1)) diff --git a/src/library/scala/collection/immutable/RedBlack.scala b/src/library/scala/collection/immutable/RedBlack.scala index a3ab27f814..77e5a87e73 100644 --- a/src/library/scala/collection/immutable/RedBlack.scala +++ b/src/library/scala/collection/immutable/RedBlack.scala @@ -18,7 +18,7 @@ package immutable * * @since 2.3 */ -@deprecated("use `TreeMap` or `TreeSet` instead", "2.10") +@deprecated("use `TreeMap` or `TreeSet` instead", "2.10.0") @SerialVersionUID(8691885935445612921L) abstract class RedBlack[A] extends Serializable { diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala index bac90341ec..461a375317 100644 --- a/src/library/scala/collection/immutable/Stream.scala +++ b/src/library/scala/collection/immutable/Stream.scala @@ -422,6 +422,9 @@ self => * // produces: 10, 10, 11, 10, 11, 11, 10, 11, 11, 12, 10, 11, 11, 12, 13 * }}} * + * ''Note:'' Currently `flatMap` will evaluate as much of the Stream as needed + * until it finds a non-empty element for the head, which is non-lazy. + * * @tparam B The element type of the returned collection '''That'''. * @param f the function to apply on each element. * @return `f(a,,0,,) ::: ... ::: f(a,,n,,)` if diff --git a/src/library/scala/collection/immutable/TreeMap.scala b/src/library/scala/collection/immutable/TreeMap.scala index 51bc76efc3..f7a24f3d66 100644 --- a/src/library/scala/collection/immutable/TreeMap.scala +++ b/src/library/scala/collection/immutable/TreeMap.scala @@ -51,7 +51,7 @@ class TreeMap[A, +B] private (tree: RB.Tree[A, B])(implicit val ordering: Orderi with MapLike[A, B, TreeMap[A, B]] with Serializable { - @deprecated("use `ordering.lt` instead", "2.10") + @deprecated("use `ordering.lt` instead", "2.10.0") def isSmaller(x: A, y: A) = ordering.lt(x, y) override protected[this] def newBuilder : Builder[(A, B), TreeMap[A, B]] = diff --git a/src/library/scala/collection/immutable/TreeSet.scala b/src/library/scala/collection/immutable/TreeSet.scala index 697da2bc4b..0fdb16c23b 100644 --- a/src/library/scala/collection/immutable/TreeSet.scala +++ b/src/library/scala/collection/immutable/TreeSet.scala @@ -96,7 +96,7 @@ class TreeSet[A] private (tree: RB.Tree[A, Unit])(implicit val ordering: Orderin override def takeWhile(p: A => Boolean) = take(countWhile(p)) override def span(p: A => Boolean) = splitAt(countWhile(p)) - @deprecated("use `ordering.lt` instead", "2.10") + @deprecated("use `ordering.lt` instead", "2.10.0") def isSmaller(x: A, y: A) = compare(x,y) < 0 def this()(implicit ordering: Ordering[A]) = this(null)(ordering) diff --git a/src/library/scala/concurrent/Awaitable.scala b/src/library/scala/concurrent/Awaitable.scala index 3bd7617bce..c0c688bf42 100644 --- a/src/library/scala/concurrent/Awaitable.scala +++ b/src/library/scala/concurrent/Awaitable.scala @@ -14,36 +14,47 @@ import scala.concurrent.duration.Duration +/** + * An object that may eventually be completed with a result value of type `T` which may be + * awaited using blocking methods. + * + * The [[Await]] object provides methods that allow accessing the result of an `Awaitable` + * by blocking the current thread until the `Awaitable` has been completed or a timeout has + * occurred. + */ trait Awaitable[+T] { + /** - * Await the "resolved" state of this Awaitable. - * This method should not be called directly. - * - * @param atMost - * maximum wait time, which may be negative (no waiting is done), - * [[Duration.Inf]] for unbounded waiting, or a finite positive - * duration - * @return the Awaitable itself - * @throws InterruptedException if the wait call was interrupted - * @throws TimeoutException if after waiting for the specified time this Awaitable is still not ready - * @throws IllegalArgumentException if `atMost` is [[Duration.Undefined]] + * Await the "completed" state of this `Awaitable`. + * + * '''''This method should not be called directly; use [[Await.ready]] instead.''''' + * + * @param atMost + * maximum wait time, which may be negative (no waiting is done), + * [[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting, or a finite positive + * duration + * @return this `Awaitable` + * @throws InterruptedException if the current thread is interrupted while waiting + * @throws TimeoutException if after waiting for the specified time this `Awaitable` is still not ready + * @throws IllegalArgumentException if `atMost` is [[scala.concurrent.duration.Duration.Undefined Duration.Undefined]] */ @throws(classOf[TimeoutException]) @throws(classOf[InterruptedException]) def ready(atMost: Duration)(implicit permit: CanAwait): this.type /** - * Await and return the result of this Awaitable, which is either of type T or a thrown exception (any Throwable). - * This method should not be called directly. - * - * @param atMost - * maximum wait time, which may be negative (no waiting is done), - * [[Duration.Inf]] for unbounded waiting, or a finite positive - * duration - * @return the value if the Awaitable was successful within the specific maximum wait time - * @throws InterruptedException if the wait call was interrupted - * @throws TimeoutException if after waiting for the specified time this Awaitable is still not ready - * @throws IllegalArgumentException if `atMost` is [[Duration.Undefined]] + * Await and return the result (of type `T`) of this `Awaitable`. + * + * '''''This method should not be called directly; use [[Await.result]] instead.''''' + * + * @param atMost + * maximum wait time, which may be negative (no waiting is done), + * [[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting, or a finite positive + * duration + * @return the result value if the `Awaitable` is completed within the specific maximum wait time + * @throws InterruptedException if the current thread is interrupted while waiting + * @throws TimeoutException if after waiting for the specified time this `Awaitable` is still not ready + * @throws IllegalArgumentException if `atMost` is [[scala.concurrent.duration.Duration.Undefined Duration.Undefined]] */ @throws(classOf[Exception]) def result(atMost: Duration)(implicit permit: CanAwait): T diff --git a/src/library/scala/concurrent/impl/Promise.scala b/src/library/scala/concurrent/impl/Promise.scala index a1a3305db0..ff268d850c 100644 --- a/src/library/scala/concurrent/impl/Promise.scala +++ b/src/library/scala/concurrent/impl/Promise.scala @@ -107,7 +107,7 @@ private[concurrent] object Promise { case _ => None } - override def isCompleted(): Boolean = getState match { // Cheaper than boxing result into Option due to "def value" + override def isCompleted: Boolean = getState match { // Cheaper than boxing result into Option due to "def value" case _: Try[_] => true case _ => false } @@ -156,7 +156,7 @@ private[concurrent] object Promise { val value = Some(resolveTry(suppliedValue)) - override def isCompleted(): Boolean = true + override def isCompleted: Boolean = true def tryComplete(value: Try[T]): Boolean = false diff --git a/src/library/scala/concurrent/package.scala b/src/library/scala/concurrent/package.scala index e683732e41..c0d46df883 100644 --- a/src/library/scala/concurrent/package.scala +++ b/src/library/scala/concurrent/package.scala @@ -23,7 +23,7 @@ package object concurrent { * The result becomes available once the asynchronous computation is completed. * * @tparam T the type of the result - * @param body the asychronous computation + * @param body the asynchronous computation * @param execctx the execution context on which the future is run * @return the `Future` holding the result of the computation */ @@ -37,17 +37,15 @@ package object concurrent { */ def promise[T]()(implicit execctx: ExecutionContext): Promise[T] = Promise[T]() - /** Used to designate a piece of code which potentially blocks, allowing the BlockContext to adjust the runtime's behavior. + /** Used to designate a piece of code which potentially blocks, allowing the current [[BlockContext]] to adjust + * the runtime's behavior. * Properly marking blocking code may improve performance or avoid deadlocks. * - * If you have an `Awaitable` then you should use Await.result instead of `blocking`. + * Blocking on an [[Awaitable]] should be done using [[Await.result]] instead of `blocking`. * * @param body A piece of code which contains potentially blocking or long running calls. - * - * Calling this method may throw the following exceptions: - * - CancellationException - if the computation was cancelled - * - InterruptedException - in the case that a wait within the blockable object was interrupted - * - TimeoutException - in the case that the blockable object timed out + * @throws `CancellationException` if the computation was cancelled + * @throws `InterruptedException` in the case that a wait within the blocking `body` was interrupted */ @throws(classOf[Exception]) def blocking[T](body: =>T): T = BlockContext.current.blockOn(body)(scala.concurrent.AwaitPermission) @@ -67,19 +65,21 @@ package concurrent { */ object Await { /** - * Await the "resolved" state of this Awaitable. - * Invokes ready() on the awaitable, properly wrapped by a call to `scala.concurrent.blocking`. - * - * @param awaitable - * the `Awaitable` on which `ready` is to be called - * @param atMost - * maximum wait time, which may be negative (no waiting is done), - * [[Duration.Inf]] for unbounded waiting, or a finite positive - * duration - * @return the awaitable itself - * @throws InterruptedException if the wait call was interrupted - * @throws TimeoutException if after waiting for the specified time this Awaitable is still not ready - * @throws IllegalArgumentException if `atMost` is [[Duration.Undefined]] + * Await the "completed" state of an `Awaitable`. + * + * Although this method is blocking, the internal use of [[scala.concurrent.blocking blocking]] ensures that + * the underlying [[ExecutionContext]] is prepared to properly manage the blocking. + * + * @param awaitable + * the `Awaitable` to be awaited + * @param atMost + * maximum wait time, which may be negative (no waiting is done), + * [[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting, or a finite positive + * duration + * @return the `awaitable` + * @throws InterruptedException if the current thread is interrupted while waiting + * @throws TimeoutException if after waiting for the specified time this `Awaitable` is still not ready + * @throws IllegalArgumentException if `atMost` is [[scala.concurrent.duration.Duration.Undefined Duration.Undefined]] */ @throws(classOf[TimeoutException]) @throws(classOf[InterruptedException]) @@ -87,19 +87,21 @@ package concurrent { blocking(awaitable.ready(atMost)(AwaitPermission)) /** - * Await and return the result of this Awaitable, which is either of type T or a thrown exception (any Throwable). - * Invokes result() on the awaitable, properly wrapped by a call to `scala.concurrent.blocking`. - * - * @param awaitable - * the `Awaitable` on which `result` is to be called - * @param atMost - * maximum wait time, which may be negative (no waiting is done), - * [[Duration.Inf]] for unbounded waiting, or a finite positive - * duration - * @return the value if the Awaitable was successful within the specific maximum wait time - * @throws InterruptedException if the wait call was interrupted - * @throws TimeoutException if after waiting for the specified time this Awaitable is still not ready - * @throws IllegalArgumentException if `atMost` is [[Duration.Undefined]] + * Await and return the result (of type `T`) of an `Awaitable`. + * + * Although this method is blocking, the internal use of [[scala.concurrent.blocking blocking]] ensures that + * the underlying [[ExecutionContext]] to properly detect blocking and ensure that there are no deadlocks. + * + * @param awaitable + * the `Awaitable` to be awaited + * @param atMost + * maximum wait time, which may be negative (no waiting is done), + * [[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting, or a finite positive + * duration + * @return the result value if `awaitable` is completed within the specific maximum wait time + * @throws InterruptedException if the current thread is interrupted while waiting + * @throws TimeoutException if after waiting for the specified time `awaitable` is still not ready + * @throws IllegalArgumentException if `atMost` is [[scala.concurrent.duration.Duration.Undefined Duration.Undefined]] */ @throws(classOf[Exception]) def result[T](awaitable: Awaitable[T], atMost: Duration): T = diff --git a/src/library/scala/language.scala b/src/library/scala/language.scala index 297f344f65..c638f531bb 100644 --- a/src/library/scala/language.scala +++ b/src/library/scala/language.scala @@ -1,5 +1,28 @@ package scala +/** + * The `scala.language` object controls the language features available to the programmer, as proposed in the + * [[https://docs.google.com/document/d/1nlkvpoIRkx7at1qJEZafJwthZ3GeIklTFhqmXMvTX9Q/edit '''SIP-18 document''']]. + * + * Each of these features has to be explicitly imported into the current scope to become available: + * {{{ + * import language.postfixOps // or language._ + * List(1, 2, 3) reverse + * }}} + * + * The language features are: + * - [[dynamics `dynamics`]] enables defining calls rewriting using the [[scala.Dynamic `Dynamic`]] trait + * - [[postfixOps `postfixOps`]] enables postfix operators + * - [[reflectiveCalls `reflectiveCalls`]] enables using structural types + * - [[implicitConversions `implicitConversions`]] enables defining implicit methods and members + * - [[higherKinds `higherKinds`]] enables writing higher-kinded types + * - [[existentials `existentials`]] enables writing existential types + * - [[experimental `experimental`]] contains newer features that have not yet been tested in production + * + * @groupname production Language Features + * @groupname experimental Experimental Language Features + * @groupprio experimental 10 + */ object language { import languageFeature._ @@ -10,21 +33,25 @@ object language { * selection of existing subclasses of trait Dynamic are unaffected; * they can be used anywhere. * - * _Why introduce the feature?_ To enable flexible DSLs and convenient interfacing + * '''Why introduce the feature?''' To enable flexible DSLs and convenient interfacing * with dynamic languages. * - * _Why control it?_ Dynamic member selection can undermine static checkability + * '''Why control it?''' Dynamic member selection can undermine static checkability * of programs. Furthermore, dynamic member selection often relies on reflection, * which is not available on all platforms. + * + * @group production */ implicit lazy val dynamics: dynamics = languageFeature.dynamics /** Only where enabled, postfix operator notation `(expr op)` will be allowed. * - * _Why keep the feature?_ Several DSLs written in Scala need the notation. + * '''Why keep the feature?''' Several DSLs written in Scala need the notation. * - * _Why control it?_ Postfix operators interact poorly with semicolon inference. + * '''Why control it?''' Postfix operators interact poorly with semicolon inference. * Most programmers avoid them for this reason. + * + * @group production */ implicit lazy val postfixOps: postfixOps = languageFeature.postfixOps @@ -34,13 +61,15 @@ object language { * not override any member in `Parents`. To access one of these members, a * reflective call is needed. * - * _Why keep the feature?_ Structural types provide great flexibility because + * '''Why keep the feature?''' Structural types provide great flexibility because * they avoid the need to define inheritance hierarchies a priori. Besides, * their definition falls out quite naturally from Scala’s concept of type refinement. * - * _Why control it?+ Reflection is not available on all platforms. Popular tools + * '''Why control it?''' Reflection is not available on all platforms. Popular tools * such as ProGuard have problems dealing with it. Even where reflection is available, * reflective dispatch can lead to surprising performance degradations. + * + * @group production */ implicit lazy val reflectiveCalls: reflectiveCalls = languageFeature.reflectiveCalls @@ -49,32 +78,36 @@ object language { * or an implicit method that has in its first parameter section a single, * non-implicit parameter. Examples: * + * {{{ * implicit def stringToInt(s: String): Int = s.length * implicit val conv = (s: String) => s.length - * implicit def listToX(xs: List[T])(implicit f: T => X): X = … + * implicit def listToX(xs: List[T])(implicit f: T => X): X = ... + * }}} * * implicit values of other types are not affected, and neither are implicit * classes. * - * _Why keep the feature?_ Implicit conversions are central to many aspects + * '''Why keep the feature?''' Implicit conversions are central to many aspects * of Scala’s core libraries. * - * _Why control it?_ Implicit conversions are known to cause many pitfalls + * '''Why control it?''' Implicit conversions are known to cause many pitfalls * if over-used. And there is a tendency to over-use them because they look * very powerful and their effects seem to be easy to understand. Also, in * most situations using implicit parameters leads to a better design than * implicit conversions. + * + * @group production */ implicit lazy val implicitConversions: implicitConversions = languageFeature.implicitConversions /** Only where this flag is enabled, higher-kinded types can be written. * - * _Why keep the feature?_ Higher-kinded types enable the definition of very general + * '''Why keep the feature?''' Higher-kinded types enable the definition of very general * abstractions such as functor, monad, or arrow. A significant set of advanced * libraries relies on them. Higher-kinded types are also at the core of the * scala-virtualized effort to produce high-performance parallel DSLs through staging. * - * _Why control it?_ Higher kinded types in Scala lead to a Turing-complete + * '''Why control it?''' Higher kinded types in Scala lead to a Turing-complete * type system, where compiler termination is no longer guaranteed. They tend * to be useful mostly for type-level computation and for highly generic design * patterns. The level of abstraction implied by these design patterns is often @@ -85,6 +118,8 @@ object language { * higher-kinded types will change in future versions of Scala. So an explicit * enabling also serves as a warning that code involving higher-kinded types * might have to be slightly revised in the future. + * + * @group production */ implicit lazy val higherKinds: higherKinds = languageFeature.higherKinds @@ -93,17 +128,31 @@ object language { * types of methods. Existential types with wildcard type syntax such as `List[_]`, * or `Map[String, _]` are not affected. * - * _Why keep the feature?_ Existential types are needed to make sense of Java’s wildcard + * '''Why keep the feature?''' Existential types are needed to make sense of Java’s wildcard * types and raw types and the erased types of run-time values. * - * Why control it? Having complex existential types in a code base usually makes + * '''Why control it?''' Having complex existential types in a code base usually makes * application code very brittle, with a tendency to produce type errors with * obscure error messages. Therefore, going overboard with existential types * is generally perceived not to be a good idea. Also, complicated existential types * might be no longer supported in a future simplification of the language. + * + * @group production */ implicit lazy val existentials: existentials = languageFeature.existentials + /** The experimental object contains features that have been recently added but have not + * been thoroughly tested in production yet. + * + * Experimental features '''may undergo API changes''' in future releases, so production + * code should not rely on them. + * + * Programmers are encouraged to try out experimental features and + * [[http://issues.scala-lang.org report any bugs or API inconsistencies]] + * they encounter so they can be improved in future releases. + * + * @group experimental + */ object experimental { import languageFeature.experimental._ @@ -111,12 +160,12 @@ object language { /** Where enabled, macro definitions are allowed. Macro implementations and * macro applications are unaffected; they can be used anywhere. * - * _Why introduce the feature?_ Macros promise to make the language more regular, + * '''Why introduce the feature?''' Macros promise to make the language more regular, * replacing ad-hoc language constructs with a general powerful abstraction * capability that can express them. Macros are also a more disciplined and * powerful replacement for compiler plugins. * - * _Why control it?_ For their very power, macros can lead to code that is hard + * '''Why control it?''' For their very power, macros can lead to code that is hard * to debug and understand. */ implicit lazy val macros: macros = languageFeature.experimental.macros diff --git a/src/library/scala/package.scala b/src/library/scala/package.scala index a41cdedfa9..fbb98d0582 100644 --- a/src/library/scala/package.scala +++ b/src/library/scala/package.scala @@ -95,7 +95,10 @@ package object scala { val Equiv = scala.math.Equiv type Fractional[T] = scala.math.Fractional[T] + val Fractional = scala.math.Fractional + type Integral[T] = scala.math.Integral[T] + val Integral = scala.math.Integral type Numeric[T] = scala.math.Numeric[T] val Numeric = scala.math.Numeric diff --git a/src/library/scala/reflect/ClassTag.scala b/src/library/scala/reflect/ClassTag.scala index 5c2067a548..d699e34ffc 100644 --- a/src/library/scala/reflect/ClassTag.scala +++ b/src/library/scala/reflect/ClassTag.scala @@ -5,19 +5,34 @@ import java.lang.{ Class => jClass } import scala.language.{implicitConversions, existentials} import scala.runtime.ScalaRunTime.{ arrayClass, arrayElementClass } -/** A `ClassTag[T]` wraps a runtime class (the erasure) and can create array instances. +/** + * + * A `ClassTag[T]` stores the erased class of a given type `T`, accessible via the `runtimeClass` + * field. This is particularly useful for instantiating `Array`s whose element types are unknown + * at compile time. + * + * `ClassTag`s are a weaker special case of [[scala.reflect.api.TypeTags#TypeTag]]s, in that they + * wrap only the runtime class of a given type, whereas a `TypeTag` contains all static type + * information. That is, `ClassTag`s are constructed from knowing only the top-level class of a + * type, without necessarily knowing all of its argument types. This runtime information is enough + * for runtime `Array` creation. * - * If an implicit value of type ClassTag[T] is requested, the compiler will create one. - * The runtime class (i.e. the erasure, a java.lang.Class on the JVM) of T can be accessed - * via the `runtimeClass` field. References to type parameters or abstract type members are - * replaced by the concrete types if ClassTags are available for them. + * For example: + * {{{ + * scala> def mkArray[T : ClassTag](elems: T*) = Array[T](elems: _*) + * mkArray: [T](elems: T*)(implicit evidence$1: scala.reflect.ClassTag[T])Array[T] * - * Besides accessing the erasure, a ClassTag knows how to instantiate single- and multi- - * dimensional `Arrays` where the element type is unknown at compile time. + * scala> mkArray(42, 13) + * res0: Array[Int] = Array(42, 13) * - * [[scala.reflect.ClassTag]] corresponds to a previous concept of [[scala.reflect.ClassManifest]]. + * scala> mkArray("Japan","Brazil","Germany") + * res1: Array[String] = Array(Japan, Brazil, Germany) + * }}} + * + * See [[scala.reflect.api.TypeTags]] for more examples, or the + * [[http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html Reflection Guide: TypeTags]] + * for more details. * - * @see [[scala.reflect.api.TypeTags]] */ @scala.annotation.implicitNotFound(msg = "No ClassTag available for ${T}") trait ClassTag[T] extends ClassManifestDeprecatedApis[T] with Equals with Serializable { @@ -29,7 +44,7 @@ trait ClassTag[T] extends ClassManifestDeprecatedApis[T] with Equals with Serial */ def runtimeClass: jClass[_] - /** Produces a `ClassTag` that knows how to build `Array[Array[T]]` */ + /** Produces a `ClassTag` that knows how to instantiate an `Array[Array[T]]` */ def wrap: ClassTag[Array[T]] = ClassTag[Array[T]](arrayClass(runtimeClass)) /** Produces a new array with element type `T` and length `len` */ diff --git a/src/library/scala/reflect/Manifest.scala b/src/library/scala/reflect/Manifest.scala index 8b021e0444..e3e1dfdbf7 100644 --- a/src/library/scala/reflect/Manifest.scala +++ b/src/library/scala/reflect/Manifest.scala @@ -39,7 +39,8 @@ import scala.collection.mutable.{ ArrayBuilder, WrappedArray } * */ @scala.annotation.implicitNotFound(msg = "No Manifest available for ${T}.") -@deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") +// TODO undeprecated until Scala reflection becomes non-experimental +// @deprecated("Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") trait Manifest[T] extends ClassManifest[T] with Equals { override def typeArguments: List[Manifest[_]] = Nil @@ -60,7 +61,8 @@ trait Manifest[T] extends ClassManifest[T] with Equals { override def hashCode = this.erasure.## } -@deprecated("Use type tags and manually check the corresponding class or type instead", "2.10.0") +// TODO undeprecated until Scala reflection becomes non-experimental +// @deprecated("Use type tags and manually check the corresponding class or type instead", "2.10.0") abstract class AnyValManifest[T <: AnyVal](override val toString: String) extends Manifest[T] with Equals { override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Manifest.Any) || (that eq Manifest.AnyVal) diff --git a/src/library/scala/reflect/NoManifest.scala b/src/library/scala/reflect/NoManifest.scala index 95b4ddca1c..4f9c954235 100644 --- a/src/library/scala/reflect/NoManifest.scala +++ b/src/library/scala/reflect/NoManifest.scala @@ -10,7 +10,8 @@ package scala.reflect /** One of the branches of an [[scala.reflect.OptManifest]]. */ -@deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") +// TODO undeprecated until Scala reflection becomes non-experimental +// @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") object NoManifest extends OptManifest[Nothing] with Serializable { override def toString = "<?>" }
\ No newline at end of file diff --git a/src/library/scala/reflect/OptManifest.scala b/src/library/scala/reflect/OptManifest.scala index 0ea66cb53d..e3fa84b4b6 100644 --- a/src/library/scala/reflect/OptManifest.scala +++ b/src/library/scala/reflect/OptManifest.scala @@ -14,5 +14,6 @@ package scala.reflect * * @author Martin Odersky */ -@deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") +// TODO undeprecated until Scala reflection becomes non-experimental +// @deprecated("This notion doesn't have a corresponding concept in 2.10, because scala.reflect.runtime.universe.TypeTag can capture arbitrary types. Use type tags instead of manifests, and there will be no need in opt manifests.", "2.10.0") trait OptManifest[+T] extends Serializable
\ No newline at end of file diff --git a/src/library/scala/reflect/package.scala b/src/library/scala/reflect/package.scala index 4f1cc03dc8..10e6d7d9a4 100644 --- a/src/library/scala/reflect/package.scala +++ b/src/library/scala/reflect/package.scala @@ -36,7 +36,8 @@ package object reflect { /** The object `Manifest` defines factory methods for manifests. * It is intended for use by the compiler and should not be used in client code. */ - @deprecated("Use scala.reflect.ClassTag (to capture erasures), scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") + // TODO undeprecated until Scala reflection becomes non-experimental + // @deprecated("Use scala.reflect.ClassTag (to capture erasures), scala.reflect.runtime.universe.TypeTag (to capture types) or both instead", "2.10.0") val Manifest = ManifestFactory def classTag[T](implicit ctag: ClassTag[T]) = ctag diff --git a/src/library/scala/runtime/WorksheetSupport.scala b/src/library/scala/runtime/WorksheetSupport.scala index a003bba034..016a0d04e0 100644 --- a/src/library/scala/runtime/WorksheetSupport.scala +++ b/src/library/scala/runtime/WorksheetSupport.scala @@ -4,6 +4,7 @@ import scala.runtime.ScalaRunTime.stringOf /** A utility object that's needed by the code that executes a worksheet. */ +@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") object WorksheetSupport { /** The offset in the source which should be printed */ diff --git a/src/library/scala/testing/Show.scala b/src/library/scala/testing/Show.scala index da1868c7f6..c6c58f5da2 100644 --- a/src/library/scala/testing/Show.scala +++ b/src/library/scala/testing/Show.scala @@ -37,7 +37,7 @@ trait Show { } } - @deprecated("use SymApply instead", "2.10") + @deprecated("use SymApply instead", "2.10.0") def symApply(sym: Symbol): SymApply = new SymApply(sym) /** Apply method with name of given symbol `f` to given arguments and return diff --git a/src/library/scala/throws.scala b/src/library/scala/throws.scala index 0aa0d31c9f..02dffb00b0 100644 --- a/src/library/scala/throws.scala +++ b/src/library/scala/throws.scala @@ -14,7 +14,7 @@ package scala * {{{ * class Reader(fname: String) { * private val in = new BufferedReader(new FileReader(fname)) - * @throws(classOf[IOException]) + * @throws[IOException]("if the file doesn't exist") * def read() = in.read() * } * }}} @@ -23,4 +23,6 @@ package scala * @version 1.0, 19/05/2006 * @since 2.1 */ -class throws(clazz: Class[_]) extends scala.annotation.StaticAnnotation +class throws[T <: Throwable](cause: String = "") extends scala.annotation.StaticAnnotation { + def this(clazz: Class[T]) = this() +} diff --git a/src/library/scala/util/Either.scala b/src/library/scala/util/Either.scala index f0253eee07..51342eda78 100644 --- a/src/library/scala/util/Either.scala +++ b/src/library/scala/util/Either.scala @@ -221,7 +221,7 @@ object Either { case Right(a) => a } } - @deprecated("use MergeableEither instead", "2.10") + @deprecated("use MergeableEither instead", "2.10.0") def either2mergeable[A](x: Either[A, A]): MergeableEither[A] = new MergeableEither(x) /** diff --git a/src/library/scala/xml/Elem.scala b/src/library/scala/xml/Elem.scala index 2ca1dbfcd0..a92d7859c3 100755 --- a/src/library/scala/xml/Elem.scala +++ b/src/library/scala/xml/Elem.scala @@ -59,7 +59,7 @@ class Elem( val child: Node*) extends Node with Serializable { - @deprecated("This constructor is retained for backward compatibility. Please use the primary constructor, which lets you specify your own preference for `minimizeEmpty`.", "2.10") + @deprecated("This constructor is retained for backward compatibility. Please use the primary constructor, which lets you specify your own preference for `minimizeEmpty`.", "2.10.0") def this(prefix: String, label: String, attributes: MetaData, scope: NamespaceBinding, child: Node*) = { this(prefix, label, attributes, scope, child.isEmpty, child: _*) } diff --git a/src/library/scala/xml/Utility.scala b/src/library/scala/xml/Utility.scala index 50a284d7cd..b390235d59 100755 --- a/src/library/scala/xml/Utility.scala +++ b/src/library/scala/xml/Utility.scala @@ -175,7 +175,7 @@ object Utility extends AnyRef with parsing.TokenTests { * Note that calling this source-compatible method will result in the same old, arguably almost universally unwanted, * behaviour. */ - @deprecated("Please use `serialize` instead and specify a `minimizeTags` parameter", "2.10") + @deprecated("Please use `serialize` instead and specify a `minimizeTags` parameter", "2.10.0") def toXML( x: Node, pscope: NamespaceBinding = TopScope, diff --git a/src/partest/scala/tools/partest/DirectTest.scala b/src/partest/scala/tools/partest/DirectTest.scala index ff047daf9e..af2fc986fa 100644 --- a/src/partest/scala/tools/partest/DirectTest.scala +++ b/src/partest/scala/tools/partest/DirectTest.scala @@ -37,7 +37,7 @@ abstract class DirectTest extends App { } // new compiler def newCompiler(args: String*): Global = { - val settings = newSettings((CommandLineParser tokenize extraSettings) ++ args.toList) + val settings = newSettings((CommandLineParser tokenize ("-d \"" + testOutput.path + "\" " + extraSettings)) ++ args.toList) if (settings.Yrangepos.value) new Global(settings) with interactive.RangePositions else new Global(settings) } diff --git a/src/reflect/scala/reflect/api/Annotations.scala b/src/reflect/scala/reflect/api/Annotations.scala index 37882a9f3c..fb353a5520 100644 --- a/src/reflect/scala/reflect/api/Annotations.scala +++ b/src/reflect/scala/reflect/api/Annotations.scala @@ -3,122 +3,195 @@ package api import scala.collection.immutable.ListMap -/** - * Defines the type hierarchy for annotations. +/** This trait provides annotation support for the reflection API. + * + * The API distinguishes between two kinds of annotations: + * + * <ul> + * <li>''Java annotations'': annotations on definitions produced by the Java compiler, i.e., subtypes of [[java.lang.annotation.Annotation]] + * attached to program definitions. When read by Scala reflection, the [[scala.annotation.ClassfileAnnotation]] trait + * is automatically added as a subclass to every Java annotation.</li> + * <li>''Scala annotations'': annotations on definitions or types produced by the Scala compiler.</li> + * </ul> + * + * When a Scala annotation that inherits from [[scala.annotation.StaticAnnotation]] or [[scala.annotation.ClassfileAnnotation]] is compiled, + * it is stored as special attributes in the corresponding classfile, and not as a Java annotation. Note that subclassing + * just [[scala.annotation.Annotation]] is not enough to have the corresponding metadata persisted for runtime reflection. + * + * The distinction between Java and Scala annotations is manifested in the contract of [[scala.reflect.api.Annotations#Annotation]], which exposes + * both `scalaArgs` and `javaArgs`. For Scala or Java annotations extending [[scala.annotation.ClassfileAnnotation]] `scalaArgs` is empty + * and arguments are stored in `javaArgs`. For all other Scala annotations, arguments are stored in `scalaArgs` and `javaArgs` is empty. + * + * Arguments in `scalaArgs` are represented as typed trees. Note that these trees are not transformed by any phases + * following the type-checker. Arguments in `javaArgs` are repesented as a map from [[scala.reflect.api.Names#Name]] to + * [[scala.reflect.api.Annotations#JavaArgument]]. Instances of `JavaArgument` represent different kinds of Java annotation arguments: + * - literals (primitive and string constants), + * - arrays and + * - nested annotations. + * + * @contentDiagram hideNodes "*Api" */ trait Annotations { self: Universe => - /** Typed information about an annotation. It can be attached to either a symbol or an annotated type. - * - * Annotations are either ''Scala annotations'', which conform to [[scala.annotation.StaticAnnotation]] - * or ''Java annotations'', which conform to [[scala.annotation.ClassfileAnnotation]]. - * Trait `ClassfileAnnotation` is automatically added to every Java annotation by the scalac classfile parser. + /** Information about an annotation. + * @template + * @group Annotations */ type Annotation >: Null <: AnyRef with AnnotationApi /** A tag that preserves the identity of the `Annotation` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AnnotationTag: ClassTag[Annotation] - /** The constructor/deconstructor for `Annotation` instances. */ + /** The constructor/deconstructor for `Annotation` instances. + * @group Extractors + */ val Annotation: AnnotationExtractor - /** An extractor class to create and pattern match with syntax `Annotation(atp, scalaArgs, javaArgs)`. - * Here, `atp` is the annotation type, `scalaArgs` the arguments, and `javaArgs` the annotation's key-value - * pairs. - * - * Annotations are pickled, i.e. written to scala symtab attribute in the classfile. - * Annotations are written to the classfile as Java annotations if `atp` conforms to `ClassfileAnnotation`. - * - * For Scala annotations, arguments are stored in `scalaArgs` and `javaArgs` is empty. Arguments in - * `scalaArgs` are represented as typed trees. Note that these trees are not transformed by any phases - * following the type-checker. For Java annotations, `scalaArgs` is empty and arguments are stored in - * `javaArgs`. - */ + /** An extractor class to create and pattern match with syntax `Annotation(tpe, scalaArgs, javaArgs)`. + * Here, `tpe` is the annotation type, `scalaArgs` the payload of Scala annotations, and `javaArgs` the payload of Java annotations. + * @group Extractors + */ abstract class AnnotationExtractor { def apply(tpe: Type, scalaArgs: List[Tree], javaArgs: ListMap[Name, JavaArgument]): Annotation def unapply(ann: Annotation): Option[(Type, List[Tree], ListMap[Name, JavaArgument])] } + /** The API of `Annotation` instances. + * The main source of information about annotations is the [[scala.reflect.api.Annotations]] page. + * @group API + */ trait AnnotationApi { + /** The type of the annotation. */ def tpe: Type + + /** Payload of the Scala annotation: a list of abstract syntax trees that represent the argument. + * Empty for Java annotations. + */ def scalaArgs: List[Tree] + + /** Payload of the Java annotation: a list of name-value pairs. + * Empty for Scala annotations. + */ def javaArgs: ListMap[Name, JavaArgument] } - /** A Java annotation argument */ + /** A Java annotation argument + * @template + * @group Annotations + */ type JavaArgument >: Null <: AnyRef + + /** A tag that preserves the identity of the `JavaArgument` abstract type from erasure. + * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags + */ implicit val JavaArgumentTag: ClassTag[JavaArgument] - /** A literal argument to a Java annotation as `"Use X instead"` in `@Deprecated("Use X instead")`*/ + /** A literal argument to a Java annotation as `"Use X instead"` in `@Deprecated("Use X instead")` + * @template + * @group Annotations + */ type LiteralArgument >: Null <: AnyRef with JavaArgument with LiteralArgumentApi /** A tag that preserves the identity of the `LiteralArgument` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val LiteralArgumentTag: ClassTag[LiteralArgument] - /** The constructor/deconstructor for `LiteralArgument` instances. */ + /** The constructor/deconstructor for `LiteralArgument` instances. + * @group Extractors + */ val LiteralArgument: LiteralArgumentExtractor /** An extractor class to create and pattern match with syntax `LiteralArgument(value)` * where `value` is the constant argument. + * @group Extractors */ abstract class LiteralArgumentExtractor { def apply(value: Constant): LiteralArgument def unapply(arg: LiteralArgument): Option[Constant] } + /** The API of `LiteralArgument` instances. + * The main source of information about annotations is the [[scala.reflect.api.Annotations]] page. + * @group API + */ trait LiteralArgumentApi { + /** The underlying compile-time constant value. */ def value: Constant } /** An array argument to a Java annotation as in `@Target(value={TYPE,FIELD,METHOD,PARAMETER})` + * @template + * @group Annotations */ type ArrayArgument >: Null <: AnyRef with JavaArgument with ArrayArgumentApi /** A tag that preserves the identity of the `ArrayArgument` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ArrayArgumentTag: ClassTag[ArrayArgument] - /** The constructor/deconstructor for `ArrayArgument` instances. */ + /** The constructor/deconstructor for `ArrayArgument` instances. + * @group Extractors + */ val ArrayArgument: ArrayArgumentExtractor /** An extractor class to create and pattern match with syntax `ArrayArgument(args)` * where `args` is the argument array. + * @group Extractors */ abstract class ArrayArgumentExtractor { def apply(args: Array[JavaArgument]): ArrayArgument def unapply(arg: ArrayArgument): Option[Array[JavaArgument]] } + /** API of `ArrayArgument` instances. + * The main source of information about annotations is the [[scala.reflect.api.Annotations]] page. + * @group API + */ trait ArrayArgumentApi { + /** The underlying array of Java annotation arguments. */ def args: Array[JavaArgument] } /** A nested annotation argument to a Java annotation as `@Nested` in `@Outer(@Nested)`. + * @template + * @group Annotations */ type NestedArgument >: Null <: AnyRef with JavaArgument with NestedArgumentApi /** A tag that preserves the identity of the `NestedArgument` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val NestedArgumentTag: ClassTag[NestedArgument] - /** The constructor/deconstructor for `NestedArgument` instances. */ + /** The constructor/deconstructor for `NestedArgument` instances. + * @group Extractors + */ val NestedArgument: NestedArgumentExtractor /** An extractor class to create and pattern match with syntax `NestedArgument(annotation)` * where `annotation` is the nested annotation. + * @group Extractors */ abstract class NestedArgumentExtractor { def apply(annotation: Annotation): NestedArgument def unapply(arg: NestedArgument): Option[Annotation] } + /** API of `NestedArgument` instances. + * The main source of information about annotations is the [[scala.reflect.api.Annotations]] page. + * @group API + */ trait NestedArgumentApi { + /** The underlying nested annotation. */ def annotation: Annotation } }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/api/BuildUtils.scala b/src/reflect/scala/reflect/api/BuildUtils.scala index 2bb0cc3c76..0c8e81a220 100644 --- a/src/reflect/scala/reflect/api/BuildUtils.scala +++ b/src/reflect/scala/reflect/api/BuildUtils.scala @@ -3,15 +3,18 @@ package api /** * This is an internal implementation class. + * @groupname TreeBuilders Tree Building */ -trait BuildUtils { self: Universe => +private[reflect] trait BuildUtils { self: Universe => + /** @group TreeBuilders */ val build: BuildApi // this API abstracts away the functionality necessary for reification // it's too gimmicky and unstructured to be exposed directly in the universe // but we need it in a publicly available place for reification to work + /** @group TreeBuilders */ abstract class BuildApi { /** Selects type symbol with given simple name `name` from the defined members of `owner`. */ diff --git a/src/reflect/scala/reflect/api/Constants.scala b/src/reflect/scala/reflect/api/Constants.scala index f2d8ef2eb9..a92fc5cbb3 100644 --- a/src/reflect/scala/reflect/api/Constants.scala +++ b/src/reflect/scala/reflect/api/Constants.scala @@ -7,50 +7,214 @@ package scala.reflect package api /** - * Defines the type hierachy for compile-time constants. + * According to the section 6.24 "Constant Expressions" of the Scala language specification, + * certain expressions (dubbed ''constant expressions'') can be evaluated by the Scala compiler at compile-time. * - * @see [[scala.reflect]] for a description on how the class hierarchy is encoded here. + * [[scala.reflect.api.Constants#Constant]] instances represent certain kinds of these expressions + * (with values stored in the `value` field and its strongly-typed views named `booleanValue`, `intValue` etc.), namely: + * 1. Literals of primitive value classes (bytes, shorts, ints, longs, floats, doubles, chars, booleans and voids). + * 1. String literals. + * 1. References to classes (typically constructed with [[scala.Predef#classOf]]). + * 1. References to enumeration values. + * + * Such constants are used to represent literals in abstract syntax trees (the [[scala.reflect.api.Trees#Literal]] node) + * and literal arguments for Java class file annotations (the [[scala.reflect.api.Annotations#LiteralArgument]] class). + * + * === Example === + * + * The `value` field deserves some explanation. Primitive and string values are represented as themselves, whereas + * references to classes and enums are a bit roundabout. + * + * Class references are represented as instances of [[scala.reflect.api.Types#Type]] + * (because when the Scala compiler processes a class reference, the underlying runtime class might not yet have been compiled). + * To convert such a reference to a runtime class, one should use the `runtimeClass` method of a mirror such as [[scala.reflect.api.Mirrors#RuntimeMirror]] + * (the simplest way to get such a mirror is using [[scala.reflect.runtime.package#currentMirror]]). + * + * Enumeration value references are represented as instances of [[scala.reflect.api.Symbols#Symbol]], which on JVM point to methods + * that return underlying enum values. To inspect an underlying enumeration or to get runtime value of a reference to an enum, + * one should use a [[scala.reflect.api.Mirrors#RuntimeMirror]] (the simplest way to get such a mirror is again [[scala.reflect.runtime.package#currentMirror]]). + + * {{{ + * enum JavaSimpleEnumeration { FOO, BAR } + * + * import java.lang.annotation.*; + * @Retention(RetentionPolicy.RUNTIME) + * @Target({ElementType.TYPE}) + * public @interface JavaSimpleAnnotation { + * Class<?> classRef(); + * JavaSimpleEnumeration enumRef(); + * } + * + * @JavaSimpleAnnotation( + * classRef = JavaAnnottee.class, + * enumRef = JavaSimpleEnumeration.BAR + * ) + * public class JavaAnnottee {} + * }}} + * {{{ + * import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.{currentMirror => cm} + * + * object Test extends App { + * val jann = typeOf[JavaAnnottee].typeSymbol.annotations(0).javaArgs + * def jarg(name: String) = jann(newTermName(name)).asInstanceOf[LiteralArgument].value + * + * val classRef = jarg("classRef").typeValue + * println(showRaw(classRef)) // TypeRef(ThisType(<empty>), JavaAnnottee, List()) + * println(cm.runtimeClass(classRef)) // class JavaAnnottee + * + * val enumRef = jarg("enumRef").symbolValue + * println(enumRef) // value BAR + * + * val siblings = enumRef.owner.typeSignature.declarations + * val enumValues = siblings.filter(sym => sym.isVal && sym.isPublic) + * println(enumValues) // Scope{ + * // final val FOO: JavaSimpleEnumeration; + * // final val BAR: JavaSimpleEnumeration + * // } + * + * // doesn't work because of https://issues.scala-lang.org/browse/SI-6459 + * // val enumValue = mirror.reflectField(enumRef.asTerm).get + * val enumClass = cm.runtimeClass(enumRef.owner.asClass) + * val enumValue = enumClass.getDeclaredField(enumRef.name.toString).get(null) + * println(enumValue) // BAR + * } + * }}} + * + * @contentDiagram hideNodes "*Api" */ trait Constants { self: Universe => - /** The type of compile-time constants. + /** + * This "virtual" case class represents the reflection interface for literal expressions which can not be further + * broken down or evaluated, such as "true", "0", "classOf[List]". Such values become parts of the Scala abstract + * syntax tree representing the program. The constants + * correspond to section 6.24 "Constant Expressions" of the + * [[http://www.scala-lang.org/docu/files/ScalaReference.pdf Scala language specification]]. + * + * Such constants are used to represent literals in abstract syntax trees (the [[scala.reflect.api.Trees#Literal]] node) + * and literal arguments for Java class file annotations (the [[scala.reflect.api.Annotations#LiteralArgument]] class). + * + * Constants can be matched against and can be constructed directly, as if they were case classes: + * {{{ + * assert(Constant(true).value == true) + * Constant(true) match { + * case Constant(s: String) => println("A string: " + s) + * case Constant(b: Boolean) => println("A boolean value: " + b) + * case Constant(x) => println("Something else: " + x) + * } + * }}} + * + * `Constant` instances can wrap certain kinds of these expressions: + * 1. Literals of primitive value classes ([[scala.Byte `Byte`]], [[scala.Short `Short`]], [[scala.Int `Int`]], [[scala.Long `Long`]], [[scala.Float `Float`]], [[scala.Double `Double`]], [[scala.Char `Char`]], [[scala.Boolean `Boolean`]] and [[scala.Unit `Unit`]]) - represented directly as the corresponding type + * 1. String literals - represented as instances of the `String`. + * 1. References to classes, typically constructed with [[scala.Predef#classOf]] - represented as [[scala.reflect.api.Types#Type types]]. + * 1. References to enumeration values - represented as [[scala.reflect.api.Symbols#Symbol symbols]]. + * + * Class references are represented as instances of [[scala.reflect.api.Types#Type]] + * (because when the Scala compiler processes a class reference, the underlying runtime class might not yet have + * been compiled). To convert such a reference to a runtime class, one should use the [[scala.reflect.api.Mirrors#RuntimeMirror#runtimeClass `runtimeClass`]] method of a + * mirror such as [[scala.reflect.api.Mirrors#RuntimeMirror `RuntimeMirror`]] (the simplest way to get such a mirror is using + * [[scala.reflect.runtime#currentMirror `scala.reflect.runtime.currentMirror`]]). + * + * Enumeration value references are represented as instances of [[scala.reflect.api.Symbols#Symbol]], which on JVM point to methods + * that return underlying enum values. To inspect an underlying enumeration or to get runtime value of a reference to an enum, + * one should use a [[scala.reflect.api.Mirrors#RuntimeMirror]] (the simplest way to get such a mirror is again [[scala.reflect.runtime.package#currentMirror]]). + * + * Usage example: + * {{{ + * enum JavaSimpleEnumeration { FOO, BAR } + * + * import java.lang.annotation.*; + * @Retention(RetentionPolicy.RUNTIME) + * @Target({ElementType.TYPE}) + * public @interface JavaSimpleAnnotation { + * Class<?> classRef(); + * JavaSimpleEnumeration enumRef(); + * } + * + * @JavaSimpleAnnotation( + * classRef = JavaAnnottee.class, + * enumRef = JavaSimpleEnumeration.BAR + * ) + * public class JavaAnnottee {} + * }}} + * {{{ + * import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.{currentMirror => cm} + * + * object Test extends App { + * val jann = typeOf[JavaAnnottee].typeSymbol.annotations(0).javaArgs + * def jarg(name: String) = jann(newTermName(name)) match { + * // Constant is always wrapped into a Literal or LiteralArgument tree node + * case LiteralArgument(ct: Constant) => value + * case _ => sys.error("Not a constant") + * } + * + * val classRef = jarg("classRef").value.asInstanceOf[Type] + * // ideally one should match instead of casting + * println(showRaw(classRef)) // TypeRef(ThisType(<empty>), JavaAnnottee, List()) + * println(cm.runtimeClass(classRef)) // class JavaAnnottee + * + * val enumRef = jarg("enumRef").value.asInstanceOf[Symbol] + * // ideally one should match instead of casting + * println(enumRef) // value BAR + * + * val siblings = enumRef.owner.typeSignature.declarations + * val enumValues = siblings.filter(sym => sym.isVal && sym.isPublic) + * println(enumValues) // Scope{ + * // final val FOO: JavaSimpleEnumeration; + * // final val BAR: JavaSimpleEnumeration + * // } + * + * // doesn't work because of https://issues.scala-lang.org/browse/SI-6459 + * // val enumValue = mirror.reflectField(enumRef.asTerm).get + * val enumClass = cm.runtimeClass(enumRef.owner.asClass) + * val enumValue = enumClass.getDeclaredField(enumRef.name.toString).get(null) + * println(enumValue) // BAR + * } + * }}} + * @template + * @group Constants */ type Constant >: Null <: AnyRef with ConstantApi /** A tag that preserves the identity of the `Constant` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ConstantTag: ClassTag[Constant] - /** The constructor/deconstructor for `Constant` instances. */ + /** The constructor/deconstructor for `Constant` instances. + * @group Extractors + */ val Constant: ConstantExtractor /** An extractor class to create and pattern match with syntax `Constant(value)` * where `value` is the Scala value of the constant. + * @group Extractors */ abstract class ConstantExtractor { + /** A factory method that produces [[Constant `Constant`]] instances. + * + * Notice that not any value can be passed to a constant: it must be either a primitive, a `String`, a + * [[scala.reflect.api.Types#Type type]] or a [[scala.reflect.api.Symbols#Symbol symbol]]. + * See [[Constant the `Constant` class]] for more information. + */ def apply(value: Any): Constant + /** An extractor that enables writing pattern matches against the [[Constant `Constant`]] class. */ def unapply(arg: Constant): Option[Any] } + /** The API of [[Constant]] instances. + * @group API + */ abstract class ConstantApi { + /** Payload of the constant, that can be accessed directly or pattern matched against. */ val value: Any + + /** Scala type that describes the constant. It is generated automatically based on the type of the value. */ def tpe: Type - def isNaN: Boolean - - def booleanValue: Boolean - def byteValue: Byte - def shortValue: Short - def charValue: Char - def intValue: Int - def longValue: Long - def floatValue: Float - def doubleValue: Double - def stringValue: String - def typeValue: Type - def symbolValue: Symbol - - def convertTo(pt: Type): Constant } } diff --git a/src/reflect/scala/reflect/api/Exprs.scala b/src/reflect/scala/reflect/api/Exprs.scala index 65b0eb9301..45bfddb55d 100644 --- a/src/reflect/scala/reflect/api/Exprs.scala +++ b/src/reflect/scala/reflect/api/Exprs.scala @@ -8,30 +8,55 @@ package api import scala.reflect.runtime.{universe => ru} +/** A trait that defines strongly-typed tree wrappers and operations on them for use in Scala Reflection. + * + * `Expr` wraps an abstract syntax tree ([[scala.reflect.api.Trees#Tree]]) and tags it with its type ([[scala.reflect.api.Types#Type]]). + * + * Usually `Expr`s are created via [[scala.reflect.api.Universe#reify]], in which case a compiler + * produces a [[scala.reflect.api.TreeCreator]] for the provided expression and also + * creates a complementary [[scala.reflect.api.TypeTags#WeakTypeTag]] that corresponds to the type of that expression. + * + * `Expr`s can also be created manually via the `Expr` companion object, but then the burden of providing a `TreeCreator` lies on the programmer. + * Compile-time reflection via macros, as described in [[scala.reflect.macros.Aliases]], provides an easier way to instantiate exprs manually. + * Manual creation, however, is very rarely needed when working with runtime reflection. + * + * `Expr` can be migrated from one mirror to another by using the `in` method. Migration means that all symbolic references + * to classes/objects/packages in the expression are re-resolved within the new mirror + * (typically using that mirror's classloader). The default universe of an `Expr` is typically + * [[scala.reflect.runtime#universe]], the default mirror is typically [[scala.reflect.runtime#currentMirror]]. + */ trait Exprs { self: Universe => - /** Expr wraps an expression tree and tags it with its type. */ + /** Expr wraps an abstract syntax tree and tags it with its type. + * The main source of information about exprs is the [[scala.reflect.api.Exprs]] page. + * @group Expressions + */ trait Expr[+T] extends Equals with Serializable { + /** + * Underlying mirror of this expr. + */ val mirror: Mirror + /** * Migrates the expression into another mirror, jumping into a different universe if necessary. - * - * This means that all symbolic references to classes/objects/packages in the expression - * will be re-resolved within the new mirror (typically using that mirror's classloader). */ - def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # Expr[T] + def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # Expr[T] /** - * The Scala syntax tree representing the wrapped expression. + * The Scala abstract syntax tree representing the wrapped expression. */ def tree: Tree /** - * Representation of the type of the wrapped expression tree as found via type tags. + * Type of the wrapped expression tree as provided during creation. + * + * When exprs are created by the compiler, `staticType` represents + * a statically known type of the tree as calculated at that point by the compiler. */ def staticType: Type + /** - * Representation of the type of the wrapped expression tree as found in the tree. + * Type of the wrapped expression tree as found in the underlying tree. */ def actualType: Type @@ -61,6 +86,7 @@ trait Exprs { self: Universe => * because expr of type Expr[T] itself does not have a method foo. */ def splice: T + /** * A dummy value to denote cross-stage path-dependent type dependencies. * @@ -77,10 +103,16 @@ trait Exprs { self: Universe => */ val value: T - /** case class accessories */ + /** TODO how do I doc this? */ override def canEqual(x: Any) = x.isInstanceOf[Expr[_]] + + /** TODO how do I doc this? */ override def equals(x: Any) = x.isInstanceOf[Expr[_]] && this.mirror == x.asInstanceOf[Expr[_]].mirror && this.tree == x.asInstanceOf[Expr[_]].tree + + /** TODO how do I doc this? */ override def hashCode = mirror.hashCode * 31 + tree.hashCode + + /** TODO how do I doc this? */ override def toString = "Expr["+staticType+"]("+tree+")" } @@ -89,15 +121,18 @@ trait Exprs { self: Universe => * * Can be useful, when having a tree and wanting to splice it in reify call, * in which case the tree first needs to be wrapped in an expr. + + * The main source of information about exprs is the [[scala.reflect.api.Exprs]] page. + * @group Expressions */ object Expr { - def apply[T: WeakTypeTag](mirror: MirrorOf[self.type], treec: TreeCreator): Expr[T] = new ExprImpl[T](mirror.asInstanceOf[Mirror], treec) + def apply[T: WeakTypeTag](mirror: scala.reflect.api.Mirror[self.type], treec: TreeCreator): Expr[T] = new ExprImpl[T](mirror.asInstanceOf[Mirror], treec) def unapply[T](expr: Expr[T]): Option[Tree] = Some(expr.tree) } private class ExprImpl[+T: WeakTypeTag](val mirror: Mirror, val treec: TreeCreator) extends Expr[T] { - def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # Expr[T] = { - val otherMirror1 = otherMirror.asInstanceOf[MirrorOf[otherMirror.universe.type]] + def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # Expr[T] = { + val otherMirror1 = otherMirror.asInstanceOf[scala.reflect.api.Mirror[otherMirror.universe.type]] val tag1 = (implicitly[WeakTypeTag[T]] in otherMirror).asInstanceOf[otherMirror.universe.WeakTypeTag[T]] otherMirror.universe.Expr[T](otherMirror1, treec)(tag1) } diff --git a/src/reflect/scala/reflect/api/FlagSets.scala b/src/reflect/scala/reflect/api/FlagSets.scala index 599c4ca426..a7d1ca05a6 100644 --- a/src/reflect/scala/reflect/api/FlagSets.scala +++ b/src/reflect/scala/reflect/api/FlagSets.scala @@ -3,32 +3,95 @@ package api import scala.language.implicitConversions +/** + * The trait that defines flag sets and operations on them. + * + * `Flag`s are used to provide modifiers for abstract syntax trees that represent definitions + * via the `flags` field of [[scala.reflect.api.Trees#Modifiers]]. Trees that accept modifiers are: + * + * - '''[[scala.reflect.api.Trees#ClassDef]]'''. Classes and traits. + * - '''[[scala.reflect.api.Trees#ModuleDef]]'''. Objects. + * - '''[[scala.reflect.api.Trees#ValDef]]'''. Vals, vars, parameters and self-type annotations. + * - '''[[scala.reflect.api.Trees#DefDef]]'''. Methods and constructors. + * - '''[[scala.reflect.api.Trees#TypeDef]]'''. Type aliases, abstract type members and type parameters. + * + * For example, to create a class named `C` one would write something like: + * {{{ + * ClassDef(Modifiers(NoFlags), newTypeName("C"), Nil, ...) + * }}} + * + * Here, the flag set is empty. + * + * To make `C` private, one would write something like: + * {{{ + * ClassDef(Modifiers(PRIVATE), newTypeName("C"), Nil, ...) + * }}} + * + * Flags can also be combined with the vertical bar operator (`|`). + * For example, a private final class is written something like: + * {{{ + * ClassDef(Modifiers(PRIVATE | FINAL), newTypeName("C"), Nil, ...) + * }}} + * + * The list of all available flags is defined in [[scala.reflect.api.FlagSets#FlagValues]], available via + * [[scala.reflect.api.FlagSets#Flag]]. (Typically one writes a blanket import for this, e.g. + * `import scala.reflect.runtime.universe.Flag._`). + * + * Definition trees are compiled down to symbols, so flags on modifiers of these trees are transformed into flags + * on the resulting symbols. Unlike trees, symbols don't expose flags, but rather provide `isXXX` test methods + * (e.g. `isFinal` can be used to test finality). These test methods might require an upcast with `asTerm`, + * `asType` or `asClass` as some flags only make sense for certain kinds of symbols. + * + * ''Of Note:'' This part of the Reflection API is being considered as a candidate for redesign. It is + * quite possible that in future releases of the reflection API, flag sets could be replaced with something else. + * + * For more details about `FlagSet`s and other aspects of Scala reflection, see the + * [[http://docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] + * + */ trait FlagSets { self: Universe => - /** An abstract type representing sets of flags (like private, final, etc.) that apply to definition trees and symbols */ + /** An abstract type representing sets of flags (like private, final, etc.) that apply to definition trees and symbols + * @template + * @group Flags + */ type FlagSet /** A tag that preserves the identity of the `FlagSet` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val FlagSetTag: ClassTag[FlagSet] + /** The API of `FlagSet` instances. + * The main source of information about flag sets is the [[scala.reflect.api.FlagSets]] page. + * @group Flags + */ trait FlagOps extends Any { + /** Produces a flag set that's a union of this flag set and the provided flag set. */ def | (right: FlagSet): FlagSet } + /** The API of `FlagSet` instances. + * @group Flags + */ implicit def addFlagOps(left: FlagSet): FlagOps + /** A module that contains all possible values that can constitute flag sets. + * @group Flags + */ val Flag: FlagValues - type FlagValues >: Null <: FlagValuesApi - // Q: I have a pretty flag. Can I put it here? // A: Only if there's a tree that cannot be built without it. // If you want to put a flag here so that it can be tested against, // introduce an `isXXX` method in one of the `api.Symbols` classes instead. - trait FlagValuesApi { + /** All possible values that can constitute flag sets. + * The main source of information about flag sets is the [[scala.reflect.api.FlagSets]] page. + * @group Flags + */ + trait FlagValues { /** Flag indicating that tree represents a trait */ val TRAIT: FlagSet @@ -106,6 +169,8 @@ trait FlagSets { self: Universe => val DEFAULTINIT: FlagSet } - /** The empty set of flags */ + /** The empty set of flags + * @group Flags + */ val NoFlags: FlagSet } diff --git a/src/reflect/scala/reflect/api/FrontEnds.scala b/src/reflect/scala/reflect/api/FrontEnds.scala deleted file mode 100644 index 61ea227c47..0000000000 --- a/src/reflect/scala/reflect/api/FrontEnds.scala +++ /dev/null @@ -1,70 +0,0 @@ -package scala.reflect -package api - -trait FrontEnds { - - type Position >: Null - - trait FrontEnd { - object severity extends Enumeration - class Severity(val id: Int) extends severity.Value { - var count: Int = 0 - override def toString() = this match { - case INFO => "INFO" - case WARNING => "WARNING" - case ERROR => "ERROR" - case _ => "<unknown>" - } - } - val INFO = new Severity(0) - val WARNING = new Severity(1) - val ERROR = new Severity(2) - - def hasErrors = ERROR.count > 0 - def hasWarnings = WARNING.count > 0 - - case class Info(val pos: Position, val msg: String, val severity: Severity) - val infos = new scala.collection.mutable.LinkedHashSet[Info] - - /** Handles incoming info */ - def log(pos: Position, msg: String, severity: Severity) { - infos += new Info(pos, msg, severity) - severity.count += 1 - display(infos.last) - } - - /** Displays incoming info */ - def display(info: Info): Unit - - /** Services a request to drop into interactive mode */ - def interactive(): Unit - - /** Refreshes the UI */ - def flush(): Unit = {} - - /** Resets the reporter */ - def reset(): Unit = { - INFO.count = 0 - WARNING.count = 0 - ERROR.count = 0 - infos.clear() - } - } - - class SilentFrontEnd extends FrontEnd { - def display(info: Info) {} - def interactive() {} - } - - /** Creates a UI-less reporter that simply accumulates all the messages - */ - def mkSilentFrontEnd(): FrontEnd = new SilentFrontEnd() - - /** Creates a reporter that prints messages to the console according to the settings. - * - * ``minSeverity'' determines minimum severity of the messages to be printed. - * 0 stands for INFO, 1 stands for WARNING and 2 stands for ERROR. - */ - // todo. untangle warningsAsErrors from Reporters. I don't feel like moving this flag here! - def mkConsoleFrontEnd(minSeverity: Int = 1): FrontEnd -} diff --git a/src/reflect/scala/reflect/api/Importers.scala b/src/reflect/scala/reflect/api/Importers.scala index fbc29a514e..4286b2b45c 100644 --- a/src/reflect/scala/reflect/api/Importers.scala +++ b/src/reflect/scala/reflect/api/Importers.scala @@ -1,21 +1,97 @@ package scala.reflect package api +/** This trait provides support for importers, a facility to migrate reflection artifacts between universes. + * + * Reflection artifacts, such as [[scala.reflect.api.Symbols Symbols]] and [[scala.reflect.api.Types Types]], + * are contained in [[scala.reflect.api.Universes Universe]]s. Typically all processing happens + * within a single `Universe` (e.g. a compile-time macro `Universe` or a runtime reflection `Universe`), but sometimes + * there is a need to migrate artifacts from one `Universe` to another. For example, runtime compilation works by + * importing runtime reflection trees into a runtime compiler universe, compiling the importees and exporting the + * result back. + * + * Reflection artifacts are firmly grounded in their `Universe`s, which is reflected by the fact that types of artifacts + * from different universes are not compatible. By using `Importer`s, however, they be imported from one universe + * into another. For example, to import `foo.bar.Baz` from the source `Universe` to the target `Universe`, + * an importer will first check whether the entire owner chain exists in the target `Universe`. + * If it does, then nothing else will be done. Otherwise, the importer will recreate the entire owner chain + * and will import the corresponding type signatures into the target `Universe`. + * + * Since importers match `Symbol` tables of the source and the target `Universe`s using plain string names, + * it is programmer's responsibility to make sure that imports don't distort semantics, e.g., that + * `foo.bar.Baz` in the source `Universe` means the same that `foo.bar.Baz` does in the target `Universe`. + * + * === Example === + * + * Here's how one might implement a macro that performs compile-time evaluation of its argument + * by using a runtime compiler to compile and evaluate a tree that belongs to a compile-time compiler: + * + * {{{ + * def staticEval[T](x: T) = macro staticEval[T] + * + * def staticEval[T](c: scala.reflect.macros.Context)(x: c.Expr[T]) = { + * // creates a runtime reflection universe to host runtime compilation + * import scala.reflect.runtime.{universe => ru} + * val mirror = ru.runtimeMirror(c.libraryClassLoader) + * import scala.tools.reflect.ToolBox + * val toolBox = mirror.mkToolBox() + * + * // runtime reflection universe and compile-time macro universe are different + * // therefore an importer is needed to bridge them + * // currently mkImporter requires a cast to correctly assign the path-dependent types + * val importer0 = ru.mkImporter(c.universe) + * val importer = importer0.asInstanceOf[ru.Importer { val from: c.universe.type }] + * + * // the created importer is used to turn a compiler tree into a runtime compiler tree + * // both compilers use the same classpath, so semantics remains intact + * val imported = importer.importTree(tree) + * + * // after the tree is imported, it can be evaluated as usual + * val tree = toolBox.resetAllAttrs(imported.duplicate) + * val valueOfX = toolBox.eval(imported).asInstanceOf[T] + * ... + * } + * }}} + */ trait Importers { self: Universe => + /** Creates an importer that moves reflection artifacts between universes. + * @group Importers + */ def mkImporter(from0: Universe): Importer { val from: from0.type } + /** The API of importers. + * The main source of information about importers is the [[scala.reflect.api.Importers]] page. + * @group Importers + */ trait Importer { + /** The source universe of reflection artifacts that will be processed. + * The target universe is universe that created this importer with `mkImporter`. + */ val from: Universe + /** An importer that works in reverse direction, namely: + * imports reflection artifacts from the current universe to the universe specified in `from`. + */ val reverse: from.Importer { val from: self.type } + /** In the current universe, locates or creates a symbol that corresponds to the provided symbol in the source universe. + * If necessary imports the owner chain, companions, type signature, annotations and attachments. + */ def importSymbol(sym: from.Symbol): Symbol + /** In the current universe, locates or creates a type that corresponds to the provided type in the source universe. + * If necessary imports the underlying symbols, annotations, scopes and trees. + */ def importType(tpe: from.Type): Type + /** In the current universe, creates a tree that corresponds to the provided tree in the source universe. + * If necessary imports the underlying symbols, types and attachments. + */ def importTree(tree: from.Tree): Tree + /** In the current universe, creates a position that corresponds to the provided position in the source universe. + */ def importPosition(pos: from.Position): Position } }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/api/JavaMirrors.scala b/src/reflect/scala/reflect/api/JavaMirrors.scala new file mode 100644 index 0000000000..df099006b5 --- /dev/null +++ b/src/reflect/scala/reflect/api/JavaMirrors.scala @@ -0,0 +1,52 @@ +package scala.reflect +package api + +/** A refinement of [[scala.reflect.api.Mirror]] for runtime reflection using JVM classloaders. + * + * This refinement equips mirrors with reflection capabilities for the JVM. `JavaMirror` can + * convert Scala reflection artifacts (symbols and types) into Java reflection artifacts (classes) + * and vice versa. It can also perform reflective invocations (getting/setting field values, + * calling methods, etc). + * + * For more information about `Mirrors`s, see [[scala.reflect.api.Mirrors]] or the + * [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Mirrors]] + * + * @groupname JavaMirrors Java Mirrors + */ +trait JavaMirrors { self: JavaUniverse => + + /** In runtime reflection universes, runtime representation of a class is `java.lang.Class`. + * @group JavaMirrors + */ + type RuntimeClass = java.lang.Class[_] + + /** In runtime reflection universes, mirrors are `JavaMirrors`. + * @group JavaMirrors + */ + override type Mirror >: Null <: JavaMirror + + /** A refinement of [[scala.reflect.api.Mirror]] for runtime reflection using JVM classloaders. + * + * With this upgrade, mirrors become capable of converting Scala reflection artifacts (symbols and types) + * into Java reflection artifacts (classes) and vice versa. Consequently, refined mirrors + * become capable of performing reflective invocations (getting/setting field values, calling methods, etc). + * + * For more information about `Mirrors`s, see [[scala.reflect.api.Mirrors]] or the + * [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Mirrors]] + * + * @group JavaMirrors + */ + trait JavaMirror extends scala.reflect.api.Mirror[self.type] with RuntimeMirror { + val classLoader: ClassLoader + override def toString = s"JavaMirror with ${runtime.ReflectionUtils.show(classLoader)}" + } + + /** Creates a runtime reflection mirror from a JVM classloader. + * + * For more information about `Mirrors`s, see [[scala.reflect.api.Mirrors]] or the + * [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Mirrors]] + * + * @group JavaMirrors + */ + def runtimeMirror(cl: ClassLoader): Mirror +} diff --git a/src/reflect/scala/reflect/api/JavaUniverse.scala b/src/reflect/scala/reflect/api/JavaUniverse.scala index ba38381561..f83692034f 100644 --- a/src/reflect/scala/reflect/api/JavaUniverse.scala +++ b/src/reflect/scala/reflect/api/JavaUniverse.scala @@ -1,19 +1,19 @@ package scala.reflect package api -trait JavaUniverse extends Universe with Mirrors { self => - - type RuntimeClass = java.lang.Class[_] - - override type Mirror >: Null <: JavaMirror - - trait JavaMirror extends MirrorOf[self.type] with RuntimeMirror { - val classLoader: ClassLoader - override def toString = s"JavaMirror with ${runtime.ReflectionUtils.show(classLoader)}" - } - - def runtimeMirror(cl: ClassLoader): Mirror +/** A refinement of [[scala.reflect.api.Universe]] for runtime reflection using JVM classloaders. + * + * The refinement consists of an upgrade to the mirror API, which gets extended from [[scala.reflect.api.Mirror]] + * to [[scala.reflect.api.JavaMirrors#JavaMirror]]. + * + * See the [[http://docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] for details on how to use runtime reflection. + * @groupname JavaUniverse Java Mirrors + * + * @contentDiagram hideNodes "*Api" + */ +trait JavaUniverse extends Universe with JavaMirrors { self => + /* @group JavaUniverse */ override def typeTagToManifest[T: ClassTag](mirror0: Any, tag: Universe # TypeTag[T]): Manifest[T] = { // SI-6239: make this conversion more precise val mirror = mirror0.asInstanceOf[Mirror] @@ -21,9 +21,10 @@ trait JavaUniverse extends Universe with Mirrors { self => Manifest.classType(runtimeClass).asInstanceOf[Manifest[T]] } + /* @group JavaUniverse */ override def manifestToTypeTag[T](mirror0: Any, manifest: Manifest[T]): Universe # TypeTag[T] = TypeTag(mirror0.asInstanceOf[Mirror], new TypeCreator { - def apply[U <: Universe with Singleton](mirror: MirrorOf[U]): U # Type = { + def apply[U <: Universe with Singleton](mirror: scala.reflect.api.Mirror[U]): U # Type = { mirror.universe match { case ju: JavaUniverse => val jm = mirror.asInstanceOf[ju.Mirror] diff --git a/src/reflect/scala/reflect/api/MirrorOf.scala b/src/reflect/scala/reflect/api/Mirror.scala index cd5641e692..b1290cc02e 100644 --- a/src/reflect/scala/reflect/api/MirrorOf.scala +++ b/src/reflect/scala/reflect/api/Mirror.scala @@ -2,32 +2,41 @@ package scala.reflect package api /** - * The base interface for all mirrors. + * The base class for all mirrors. * - * @tparam U the type of the universe this mirror belongs to. - * - * This is defined outside the reflection universe cake pattern implementation - * so that it can be referenced from outside. For example TypeCreator and TreeCreator - * reference MirrorOf and also need to be defined outside the cake as they are - * used by type tags, which can be migrated between different universes and consequently - * cannot be bound to a fixed one. + * See [[scala.reflect.api.Mirrors]] or [[docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] + * for a complete overview of `Mirror`s. * - * @see [[Mirrors]] + * @tparam U the type of the universe this mirror belongs to. */ -abstract class MirrorOf[U <: Universe with Singleton] { - /** The universe this mirror belongs to. */ +// Note: Unlike most Scala reflection artifact classes, `Mirror` is not defined as an inner class, +// so that it can be referenced from outside. For example, [[scala.reflect.api.TypeCreator]] and [[scala.reflect.api.TreeCreator]] +// reference `Mirror` and also need to be defined outside the cake as they are used by type tags, which can be migrated between +// different universes and consequently cannot be bound to a fixed one. +abstract class Mirror[U <: Universe with Singleton] { + /** The universe this mirror belongs to. + * @group Mirror + */ val universe: U - /** The class symbol of the `_root_` package */ + /** The class symbol of the `_root_` package + * @group Mirror + */ def RootClass: U#ClassSymbol - /** The module symbol of the `_root_` package */ + /** The module symbol of the `_root_` package + * @group Mirror + */ def RootPackage: U#ModuleSymbol - /** The module class symbol of the default (unnamed) package */ + /** The module class symbol of the default (unnamed) package + * @group Mirror + */ def EmptyPackageClass: U#ClassSymbol - /** The module symbol of the default (unnamed) package */ + /** The module symbol of the default (unnamed) package + * @group Mirror + */ def EmptyPackage: U#ModuleSymbol /** The symbol corresponding to the globally accessible class with the @@ -71,6 +80,7 @@ abstract class MirrorOf[U <: Universe with Singleton] { * * In the example above, to load a symbol that corresponds to the class B declared in the object foo, * use staticModule("foo") to load the module symbol and then navigate typeSignature.members of its moduleClass. + * @group Mirror */ def staticClass(fullName: String): U#ClassSymbol @@ -97,11 +107,13 @@ abstract class MirrorOf[U <: Universe with Singleton] { * * In the example above, to load a symbol that corresponds to the object B declared in the object foo, * use staticModule("foo") to load the module symbol and then navigate typeSignature.members of its moduleClass. + * @group Mirror */ def staticModule(fullName: String): U#ModuleSymbol /** The symbol corresponding to a package with the * given fully qualified name `fullName`. + * @group Mirror */ def staticPackage(fullName: String): U#ModuleSymbol } diff --git a/src/reflect/scala/reflect/api/Mirrors.scala b/src/reflect/scala/reflect/api/Mirrors.scala index c935533027..cc1b9762cb 100644 --- a/src/reflect/scala/reflect/api/Mirrors.scala +++ b/src/reflect/scala/reflect/api/Mirrors.scala @@ -1,37 +1,243 @@ package scala.reflect package api -/** - * Defines a type hierarchy for mirrors. +/** This trait provides support for Mirrors in the Scala Reflection API. * - * Every universe has one or more mirrors. A mirror defines a hierarchy of symbols starting with the root package `_root_` - * and provides methods to locate and define classes and singleton objects in that hierarchy. + * `Mirror`s are a central part of Scala Reflection. All information provided by + * reflection is made accessible through `Mirror`s. Depending on the type of information + * to be obtained, or the reflective action to be taken, different flavors of mirrors + * must be used. "Classloader" mirrors can be used to obtain representations of types + * and members. From a classloader `Mirror`, it's possible to obtain more specialized + * "invoker" `Mirror`s (the most commonly-used mirrors), which implement reflective + * invocations, such as method/constructor calls and field accesses. * - * On the JVM, there is a one to one correspondance between class loaders and mirrors. + * The two flavors of mirrors: + * + * <ul> + * <li>```“Classloader” mirrors```. These mirrors translate names to symbols + * (via methods `staticClass`/`staticModule`/`staticPackage`).</li> + * <li>```"Invoker” mirrors```. These mirrors implement reflective invocations + * (via methods `MethodMirror.apply`, `FieldMirror.get`, etc). These "invoker" + * mirrors are the types of mirrors that are most commonly used.</li> + * </ul> + * + * === Compile-time Mirrors === + * Compile-time `Mirror`s make use of only classloader `Mirror`s to load `Symbol`s + * by name. + * + * The entry point to classloader `Mirror`s is via [[scala.reflect.macros.Context#mirror]]. + * Typical methods which use classloader `Mirror`s include [[scala.reflect.api.Mirror#staticClass]], + * [[scala.reflect.api.Mirror#staticModule]], and [[scala.reflect.api.Mirror#staticPackage]]. For + * example: + * {{{ + * import scala.reflect.macros.Context + * + * case class Location(filename: String, line: Int, column: Int) + * + * object Macros { + * def currentLocation: Location = macro impl + * + * def impl(c: Context): c.Expr[Location] = { + * import c.universe._ + * val pos = c.macroApplication.pos + * val clsLocation = c.mirror.staticModule("Location") // get symbol of "Location" object + * c.Expr(Apply(Ident(clsLocation), List(Literal(Constant(pos.source.path)), Literal(Constant(pos.line)), Literal(Constant(pos.column))))) + * } + * } + * }}} + * + * ''Of Note:'' There are several high-level alternatives that one can use to avoid having to manually + * lookup symbols. For example, `typeOf[Location.type].termSymbol` (or `typeOf[Location].typeSymbol` + * if we needed a `ClassSymbol`), which are type safe since we don’t have to use `String`s to lookup + * the `Symbol`. + * + * === Runtime Mirrors === + * + * Runtime `Mirror`s make use of both classloader and invoker `Mirror`s. + * + * The entry point to `Mirror`s for use at runtime is via `ru.runtimeMirror(<classloader>)`, where + * `ru` is [[scala.reflect.runtime.universe]]. + * + * The result of a [[scala.reflect.api.JavaMirrors#runtimeMirror]] call is a classloader mirror, + * of type [[scala.reflect.api.Mirrors#ReflectiveMirror]], which can load symbols by names as + * discussed above (in the “Compile-time” section). + * + * A classloader mirror can create invoker mirrors, which include: [[scala.reflect.api.Mirrors#InstanceMirror]], + * [[scala.reflect.api.Mirrors#MethodMirror]], [[scala.reflect.api.Mirrors#FieldMirror]], + * [[scala.reflect.api.Mirrors#ClassMirror]] and [[scala.reflect.api.Mirrors#ModuleMirror]]. + * + * Examples of how these two types of `Mirror`s interact are available below. + * + * === Types of Mirrors, Their Use Cases & Examples === + * + * '''[[scala.reflect.api.Mirrors#ReflectiveMirror]]'''. Used for loading `Symbol`s by name, and + * as an entry point into invoker mirrors. Entry point: `val m = ru.runtimeMirror(<classloader>)`. + * Example: + * {{{ + * scala> val ru = scala.reflect.runtime.universe + * ru: scala.reflect.api.JavaUniverse = ... + * + * scala> val m = ru.runtimeMirror(getClass.getClassLoader) + * m: reflect.runtime.universe.Mirror = JavaMirror ... + * }}} + * + * '''[[scala.reflect.api.Mirrors#InstanceMirror]]'''. Used for creating invoker `Mirror`s for methods + * and fields and for inner classes and inner objects (modules). Entry point: `val im = m.reflect(<value>)`. + * Example: + * {{{ + * scala> class C { def x = 2 } + * defined class C + * + * scala> val im = m.reflect(new C) + * im: reflect.runtime.universe.InstanceMirror = instance mirror for C@3442299e + * }}} + * + * '''[[scala.reflect.api.Mirrors#MethodMirror]]'''. Used for invoking instance methods (Scala only has + * instance methods-- methods of objects are instance methods of object instances, obtainable + * via `ModuleMirror.instance`). Entry point: `val mm = im.reflectMethod(<method symbol>)`. + * Example: + * {{{ + * scala> val methodX = typeOf[C].declaration(newTermName("x")).asMethod + * methodX: reflect.runtime.universe.MethodSymbol = method x + * + * scala> val mm = im.reflectMethod(methodX) + * mm: reflect.runtime.universe.MethodMirror = method mirror for C.x: scala.Int (bound to C@3442299e) + * + * scala> mm() + * res0: Any = 2 + * }}} + * + * '''[[scala.reflect.api.Mirrors#FieldMirror]]'''. Used for getting/setting instance fields + * (Scala only has instance fields-- fields of objects are instance methods of object instances + * obtainable via ModuleMirror.instance). Entry point: + * `val fm = im.reflectMethod(<field or accessor symbol>)`. + * Example: + * {{{ + * scala> class C { val x = 2; val y = 3 } + * defined class C + * + * scala> val m = ru.runtimeMirror(getClass.getClassLoader) + * m: reflect.runtime.universe.Mirror = JavaMirror ... + * + * scala> val im = m.reflect(new C) + * im: reflect.runtime.universe.InstanceMirror = instance mirror for C@5f0c8ac1 + * + * scala> val fieldX = typeOf[C].declaration(newTermName("x")).asTerm.accessed.asTerm + * fieldX: reflect.runtime.universe.TermSymbol = value x + * scala> val fmX = im.reflectField(fieldX) + * fmX: reflect.runtime.universe.FieldMirror = field mirror for C.x (bound to C@5f0c8ac1) + * + * scala> fmX.get + * res0: Any = 2 + * + * scala> fmX.set(3) + * scala.ScalaReflectionException: cannot set an immutable field x + * ... + * + * scala> val fieldY = typeOf[C].declaration(newTermName("y")).asTerm.accessed.asTerm + * fieldY: reflect.runtime.universe.TermSymbol = variable y + * + * scala> val fmY = im.reflectField(fieldY) + * fmY: reflect.runtime.universe.FieldMirror = field mirror for C.y (bound to C@5f0c8ac1) + * + * scala> fmY.get + * res1: Any = 3 + * + * scala> fmY.set(4) + * + * scala> fmY.get + * res2: Any = 4 + * }}} + * + * '''[[scala.reflect.api.Mirrors#ClassMirror]]'''. Used for creating invoker mirrors for constructors. + * Entry points: for ''static classes'' `val cm1 = m.reflectClass(<class symbol>)`, + * for ''inner classes'' `val mm2 = im.reflectClass(<module symbol>)`. + * Example: + * {{{ + * scala> case class C(x: Int) + * defined class C + * + * scala> val m = ru.runtimeMirror(getClass.getClassLoader) + * m: reflect.runtime.universe.Mirror = JavaMirror ... + * + * scala> val classC = typeOf[C].typeSymbol.asClass + * + * classC: reflect.runtime.universe.Symbol = class C + * + * scala> val cm = m.reflectClass(classC) + * cm: reflect.runtime.universe.ClassMirror = class mirror for C (bound to null) + * + * scala> val ctorC = typeOf[C].declaration(ru.nme.CONSTRUCTOR).asMethod + * ctorC: reflect.runtime.universe.MethodSymbol = constructor C + * + * scala> val ctorm = cm.reflectConstructor(ctorC) + * ctorm: reflect.runtime.universe.MethodMirror = constructor mirror for C.<init>(x: scala.Int): C (bound to null) + * + * scala> ctorm(2) + * res0: Any = C(2) + * }}} + * + * '''[[scala.reflect.api.Mirrors#ModuleMirror]]'''. Used for getting singleton instances of objects. + * Entry points: for ''static objects (modules)'' `val mm1 = m.reflectModule(<module symbol>)`, + * for ''inner objects (modules)'' `val mm2 = im.reflectModule(<module symbol>)`. + * Example: + * {{{ + * scala> object C { def x = 2 } + * defined module C + * + * scala> val m = ru.runtimeMirror(getClass.getClassLoader) + * m: reflect.runtime.universe.Mirror = JavaMirror ... + * + * scala> val objectC = typeOf[C.type].termSymbol.asModule + * objectC: reflect.runtime.universe.ModuleSymbol = object C + * + * scala> val mm = m.reflectModule(objectC) + * mm: reflect.runtime.universe.ModuleMirror = module mirror for C (bound to null) + * + * scala> val obj = mm.instance + * obj: Any = C$@1005ec04 + * }}} + * + * For more information about `Mirrors`s, see the + * [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Mirrors]] + * + * @contentDiagram hideNodes "*Api" */ trait Mirrors { self: Universe => - /** The base type of all mirrors of this universe */ - type Mirror >: Null <: MirrorOf[self.type] + /** The base type of all mirrors of this universe. + * + * This abstract type conforms the base interface for all mirrors defined in [[scala.reflect.api.Mirror]] + * and is gradually refined in specific universes (e.g. `Mirror` of a [[scala.reflect.api.JavaUniverse]] is capable of reflection). + * @group Mirrors + */ + type Mirror >: Null <: scala.reflect.api.Mirror[self.type] /** The root mirror of this universe. This mirror contains standard Scala classes and types such as `Any`, `AnyRef`, `AnyVal`, * `Nothing`, `Null`, and all classes loaded from scala-library, which are shared across all mirrors within the enclosing universe. + * @group Mirrors */ val rootMirror: Mirror + /** Abstracts the runtime representation of a class on the underlying platform. + * @group Mirrors + */ type RuntimeClass >: Null // todo. an improvement might be having mirrors reproduce the structure of the reflection domain // e.g. a ClassMirror could also have a list of fields, methods, constructors and so on // read up more on the proposed design in "Reflecting Scala" by Y. Coppel - /** A mirror that reflects a runtime value */ + /** A mirror that reflects a runtime value. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait InstanceMirror { /** The instance value reflected by this mirror */ def instance: Any - /** The symbol corresponding to the run-time class of the reflected instance */ + /** The symbol corresponding to the runtime class of the reflected instance */ def symbol: ClassSymbol /** Reflects against a field symbol and returns a mirror @@ -99,7 +305,10 @@ trait Mirrors { self: Universe => def reflectModule(mod: ModuleSymbol): ModuleMirror } - /** A mirror that reflects a field */ + /** A mirror that reflects a field. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait FieldMirror { /** The object containing the field */ @@ -141,7 +350,10 @@ trait Mirrors { self: Universe => def set(value: Any): Unit } - /** A mirror that reflects a method handle */ + /** A mirror that reflects a method. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait MethodMirror { /** The receiver object of the method */ @@ -159,12 +371,12 @@ trait Mirrors { self: Universe => def apply(args: Any*): Any } - /** A mirror that reflects the instance or static parts of a runtime class */ + /** A mirror that reflects the instance or static parts of a runtime class. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait TemplateMirror { - /** The runtime class reflected by this mirror */ - def runtimeClass: RuntimeClass - /** True if the mirror represents the static part * of a runtime class or the companion object of a Scala class. * One has: @@ -176,21 +388,12 @@ trait Mirrors { self: Universe => /** The Scala symbol corresponding to the reflected runtime class or object */ def symbol: Symbol - - /** Optionally, the mirror of the companion reflected by this mirror. - * If this mirror reflects a Scala object, the mirror for the companion class, or None - * if the mirror represents a Scala object that comes without a class. - * Otherwise, if the mirror represents the static part of a runtime class, the - * mirror representing the instance part of the same class. - * Otherwise, if the mirror represents a Scala instance class, the mirror for the companion - * object of that class, or None if no such object exists. - * Otherwise, if the mirror represents a runtime instance class, a mirror representing the static - * part of the same class. - */ - def companion: Option[TemplateMirror] } - /** A mirror that reflects a Scala object definition or the static parts of a runtime class */ + /** A mirror that reflects a Scala object definition or the static parts of a runtime class. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait ModuleMirror extends TemplateMirror { /** The Scala module symbol corresponding to the reflected object */ @@ -201,17 +404,12 @@ trait Mirrors { self: Universe => * If this mirror reflects the static part of a runtime class, returns `null`. */ def instance: Any - - /** Optionally, the mirror of the companion class if the object reflected by this mirror. - * If this mirror reflects a Scala object, the mirror for the companion class, or None - * if the mirror represents a Scala object that comes without a class. - * Otherwise, if the mirror represents the static part of a runtime class, the - * mirror representing the instance part of the same class. - */ - override def companion: Option[ClassMirror] } - /** A mirror that reflects the instance parts of a runtime class */ + /** A mirror that reflects the instance parts of a runtime class. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait ClassMirror extends TemplateMirror { /** The Scala class symbol corresponding to the reflected class */ @@ -228,18 +426,13 @@ trait Mirrors { self: Universe => * It must be a member (declared or inherited) of the class underlying this mirror. */ def reflectConstructor(constructor: MethodSymbol): MethodMirror - - /** Optionally, the mirror of the companion object of the class reflected by this mirror. - * If this mirror represents a Scala instance class, the mirror for the companion - * object of that class, or None if no such object exists. - * Otherwise, if the mirror represents a runtime instance class, a mirror representing the static - * part of the same class. - */ - override def companion: Option[ModuleMirror] } - /** A mirror that reflects instances and static classes */ - trait ReflectiveMirror extends MirrorOf[Mirrors.this.type] { + /** A mirror that reflects instances and static classes. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ + trait ReflectiveMirror extends scala.reflect.api.Mirror[Mirrors.this.type] { /** A reflective mirror for the given object. * @@ -273,7 +466,10 @@ trait Mirrors { self: Universe => def reflectModule(mod: ModuleSymbol): ModuleMirror } - /** The API of a mirror for a reflective universe */ + /** The API of a mirror for a reflective universe. + * See [[scala.reflect.api.package the overview page]] for details on how to use runtime reflection. + * @group Mirrors + */ trait RuntimeMirror extends ReflectiveMirror { self => /** Maps a Scala type to the corresponding Java class object */ diff --git a/src/reflect/scala/reflect/api/Names.scala b/src/reflect/scala/reflect/api/Names.scala index e8665ca736..02eb79f8ed 100644 --- a/src/reflect/scala/reflect/api/Names.scala +++ b/src/reflect/scala/reflect/api/Names.scala @@ -1,40 +1,70 @@ package scala.reflect package api -/** A trait that manages names. +/** This trait defines Names (a Scala reflection concept) and operations on them. * - * @see TermName - * @see TypeName + * Names are simple wrappers for strings. [[scala.reflect.api.Names#Name Name]] has two subtypes [[scala.reflect.api.Names#TermName TermName]] and [[scala.reflect.api.Names#TypeName TypeName]] which + * distinguish names of terms (like objects or members) and types. A term and a type of the + * same name can co-exist in an object. + * + * === Examples === + * + * To search for the `map` method (which is a term) declared in the `List` class, + * use `typeOf[List[_]].member(newTermName("map"))`. To search for a type member, use + * newTypeName instead. + * + * See the [[docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] for more about Scala Reflection. + * + * @contentDiagram hideNodes "*Api" */ trait Names { - // Intentionally no implicit from String => Name. + /** An implicit conversion from String to TermName. + * Enables an alternative notation `"map": TermName` as opposed to `newTermName("map")`. + * @group Names + */ implicit def stringToTermName(s: String): TermName = newTermName(s) + + /** An implicit conversion from String to TypeName. + * Enables an alternative notation `"List": TypeName` as opposed to `newTypeName("List")`. + * @group Names + */ implicit def stringToTypeName(s: String): TypeName = newTypeName(s) - /** - * The abstract type of names - * - * A Name wraps a string as the name for either a type ([[TypeName]]) of a term ([[TermName]]). - * Two names are equal, if the wrapped string are equal and they are either both `TypeName` or both `TermName`. - * The same string can co-exist as a `TypeName` and a `TermName`, but they would not be equal. - * Names are interned. That is, for two names `name11 and `name2`, - * `name1 == name2` implies `name1 eq name2`. - * - * One of the reasons for the existence of names rather than plain strings is being more explicit about what is a name and if it represents a type or a term. + /** The abstract type of names. + * @group Names */ type Name >: Null <: NameApi + + /** A tag that preserves the identity of the `Name` abstract type from erasure. + * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags + */ implicit val NameTag: ClassTag[Name] - /** The abstract type of names representing terms */ + /** The abstract type of names representing terms. + * @group Names + */ type TypeName >: Null <: Name - implicit val TypeNameTag: ClassTag[TypeName] - /** The abstract type of names representing types */ + /** A tag that preserves the identity of the `TypeName` abstract type from erasure. + * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags + */ +implicit val TypeNameTag: ClassTag[TypeName] + + /** The abstract type of names representing types. + * @group Names + */ type TermName >: Null <: Name + + /** A tag that preserves the identity of the `TermName` abstract type from erasure. + * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags + */ implicit val TermNameTag: ClassTag[TermName] - /** The API of names that's supported on reflect mirror via an - * implicit conversion in reflect.ops + /** The API of Name instances. + * @group API */ abstract class NameApi { /** Checks wether the name is a a term name */ @@ -69,18 +99,12 @@ trait Names { } /** Create a new term name. + * @group Names */ def newTermName(s: String): TermName /** Creates a new type name. + * @group Names */ def newTypeName(s: String): TypeName - - /** Wraps the empty string. Can be used as the null object for term name. - */ - def EmptyTermName: TermName = newTermName("") - - /** Wraps the empty string. Can be used as the null object for type name. - */ - def EmptyTypeName: TypeName = EmptyTermName.toTypeName } diff --git a/src/reflect/scala/reflect/api/Position.scala b/src/reflect/scala/reflect/api/Position.scala new file mode 100644 index 0000000000..61d643b449 --- /dev/null +++ b/src/reflect/scala/reflect/api/Position.scala @@ -0,0 +1,190 @@ +package scala.reflect +package api + +import scala.reflect.macros.Attachments + +/** Position tracks the origin of [[Symbols#Symbol symbols]] and [[Trees#Tree tree nodes]]. They are commonly used when + * displaying warnings and errors, to indicate the incorrect point in the program. + * + * A position indicates the [[source source file]] and an [[point offset]]. A position may be + * undefined, which means it's pointing to the [[Positions#NoPosition]] element. + * + * <b>Please note that this trait may be refactored in future versions of the Scala reflection API.</b> + * + * @see [[http://docs.scala-lang.org/overviews/reflection/names-exprs-scopes-more.html]] + * + * The compiler adds more information to positions, such a ranges in the source file and defines different types of + * positions depending on how a symbol or tree node was generated. The guide fully describes compiler-generated positions. + * + * - INV1: A tree with an offset position never contains a child + * with a range position + * - INV2: If the child of a tree with a range position also has a range position, + * then the child's range is contained in the parent's range. + * - INV3: Opaque range positions of children of the same node are non-overlapping + * (this means their overlap is at most a single point). + * + * The following tests are useful on positions: + * `pos.isDefined` true if position is not a NoPosition, + * `pos.isRange` true if position is a range, + * `pos.isOpaqueRange` true if position is an opaque range, + * + * There are also convenience methods, such as + * `pos.startOrPoint`, + * `pos.endOrPoint`, + * `pos.pointOrElse(default)`. + * These are less strict about the kind of position on which they can be applied. + * + * The following conversion methods are often used: + * `pos.focus` converts a range position to an offset position, keeping its point; + * returns all other positions unchanged, + * `pos.makeTransparent` converts an opaque range position into a transparent one. + * returns all other positions unchanged. + * + * @groupname Common Commonly used methods + */ +trait Position extends Attachments { + + /** @inheritdoc */ + type Pos >: Null <: Position + + /** Java file corresponding to the source file of this position. + * + * The return type is `scala.reflect.io.AbstractFile`, which belongs to an experimental part of Scala reflection. + * It should not be used unless you know what you are doing. In subsequent releases, this API will be refined + * and exposed as a part of scala.reflect.api. + * + * @group Common + */ + def source: scala.reflect.internal.util.SourceFile + + /** Is this position neither a NoPosition nor a FakePosition? + * If isDefined is true, offset and source are both defined. + * @group Common + */ + def isDefined: Boolean + + /** Is this position a range position? */ + def isRange: Boolean + + /** Is this position a transparent position? */ + def isTransparent: Boolean + + /** Is this position a non-transparent range position? */ + def isOpaqueRange: Boolean + + /** If opaque range, make this position transparent. */ + def makeTransparent: Pos + + /** The start of the position's range, error if not a range position. */ + def start: Int + + /** The start of the position's range, or point if not a range position. */ + def startOrPoint: Int + + /** The point (where the ^ is) of the position, which is easiest to access using the [[line]] and [[column]] values. + * The [[lineContent line content]] is also available. + * @group Common + */ + def point: Int + + /** The point (where the ^ is) of the position, or else `default` if undefined. + * @group Common + */ + def pointOrElse(default: Int): Int + + /** The end of the position's range, error if not a range position. + */ + def end: Int + + /** The end of the position's range, or point if not a range position. + */ + def endOrPoint: Int + + /** The same position with a different start value (if a range). + */ + def withStart(off: Int): Pos + + /** The same position with a different end value (if a range). + */ + def withEnd(off: Int): Pos + + /** The same position with a different point value (if a range or offset). + */ + def withPoint(off: Int): Pos + + /** If this is a range, the union with the other range, with the point of this position. + * Otherwise, this position + */ + def union(pos: Pos): Pos + + /** If this is a range position, the offset position of its point. + * Otherwise the position itself + */ + def focus: Pos + + /** If this is a range position, the offset position of its start. + * Otherwise the position itself + */ + def focusStart: Pos + + /** If this is a range position, the offset position of its end. + * Otherwise the position itself + */ + def focusEnd: Pos + + /** Does this position include the given position `pos`? + * This holds if `this` is a range position and its range [start..end] + * is the same or covers the range of the given position, which may or may not be a range position. + */ + def includes(pos: Pos): Boolean + + /** Does this position properly include the given position `pos` ("properly" meaning their + * ranges are not the same)? + */ + def properlyIncludes(pos: Pos): Boolean + + /** Does this position precede that position? + * This holds if both positions are defined and the end point of this position + * is not larger than the start point of the given position. + */ + def precedes(pos: Pos): Boolean + + /** Does this position properly precede the given position `pos` ("properly" meaning their ranges + * do not share a common point). + */ + def properlyPrecedes(pos: Pos): Boolean + + /** Does this position overlap with that position? + * This holds if both positions are ranges and there is an interval of + * non-zero length that is shared by both position ranges. + */ + def overlaps(pos: Pos): Boolean + + /** Does this position cover the same range as that position? + * Holds only if both position are ranges + */ + def sameRange(pos: Pos): Boolean + + /** The position indicates a [[column `column`]] and the `line` in the source file. + * @group Common + */ + def line: Int + + /** The position indicates a `column` and the [[line `line`]] in the source file. + * @group Common + */ + def column: Int + + /** Convert this to a position around `point` that spans a single source line + */ + def toSingleLine: Pos + + /** The content of the line this Position refers to. + * @group Common + */ + def lineContent: String + + /** Show a textual representation of the position. + */ + def show: String +} diff --git a/src/reflect/scala/reflect/api/Positions.scala b/src/reflect/scala/reflect/api/Positions.scala index 0eddc88fc4..8d8a0081cc 100644 --- a/src/reflect/scala/reflect/api/Positions.scala +++ b/src/reflect/scala/reflect/api/Positions.scala @@ -1,26 +1,34 @@ package scala.reflect package api -/** - * Defines the type hierachy for positions. +/** This trait defines the concept of positions and operations on them. * - * @see [[scala.reflect]] for a description on how the class hierarchy is encoded here. + * @see [[scala.reflect.api.Position]] + * + * @contentDiagram hideNodes "*Api" */ trait Positions { self: Universe => - /** .. */ - type Position >: Null <: PositionApi { type Pos = Position } + /** Defines a universe-specific notion of positions. + * The main documentation entry about positions is located at [[scala.reflect.api.Position]]. + * @group Positions + */ + type Position >: Null <: scala.reflect.api.Position { type Pos = Position } /** A tag that preserves the identity of the `Position` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val PositionTag: ClassTag[Position] - /** A special "missing" position. */ + /** A special "missing" position. + * @group Positions + */ val NoPosition: Position /** Assigns a given position to all position-less nodes of a given AST. + * @group Positions */ def atPos[T <: Tree](pos: Position)(tree: T): T @@ -28,6 +36,7 @@ trait Positions { * The point of the wrapping position is the point of the default position. * If some of the trees are ranges, returns a range position enclosing all ranges * Otherwise returns default position. + * @group Positions */ def wrappingPos(default: Position, trees: List[Tree]): Position @@ -35,171 +44,7 @@ trait Positions { * The point of the wrapping position is the point of the first trees' position. * If all some the trees are non-synthetic, returns a range position enclosing the non-synthetic trees * Otherwise returns a synthetic offset position to point. + * @group Positions */ def wrappingPos(trees: List[Tree]): Position } - -/** The Position class and its subclasses represent positions of ASTs and symbols. - * Except for NoPosition and FakePos, every position refers to a SourceFile - * and to an offset in the sourcefile (its `point`). For batch compilation, - * that's all. For interactive IDE's there are also RangePositions - * and TransparentPositions. A RangePosition indicates a start and an end - * in addition to its point. TransparentPositions are a subclass of RangePositions. - * Range positions that are not transparent are called opaque. - * Trees with RangePositions need to satisfy the following invariants. - * - * INV1: A tree with an offset position never contains a child - * with a range position - * INV2: If the child of a tree with a range position also has a range position, - * then the child's range is contained in the parent's range. - * INV3: Opaque range positions of children of the same node are non-overlapping - * (this means their overlap is at most a single point). - * - * The following tests are useful on positions: - * - * pos.isDefined true if position is not a NoPosition nor a FakePosition - * pos.isRange true if position is a range - * pos.isOpaqueRange true if position is an opaque range - * - * The following accessor methods are provided: - * - * pos.source The source file of the position, which must be defined - * pos.point The offset of the position's point, which must be defined - * pos.start The start of the position, which must be a range - * pos.end The end of the position, which must be a range - * - * There are also convenience methods, such as - * - * pos.startOrPoint - * pos.endOrPoint - * pos.pointOrElse(default) - * - * These are less strict about the kind of position on which they can be applied. - * - * The following conversion methods are often used: - * - * pos.focus converts a range position to an offset position, keeping its point; - * returns all other positions unchanged. - * pos.makeTransparent converts an opaque range position into a transparent one. - * returns all other positions unchanged. - */ -trait PositionApi extends Attachments { - - type Pos >: Null <: PositionApi - - /** Java file corresponding to the source file of this position. - */ - def fileInfo: java.io.File - - /** Content of the source file that contains this position. - */ - def fileContent: Array[Char] - - /** Is this position neither a NoPosition nor a FakePosition? - * If isDefined is true, offset and source are both defined. - */ - def isDefined: Boolean - - /** Is this position a range position? */ - def isRange: Boolean - - /** Is this position a transparent position? */ - def isTransparent: Boolean - - /** Is this position a non-transparent range position? */ - def isOpaqueRange: Boolean - - /** if opaque range, make this position transparent */ - def makeTransparent: Pos - - /** The start of the position's range, error if not a range position */ - def start: Int - - /** The start of the position's range, or point if not a range position */ - def startOrPoint: Int - - /** The point (where the ^ is) of the position */ - def point: Int - - /** The point (where the ^ is) of the position, or else `default` if undefined */ - def pointOrElse(default: Int): Int - - /** The end of the position's range, error if not a range position */ - def end: Int - - /** The end of the position's range, or point if not a range position */ - def endOrPoint: Int - - /** The same position with a different start value (if a range) */ - def withStart(off: Int): Pos - - /** The same position with a different end value (if a range) */ - def withEnd(off: Int): Pos - - /** The same position with a different point value (if a range or offset) */ - def withPoint(off: Int): Pos - - /** If this is a range, the union with the other range, with the point of this position. - * Otherwise, this position - */ - def union(pos: Pos): Pos - - /** If this is a range position, the offset position of its point. - * Otherwise the position itself - */ - def focus: Pos - - /** If this is a range position, the offset position of its start. - * Otherwise the position itself - */ - def focusStart: Pos - - /** If this is a range position, the offset position of its end. - * Otherwise the position itself - */ - def focusEnd: Pos - - /** Does this position include the given position `pos`. - * This holds if `this` is a range position and its range [start..end] - * is the same or covers the range of the given position, which may or may not be a range position. - */ - def includes(pos: Pos): Boolean - - /** Does this position properly include the given position `pos` ("properly" meaning their - * ranges are not the same)? - */ - def properlyIncludes(pos: Pos): Boolean - - /** Does this position precede that position? - * This holds if both positions are defined and the end point of this position - * is not larger than the start point of the given position. - */ - def precedes(pos: Pos): Boolean - - /** Does this position properly precede the given position `pos` ("properly" meaning their ranges - * do not share a common point). - */ - def properlyPrecedes(pos: Pos): Boolean - - /** Does this position overlap with that position? - * This holds if both positions are ranges and there is an interval of - * non-zero length that is shared by both position ranges. - */ - def overlaps(pos: Pos): Boolean - - /** Does this position cover the same range as that position? - * Holds only if both position are ranges - */ - def sameRange(pos: Pos): Boolean - - def line: Int - - def column: Int - - /** Convert this to a position around `point` that spans a single source line */ - def toSingleLine: Pos - - def lineContent: String - - def show: String -} diff --git a/src/reflect/scala/reflect/api/Printers.scala b/src/reflect/scala/reflect/api/Printers.scala index 65ff2ed9fa..1e8161aeef 100644 --- a/src/reflect/scala/reflect/api/Printers.scala +++ b/src/reflect/scala/reflect/api/Printers.scala @@ -3,9 +3,135 @@ package api import java.io.{ PrintWriter, StringWriter } +/** Utilities for nicely printing [[scala.reflect.api.Trees]] and [[scala.reflect.api.Types]]. + * + * === Printing Trees === + * The method `show` displays the "prettified" representation of reflection artifacts. + * This representation provides one with the desugared Java representation of Scala code. + * For example: + * + * {{{ + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> def tree = reify{ final class C { def x = 2 } }.tree + * tree: reflect.runtime.universe.Tree + * + * scala> show(tree) + * res0: String = + * { + * final class C extends AnyRef { + * def <init>() = { + * super.<init>(); + * () + * }; + * def x = 2 + * }; + * () + * } + * }}} + * + * The method `showRaw` displays internal structure of a given reflection object + * as a Scala abstract syntax tree (AST), the representation that the Scala typechecker + * operates on. + * + * Note, that while this representation appears to generate correct trees that one + * might think would be possible to use in a macro implementation, this is not usually + * the case. Symbols aren't fully represented (only their names are). Thus, this method + * is best-suited for use simply inspecting ASTs given some valid Scala code. + * {{{ + * scala> showRaw(tree) + * res1: String = Block(List( + * ClassDef(Modifiers(FINAL), newTypeName("C"), List(), Template( + * List(Ident(newTypeName("AnyRef"))), + * emptyValDef, + * List( + * DefDef(Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree(), + * Block(List( + * Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), + * Literal(Constant(())))), + * DefDef(Modifiers(), newTermName("x"), List(), List(), TypeTree(), + * Literal(Constant(2))))))), + * Literal(Constant(()))) + * }}} + * + * The method `showRaw` can also print [[scala.reflect.api.Types]] next to the artifacts + * being inspected + * {{{ + * scala> import scala.tools.reflect.ToolBox // requires scala-compiler.jar + * import scala.tools.reflect.ToolBox + * + * scala> import scala.reflect.runtime.{currentMirror => cm} + * import scala.reflect.runtime.{currentMirror=>cm} + * + * scala> showRaw(cm.mkToolBox().typeCheck(tree), printTypes = true) + * res2: String = Block[1](List( + * ClassDef[2](Modifiers(FINAL), newTypeName("C"), List(), Template[3]( + * List(Ident[4](newTypeName("AnyRef"))), + * emptyValDef, + * List( + * DefDef[2](Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree[3](), + * Block[1](List( + * Apply[4](Select[5](Super[6](This[3](newTypeName("C")), tpnme.EMPTY), ...))), + * Literal[1](Constant(())))), + * DefDef[2](Modifiers(), newTermName("x"), List(), List(), TypeTree[7](), + * Literal[8](Constant(2))))))), + * Literal[1](Constant(()))) + * [1] TypeRef(ThisType(scala), scala.Unit, List()) + * [2] NoType + * [3] TypeRef(NoPrefix, newTypeName("C"), List()) + * [4] TypeRef(ThisType(java.lang), java.lang.Object, List()) + * [5] MethodType(List(), TypeRef(ThisType(java.lang), java.lang.Object, List())) + * [6] SuperType(ThisType(newTypeName("C")), TypeRef(... java.lang.Object ...)) + * [7] TypeRef(ThisType(scala), scala.Int, List()) + * [8] ConstantType(Constant(2)) + * }}} + * + * === Printing Types === + * + * The method `show` + * {{{ + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> def tpe = typeOf[{ def x: Int; val y: List[Int] }] + * tpe: reflect.runtime.universe.Type + * + * scala> show(tpe) + * res0: String = scala.AnyRef{def x: Int; val y: scala.List[Int]} + * }}} + * + * Like the method `showRaw` for [[scala.reflect.api.Trees]], `showRaw` + * for [[scala.reflect.api.Types]] provides a visualization of the Scala + * AST operated on by the Scala typechecker. + * {{{ + * // showRaw has already been discussed above + * scala> showRaw(tpe) + * res1: String = RefinedType( + * List(TypeRef(ThisType(scala), newTypeName("AnyRef"), List())), + * Scope( + * newTermName("x"), + * newTermName("y"))) + * }}} + * + * `printIds` and/or `printKinds` can additionally be supplied as arguments in a call to + * `showRaw` which additionally shows the unique identifiers of symbols. + * scala> showRaw(tpe, printIds = true, printKinds = true) + * res2: String = RefinedType( + * List(TypeRef(ThisType(scala#2043#PK), newTypeName("AnyRef")#691#TPE, List())), + * Scope( + * newTermName("x")#2540#METH, + * newTermName("y")#2541#GET)) + * }}} + * + * For more details about `Printer`s and other aspects of Scala reflection, see the + * [[http://docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] + * + */ trait Printers { self: Universe => - trait TreePrinter { + /** @group Printers */ + protected trait TreePrinter { def print(args: Any*) protected var printTypes = false protected var printIds = false @@ -21,13 +147,16 @@ trait Printers { self: Universe => def withoutMirrors: this.type = { printMirrors = false; this } } + /** @group Printers */ case class BooleanFlag(val value: Option[Boolean]) + /** @group Printers */ object BooleanFlag { import scala.language.implicitConversions implicit def booleanToBooleanFlag(value: Boolean): BooleanFlag = BooleanFlag(Some(value)) implicit def optionToBooleanFlag(value: Option[Boolean]): BooleanFlag = BooleanFlag(value) } + /** @group Printers */ protected def render(what: Any, mkPrinter: PrintWriter => TreePrinter, printTypes: BooleanFlag = None, printIds: BooleanFlag = None, printKinds: BooleanFlag = None, printMirrors: BooleanFlag = None): String = { val buffer = new StringWriter() val writer = new PrintWriter(buffer) @@ -41,41 +170,54 @@ trait Printers { self: Universe => buffer.toString } - /** By default trees are printed with `show` */ + /** By default trees are printed with `show` + * @group Printers + */ override protected def treeToString(tree: Tree) = show(tree) - /** Renders a prettified representation of a reflection artifact. - * Typically it looks very close to the Scala code it represents. + /** Renders a representation of a reflection artifact + * as desugared Java code. + * + * @group Printers */ def show(any: Any, printTypes: BooleanFlag = None, printIds: BooleanFlag = None, printKinds: BooleanFlag = None, printMirrors: BooleanFlag = None): String = render(any, newTreePrinter(_), printTypes, printIds, printKinds, printMirrors) /** Hook to define what `show(...)` means. + * @group Printers */ - def newTreePrinter(out: PrintWriter): TreePrinter + protected def newTreePrinter(out: PrintWriter): TreePrinter - /** Renders internal structure of a reflection artifact. + /** Renders internal structure of a reflection artifact as the + * visualization of a Scala syntax tree. + * + * @group Printers */ def showRaw(any: Any, printTypes: BooleanFlag = None, printIds: BooleanFlag = None, printKinds: BooleanFlag = None, printMirrors: BooleanFlag = None): String = render(any, newRawTreePrinter(_), printTypes, printIds, printKinds, printMirrors) /** Hook to define what `showRaw(...)` means. + * @group Printers */ - def newRawTreePrinter(out: PrintWriter): TreePrinter + protected def newRawTreePrinter(out: PrintWriter): TreePrinter /** Renders a prettified representation of a name. + * @group Printers */ def show(name: Name): String /** Renders internal structure of a name. + * @group Printers */ def showRaw(name: Name): String = name.toString /** Renders a prettified representation of a flag set. + * @group Printers */ def show(flags: FlagSet): String /** Renders internal structure of a flag set. + * @group Printers */ def showRaw(flags: FlagSet): String = flags.toString } diff --git a/src/reflect/scala/reflect/api/Scopes.scala b/src/reflect/scala/reflect/api/Scopes.scala index d30da07ad5..80683c8e76 100644 --- a/src/reflect/scala/reflect/api/Scopes.scala +++ b/src/reflect/scala/reflect/api/Scopes.scala @@ -1,34 +1,57 @@ package scala.reflect package api -/** - * Defines the type hierachy for scopes. +/** This trait provides support for scopes in the reflection API. * - * @see [[scala.reflect]] for a description on how the class hierarchy is encoded here. + * A scope object generally maps names to symbols available in a corresponding lexical scope. + * Scopes can be nested. The base type exposed to the reflection API, however, + * only exposes a minimal interface, representing a scope as an iterable of symbols. + * + * For rare occasions when it is necessary to create a scope manually, + * e.g., to populate members of [[scala.reflect.api.Types#RefinedType]], + * there is the `newScopeWith` function. + * + * Additional functionality is exposed in member scopes that are returned by + * `members` and `declarations` defined in [[scala.reflect.api.Types#TypeApi]]. + * Such scopes support the `sorted` method, which sorts members in declaration order. */ trait Scopes { self: Universe => - /** The base type of all scopes. A scope object generally maps names to symbols available in the current lexical scope. - * Scopes can be nested. This base type, however, only exposes a minimal interface, representing a scope as an iterable of symbols. + /** The base type of all scopes. + * @template + * @group Scopes */ type Scope >: Null <: ScopeApi - /** The API that all scopes support */ + /** The API that all scopes support + * @group API + */ trait ScopeApi extends Iterable[Symbol] /** A tag that preserves the identity of the `Scope` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ScopeTag: ClassTag[Scope] - /** The type of member scopes, as in class definitions, for example. */ + /** Create a new scope with the given initial elements. + * @group Scopes + */ + def newScopeWith(elems: Symbol*): Scope + + /** The type of member scopes, as in class definitions, for example. + * @template + * @group Scopes + */ type MemberScope >: Null <: Scope with MemberScopeApi - /** The API that all member scopes support */ + /** The API that all member scopes support + * @group API + */ trait MemberScopeApi extends ScopeApi { /** Sorts the symbols included in this scope so that: * 1) Symbols appear in the linearization order of their owners. - * 2) Symbols with the same owner appear in reverse order of their declarations. + * 2) Symbols with the same owner appear in same order of their declarations. * 3) Synthetic members (e.g. getters/setters for vals/vars) might appear in arbitrary order. */ def sorted: List[Symbol] @@ -36,15 +59,7 @@ trait Scopes { self: Universe => /** A tag that preserves the identity of the `MemberScope` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val MemberScopeTag: ClassTag[MemberScope] - - /** Create a new scope. */ - def newScope: Scope - - /** Create a new scope nested in another one with which it shares its elements. */ - def newNestedScope(outer: Scope): Scope - - /** Create a new scope with the given initial elements. */ - def newScopeWith(elems: Symbol*): Scope }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/api/StandardDefinitions.scala b/src/reflect/scala/reflect/api/StandardDefinitions.scala index 03f2a6b0aa..a31a501357 100644 --- a/src/reflect/scala/reflect/api/StandardDefinitions.scala +++ b/src/reflect/scala/reflect/api/StandardDefinitions.scala @@ -5,139 +5,305 @@ package scala.reflect package api -/** - * Defines standard symbols and types. +/** All Scala standard symbols and types. + * + * These standard definitions can accessed to using `definitions`. + * They're typically imported with a blanket import `import definitions`, and are + * listed in [[scala.reflect.api.StandardDefinitions#DefinitionsApi]]. */ trait StandardDefinitions { self: Universe => - /** A value containing all standard defnitions. */ + /** A value containing all standard definitions in [[DefinitionsApi]] + * @group Definitions + */ val definitions: DefinitionsApi - /** Defines standard symbols (and types via its base trait). */ + /** Defines standard symbols (and types via its base trait). + * @group API + */ trait DefinitionsApi extends StandardTypes { - /** The class symbol of package `scala`. */ + /** The module class symbol of package `scala`. */ def ScalaPackageClass: ClassSymbol - /** The module class symbol of package `scala`. */ + /** The module symbol of package `scala`. */ def ScalaPackage: ModuleSymbol - // top types + /** The class symbol of core class `scala.Any`. */ def AnyClass : ClassSymbol + + /** The class symbol of core class `scala.AnyVal`. */ def AnyValClass: ClassSymbol + + /** The class symbol of core class `java.lang.Object`. */ def ObjectClass: ClassSymbol + + /** The type symbol of core class `scala.AnyRef`. */ def AnyRefClass: TypeSymbol - // bottom types + /** The class symbol of core class `scala.Null`. */ def NullClass : ClassSymbol + + /** The class symbol of core class `scala.Nothing`. */ def NothingClass: ClassSymbol - // the scala value classes + /** The class symbol of primitive class `scala.Unit`. */ def UnitClass : ClassSymbol + + /** The class symbol of primitive class `scala.Byte`. */ def ByteClass : ClassSymbol + + /** The class symbol of primitive class `scala.Short`. */ def ShortClass : ClassSymbol + + /** The class symbol of primitive class `scala.Char`. */ def CharClass : ClassSymbol + + /** The class symbol of primitive class `scala.Int`. */ def IntClass : ClassSymbol + + /** The class symbol of primitive class `scala.Long`. */ def LongClass : ClassSymbol + + /** The class symbol of primitive class `scala.Float`. */ def FloatClass : ClassSymbol + + /** The class symbol of primitive class `scala.Double`. */ def DoubleClass : ClassSymbol + + /** The class symbol of primitive class `scala.Boolean`. */ def BooleanClass: ClassSymbol - /** The class symbol of class `String`. */ + /** The class symbol of class `scala.String`. */ def StringClass : ClassSymbol - /** The class symbol of class `Class`. */ + /** The class symbol of class `java.lang.Class`. */ def ClassClass : ClassSymbol - /** The class symbol of class `Array`. */ + /** The class symbol of class `scala.Array`. */ def ArrayClass : ClassSymbol - /** The class symbol of class `List`. */ + /** The class symbol of class `scala.List`. */ def ListClass : ClassSymbol - /** The module symbol of `scala.Predef`. */ + /** The module symbol of module `scala.Predef`. */ def PredefModule: ModuleSymbol + /** The module class symbol of package `java.lang`. */ def JavaLangPackageClass: ClassSymbol + + /** The module symbol of package `java.lang`. */ def JavaLangPackage: ModuleSymbol + + /** The module symbol of module `scala.Array`. */ def ArrayModule: ModuleSymbol + + /** The method symbol of method `apply` in module `scala.Array`. */ def ArrayModule_overloadedApply: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** The method symbol of method `apply` in class `scala.Array`. */ def Array_apply: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** The method symbol of method `clone` in class `scala.Array`. */ def Array_clone: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** The method symbol of method `length` in class `scala.Array`. */ def Array_length: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** The method symbol of method `update` in class `scala.Array`. */ def Array_update: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** A dummy class symbol that is used to indicate by-name parameters. + * + * {{{ + * scala> class C { def m(x: => Int) = ??? } + * defined class C + * + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> val m = typeOf[C].member(newTermName("m")).asMethod + * m: reflect.runtime.universe.MethodSymbol = method m + * + * scala> m.params(0)(0).typeSignature + * res1: reflect.runtime.universe.Type = => scala.Int + * + * scala> showRaw(m.params(0)(0).typeSignature) + * res2: String = TypeRef( + * ThisType(scala), + * scala.<byname>, // <-- ByNameParamClass + * List(TypeRef(ThisType(scala), scala.Int, List()))) + * }}} + */ def ByNameParamClass: ClassSymbol - def ConsClass: ClassSymbol - def FunctionClass : Array[ClassSymbol] - def IterableClass: ClassSymbol - def IteratorClass: ClassSymbol - def IteratorModule: ModuleSymbol - def Iterator_apply: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** A dummy class symbol that is used to indicate repeated parameters + * compiled by the Java compiler. + * + * {{{ + * class C { + * public void m(Object... x) {} + * } + * }}} + * + * {{{ + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> val m = typeOf[C].member(newTermName("m")).asMethod + * m: reflect.runtime.universe.MethodSymbol = method m + * + * scala> m.params(0)(0).typeSignature + * res1: reflect.runtime.universe.Type = <repeated...>[Object] + * + * scala> showRaw(m.params(0)(0).typeSignature) + * res2: String = TypeRef( + * ThisType(scala), + * scala.<repeated...>, // <-- JavaRepeatedParamClass + * List(TypeRef(ThisType(java.lang), Object, List()))) + * }}} + */ def JavaRepeatedParamClass: ClassSymbol + + /** A dummy class symbol that is used to indicate repeated parameters + * compiled by the Scala compiler. + * + * {{{ + * scala> class C { def m(x: Int*) = ??? } + * defined class C + * + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> val m = typeOf[C].member(newTermName("m")).asMethod + * m: reflect.runtime.universe.MethodSymbol = method m + * + * scala> m.params(0)(0).typeSignature + * res1: reflect.runtime.universe.Type = scala.Int* + * + * scala> showRaw(m.params(0)(0).typeSignature) + * res2: String = TypeRef( + * ThisType(scala), + * scala.<repeated>, // <-- RepeatedParamClass + * List(TypeRef(ThisType(scala), scala.Int, List()))) + * }}} + */ + def RepeatedParamClass: ClassSymbol + + /** The module symbol of module `scala.List`. */ def ListModule: ModuleSymbol + + /** The method symbol of method `apply` in class `scala.List`. */ def List_apply: TermSymbol // todo. fix the bug in Definitions.getMemberMethod + + /** The module symbol of module `scala.collection.immutable.Nil`. */ def NilModule: ModuleSymbol - def NoneModule: ModuleSymbol + + /** The class symbol of class `scala.Option`. */ def OptionClass: ClassSymbol - def ProductClass : Array[ClassSymbol] - def RepeatedParamClass: ClassSymbol - def SeqClass: ClassSymbol - def SeqModule: ModuleSymbol - def SomeClass: ClassSymbol + + /** The module symbol of module `scala.None`. */ + def NoneModule: ModuleSymbol + + /** The module symbol of module `scala.Some`. */ def SomeModule: ModuleSymbol - def StringBuilderClass: ClassSymbol - def SymbolClass : ClassSymbol - def TraversableClass: ClassSymbol + + /** The array of class symbols for classes `scala.ProductX`. + * - 0th element is `Unit` + * - 1st element is `Product1` + * - ... + * - 22nd element is `Product22` + */ + def ProductClass : Array[ClassSymbol] + + /** The array of class symbols for classes `scala.FunctionX`. + * - 0th element is `Function0` + * - 1st element is `Function1` + * - ... + * - 22nd element is `Function22` + */ + def FunctionClass : Array[ClassSymbol] + + /** The array of class symbols for classes `scala.TupleX`. + * - 0th element is `NoSymbol` + * - 1st element is `Product1` + * - ... + * - 22nd element is `Product22` + */ def TupleClass: Array[Symbol] // cannot make it Array[ClassSymbol], because TupleClass(0) is supposed to be NoSymbol. weird + + /** Contains Scala primitive value classes: + * - Byte + * - Short + * - Int + * - Long + * - Float + * - Double + * - Char + * - Boolean + * - Unit + */ def ScalaPrimitiveValueClasses: List[ClassSymbol] + + /** Contains Scala numeric value classes: + * - Byte + * - Short + * - Int + * - Long + * - Float + * - Double + * - Char + */ def ScalaNumericValueClasses: List[ClassSymbol] } - /** Defines standard types. */ + /** Defines standard types. + * @group Definitions + */ trait StandardTypes { - /** The `Type` of type `Unit`. */ + /** The type of primitive type `Unit`. */ val UnitTpe: Type - /** The `Type` of primitive type `Byte`. */ + /** The type of primitive type `Byte`. */ val ByteTpe: Type - /** The `Type` of primitive type `Short`. */ + /** The type of primitive type `Short`. */ val ShortTpe: Type - /** The `Type` of primitive type `Char`. */ + /** The type of primitive type `Char`. */ val CharTpe: Type - /** The `Type` of primitive type `Int`. */ + /** The type of primitive type `Int`. */ val IntTpe: Type - /** The `Type` of primitive type `Long`. */ + /** The type of primitive type `Long`. */ val LongTpe: Type - /** The `Type` of primitive type `Float`. */ + /** The type of primitive type `Float`. */ val FloatTpe: Type - /** The `Type` of primitive type `Double`. */ + /** The type of primitive type `Double`. */ val DoubleTpe: Type - /** The `Type` of primitive type `Boolean`. */ + /** The type of primitive type `Boolean`. */ val BooleanTpe: Type - /** The `Type` of type `Any`. */ + /** The type of core type `Any`. */ val AnyTpe: Type - /** The `Type` of type `AnyVal`. */ + /** The type of core type `AnyVal`. */ val AnyValTpe: Type - /** The `Type` of type `AnyRef`. */ + /** The type of core type `AnyRef`. */ val AnyRefTpe: Type - /** The `Type` of type `Object`. */ + /** The type of core type `Object`. */ val ObjectTpe: Type - /** The `Type` of type `Nothing`. */ + /** The type of core type `Nothing`. */ val NothingTpe: Type - /** The `Type` of type `Null`. */ + /** The type of core type `Null`. */ val NullTpe: Type } } diff --git a/src/reflect/scala/reflect/api/StandardNames.scala b/src/reflect/scala/reflect/api/StandardNames.scala index 354a9f9328..fc18c02706 100644 --- a/src/reflect/scala/reflect/api/StandardNames.scala +++ b/src/reflect/scala/reflect/api/StandardNames.scala @@ -10,35 +10,95 @@ package api // Is it necessary to perform reflection (like ERROR or LOCAL_SUFFIX_STRING)? If yes, then sure. // Otherwise you'd better not - reflection API should stay minimalistic. -// TODO: document better /** - * Names necessary to create Scala trees. + * Standard names are names that are essential to creating trees or to reflecting Scala artifacts. + * For example, `CONSTRUCTOR` (aka `<init>` on JVM) is necessary to create and invoke constructors. + * + * These standard names can be referred to using [[nme `nme`]] for term names and [[tpnme `tpnme`]] for type names + * + * @see [[Names]] + * + * The API for names in Scala reflection. + * @groupname StandardNames Standard Names */ trait StandardNames { self: Universe => + /** A value containing all [[TermNamesApi standard term names]]. + * @group StandardNames + */ val nme: TermNamesApi + + /** A value containing all [[TypeNamesApi standard type names]]. + * @group StandardNames + */ val tpnme: TypeNamesApi + /** Defines standard names, common for term and type names: These can be accessed via the [[nme]] and [[tpnme]] members. + * @group API + */ trait NamesApi { + /** An abstract type that represents the exact flavor of the name. */ type NameType >: Null <: Name + + /** The term or type name `_`. + * Used to construct trees that correspond to underscores in Scala. + */ val WILDCARD: NameType - val ROOT: NameType + + /** The term or type name corresponding to an empty string. + * Represents an empty name, used to denote the fact that no name was specified + * for `privateWithin` in [[Trees#Modifiers]], for [[Trees#This]], + * for [[Trees#Super]], etc. + */ val EMPTY: NameType + + /** The term or type name `<error>`. + * Indicates that the enclosing tree or symbol contains a compilation error. + */ val ERROR: NameType + + /** The term or type name `package`. + * Used to get modules representing package objects. + */ val PACKAGE: NameType } + /** Defines standard term names that can be accessed via the [[nme]] member. + * @group API + */ trait TermNamesApi extends NamesApi { + /** @inheritdoc */ type NameType = TermName + + /** The term name `<init>`. + * Represents the constructor name on the JVM. + */ val CONSTRUCTOR: NameType + + /** The term name `_root_`. + * Represents the root package. + */ val ROOTPKG: NameType + + /** The string " " (a single whitespace). + * `LOCAL_SUFFIX_STRING` is appended to the names of local identifiers, + * when it's necessary to prevent a naming conflict. For example, underlying fields + * of non-private vals and vars are renamed using `LOCAL_SUFFIX_STRING`. + */ val LOCAL_SUFFIX_STRING: String } + /** Defines standard type names that can be accessed via the [[tpnme]] member. + * @group API + */ trait TypeNamesApi extends NamesApi { + /** @inheritdoc */ type NameType = TypeName - val EMPTY: NameType + + /** The type name `_*`. + * Used to construct types that specify sequence arguments to repeated parameters. + */ val WILDCARD_STAR: NameType } } diff --git a/src/reflect/scala/reflect/api/Symbols.scala b/src/reflect/scala/reflect/api/Symbols.scala index 78345e27f2..993cbd97a5 100644 --- a/src/reflect/scala/reflect/api/Symbols.scala +++ b/src/reflect/scala/reflect/api/Symbols.scala @@ -1,95 +1,176 @@ package scala.reflect package api -/** - * Defines the type hierachy for symbols +/** This trait defines symbols and operations on them. * - * @see [[scala.reflect]] for a description on how the class hierarchy is encoded here. + * Symbols are used to establish bindings between a name and the entity it refers to, such as a class or a method. + * Anything you define and can give a name to in Scala has an associated symbol. + * + * Certain types of tree nodes, such as [[Trees#Ident Ident]] (references to identifiers) and + * [[Trees#Select Select]] (references to members) expose method [[Trees.SymTreeApi.symbol `symbol`]] + * to obtain the symbol that represents their declaration. During the typechecking phase, the compiler looks up the + * symbol based on the name and scope and sets the [[Trees.SymTreeApi.symbol `symbol` field]] of tree nodes. + * + * @contentDiagram hideNodes "*Api" + * + * @see [[http://docs.scala-lang.org/overviews/reflection/overview.html]] + * + * The Reflection Guide provides more details on symbol usage and attached intricacies. + * + * @define SYMACCESSORS Class [[Symbol]] defines `isXXX` test methods such as `isPublic` or `isFinal`, `params` and + * `returnType` methods for method symbols, `baseClasses` for class symbols and so on. Some of these methods don't + * make sense for certain subclasses of `Symbol` and return `NoSymbol`, `Nil` or other empty values. */ trait Symbols { self: Universe => - /** The type of symbols representing declarations */ + /** The type of symbols representing declarations. + * @group Symbols + * @template + */ type Symbol >: Null <: SymbolApi /** A tag that preserves the identity of the `Symbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SymbolTag: ClassTag[Symbol] /** The type of type symbols representing type, class, and trait declarations, - * as well as type parameters + * as well as type parameters. + * @group Symbols + * @template */ type TypeSymbol >: Null <: Symbol with TypeSymbolApi /** A tag that preserves the identity of the `TypeSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeSymbolTag: ClassTag[TypeSymbol] /** The type of term symbols representing val, var, def, and object declarations as * well as packages and value parameters. + * @group Symbols + * @template */ type TermSymbol >: Null <: Symbol with TermSymbolApi /** A tag that preserves the identity of the `TermSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TermSymbolTag: ClassTag[TermSymbol] - /** The type of method symbols representing def declarations */ + /** The type of method symbols representing def declarations. + * @group Symbols + * @template + */ type MethodSymbol >: Null <: TermSymbol with MethodSymbolApi /** A tag that preserves the identity of the `MethodSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val MethodSymbolTag: ClassTag[MethodSymbol] - /** The type of module symbols representing object declarations */ + /** The type of module symbols representing object declarations. + * @group Symbols + * @template + */ type ModuleSymbol >: Null <: TermSymbol with ModuleSymbolApi /** A tag that preserves the identity of the `ModuleSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ModuleSymbolTag: ClassTag[ModuleSymbol] - /** The type of class symbols representing class and trait definitions */ + /** The type of class symbols representing class and trait definitions. + * @group Symbols + * @template + */ type ClassSymbol >: Null <: TypeSymbol with ClassSymbolApi /** A tag that preserves the identity of the `ClassSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ClassSymbolTag: ClassTag[ClassSymbol] - /** The type of free terms introduced by reification */ + /** The type of free terms introduced by reification. + * @group Symbols + * @template + */ type FreeTermSymbol >: Null <: TermSymbol with FreeTermSymbolApi /** A tag that preserves the identity of the `FreeTermSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val FreeTermSymbolTag: ClassTag[FreeTermSymbol] - /** The type of free types introduced by reification */ + /** The type of free types introduced by reification. + * @group Symbols + * @template + */ type FreeTypeSymbol >: Null <: TypeSymbol with FreeTypeSymbolApi /** A tag that preserves the identity of the `FreeTypeSymbol` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val FreeTypeSymbolTag: ClassTag[FreeTypeSymbol] - /** A special "missing" symbol */ + /** A special "missing" symbol. Commonly used in the API to denote a default or empty value. + * @group Symbols + * @template + */ val NoSymbol: Symbol - /** The API of symbols */ + /** The API of symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + * @groupname Basics Symbol Basic Information + * @groupprio Basics 0 + * @groupname Tests Symbol Type Tests + * @groupprio Tests 1 + * @groupname Conversions Symbol Conversions + * @groupprio Conversions 2 + * @groupname Constructors New Symbol Constructors + * @groupprio Constructors 3 + * @groupdesc Constructors These methods construct new symbols owned by the current symbol. + * @groupname Helpers Iteration Helpers + * @groupprio Helpers 4 + * @groupdesc Helpers These methods enable collections-like operations on symbols. + * @groupname Type TypeSymbol Members + * @groupprio Type -1 + * @groupname FreeType FreeType Symbol Members + * @groupprio FreeType -2 + * @groupname Term TermSymbol Members + * @groupprio Term -1 + * @groupname FreeTerm FreeTerm Symbol Members + * @groupprio FreeTerm -2 + * @groupname Class Class Symbol Members + * @groupprio Class -2 + * @groupname Method Method Symbol Members + * @groupprio Method -2 + * @groupname Module Module Symbol Members + * @groupprio Module -2 + */ trait SymbolApi { this: Symbol => /** The owner of this symbol. This is the symbol * that directly contains the current symbol's definition. * The `NoSymbol` symbol does not have an owner, and calling this method * on one causes an internal error. - * The owner of the Scala root class [[scala.reflect.api.MirrorOf.RootClass]] - * and the Scala root object [[scala.reflect.api.MirrorOf.RootPackage]] is `NoSymbol`. + * The owner of the Scala root class [[scala.reflect.api.Mirror.RootClass]] + * and the Scala root object [[scala.reflect.api.Mirror.RootPackage]] is `NoSymbol`. * Every other symbol has a chain of owners that ends in - * [[scala.reflect.api.MirrorOf.RootClass]]. + * [[scala.reflect.api.Mirror.RootClass]]. + * + * @group Basics */ def owner: Symbol @@ -98,15 +179,18 @@ trait Symbols { self: Universe => * * Type name namespaces do not intersect with term name namespaces. * This fact is reflected in different types for names of `TermSymbol` and `TypeSymbol`. + * @group Basics */ type NameType >: Null <: Name /** The name of the symbol as a member of the `Name` type. + * @group Basics */ def name: Name /** The encoded full path name of this symbol, where outer names and inner names * are separated by periods. + * @group Basics */ def fullName: String @@ -114,11 +198,15 @@ trait Symbols { self: Universe => * Note that every symbol is either a term or a type. * So for every symbol `sym` (except for `NoSymbol`), * either `sym.isTerm` is true or `sym.isType` is true. + * + * @group Tests */ def isType: Boolean = false /** This symbol cast to a TypeSymbol. * @throws ScalaReflectionException if `isType` is false. + * + * @group Conversions */ def asType: TypeSymbol = throw new ScalaReflectionException(s"$this is not a type") @@ -126,21 +214,29 @@ trait Symbols { self: Universe => * Note that every symbol is either a term or a type. * So for every symbol `sym` (except for `NoSymbol`), * either `sym.isTerm` is true or `sym.isTerm` is true. + * + * @group Tests */ def isTerm: Boolean = false /** This symbol cast to a TermSymbol. * @throws ScalaReflectionException if `isTerm` is false. + * + * @group Conversions */ def asTerm: TermSymbol = throw new ScalaReflectionException(s"$this is not a term") /** Does this symbol represent the definition of a method? * If yes, `isTerm` is also guaranteed to be true. + * + * @group Tests */ def isMethod: Boolean = false /** This symbol cast to a MethodSymbol. * @throws ScalaReflectionException if `isMethod` is false. + * + * @group Conversions */ def asMethod: MethodSymbol = { def overloadedMsg = @@ -151,103 +247,135 @@ trait Symbols { self: Universe => throw new ScalaReflectionException(s"$this $msg") } - /** Used to provide a better error message for `asMethod` */ + /** Used to provide a better error message for `asMethod` + * + * @group Tests + */ protected def isOverloadedMethod = false /** Does this symbol represent the definition of a module (i.e. it * results from an object definition?). * If yes, `isTerm` is also guaranteed to be true. + * + * @group Tests */ def isModule: Boolean = false /** This symbol cast to a ModuleSymbol defined by an object definition. * @throws ScalaReflectionException if `isModule` is false. + * + * @group Conversions */ def asModule: ModuleSymbol = throw new ScalaReflectionException(s"$this is not a module") /** Does this symbol represent the definition of a class or trait? * If yes, `isType` is also guaranteed to be true. + * + * @group Tests */ def isClass: Boolean = false /** Does this symbol represent the definition of a class implicitly associated * with an object definition (module class in scala compiler parlance). * If yes, `isType` is also guaranteed to be true. + * + * @group Tests */ def isModuleClass: Boolean = false /** This symbol cast to a ClassSymbol representing a class or trait. * @throws ScalaReflectionException if `isClass` is false. + * + * @group Conversions */ def asClass: ClassSymbol = throw new ScalaReflectionException(s"$this is not a class") /** Does this symbol represent a free term captured by reification? * If yes, `isTerm` is also guaranteed to be true. + * + * @group Tests */ def isFreeTerm: Boolean = false /** This symbol cast to a free term symbol. * @throws ScalaReflectionException if `isFreeTerm` is false. + * + * @group Conversions */ def asFreeTerm: FreeTermSymbol = throw new ScalaReflectionException(s"$this is not a free term") /** Does this symbol represent a free type captured by reification? * If yes, `isType` is also guaranteed to be true. + * + * @group Tests */ def isFreeType: Boolean = false /** This symbol cast to a free type symbol. * @throws ScalaReflectionException if `isFreeType` is false. + * + * @group Conversions */ def asFreeType: FreeTypeSymbol = throw new ScalaReflectionException(s"$this is not a free type") + /** @group Constructors */ def newTermSymbol(name: TermName, pos: Position = NoPosition, flags: FlagSet = NoFlags): TermSymbol + /** @group Constructors */ def newModuleAndClassSymbol(name: Name, pos: Position = NoPosition, flags: FlagSet = NoFlags): (ModuleSymbol, ClassSymbol) + /** @group Constructors */ def newMethodSymbol(name: TermName, pos: Position = NoPosition, flags: FlagSet = NoFlags): MethodSymbol + /** @group Constructors */ def newTypeSymbol(name: TypeName, pos: Position = NoPosition, flags: FlagSet = NoFlags): TypeSymbol + /** @group Constructors */ def newClassSymbol(name: TypeName, pos: Position = NoPosition, flags: FlagSet = NoFlags): ClassSymbol /** Source file if this symbol is created during this compilation run, * or a class file if this symbol is loaded from a *.class or *.jar. + * + * The return type is `scala.reflect.io.AbstractFile`, which belongs to an experimental part of Scala reflection. + * It should not be used unless you know what you are doing. In subsequent releases, this API will be refined + * and exposed as a part of scala.reflect.api. + * + * @group Basics */ def associatedFile: scala.reflect.io.AbstractFile /** A list of annotations attached to this Symbol. + * + * @group Basics */ - // we cannot expose the `annotations` method because it doesn't auto-initialize a symbol (see SI-5423) - // there was an idea to use the `isCompilerUniverse` flag and auto-initialize symbols in `annotations` whenever this flag is false - // but it doesn't work, because the unpickler (that is shared between reflective universes and global universes) is very picky about initialization - // scala.reflect.internal.Types$TypeError: bad reference while unpickling scala.collection.immutable.Nil: type Nothing not found in scala.type not found. - // at scala.reflect.internal.pickling.UnPickler$Scan.toTypeError(UnPickler.scala:836) - // at scala.reflect.internal.pickling.UnPickler$Scan$LazyTypeRef.complete(UnPickler.scala:849) // auto-initialize goes boom - // at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1140) - // at scala.reflect.internal.Symbols$Symbol.initialize(Symbols.scala:1272) // this triggers auto-initialize - // at scala.reflect.internal.Symbols$Symbol.annotations(Symbols.scala:1438) // unpickler first tries to get pre-existing annotations - // at scala.reflect.internal.Symbols$Symbol.addAnnotation(Symbols.scala:1458) // unpickler tries to add the annotation being read - // at scala.reflect.internal.pickling.UnPickler$Scan.readSymbolAnnotation(UnPickler.scala:489) // unpickler detects an annotation - // at scala.reflect.internal.pickling.UnPickler$Scan.run(UnPickler.scala:88) - // at scala.reflect.internal.pickling.UnPickler.unpickle(UnPickler.scala:37) - // at scala.reflect.runtime.JavaMirrors$JavaMirror.unpickleClass(JavaMirrors.scala:253) // unpickle from within a reflexive mirror - // def annotations: List[Annotation] - def getAnnotations: List[Annotation] + def annotations: List[Annotation] /** For a class: the module or case class factory with the same name in the same package. * For a module: the class with the same name in the same package. * For all others: NoSymbol + * + * @group Basics */ def companionSymbol: Symbol /** The type signature of this symbol seen as a member of given type `site`. + * + * @group Basics */ def typeSignatureIn(site: Type): Type /** The type signature of this symbol. - * Note if the symbol is a member of a class, one almost always is interested - * in `typeSignatureIn` with a site type instead. + * + * This method always returns signatures in the most generic way possible, even if the underlying symbol is obtained from an + * instantiation of a generic type. For example, signature + * of the method `def map[B](f: (A) ⇒ B): List[B]`, which refers to the type parameter `A` of the declaring class `List[A]`, + * will always feature `A`, regardless of whether `map` is loaded from the `List[_]` or from `List[Int]`. To get a signature + * with type parameters appropriately instantiated, one should use `typeSignatureIn`. + * + * @group Basics */ def typeSignature: Type - /** Returns all symbols overriden by this symbol. */ + /** Returns all symbols overriden by this symbol. + * + * @group Basics + */ def allOverriddenSymbols: List[Symbol] /******************* tests *******************/ @@ -255,11 +383,15 @@ trait Symbols { self: Universe => /** Does this symbol represent a synthetic (i.e. a compiler-generated) entity? * Examples of synthetic entities are accessors for vals and vars * or mixin constructors in trait implementation classes. + * + * @group Tests */ def isSynthetic: Boolean /** Does this symbol represent an implementation artifact that isn't meant for public use? - * Examples of such artifacts are erasure bridges and $outer fields. + * Examples of such artifacts are erasure bridges and outer fields. + * + * @group Tests */ def isImplementationArtifact: Boolean @@ -269,20 +401,28 @@ trait Symbols { self: Universe => * Local symbols can only be accessed from the same object instance. * * If yes, `privateWithin` might tell more about this symbol's visibility scope. + * + * @group Tests */ def isLocal: Boolean /** Does this symbol represent a private declaration or definition? * If yes, `privateWithin` might tell more about this symbol's visibility scope. + * + * @group Tests */ def isPrivate: Boolean /** Does this symbol represent a protected declaration or definition? * If yes, `privateWithin` might tell more about this symbol's visibility scope. + * + * @group Tests */ def isProtected: Boolean /** Does this symbol represent a public declaration or definition? + * + * @group Tests */ def isPublic: Boolean @@ -310,20 +450,28 @@ trait Symbols { self: Universe => * java package: !isPrivate && !isProtected && (privateWithin == enclosingPackage) * java protected: isProtected && (privateWithin == enclosingPackage) * java public: !isPrivate && !isProtected && (privateWithin == NoSymbol) + * + * @group Tests */ def privateWithin: Symbol /** Does this symbol represent the definition of a package? * If yes, `isTerm` is also guaranteed to be true. + * + * @group Tests */ def isPackage: Boolean /** Does this symbol represent a package class? * If yes, `isClass` is also guaranteed to be true. + * + * @group Tests */ def isPackageClass: Boolean /** Does this symbol or its underlying type represent a typechecking error? + * + * @group Tests */ def isErroneous : Boolean @@ -331,62 +479,96 @@ trait Symbols { self: Universe => * Q: When exactly is a sym marked as STATIC? * A: If it's a member of a toplevel object, or of an object contained in a toplevel object, or any number of levels deep. * http://groups.google.com/group/scala-internals/browse_thread/thread/d385bcd60b08faf6 + * + * @group Tests */ def isStatic: Boolean /** Is this symbol final? + * + * @group Tests */ def isFinal: Boolean /** Is this symbol overriding something? + * + * @group Tests */ def isOverride: Boolean /** Is this symbol labelled as "abstract override"? + * + * @group Tests */ def isAbstractOverride: Boolean /** Is this symbol a macro? + * + * @group Tests */ def isMacro: Boolean /** Is this symbol a parameter (either a method parameter or a type parameter)? + * + * @group Tests */ def isParameter: Boolean /** Is this symbol a specialized type parameter or a generated specialized member? + * + * @group Tests */ def isSpecialized: Boolean /** Is this symbol defined by Java? + * + * @group Tests */ def isJava: Boolean /** Does this symbol represent an implicit value, definition, class or parameter? + * + * @group Tests */ def isImplicit: Boolean /******************* helpers *******************/ - /** ... + /** Provides an alternate if symbol is a NoSymbol. + * + * @group Helpers */ def orElse(alt: => Symbol): Symbol - /** ... + /** Filters the underlying alternatives (or a single-element list + * composed of the symbol itself if the symbol is not overloaded). + * Returns an overloaded symbol is there are multiple matches. + * Returns a NoSymbol if there are no matches. + * + * @group Helpers */ def filter(cond: Symbol => Boolean): Symbol /** If this is a NoSymbol, returns NoSymbol, otherwise * returns the result of applying `f` to this symbol. + * + * @group Helpers */ def map(f: Symbol => Symbol): Symbol - /** ... + /** Does the same as `filter`, but crashes if there are multiple matches. + * + * @group Helpers */ def suchThat(cond: Symbol => Boolean): Symbol } - /** The API of term symbols */ + /** The API of term symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait TermSymbolApi extends SymbolApi { this: TermSymbol => /** Term symbols have their names of type `TermName`. */ @@ -396,78 +578,117 @@ trait Symbols { self: Universe => final override def asTerm = this /** Is this symbol introduced as `val`? + * + * @group Term */ def isVal: Boolean - /** Does this symbol denote a stable value? */ + /** Does this symbol denote a stable value? + * + * @group Term + */ def isStable: Boolean /** Is this symbol introduced as `var`? + * + * @group Term */ def isVar: Boolean /** Does this symbol represent a getter or a setter? + * + * @group Term */ def isAccessor: Boolean /** Does this symbol represent a getter of a field? * If yes, `isMethod` is also guaranteed to be true. + * + * @group Term */ def isGetter: Boolean /** Does this symbol represent a setter of a field? * If yes, `isMethod` is also guaranteed to be true. + * + * @group Term */ def isSetter: Boolean /** Does this symbol represent an overloaded method? * If yes, `isMethod` is false, and the list of the enclosed alternatives can be found out via `alternatives`. + * + * @group Term */ def isOverloaded : Boolean /** Does this symbol represent a lazy value? + * + * @group Term */ def isLazy: Boolean - /** The overloaded alternatives of this symbol */ + /** The overloaded alternatives of this symbol + * + * @group Term + */ def alternatives: List[Symbol] /** Used to provide a better error message for `asMethod` */ override protected def isOverloadedMethod = alternatives exists (_.isMethod) /** Backing field for an accessor method, NoSymbol for all other term symbols. + * + * @group Term */ def accessed: Symbol /** Getter method for a backing field of a val or a val, NoSymbol for all other term symbols. + * + * @group Term */ def getter: Symbol /** Setter method for a backing field of a val or a val, NoSymbol for all other term symbols. + * + * @group Term */ def setter: Symbol /** Does this symbol represent a field of a class * that was generated from a parameter of that class? + * + * @group Term */ def isParamAccessor: Boolean /** Does this symbol represent a field of a case class * that corresponds to a parameter in the first parameter list of the * primary constructor of that class? + * + * @group Term */ def isCaseAccessor: Boolean /** Does this symbol represent a parameter with a default value? + * + * @group Term */ def isParamWithDefault: Boolean /** Does this symbol represent a by-name parameter? + * + * @group Term */ def isByNameParam: Boolean } - /** The API of type symbols */ + /** The API of type symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait TypeSymbolApi extends SymbolApi { this: TypeSymbol => /** Type symbols have their names of type `TypeName`. */ @@ -479,11 +700,15 @@ trait Symbols { self: Universe => * * Example: Given a class declaration `class C[T] { ... } `, that generates a symbol * `C`. Then `C.toType` is the type `C[T]`, but `C.toTypeConstructor` is `C`. + * + * @group Type */ def toTypeConstructor: Type /** A type reference that refers to this type symbol seen * as a member of given type `site`. + * + * @group Type */ def toTypeIn(site: Type): Type @@ -497,42 +722,64 @@ trait Symbols { self: Universe => * By contrast, `C.typeSignature` would be a type signature of form * `PolyType(ClassInfoType(...))` that describes type parameters, value * parameters, parent types, and members of `C`. - */ + * + * @group Type + */ def toType: Type final override def isType = true final override def asType = this /** Is the type parameter represented by this symbol contravariant? + * + * @group Type */ def isContravariant : Boolean /** Is the type parameter represented by this symbol contravariant? + * + * @group Type */ def isCovariant : Boolean /** Does this symbol represent the definition of a skolem? * Skolems are used during typechecking to represent type parameters viewed from inside their scopes. + * + * @group Type */ def isSkolem : Boolean /** Does this symbol represent the definition of a type alias? + * + * @group Type */ def isAliasType : Boolean /** Does this symbol represent the definition of an abstract type? + * + * @group Type */ def isAbstractType : Boolean /** Does this symbol represent an existentially bound type? + * + * @group Type */ def isExistential : Boolean - /** For a polymorphic type, its type parameters, the empty list for all other types */ + /** For a polymorphic type, its type parameters, the empty list for all other types + * + * @group Type + */ def typeParams: List[Symbol] } - /** The API of method symbols */ + /** The API of method symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait MethodSymbolApi extends TermSymbolApi { this: MethodSymbol => final override def isMethod = true final override def asMethod = this @@ -541,36 +788,59 @@ trait Symbols { self: Universe => * * If `owner` is a class, then this is a vanilla JVM constructor. * If `owner` is a trait, then this is a mixin constructor. + * + * @group Method */ def isConstructor: Boolean - /** Does this symbol denote the primary constructor of its enclosing class? */ + /** Does this symbol denote the primary constructor of its enclosing class? + * + * @group Method + */ def isPrimaryConstructor: Boolean - /** For a polymorphic method, its type parameters, the empty list for all other methods */ + /** For a polymorphic method, its type parameters, the empty list for all other methods + * + * @group Method + */ def typeParams: List[Symbol] /** All parameter lists of the method. + * The name ending with "ss" indicates that the result type is a list of lists. * * Can be used to distinguish nullary methods and methods with empty parameter lists. * For a nullary method, returns the empty list (i.e. `List()`). * For a method with an empty parameter list, returns a list that contains the empty list (i.e. `List(List())`). + * + * @group Method */ - def params: List[List[Symbol]] + def paramss: List[List[Symbol]] /** Does this method support variable length argument lists? + * + * @group Method */ def isVarargs: Boolean - /** The return type of the method */ + /** The return type of the method + * + * @group Method + */ def returnType: Type } - /** The API of module symbols */ + /** The API of module symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait ModuleSymbolApi extends TermSymbolApi { this: ModuleSymbol => /** The class implicitly associated with the object definition. * One can go back from a module class to the associated module symbol * by inspecting its `selfType.termSymbol`. + * + * @group Module */ def moduleClass: Symbol // needed for tree traversals // when this becomes `moduleClass: ClassSymbol`, it will be the happiest day in my life @@ -579,7 +849,12 @@ trait Symbols { self: Universe => final override def asModule = this } - /** The API of class symbols */ + /** The API of class symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait ClassSymbolApi extends TypeSymbolApi { this: ClassSymbol => final override def isClass = true final override def asClass = this @@ -587,82 +862,129 @@ trait Symbols { self: Universe => /** Does this symbol represent the definition of a primitive class? * Namely, is it one of [[scala.Double]], [[scala.Float]], [[scala.Long]], [[scala.Int]], [[scala.Char]], * [[scala.Short]], [[scala.Byte]], [[scala.Unit]] or [[scala.Boolean]]? + * + * @group Class */ def isPrimitive: Boolean /** Does this symbol represent the definition of a numeric value class? * Namely, is it one of [[scala.Double]], [[scala.Float]], [[scala.Long]], [[scala.Int]], [[scala.Char]], * [[scala.Short]], [[scala.Byte]], [[scala.Unit]] or [[scala.Boolean]]? + * + * @group Class */ def isNumeric: Boolean /** Does this symbol represent the definition of a custom value class? * Namely, is AnyVal among its parent classes? + * + * @group Class */ def isDerivedValueClass: Boolean /** Does this symbol represent a trait? + * + * @group Class */ def isTrait: Boolean /** Does this symbol represent an abstract class? + * + * @group Class */ def isAbstractClass: Boolean /** Does this symbol represent a case class? + * + * @group Class */ def isCaseClass: Boolean /** Does this symbol represent a sealed class? + * + * @group Class */ def isSealed: Boolean /** If this is a sealed class, its known direct subclasses. * Otherwise, the empty set. + * + * @group Class */ def knownDirectSubclasses: Set[Symbol] /** The list of all base classes of this type (including its own typeSymbol) * in reverse linearization order, starting with the class itself and ending * in class Any. + * + * @group Class */ def baseClasses: List[Symbol] /** The module corresponding to this module class, * or NoSymbol if this symbol is not a module class. + * + * @group Class */ def module: Symbol /** If this symbol is a class or trait, its self type, otherwise the type * of the symbol itself. + * + * @group Class */ def selfType: Type - /** The type `C.this`, where `C` is the current class */ + /** The type `C.this`, where `C` is the current class + * + * @group Class + */ def thisPrefix: Type - /** For a polymorphic class/trait, its type parameters, the empty list for all other classes/trait */ + /** For a polymorphic class/trait, its type parameters, the empty list for all other classes/trait + * + * @group Class + */ def typeParams: List[Symbol] } - /** The API of free term symbols */ + /** The API of free term symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait FreeTermSymbolApi extends TermSymbolApi { this: FreeTermSymbol => final override def isFreeTerm = true final override def asFreeTerm = this - /** The place where this symbol has been spawned */ + /** The place where this symbol has been spawned + * + * @group FreeTerm + */ def origin: String - /** The valus this symbol refers to */ + /** The valus this symbol refers to + * + * @group FreeTerm + */ def value: Any } - /** The API of free term symbols */ + /** The API of free type symbols. + * The main source of information about symbols is the [[Symbols]] page. + * + * $SYMACCESSORS + * @group API + */ trait FreeTypeSymbolApi extends TypeSymbolApi { this: FreeTypeSymbol => final override def isFreeType = true final override def asFreeType = this - /** The place where this symbol has been spawned */ + /** The place where this symbol has been spawned + * + * @group FreeType + */ def origin: String } } diff --git a/src/reflect/scala/reflect/api/TagInterop.scala b/src/reflect/scala/reflect/api/TagInterop.scala index fc0558d717..4e43f59706 100644 --- a/src/reflect/scala/reflect/api/TagInterop.scala +++ b/src/reflect/scala/reflect/api/TagInterop.scala @@ -1,26 +1,37 @@ package scala.reflect package api +/** This trait provides type tag <-> manifest interoperability. + * @groupname TagInterop TypeTag and Manifest Interoperability + */ trait TagInterop { self: Universe => // TODO `mirror` parameters are now of type `Any`, because I can't make these path-dependent types work // if you're brave enough, replace `Any` with `Mirror`, recompile and run interop_typetags_are_manifests.scala /** - * Convert a typetag to a pre `Scala-2.10` manifest. - * For example + * Convert a [[scala.reflect.api.TypeTags#TypeTag]] to a [[scala.reflect.Manifest]]. + * + * Compiler usually generates these conversions automatically, when a type tag for a type `T` is in scope, + * and an implicit of type `Manifest[T]` is requested, but this method can also be called manually. + * For example: * {{{ - * typeTagToManifest( scala.reflect.runtime.currentMirror, implicitly[TypeTag[String]] ) + * typeTagToManifest(scala.reflect.runtime.currentMirror, implicitly[TypeTag[String]]) * }}} + * @group TagInterop */ def typeTagToManifest[T: ClassTag](mirror: Any, tag: Universe#TypeTag[T]): Manifest[T] = throw new UnsupportedOperationException("This universe does not support tag -> manifest conversions. Use a JavaUniverse, e.g. the scala.reflect.runtime.universe.") /** - * Convert a pre `Scala-2.10` manifest to a typetag. - * For example + * Convert a [[scala.reflect.Manifest]] to a [[scala.reflect.api.TypeTags#TypeTag]]. + * + * Compiler usually generates these conversions automatically, when a manifest for a type `T` is in scope, + * and an implicit of type `TypeTag[T]` is requested, but this method can also be called manually. + * For example: * {{{ - * manifestToTypeTag( scala.reflect.runtime.currentMirror, implicitly[Manifest[String]] ) + * manifestToTypeTag(scala.reflect.runtime.currentMirror, implicitly[Manifest[String]]) * }}} + * @group TagInterop */ def manifestToTypeTag[T](mirror: Any, manifest: Manifest[T]): Universe#TypeTag[T] = throw new UnsupportedOperationException("This universe does not support manifest -> tag conversions. Use a JavaUniverse, e.g. the scala.reflect.runtime.universe.") diff --git a/src/reflect/scala/reflect/api/TreeCreator.scala b/src/reflect/scala/reflect/api/TreeCreator.scala index 0c8701775c..cba90b72e6 100644 --- a/src/reflect/scala/reflect/api/TreeCreator.scala +++ b/src/reflect/scala/reflect/api/TreeCreator.scala @@ -1,26 +1,10 @@ package scala.reflect package api -/** A mirror-aware factory for trees. +/** This is an internal implementation class. * - * In the reflection API, artifacts are specific to universes and - * symbolic references used in artifacts (e.g. `scala.Int`) are resolved by mirrors. - * - * Therefore to build a tree one needs to know a universe that the tree is going to be bound to - * and a mirror that is going to resolve symbolic references (e.g. to determine that `scala.Int` - * points to a core class `Int` from scala-library.jar). - * - * `TreeCreator` implements this notion by providing a standalone tree factory. - * - * This is immediately useful for reification. When the compiler reifies an expression, - * the end result needs to make sense in any mirror. That's because the compiler knows - * the universe it's reifying an expression into (specified by the target of the `reify` call), - * but it cannot know in advance the mirror to instantiate the result in (e.g. on JVM - * it doesn't know what classloader use to resolve symbolic names in the reifee). - * - * Due to a typechecker restriction (no eta-expansion for dependent method types), - * `TreeCreator` can't have a functional type, so it's implemented as class with an apply method. + * This class is used internally by Scala Reflection, and is not recommended for use in client code. */ abstract class TreeCreator { - def apply[U <: Universe with Singleton](m: MirrorOf[U]): U # Tree + def apply[U <: Universe with Singleton](m: scala.reflect.api.Mirror[U]): U # Tree } diff --git a/src/reflect/scala/reflect/api/Trees.scala b/src/reflect/scala/reflect/api/Trees.scala index 1f15ee6070..44f5776a57 100644 --- a/src/reflect/scala/reflect/api/Trees.scala +++ b/src/reflect/scala/reflect/api/Trees.scala @@ -5,67 +5,62 @@ package scala.reflect package api -// Syncnote: Trees are currently not thread-safe. +/** This trait defines the node types used in Scala abstract syntax trees (AST) and operations on them. + * +* All tree node types are sub types of [[scala.reflect.api.Trees#Tree Tree]]. + * + * Trees are immutable, except for three fields + * [[Trees#TreeApi.pos pos]], [[Trees#TreeApi.symbol symbol]], and [[Trees#TreeApi.tpe tpe]], which are assigned when a tree is typechecked + * to attribute it with the information gathered by the typechecker. + * + * [[scala.reflect.api.Universe#reify reify]] can be used to get the tree for a given Scala expression. + * + * [[scala.reflect.api.Universe#showRaw showRaw]] can be used to get a readable representation of a tree. + * + * === Examples === + * `Literal(Constant(5))` creates an AST representing a literal 5 in Scala source code. + * + * `Apply(Select(Select(This(newTypeName("scala")), newTermName("Predef")), newTermName("print")), List(Literal(Constant("Hello World"))))` + * creates an AST representing `print("Hello World")`. + * + * `import scala.reflect.runtime.universe.{reify,showRaw}` + * `print( showRaw( reify{5}.tree ) )` // prints Literal(Constant(5)) + * + * @see [[http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html#trees]]. + * @groupname Traversal Tree Traversal and Transformation + * @groupprio Traversal 1 + * @groupprio Factories 1 + * @groupname Copying Tree Copying + * @groupprio Copying 1 + * + * @contentDiagram hideNodes "*Api" + */ trait Trees { self: Universe => - /** Tree is the basis for scala's abstract syntax. The nodes are - * implemented as case classes, and the parameters which initialize - * a given tree are immutable: however Trees have several mutable - * fields which are manipulated in the course of typechecking, - * including pos, symbol, and tpe. - * - * Newly instantiated trees have tpe set to null (though it - * may be set immediately thereafter depending on how it is - * constructed.) When a tree is passed to the typer, typically via - * `typer.typed(tree)`, under normal circumstances the tpe must be - * null or the typer will ignore it. Furthermore, the typer is not - * required to return the same tree it was passed. - * - * Trees can be easily traversed with e.g. foreach on the root node; - * for a more nuanced traversal, subclass Traverser. Transformations - * can be considerably trickier: see the numerous subclasses of - * Transformer found around the compiler. - * - * Copying Trees should be done with care depending on whether - * it needs be done lazily or strictly (see LazyTreeCopier and - * StrictTreeCopier) and on whether the contents of the mutable - * fields should be copied. The tree copiers will copy the mutable - * attributes to the new tree; calling Tree#duplicate will copy - * symbol and tpe, but all the positions will be focused. - * - * Trees can be coarsely divided into four mutually exclusive categories: - * - * - TermTrees, representing terms - * - TypTrees, representing types. Note that is `TypTree`, not `TypeTree`. - * - SymTrees, which may represent types or terms. - * - Other Trees, which have none of those as parents. - * - * SymTrees include important nodes Ident and Select, which are - * used as both terms and types; they are distinguishable based on - * whether the Name is a TermName or TypeName. The correct way - * to test any Tree for a type or a term are the `isTerm`/`isType` - * methods on Tree. - * - * "Others" are mostly syntactic or short-lived constructs. Examples - * include CaseDef, which wraps individual match cases: they are - * neither terms nor types, nor do they carry a symbol. Another - * example is Parens, which is eliminated during parsing. + /** The type of Scala abstract syntax trees. + * @group Trees + * @template */ type Tree >: Null <: TreeApi /** A tag that preserves the identity of the `Tree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TreeTag: ClassTag[Tree] - /** The API that all trees support */ + /** The API that all trees support. + * The main source of information about trees is the [[scala.reflect.api.Trees]] page. + * @group API + */ trait TreeApi extends Product { this: Tree => - // TODO - /** ... */ + /** Does this tree represent a definition? (of a method, of a class, etc) */ def isDef: Boolean - // TODO - /** ... */ + /** Is this tree one of the empty trees? + * Empty trees are: the `EmptyTree` null object, `TypeTree` instances that don't carry a type + * and the special `emptyValDef` singleton. + */ def isEmpty: Boolean /** The canonical way to test if a Tree represents a term. @@ -76,32 +71,37 @@ trait Trees { self: Universe => */ def isType: Boolean - /** ... */ + /** Position of the tree. */ def pos: Position - /** ... */ + /** Type of the tree. + * + * Upon creation most trees have their `tpe` set to `null`. + * Types are typically assigned to trees during typechecking. + * Some node factory methods set `tpe` immediately after creation. + * + * When the typechecker encounters a tree with a non-null tpe, + * it will assume it to be correct and not check it again. This means one has + * to be careful not to erase the `tpe` field of subtrees. + */ def tpe: Type - /** Note that symbol is fixed as null at this level. In SymTrees, - * it is overridden and implemented with a var, initialized to NoSymbol. + /** Symbol of the tree. * - * Trees which are not SymTrees but which carry symbols do so by - * overriding `def symbol` to forward it elsewhere. Examples: + * For most trees symbol is `null`. In `SymTree`s, + * it is overridden and implemented with a var, initialized to `NoSymbol`. * - * Super(qual, _) // has qual's symbol - * Apply(fun, args) // has fun's symbol - * TypeApply(fun, args) // has fun's symbol - * AppliedTypeTree(tpt, args) // has tpt's symbol - * TypeTree(tpe) // has tpe's typeSymbol, if tpe != null + * Trees which are not `SymTree`s but which carry symbols do so by + * overriding `def symbol` to forward it elsewhere. Examples: * - * Attempting to set the symbol of a Tree which does not support - * it will induce an exception. + * - `Super(qual, _)` has `qual`'s symbol, + * - `Apply(fun, args)` has `fun`'s symbol, + * - `TypeApply(fun, args)` has `fun`'s symbol, + * - `AppliedTypeTree(tpt, args)` has `tpt`'s symbol, + * - `TypeTree(tpe)` has `tpe`'s `typeSymbol`, if `tpe != null`. */ def symbol: Symbol - /** ... */ - def hasSymbol: Boolean - /** Provides an alternate if tree is empty * @param alt The alternate tree * @return If this tree is non empty, this tree, otherwise `alt`. @@ -175,166 +175,239 @@ trait Trees { self: Universe => override def toString: String = treeToString(this) } - /** Obtains string representation of a tree */ + /** Obtains string representation of a tree + * @group Trees + */ protected def treeToString(tree: Tree): String - /** The empty tree */ + /** The empty tree + * @group Trees + */ val EmptyTree: Tree /** A tree for a term. Not all trees representing terms are TermTrees; use isTerm * to reliably identify terms. + * @group Trees + * @template */ type TermTree >: Null <: AnyRef with Tree with TermTreeApi /** A tag that preserves the identity of the `TermTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TermTreeTag: ClassTag[TermTree] - /** The API that all term trees support */ + /** The API that all term trees support + * @group API + */ trait TermTreeApi extends TreeApi { this: TermTree => } /** A tree for a type. Not all trees representing types are TypTrees; use isType * to reliably identify types. + * @group Trees + * @template */ type TypTree >: Null <: AnyRef with Tree with TypTreeApi /** A tag that preserves the identity of the `TypTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypTreeTag: ClassTag[TypTree] - /** The API that all typ trees support */ + /** The API that all typ trees support + * @group API + */ trait TypTreeApi extends TreeApi { this: TypTree => } /** A tree with a mutable symbol field, initialized to NoSymbol. + * @group Trees + * @template */ type SymTree >: Null <: AnyRef with Tree with SymTreeApi /** A tag that preserves the identity of the `SymTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SymTreeTag: ClassTag[SymTree] - /** The API that all sym trees support */ + /** The API that all sym trees support + * @group API + */ trait SymTreeApi extends TreeApi { this: SymTree => + /** @inheritdoc */ def symbol: Symbol } /** A tree with a name - effectively, a DefTree or RefTree. + * @group Trees + * @template */ type NameTree >: Null <: AnyRef with Tree with NameTreeApi /** A tag that preserves the identity of the `NameTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val NameTreeTag: ClassTag[NameTree] - /** The API that all name trees support */ + /** The API that all name trees support + * @group API + */ trait NameTreeApi extends TreeApi { this: NameTree => + /** The underlying name. + * For example, the `<List>` part of `Ident("List": TermName)`. + */ def name: Name } /** A tree which references a symbol-carrying entity. * References one, as opposed to defining one; definitions * are in DefTrees. + * @group Trees + * @template */ type RefTree >: Null <: SymTree with NameTree with RefTreeApi /** A tag that preserves the identity of the `RefTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val RefTreeTag: ClassTag[RefTree] - /** The API that all ref trees support */ + /** The API that all ref trees support + * @group API + */ trait RefTreeApi extends SymTreeApi with NameTreeApi { this: RefTree => - def qualifier: Tree // empty for Idents + /** The qualifier of the reference. + * For example, the `<scala>` part of `Select("scala": TermName, "List": TermName)`. + * `EmptyTree` for `Ident` instances. + */ + def qualifier: Tree + + /** @inheritdoc */ def name: Name } /** A tree which defines a symbol-carrying entity. + * @group Trees + * @template */ type DefTree >: Null <: SymTree with NameTree with DefTreeApi /** A tag that preserves the identity of the `DefTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val DefTreeTag: ClassTag[DefTree] - /** The API that all def trees support */ + /** The API that all def trees support + * @group API + */ trait DefTreeApi extends SymTreeApi with NameTreeApi { this: DefTree => + /** @inheritdoc */ def name: Name } /** Common base class for all member definitions: types, classes, * objects, packages, vals and vars, defs. + * @group Trees + * @template */ type MemberDef >: Null <: DefTree with MemberDefApi /** A tag that preserves the identity of the `MemberDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val MemberDefTag: ClassTag[MemberDef] - /** The API that all member defs support */ + /** The API that all member defs support + * @group API + */ trait MemberDefApi extends DefTreeApi { this: MemberDef => + /** Modifiers of the declared member. */ def mods: Modifiers } /** A packaging, such as `package pid { stats }` + * @group Trees + * @template */ type PackageDef >: Null <: MemberDef with PackageDefApi /** A tag that preserves the identity of the `PackageDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val PackageDefTag: ClassTag[PackageDef] - /** The constructor/deconstructor for `PackageDef` instances. */ + /** The constructor/deconstructor for `PackageDef` instances. + * @group Extractors + */ val PackageDef: PackageDefExtractor /** An extractor class to create and pattern match with syntax `PackageDef(pid, stats)`. * This AST node corresponds to the following Scala code: * * `package` pid { stats } + * @group Extractors */ abstract class PackageDefExtractor { def apply(pid: RefTree, stats: List[Tree]): PackageDef def unapply(packageDef: PackageDef): Option[(RefTree, List[Tree])] } - /** The API that all package defs support */ + /** The API that all package defs support + * @group API + */ trait PackageDefApi extends MemberDefApi { this: PackageDef => + /** The (possibly, fully-qualified) name of the package. */ val pid: RefTree + + /** Body of the package definition. */ val stats: List[Tree] } /** A common base class for class and object definitions. + * @group Trees + * @template */ type ImplDef >: Null <: MemberDef with ImplDefApi /** A tag that preserves the identity of the `ImplDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ImplDefTag: ClassTag[ImplDef] - /** The API that all impl defs support */ + /** The API that all impl defs support + * @group API + */ trait ImplDefApi extends MemberDefApi { this: ImplDef => + /** The body of the definition. */ val impl: Template } /** A class definition. + * @group Trees + * @template */ type ClassDef >: Null <: ImplDef with ClassDefApi /** A tag that preserves the identity of the `ClassDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ClassDefTag: ClassTag[ClassDef] - /** The constructor/deconstructor for `ClassDef` instances. */ + /** The constructor/deconstructor for `ClassDef` instances. + * @group Extractors + */ val ClassDef: ClassDefExtractor /** An extractor class to create and pattern match with syntax `ClassDef(mods, name, tparams, impl)`. @@ -345,32 +418,47 @@ trait Trees { self: Universe => * Where impl stands for: * * `extends` parents { defs } + * @group Extractors */ abstract class ClassDefExtractor { def apply(mods: Modifiers, name: TypeName, tparams: List[TypeDef], impl: Template): ClassDef def unapply(classDef: ClassDef): Option[(Modifiers, TypeName, List[TypeDef], Template)] } - /** The API that all class defs support */ + /** The API that all class defs support + * @group API + */ trait ClassDefApi extends ImplDefApi { this: ClassDef => + /** @inheritdoc */ val mods: Modifiers + + /** The name of the class. */ val name: TypeName + + /** The type parameters of the class. */ val tparams: List[TypeDef] + + /** @inheritdoc */ val impl: Template } /** An object definition, e.g. `object Foo`. Internally, objects are * quite frequently called modules to reduce ambiguity. * Eliminated by compiler phase refcheck. + * @group Trees + * @template */ type ModuleDef >: Null <: ImplDef with ModuleDefApi /** A tag that preserves the identity of the `ModuleDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ModuleDefTag: ClassTag[ModuleDef] - /** The constructor/deconstructor for `ModuleDef` instances. */ + /** The constructor/deconstructor for `ModuleDef` instances. + * @group Extractors + */ val ModuleDef: ModuleDefExtractor /** An extractor class to create and pattern match with syntax `ModuleDef(mods, name, impl)`. @@ -381,32 +469,55 @@ trait Trees { self: Universe => * Where impl stands for: * * `extends` parents { defs } + * @group Extractors */ abstract class ModuleDefExtractor { def apply(mods: Modifiers, name: TermName, impl: Template): ModuleDef def unapply(moduleDef: ModuleDef): Option[(Modifiers, TermName, Template)] } - /** The API that all module defs support */ + /** The API that all module defs support + * @group API + */ trait ModuleDefApi extends ImplDefApi { this: ModuleDef => + /** @inheritdoc */ val mods: Modifiers + + /** The name of the module. */ val name: TermName + + /** @inheritdoc */ val impl: Template } /** A common base class for ValDefs and DefDefs. + * @group Trees + * @template */ type ValOrDefDef >: Null <: MemberDef with ValOrDefDefApi /** A tag that preserves the identity of the `ValOrDefDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ValOrDefDefTag: ClassTag[ValOrDefDef] - /** The API that all val defs and def defs support */ + /** The API that all val defs and def defs support + * @group API + */ trait ValOrDefDefApi extends MemberDefApi { this: ValOrDefDef => + /** @inheritdoc */ def name: Name // can't be a TermName because macros can be type names. + + /** The type ascribed to the definition. + * An empty `TypeTree` if the type hasn't been specified explicitly + * and is supposed to be inferred. + */ def tpt: Tree + + /** The body of the definition. + * The `EmptyTree` is the body is empty (e.g. for abstract members). + */ def rhs: Tree } @@ -417,15 +528,20 @@ trait Trees { self: Universe => * - lazy values, e.g. "lazy val x" - the LAZY flag set in mods * - method parameters, see vparamss in [[scala.reflect.api.Trees#DefDef]] - the PARAM flag is set in mods * - explicit self-types, e.g. class A { self: Bar => } + * @group Trees + * @template */ type ValDef >: Null <: ValOrDefDef with ValDefApi /** A tag that preserves the identity of the `ValDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ValDefTag: ClassTag[ValDef] - /** The constructor/deconstructor for `ValDef` instances. */ + /** The constructor/deconstructor for `ValDef` instances. + * @group Extractors + */ val ValDef: ValDefExtractor /** An extractor class to create and pattern match with syntax `ValDef(mods, name, tpt, rhs)`. @@ -441,31 +557,46 @@ trait Trees { self: Universe => * * If the type of a value is not specified explicitly (i.e. is meant to be inferred), * this is expressed by having `tpt` set to `TypeTree()` (but not to an `EmptyTree`!). + * @group Extractors */ abstract class ValDefExtractor { def apply(mods: Modifiers, name: TermName, tpt: Tree, rhs: Tree): ValDef def unapply(valDef: ValDef): Option[(Modifiers, TermName, Tree, Tree)] } - /** The API that all val defs support */ + /** The API that all val defs support + * @group API + */ trait ValDefApi extends ValOrDefDefApi { this: ValDef => + /** @inheritdoc */ val mods: Modifiers + + /** @inheritdoc */ val name: TermName + + /** @inheritdoc */ val tpt: Tree + + /** @inheritdoc */ val rhs: Tree } /** A method or macro definition. * @param name The name of the method or macro. Can be a type name in case this is a type macro + * @group Trees + * @template */ type DefDef >: Null <: ValOrDefDef with DefDefApi /** A tag that preserves the identity of the `DefDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val DefDefTag: ClassTag[DefDef] - /** The constructor/deconstructor for `DefDef` instances. */ + /** The constructor/deconstructor for `DefDef` instances. + * @group Extractors + */ val DefDef: DefDefExtractor /** An extractor class to create and pattern match with syntax `DefDef(mods, name, tparams, vparamss, tpt, rhs)`. @@ -475,33 +606,52 @@ trait Trees { self: Universe => * * If the return type is not specified explicitly (i.e. is meant to be inferred), * this is expressed by having `tpt` set to `TypeTree()` (but not to an `EmptyTree`!). + * @group Extractors */ abstract class DefDefExtractor { def apply(mods: Modifiers, name: Name, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree): DefDef def unapply(defDef: DefDef): Option[(Modifiers, Name, List[TypeDef], List[List[ValDef]], Tree, Tree)] } - /** The API that all def defs support */ + /** The API that all def defs support + * @group API + */ trait DefDefApi extends ValOrDefDefApi { this: DefDef => + /** @inheritdoc */ val mods: Modifiers + + /** @inheritdoc */ val name: Name + + /** The type parameters of the method. */ val tparams: List[TypeDef] + + /** The parameter lists of the method. */ val vparamss: List[List[ValDef]] + + /** @inheritdoc */ val tpt: Tree + + /** @inheritdoc */ val rhs: Tree } /** An abstract type, a type parameter, or a type alias. * Eliminated by erasure. + * @group Trees + * @template */ type TypeDef >: Null <: MemberDef with TypeDefApi /** A tag that preserves the identity of the `TypeDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeDefTag: ClassTag[TypeDef] - /** The constructor/deconstructor for `TypeDef` instances. */ + /** The constructor/deconstructor for `TypeDef` instances. + * @group Extractors + */ val TypeDef: TypeDefExtractor /** An extractor class to create and pattern match with syntax `TypeDef(mods, name, tparams, rhs)`. @@ -514,17 +664,29 @@ trait Trees { self: Universe => * First usage illustrates `TypeDefs` representing type aliases and type parameters. * Second usage illustrates `TypeDefs` representing abstract types, * where lo and hi are both `TypeBoundsTrees` and `Modifier.deferred` is set in mods. + * @group Extractors */ abstract class TypeDefExtractor { def apply(mods: Modifiers, name: TypeName, tparams: List[TypeDef], rhs: Tree): TypeDef def unapply(typeDef: TypeDef): Option[(Modifiers, TypeName, List[TypeDef], Tree)] } - /** The API that all type defs support */ + /** The API that all type defs support + * @group API + */ trait TypeDefApi extends MemberDefApi { this: TypeDef => + /** @inheritdoc */ val mods: Modifiers + + /** @inheritdoc */ val name: TypeName + + /** The type parameters of this type definition. */ val tparams: List[TypeDef] + + /** The body of the definition. + * The `EmptyTree` is the body is empty (e.g. for abstract type members). + */ val rhs: Tree } @@ -541,15 +703,20 @@ trait Trees { self: Universe => * assigned to the Idents. * * Forward jumps within a block are allowed. + * @group Trees + * @template */ type LabelDef >: Null <: DefTree with TermTree with LabelDefApi /** A tag that preserves the identity of the `LabelDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val LabelDefTag: ClassTag[LabelDef] - /** The constructor/deconstructor for `LabelDef` instances. */ + /** The constructor/deconstructor for `LabelDef` instances. + * @group Extractors + */ val LabelDef: LabelDefExtractor /** An extractor class to create and pattern match with syntax `LabelDef(name, params, rhs)`. @@ -558,21 +725,33 @@ trait Trees { self: Universe => * It is used for tailcalls and like. * For example, while/do are desugared to label defs as follows: * {{{ - * while (cond) body ==> LabelDef($L, List(), if (cond) { body; L$() } else ()) + * while (cond) body ==> LabelDef(\$L, List(), if (cond) { body; L\$() } else ()) * }}} * {{{ - * do body while (cond) ==> LabelDef($L, List(), body; if (cond) L$() else ()) + * do body while (cond) ==> LabelDef(\$L, List(), body; if (cond) L\$() else ()) * }}} + * @group Extractors */ abstract class LabelDefExtractor { def apply(name: TermName, params: List[Ident], rhs: Tree): LabelDef def unapply(labelDef: LabelDef): Option[(TermName, List[Ident], Tree)] } - /** The API that all label defs support */ + /** The API that all label defs support + * @group API + */ trait LabelDefApi extends DefTreeApi with TermTreeApi { this: LabelDef => + /** @inheritdoc */ val name: TermName + + /** Label's parameters - names that can be used in the body of the label. + * See the example for [[scala.reflect.api.Trees#LabelDefExtractor]]. + */ val params: List[Ident] + + /** The body of the label. + * See the example for [[scala.reflect.api.Trees#LabelDefExtractor]]. + */ val rhs: Tree } @@ -586,30 +765,51 @@ trait Trees { self: Universe => * @param namePos its position or -1 if undefined * @param rename the name the import is renamed to (== name if no renaming) * @param renamePos the position of the rename or -1 if undefined + * @group Trees + * @template */ type ImportSelector >: Null <: AnyRef with ImportSelectorApi /** A tag that preserves the identity of the `ImportSelector` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ImportSelectorTag: ClassTag[ImportSelector] - /** The constructor/deconstructor for `ImportSelector` instances. */ + /** The constructor/deconstructor for `ImportSelector` instances. + * @group Extractors + */ val ImportSelector: ImportSelectorExtractor /** An extractor class to create and pattern match with syntax `ImportSelector(name:, namePos, rename, renamePos)`. * This is not an AST node, it is used as a part of the `Import` node. + * @group Extractors */ abstract class ImportSelectorExtractor { def apply(name: Name, namePos: Int, rename: Name, renamePos: Int): ImportSelector def unapply(importSelector: ImportSelector): Option[(Name, Int, Name, Int)] } - /** The API that all import selectors support */ + /** The API that all import selectors support + * @group API + */ trait ImportSelectorApi { this: ImportSelector => + /** The imported name. */ val name: Name + + /** Offset of the position of the importing part of the selector in the source file. + * Is equal to -1 is the position is unknown. + */ val namePos: Int + + /** The name the import is renamed to. + * Is equal to `name` if it's not a renaming import. + */ val rename: Name + + /** Offset of the position of the renaming part of the selector in the source file. + * Is equal to -1 is the position is unknown. + */ val renamePos: Int } @@ -617,15 +817,20 @@ trait Trees { self: Universe => * * @param expr * @param selectors + * @group Trees + * @template */ type Import >: Null <: SymTree with ImportApi /** A tag that preserves the identity of the `Import` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ImportTag: ClassTag[Import] - /** The constructor/deconstructor for `Import` instances. */ + /** The constructor/deconstructor for `Import` instances. + * @group Extractors + */ val Import: ImportExtractor /** An extractor class to create and pattern match with syntax `Import(expr, selectors)`. @@ -644,15 +849,25 @@ trait Trees { self: Universe => * * The symbol of an `Import` is an import symbol @see Symbol.newImport. * It's used primarily as a marker to check that the import has been typechecked. + * @group Extractors */ abstract class ImportExtractor { def apply(expr: Tree, selectors: List[ImportSelector]): Import def unapply(import_ : Import): Option[(Tree, List[ImportSelector])] } - /** The API that all imports support */ + /** The API that all imports support + * @group API + */ trait ImportApi extends SymTreeApi { this: Import => + /** The qualifier of the import. + * See the example for [[scala.reflect.api.Trees#ImportExtractor]]. + */ val expr: Tree + + /** The selectors of the import. + * See the example for [[scala.reflect.api.Trees#ImportExtractor]]. + */ val selectors: List[ImportSelector] } @@ -660,15 +875,20 @@ trait Trees { self: Universe => * * @param parents * @param body + * @group Trees + * @template */ type Template >: Null <: SymTree with TemplateApi /** A tag that preserves the identity of the `Template` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TemplateTag: ClassTag[Template] - /** The constructor/deconstructor for `Template` instances. */ + /** The constructor/deconstructor for `Template` instances. + * @group Extractors + */ val Template: TemplateExtractor /** An extractor class to create and pattern match with syntax `Template(parents, self, body)`. @@ -688,28 +908,45 @@ trait Trees { self: Universe => * def bar // owner is local dummy * } * } + * @group Extractors */ abstract class TemplateExtractor { def apply(parents: List[Tree], self: ValDef, body: List[Tree]): Template def unapply(template: Template): Option[(List[Tree], ValDef, List[Tree])] } - /** The API that all templates support */ + /** The API that all templates support + * @group API + */ trait TemplateApi extends SymTreeApi { this: Template => + /** Superclasses of the template. */ val parents: List[Tree] + + /** Self type of the template. + * Is equal to `emptyValDef` if the self type is not specified. + */ val self: ValDef + + /** Body of the template. + */ val body: List[Tree] } - /** Block of expressions (semicolon separated expressions) */ + /** Block of expressions (semicolon separated expressions) + * @group Trees + * @template + */ type Block >: Null <: TermTree with BlockApi /** A tag that preserves the identity of the `Block` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val BlockTag: ClassTag[Block] - /** The constructor/deconstructor for `Block` instances. */ + /** The constructor/deconstructor for `Block` instances. + * @group Extractors + */ val Block: BlockExtractor /** An extractor class to create and pattern match with syntax `Block(stats, expr)`. @@ -718,30 +955,43 @@ trait Trees { self: Universe => * { stats; expr } * * If the block is empty, the `expr` is set to `Literal(Constant(()))`. + * @group Extractors */ abstract class BlockExtractor { def apply(stats: List[Tree], expr: Tree): Block def unapply(block: Block): Option[(List[Tree], Tree)] } - /** The API that all blocks support */ + /** The API that all blocks support + * @group API + */ trait BlockApi extends TermTreeApi { this: Block => + /** All, but the last, expressions in the block. + * Can very well be an empty list. + */ val stats: List[Tree] + + /** The last expression in the block. */ val expr: Tree } /** Case clause in a pattern match. * (except for occurrences in switch statements). * Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher) + * @group Trees + * @template */ type CaseDef >: Null <: AnyRef with Tree with CaseDefApi /** A tag that preserves the identity of the `CaseDef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val CaseDefTag: ClassTag[CaseDef] - /** The constructor/deconstructor for `CaseDef` instances. */ + /** The constructor/deconstructor for `CaseDef` instances. + * @group Extractors + */ val CaseDef: CaseDefExtractor /** An extractor class to create and pattern match with syntax `CaseDef(pat, guard, body)`. @@ -751,16 +1001,28 @@ trait Trees { self: Universe => * * If the guard is not present, the `guard` is set to `EmptyTree`. * If the body is not specified, the `body` is set to `Literal(Constant())` + * @group Extractors */ abstract class CaseDefExtractor { def apply(pat: Tree, guard: Tree, body: Tree): CaseDef def unapply(caseDef: CaseDef): Option[(Tree, Tree, Tree)] } - /** The API that all case defs support */ + /** The API that all case defs support + * @group API + */ trait CaseDefApi extends TreeApi { this: CaseDef => + /** The pattern of the pattern matching clause. */ val pat: Tree + + /** The guard of the pattern matching clause. + * Is equal to `EmptyTree` if the guard is not specified. + */ val guard: Tree + + /** The body of the pattern matching clause. + * Is equal to `Literal(Constant())` if the body is not specified. + */ val body: Tree } @@ -769,58 +1031,76 @@ trait Trees { self: Universe => * Eliminated by compiler phases Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher), * except for * occurrences in encoded Switch stmt (i.e. remaining Match(CaseDef(...))) + * @group Trees + * @template */ type Alternative >: Null <: TermTree with AlternativeApi /** A tag that preserves the identity of the `Alternative` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AlternativeTag: ClassTag[Alternative] - /** The constructor/deconstructor for `Alternative` instances. */ + /** The constructor/deconstructor for `Alternative` instances. + * @group Extractors + */ val Alternative: AlternativeExtractor /** An extractor class to create and pattern match with syntax `Alternative(trees)`. * This AST node corresponds to the following Scala code: * * pat1 | ... | patn + * @group Extractors */ abstract class AlternativeExtractor { def apply(trees: List[Tree]): Alternative def unapply(alternative: Alternative): Option[List[Tree]] } - /** The API that all alternatives support */ + /** The API that all alternatives support + * @group API + */ trait AlternativeApi extends TermTreeApi { this: Alternative => + /** Alternatives of the pattern matching clause. */ val trees: List[Tree] } /** Repetition of pattern. * * Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher). + * @group Trees + * @template */ type Star >: Null <: TermTree with StarApi /** A tag that preserves the identity of the `Star` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val StarTag: ClassTag[Star] - /** The constructor/deconstructor for `Star` instances. */ + /** The constructor/deconstructor for `Star` instances. + * @group Extractors + */ val Star: StarExtractor /** An extractor class to create and pattern match with syntax `Star(elem)`. * This AST node corresponds to the following Scala code: * * pat* + * @group Extractors */ abstract class StarExtractor { def apply(elem: Tree): Star def unapply(star: Star): Option[Tree] } - /** The API that all stars support */ + /** The API that all stars support + * @group API + */ trait StarApi extends TermTreeApi { this: Star => + /** The quantified pattern. */ val elem: Tree } @@ -830,30 +1110,46 @@ trait Trees { self: Universe => * * @param name * @param body + * @group Trees + * @template */ type Bind >: Null <: DefTree with BindApi /** A tag that preserves the identity of the `Bind` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val BindTag: ClassTag[Bind] - /** The constructor/deconstructor for `Bind` instances. */ + /** The constructor/deconstructor for `Bind` instances. + * @group Extractors + */ val Bind: BindExtractor /** An extractor class to create and pattern match with syntax `Bind(name, body)`. * This AST node corresponds to the following Scala code: * * pat* + * @group Extractors */ abstract class BindExtractor { def apply(name: Name, body: Tree): Bind def unapply(bind: Bind): Option[(Name, Tree)] } - /** The API that all binds support */ + /** The API that all binds support + * @group API + */ trait BindApi extends DefTreeApi { this: Bind => + /** The name that can be used to refer to this fragment of the matched expression. + * The `list` part of the `list @ List(x, y)`. + */ val name: Name + + /** The pattern that represents this fragment of the matched expression. + * The `List(x, y)` part of the `list @ List(x, y)`. + * Is equal to `EmptyTree` if the pattern is not specified as in `case x => x`. + */ val body: Tree } @@ -883,41 +1179,62 @@ trait Trees { self: Universe => * }}} * * Introduced by typer. Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher). + * @group Trees + * @template */ type UnApply >: Null <: TermTree with UnApplyApi /** A tag that preserves the identity of the `UnApply` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val UnApplyTag: ClassTag[UnApply] - /** The constructor/deconstructor for `UnApply` instances. */ + /** The constructor/deconstructor for `UnApply` instances. + * @group Extractors + */ val UnApply: UnApplyExtractor /** An extractor class to create and pattern match with syntax `UnApply(fun, args)`. * This AST node does not have direct correspondence to Scala code, * and is introduced when typechecking pattern matches and `try` blocks. + * @group Extractors */ abstract class UnApplyExtractor { def apply(fun: Tree, args: List[Tree]): UnApply def unapply(unApply: UnApply): Option[(Tree, List[Tree])] } - /** The API that all unapplies support */ + /** The API that all unapplies support + * @group API + */ trait UnApplyApi extends TermTreeApi { this: UnApply => + /** A dummy node that carries the type of unapplication. + * See the example for [[scala.reflect.api.Trees#UnApplyExtractor]]. + */ val fun: Tree + + /** The arguments of the unapplication. + * See the example for [[scala.reflect.api.Trees#UnApplyExtractor]]. + */ val args: List[Tree] } - /** Anonymous function, eliminated by compiler phase lambdalift */ + /** Anonymous function, eliminated by compiler phase lambdalift + * @group Trees + * @template + */ type Function >: Null <: TermTree with SymTree with FunctionApi /** A tag that preserves the identity of the `Function` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val FunctionTag: ClassTag[Function] - /** The constructor/deconstructor for `Function` instances. */ + /** The constructor/deconstructor for `Function` instances. + * @group Extractors + */ val Function: FunctionExtractor /** An extractor class to create and pattern match with syntax `Function(vparams, body)`. @@ -927,56 +1244,83 @@ trait Trees { self: Universe => * * The symbol of a Function is a synthetic TermSymbol. * It is the owner of the function's parameters. + * @group Extractors */ abstract class FunctionExtractor { def apply(vparams: List[ValDef], body: Tree): Function def unapply(function: Function): Option[(List[ValDef], Tree)] } - /** The API that all functions support */ + /** The API that all functions support + * @group API + */ trait FunctionApi extends TermTreeApi with SymTreeApi { this: Function => + /** The list of parameters of the function. + */ val vparams: List[ValDef] + + /** The body of the function. + */ val body: Tree } - /** Assignment */ + /** Assignment + * @group Trees + * @template + */ type Assign >: Null <: TermTree with AssignApi /** A tag that preserves the identity of the `Assign` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AssignTag: ClassTag[Assign] - /** The constructor/deconstructor for `Assign` instances. */ + /** The constructor/deconstructor for `Assign` instances. + * @group Extractors + */ val Assign: AssignExtractor /** An extractor class to create and pattern match with syntax `Assign(lhs, rhs)`. * This AST node corresponds to the following Scala code: * * lhs = rhs + * @group Extractors */ abstract class AssignExtractor { def apply(lhs: Tree, rhs: Tree): Assign def unapply(assign: Assign): Option[(Tree, Tree)] } - /** The API that all assigns support */ + /** The API that all assigns support + * @group API + */ trait AssignApi extends TermTreeApi { this: Assign => + /** The left-hand side of the assignment. + */ val lhs: Tree + + /** The right-hand side of the assignment. + */ val rhs: Tree } /** Either an assignment or a named argument. Only appears in argument lists, * eliminated by compiler phase typecheck (doTypedApply), resurrected by reifier. + * @group Trees + * @template */ type AssignOrNamedArg >: Null <: TermTree with AssignOrNamedArgApi /** A tag that preserves the identity of the `AssignOrNamedArg` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AssignOrNamedArgTag: ClassTag[AssignOrNamedArg] - /** The constructor/deconstructor for `AssignOrNamedArg` instances. */ + /** The constructor/deconstructor for `AssignOrNamedArg` instances. + * @group Extractors + */ val AssignOrNamedArg: AssignOrNamedArgExtractor /** An extractor class to create and pattern match with syntax `AssignOrNamedArg(lhs, rhs)`. @@ -989,27 +1333,41 @@ trait Trees { self: Universe => * @annotation(lhs = rhs) * }}} * + * @group Extractors */ abstract class AssignOrNamedArgExtractor { def apply(lhs: Tree, rhs: Tree): AssignOrNamedArg def unapply(assignOrNamedArg: AssignOrNamedArg): Option[(Tree, Tree)] } - /** The API that all assigns support */ + /** The API that all assigns support + * @group API + */ trait AssignOrNamedArgApi extends TermTreeApi { this: AssignOrNamedArg => + /** The left-hand side of the expression. + */ val lhs: Tree + + /** The right-hand side of the expression. + */ val rhs: Tree } - /** Conditional expression */ + /** Conditional expression + * @group Trees + * @template + */ type If >: Null <: TermTree with IfApi /** A tag that preserves the identity of the `If` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val IfTag: ClassTag[If] - /** The constructor/deconstructor for `If` instances. */ + /** The constructor/deconstructor for `If` instances. + * @group Extractors + */ val If: IfExtractor /** An extractor class to create and pattern match with syntax `If(cond, thenp, elsep)`. @@ -1018,16 +1376,28 @@ trait Trees { self: Universe => * `if` (cond) thenp `else` elsep * * If the alternative is not present, the `elsep` is set to `Literal(Constant(()))`. + * @group Extractors */ abstract class IfExtractor { def apply(cond: Tree, thenp: Tree, elsep: Tree): If def unapply(if_ : If): Option[(Tree, Tree, Tree)] } - /** The API that all ifs support */ + /** The API that all ifs support + * @group API + */ trait IfApi extends TermTreeApi { this: If => + /** The condition of the if. + */ val cond: Tree + + /** The main branch of the if. + */ val thenp: Tree + + /** The alternative of the if. + * Is equal to `Literal(Constant(()))` if not specified. + */ val elsep: Tree } @@ -1041,15 +1411,20 @@ trait Trees { self: Universe => * or `Alternative(lit|...|lit)` * - except for an "otherwise" branch, which has pattern * `Ident(nme.WILDCARD)` + * @group Trees + * @template */ type Match >: Null <: TermTree with MatchApi /** A tag that preserves the identity of the `Match` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val MatchTag: ClassTag[Match] - /** The constructor/deconstructor for `Match` instances. */ + /** The constructor/deconstructor for `Match` instances. + * @group Extractors + */ val Match: MatchExtractor /** An extractor class to create and pattern match with syntax `Match(selector, cases)`. @@ -1058,27 +1433,39 @@ trait Trees { self: Universe => * selector `match` { cases } * * `Match` is also used in pattern matching assignments like `val (foo, bar) = baz`. + * @group Extractors */ abstract class MatchExtractor { def apply(selector: Tree, cases: List[CaseDef]): Match def unapply(match_ : Match): Option[(Tree, List[CaseDef])] } - /** The API that all matches support */ + /** The API that all matches support + * @group API + */ trait MatchApi extends TermTreeApi { this: Match => + /** The scrutinee of the pattern match. */ val selector: Tree + + /** The arms of the pattern match. */ val cases: List[CaseDef] } - /** Return expression */ + /** Return expression + * @group Trees + * @template + */ type Return >: Null <: TermTree with SymTree with ReturnApi /** A tag that preserves the identity of the `Return` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ReturnTag: ClassTag[Return] - /** The constructor/deconstructor for `Return` instances. */ + /** The constructor/deconstructor for `Return` instances. + * @group Extractors + */ val Return: ReturnExtractor /** An extractor class to create and pattern match with syntax `Return(expr)`. @@ -1087,26 +1474,36 @@ trait Trees { self: Universe => * `return` expr * * The symbol of a Return node is the enclosing method. + * @group Extractors */ abstract class ReturnExtractor { def apply(expr: Tree): Return def unapply(return_ : Return): Option[Tree] } - /** The API that all returns support */ + /** The API that all returns support + * @group API + */ trait ReturnApi extends TermTreeApi { this: Return => + /** The returned expression. */ val expr: Tree } - /** [Eugene++] comment me! */ + /** Try catch node + * @group Trees + * @template + */ type Try >: Null <: TermTree with TryApi /** A tag that preserves the identity of the `Try` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TryTag: ClassTag[Try] - /** The constructor/deconstructor for `Try` instances. */ + /** The constructor/deconstructor for `Try` instances. + * @group Extractors + */ val Try: TryExtractor /** An extractor class to create and pattern match with syntax `Try(block, catches, finalizer)`. @@ -1115,55 +1512,77 @@ trait Trees { self: Universe => * `try` block `catch` { catches } `finally` finalizer * * If the finalizer is not present, the `finalizer` is set to `EmptyTree`. + * @group Extractors */ abstract class TryExtractor { def apply(block: Tree, catches: List[CaseDef], finalizer: Tree): Try def unapply(try_ : Try): Option[(Tree, List[CaseDef], Tree)] } - /** The API that all tries support */ + /** The API that all tries support + * @group API + */ trait TryApi extends TermTreeApi { this: Try => + /** The protected block. */ val block: Tree + + /** The `catch` pattern-matching clauses of the try. */ val catches: List[CaseDef] + + /** The `finally` part of the try. */ val finalizer: Tree } - /** Throw expression */ + /** Throw expression + * @group Trees + * @template + */ type Throw >: Null <: TermTree with ThrowApi /** A tag that preserves the identity of the `Throw` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ThrowTag: ClassTag[Throw] - /** The constructor/deconstructor for `Throw` instances. */ + /** The constructor/deconstructor for `Throw` instances. + * @group Extractors + */ val Throw: ThrowExtractor /** An extractor class to create and pattern match with syntax `Throw(expr)`. * This AST node corresponds to the following Scala code: * * `throw` expr + * @group Extractors */ abstract class ThrowExtractor { def apply(expr: Tree): Throw def unapply(throw_ : Throw): Option[Tree] } - /** The API that all tries support */ + /** The API that all tries support + * @group API + */ trait ThrowApi extends TermTreeApi { this: Throw => + /** The thrown expression. */ val expr: Tree } /** Object instantiation + * @group Trees + * @template */ type New >: Null <: TermTree with NewApi /** A tag that preserves the identity of the `New` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val NewTag: ClassTag[New] /** The constructor/deconstructor for `New` instances. + * @group Extractors */ val New: NewExtractor @@ -1175,6 +1594,7 @@ trait Trees { self: Universe => * This node always occurs in the following context: * * (`new` tpt).<init>[targs](args) + * @group Extractors */ abstract class NewExtractor { /** A user level `new`. @@ -1186,50 +1606,75 @@ trait Trees { self: Universe => def unapply(new_ : New): Option[Tree] } - /** The API that all news support */ + /** The API that all news support + * @group API + */ trait NewApi extends TermTreeApi { this: New => + /** The tree that represents the type being instantiated. + * See the example for [[scala.reflect.api.Trees#NewExtractor]]. + */ val tpt: Tree } - /** Type annotation, eliminated by compiler phase cleanup */ + /** Type annotation, eliminated by compiler phase cleanup + * @group Trees + * @template + */ type Typed >: Null <: TermTree with TypedApi /** A tag that preserves the identity of the `Typed` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypedTag: ClassTag[Typed] - /** The constructor/deconstructor for `Typed` instances. */ + /** The constructor/deconstructor for `Typed` instances. + * @group Extractors + */ val Typed: TypedExtractor /** An extractor class to create and pattern match with syntax `Typed(expr, tpt)`. * This AST node corresponds to the following Scala code: * * expr: tpt + * @group Extractors */ abstract class TypedExtractor { def apply(expr: Tree, tpt: Tree): Typed def unapply(typed: Typed): Option[(Tree, Tree)] } - /** The API that all typeds support */ + /** The API that all typeds support + * @group API + */ trait TypedApi extends TermTreeApi { this: Typed => + /** The expression being ascribed with the type. */ val expr: Tree + + /** The type being ascribed to the expression. */ val tpt: Tree } /** Common base class for Apply and TypeApply. + * @group Trees + * @template */ type GenericApply >: Null <: TermTree with GenericApplyApi /** A tag that preserves the identity of the `GenericApply` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val GenericApplyTag: ClassTag[GenericApply] - /** The API that all applies support */ + /** The API that all applies support + * @group API + */ trait GenericApplyApi extends TermTreeApi { this: GenericApply => + /** The target of the application. */ val fun: Tree + + /** The arguments of the application. */ val args: List[Tree] } @@ -1237,40 +1682,55 @@ trait Trees { self: Universe => * but I can't find that explicitly stated anywhere. Unless your last name * is odersky, you should probably treat it as true. */ - /** Explicit type application. */ + /** Explicit type application. + * @group Trees + * @template + */ type TypeApply >: Null <: GenericApply with TypeApplyApi /** A tag that preserves the identity of the `TypeApply` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeApplyTag: ClassTag[TypeApply] - /** The constructor/deconstructor for `TypeApply` instances. */ + /** The constructor/deconstructor for `TypeApply` instances. + * @group Extractors + */ val TypeApply: TypeApplyExtractor /** An extractor class to create and pattern match with syntax `TypeApply(fun, args)`. * This AST node corresponds to the following Scala code: * * fun[args] + * @group Extractors */ abstract class TypeApplyExtractor { def apply(fun: Tree, args: List[Tree]): TypeApply def unapply(typeApply: TypeApply): Option[(Tree, List[Tree])] } - /** The API that all type applies support */ + /** The API that all type applies support + * @group API + */ trait TypeApplyApi extends GenericApplyApi { this: TypeApply => } - /** Value application */ + /** Value application + * @group Trees + * @template + */ type Apply >: Null <: GenericApply with ApplyApi /** A tag that preserves the identity of the `Apply` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ApplyTag: ClassTag[Apply] - /** The constructor/deconstructor for `Apply` instances. */ + /** The constructor/deconstructor for `Apply` instances. + * @group Extractors + */ val Apply: ApplyExtractor /** An extractor class to create and pattern match with syntax `Apply(fun, args)`. @@ -1285,27 +1745,35 @@ trait Trees { self: Universe => * Is expressed as: * * Apply(TypeApply(fun, targs), args) + * @group Extractors */ abstract class ApplyExtractor { def apply(fun: Tree, args: List[Tree]): Apply def unapply(apply: Apply): Option[(Tree, List[Tree])] } - /** The API that all applies support */ + /** The API that all applies support + * @group API + */ trait ApplyApi extends GenericApplyApi { this: Apply => } /** Super reference, where `qual` is the corresponding `this` reference. * A super reference `C.super[M]` is represented as `Super(This(C), M)`. + * @group Trees + * @template */ type Super >: Null <: TermTree with SuperApi /** A tag that preserves the identity of the `Super` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SuperTag: ClassTag[Super] - /** The constructor/deconstructor for `Super` instances. */ + /** The constructor/deconstructor for `Super` instances. + * @group Extractors + */ val Super: SuperExtractor /** An extractor class to create and pattern match with syntax `Super(qual, mix)`. @@ -1321,27 +1789,43 @@ trait Trees { self: Universe => * * The symbol of a Super is the class _from_ which the super reference is made. * For instance in C.super(...), it would be C. + * @group Extractors */ abstract class SuperExtractor { def apply(qual: Tree, mix: TypeName): Super def unapply(super_ : Super): Option[(Tree, TypeName)] } - /** The API that all supers support */ + /** The API that all supers support + * @group API + */ trait SuperApi extends TermTreeApi { this: Super => + /** The qualifier of the `super` expression. + * See the example for [[scala.reflect.api.Trees#SuperExtractor]]. + */ val qual: Tree + + /** The selector of the `super` expression. + * See the example for [[scala.reflect.api.Trees#SuperExtractor]]. + */ val mix: TypeName } - /** Self reference */ + /** Self reference + * @group Trees + * @template + */ type This >: Null <: TermTree with SymTree with ThisApi /** A tag that preserves the identity of the `This` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ThisTag: ClassTag[This] - /** The constructor/deconstructor for `This` instances. */ + /** The constructor/deconstructor for `This` instances. + * @group Extractors + */ val This: ThisExtractor /** An extractor class to create and pattern match with syntax `This(qual)`. @@ -1351,55 +1835,77 @@ trait Trees { self: Universe => * * The symbol of a This is the class to which the this refers. * For instance in C.this, it would be C. - * - * If `mix` is empty, then ??? + * @group Extractors */ abstract class ThisExtractor { def apply(qual: TypeName): This def unapply(this_ : This): Option[TypeName] } - /** The API that all thises support */ + /** The API that all thises support + * @group API + */ trait ThisApi extends TermTreeApi with SymTreeApi { this: This => + /** The qualifier of the `this` expression. + * For an unqualified `this` refers to the enclosing class. + */ val qual: TypeName } - /** Designator <qualifier> . <name> */ + /** A member selection <qualifier> . <name> + * @group Trees + * @template + */ type Select >: Null <: RefTree with SelectApi /** A tag that preserves the identity of the `Select` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SelectTag: ClassTag[Select] - /** The constructor/deconstructor for `Select` instances. */ + /** The constructor/deconstructor for `Select` instances. + * @group Extractors + */ val Select: SelectExtractor /** An extractor class to create and pattern match with syntax `Select(qual, name)`. * This AST node corresponds to the following Scala code: * * qualifier.selector + * @group Extractors */ abstract class SelectExtractor { def apply(qualifier: Tree, name: Name): Select def unapply(select: Select): Option[(Tree, Name)] } - /** The API that all selects support */ + /** The API that all selects support + * @group API + */ trait SelectApi extends RefTreeApi { this: Select => + /** @inheritdoc */ val qualifier: Tree + + /** @inheritdoc */ val name: Name } - /** Identifier <name> */ + /** A reference to identifier `name`. + * @group Trees + * @template + */ type Ident >: Null <: RefTree with IdentApi /** A tag that preserves the identity of the `Ident` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val IdentTag: ClassTag[Ident] - /** The constructor/deconstructor for `Ident` instances. */ + /** The constructor/deconstructor for `Ident` instances. + * @group Extractors + */ val Ident: IdentExtractor /** An extractor class to create and pattern match with syntax `Ident(qual, name)`. @@ -1409,32 +1915,42 @@ trait Trees { self: Universe => * * Type checker converts idents that refer to enclosing fields or methods to selects. * For example, name ==> this.name + * @group Extractors */ abstract class IdentExtractor { def apply(name: Name): Ident def unapply(ident: Ident): Option[Name] } - /** The API that all idents support */ + /** The API that all idents support + * @group API + */ trait IdentApi extends RefTreeApi { this: Ident => + /** @inheritdoc */ val name: Name } /** Marks underlying reference to id as boxed. - * @pre id must refer to a captured variable + * + * <b>Precondition:<\b> id must refer to a captured variable * A reference such marked will refer to the boxed entity, no dereferencing * with `.elem` is done on it. * This tree node can be emitted by macros such as reify that call referenceCapturedVariable. * It is eliminated in LambdaLift, where the boxing conversion takes place. + * @group Trees + * @template */ type ReferenceToBoxed >: Null <: TermTree with ReferenceToBoxedApi /** A tag that preserves the identity of the `ReferenceToBoxed` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ReferenceToBoxedTag: ClassTag[ReferenceToBoxed] - /** The constructor/deconstructor for `ReferenceToBoxed` instances. */ + /** The constructor/deconstructor for `ReferenceToBoxed` instances. + * @group Extractors + */ val ReferenceToBoxed: ReferenceToBoxedExtractor /** An extractor class to create and pattern match with syntax `ReferenceToBoxed(ident)`. @@ -1455,40 +1971,54 @@ trait Trees { self: Universe => * Select(Ident(x), "elem") * * If `ReferenceToBoxed` were used instead of Ident, no transformation would be performed. + * @group Extractors */ abstract class ReferenceToBoxedExtractor { def apply(ident: Ident): ReferenceToBoxed def unapply(referenceToBoxed: ReferenceToBoxed): Option[Ident] } - /** The API that all references support */ + /** The API that all references support + * @group API + */ trait ReferenceToBoxedApi extends TermTreeApi { this: ReferenceToBoxed => + /** The underlying reference. */ val ident: Tree } - /** Literal */ + /** Literal + * @group Trees + * @template + */ type Literal >: Null <: TermTree with LiteralApi /** A tag that preserves the identity of the `Literal` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val LiteralTag: ClassTag[Literal] - /** The constructor/deconstructor for `Literal` instances. */ + /** The constructor/deconstructor for `Literal` instances. + * @group Extractors + */ val Literal: LiteralExtractor /** An extractor class to create and pattern match with syntax `Literal(value)`. * This AST node corresponds to the following Scala code: * * value + * @group Extractors */ abstract class LiteralExtractor { def apply(value: Constant): Literal def unapply(literal: Literal): Option[Constant] } - /** The API that all literals support */ + /** The API that all literals support + * @group API + */ trait LiteralApi extends TermTreeApi { this: Literal => + /** The compile-time constant underlying the literal. */ val value: Constant } @@ -1496,15 +2026,20 @@ trait Trees { self: Universe => * annotation ascriptions, annotations on definitions are stored in the Modifiers. * Eliminated by typechecker (typedAnnotated), the annotations are then stored in * an AnnotatedType. + * @group Trees + * @template */ type Annotated >: Null <: AnyRef with Tree with AnnotatedApi /** A tag that preserves the identity of the `Annotated` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AnnotatedTag: ClassTag[Annotated] - /** The constructor/deconstructor for `Annotated` instances. */ + /** The constructor/deconstructor for `Annotated` instances. + * @group Extractors + */ val Annotated: AnnotatedExtractor /** An extractor class to create and pattern match with syntax `Annotated(annot, arg)`. @@ -1512,54 +2047,76 @@ trait Trees { self: Universe => * * arg @annot // for types * arg: @annot // for exprs + * @group Extractors */ abstract class AnnotatedExtractor { def apply(annot: Tree, arg: Tree): Annotated def unapply(annotated: Annotated): Option[(Tree, Tree)] } - /** The API that all annotateds support */ + /** The API that all annotateds support + * @group API + */ trait AnnotatedApi extends TreeApi { this: Annotated => + /** The annotation. */ val annot: Tree + + /** The annotee. */ val arg: Tree } - /** Singleton type, eliminated by RefCheck */ + /** Singleton type, eliminated by RefCheck + * @group Trees + * @template + */ type SingletonTypeTree >: Null <: TypTree with SingletonTypeTreeApi /** A tag that preserves the identity of the `SingletonTypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SingletonTypeTreeTag: ClassTag[SingletonTypeTree] - /** The constructor/deconstructor for `SingletonTypeTree` instances. */ + /** The constructor/deconstructor for `SingletonTypeTree` instances. + * @group Extractors + */ val SingletonTypeTree: SingletonTypeTreeExtractor /** An extractor class to create and pattern match with syntax `SingletonTypeTree(ref)`. * This AST node corresponds to the following Scala code: * * ref.type + * @group Extractors */ abstract class SingletonTypeTreeExtractor { def apply(ref: Tree): SingletonTypeTree def unapply(singletonTypeTree: SingletonTypeTree): Option[Tree] } - /** The API that all singleton type trees support */ + /** The API that all singleton type trees support + * @group API + */ trait SingletonTypeTreeApi extends TypTreeApi { this: SingletonTypeTree => + /** The underlying reference. */ val ref: Tree } - /** Type selection <qualifier> # <name>, eliminated by RefCheck */ + /** Type selection <qualifier> # <name>, eliminated by RefCheck + * @group Trees + * @template + */ // [Eugene++] don't see why we need it, when we have Select type SelectFromTypeTree >: Null <: TypTree with RefTree with SelectFromTypeTreeApi /** A tag that preserves the identity of the `SelectFromTypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SelectFromTypeTreeTag: ClassTag[SelectFromTypeTree] - /** The constructor/deconstructor for `SelectFromTypeTree` instances. */ + /** The constructor/deconstructor for `SelectFromTypeTree` instances. + * @group Extractors + */ val SelectFromTypeTree: SelectFromTypeTreeExtractor /** An extractor class to create and pattern match with syntax `SelectFromTypeTree(qualifier, name)`. @@ -1568,151 +2125,219 @@ trait Trees { self: Universe => * qualifier # selector * * Note: a path-dependent type p.T is expressed as p.type # T + * @group Extractors */ abstract class SelectFromTypeTreeExtractor { def apply(qualifier: Tree, name: TypeName): SelectFromTypeTree def unapply(selectFromTypeTree: SelectFromTypeTree): Option[(Tree, TypeName)] } - /** The API that all selects from type trees support */ + /** The API that all selects from type trees support + * @group API + */ trait SelectFromTypeTreeApi extends TypTreeApi with RefTreeApi { this: SelectFromTypeTree => + /** @inheritdoc */ val qualifier: Tree + + /** @inheritdoc */ val name: TypeName } - /** Intersection type <parent1> with ... with <parentN> { <decls> }, eliminated by RefCheck */ + /** Intersection type <parent1> with ... with <parentN> { <decls> }, eliminated by RefCheck + * @group Trees + * @template + */ type CompoundTypeTree >: Null <: TypTree with CompoundTypeTreeApi /** A tag that preserves the identity of the `CompoundTypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val CompoundTypeTreeTag: ClassTag[CompoundTypeTree] - /** The constructor/deconstructor for `CompoundTypeTree` instances. */ + /** The constructor/deconstructor for `CompoundTypeTree` instances. + * @group Extractors + */ val CompoundTypeTree: CompoundTypeTreeExtractor /** An extractor class to create and pattern match with syntax `CompoundTypeTree(templ)`. * This AST node corresponds to the following Scala code: * * parent1 with ... with parentN { refinement } + * @group Extractors */ abstract class CompoundTypeTreeExtractor { def apply(templ: Template): CompoundTypeTree def unapply(compoundTypeTree: CompoundTypeTree): Option[Template] } - /** The API that all compound type trees support */ + /** The API that all compound type trees support + * @group API + */ trait CompoundTypeTreeApi extends TypTreeApi { this: CompoundTypeTree => + /** The template of the compound type - represents the parents, the optional self-type and the optional definitions. */ val templ: Template } - /** Applied type <tpt> [ <args> ], eliminated by RefCheck */ + /** Applied type <tpt> [ <args> ], eliminated by RefCheck + * @group Trees + * @template + */ type AppliedTypeTree >: Null <: TypTree with AppliedTypeTreeApi /** A tag that preserves the identity of the `AppliedTypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AppliedTypeTreeTag: ClassTag[AppliedTypeTree] - /** The constructor/deconstructor for `AppliedTypeTree` instances. */ + /** The constructor/deconstructor for `AppliedTypeTree` instances. + * @group Extractors + */ val AppliedTypeTree: AppliedTypeTreeExtractor /** An extractor class to create and pattern match with syntax `AppliedTypeTree(tpt, args)`. * This AST node corresponds to the following Scala code: * * tpt[args] + * @group Extractors */ abstract class AppliedTypeTreeExtractor { def apply(tpt: Tree, args: List[Tree]): AppliedTypeTree def unapply(appliedTypeTree: AppliedTypeTree): Option[(Tree, List[Tree])] } - /** The API that all applied type trees support */ + /** The API that all applied type trees support + * @group API + */ trait AppliedTypeTreeApi extends TypTreeApi { this: AppliedTypeTree => + /** The target of the application. */ val tpt: Tree + + /** The arguments of the application. */ val args: List[Tree] } - /** Document me! */ + /** Type bounds tree node + * @group Trees + * @template + */ type TypeBoundsTree >: Null <: TypTree with TypeBoundsTreeApi /** A tag that preserves the identity of the `TypeBoundsTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeBoundsTreeTag: ClassTag[TypeBoundsTree] - /** The constructor/deconstructor for `TypeBoundsTree` instances. */ + /** The constructor/deconstructor for `TypeBoundsTree` instances. + * @group Extractors + */ val TypeBoundsTree: TypeBoundsTreeExtractor /** An extractor class to create and pattern match with syntax `TypeBoundsTree(lo, hi)`. * This AST node corresponds to the following Scala code: * * >: lo <: hi + * @group Extractors */ abstract class TypeBoundsTreeExtractor { def apply(lo: Tree, hi: Tree): TypeBoundsTree def unapply(typeBoundsTree: TypeBoundsTree): Option[(Tree, Tree)] } - /** The API that all type bound trees support */ + /** The API that all type bound trees support + * @group API + */ trait TypeBoundsTreeApi extends TypTreeApi { this: TypeBoundsTree => + /** The lower bound. + * Is equal to `Ident(<scala.Nothing>)` if not specified explicitly. + */ val lo: Tree + + /** The upper bound. + * Is equal to `Ident(<scala.Any>)` if not specified explicitly. + */ val hi: Tree } - /** Document me! */ + /** Existential type tree node + * @group Trees + * @template + */ type ExistentialTypeTree >: Null <: TypTree with ExistentialTypeTreeApi /** A tag that preserves the identity of the `ExistentialTypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ExistentialTypeTreeTag: ClassTag[ExistentialTypeTree] - /** The constructor/deconstructor for `ExistentialTypeTree` instances. */ + /** The constructor/deconstructor for `ExistentialTypeTree` instances. + * @group Extractors + */ val ExistentialTypeTree: ExistentialTypeTreeExtractor /** An extractor class to create and pattern match with syntax `ExistentialTypeTree(tpt, whereClauses)`. * This AST node corresponds to the following Scala code: * * tpt forSome { whereClauses } + * @group Extractors */ abstract class ExistentialTypeTreeExtractor { def apply(tpt: Tree, whereClauses: List[Tree]): ExistentialTypeTree def unapply(existentialTypeTree: ExistentialTypeTree): Option[(Tree, List[Tree])] } - /** The API that all existential type trees support */ + /** The API that all existential type trees support + * @group API + */ trait ExistentialTypeTreeApi extends TypTreeApi { this: ExistentialTypeTree => + /** The underlying type of the existential type. */ val tpt: Tree + + /** The clauses of the definition of the existential type. */ val whereClauses: List[Tree] } /** A synthetic tree holding an arbitrary type. Not to be confused with - * with TypTree, the trait for trees that are only used for type trees. - * TypeTree's are inserted in several places, but most notably in - * `RefCheck`, where the arbitrary type trees are all replaced by - * TypeTree's. */ + * with TypTree, the trait for trees that are only used for type trees. + * TypeTree's are inserted in several places, but most notably in + * `RefCheck`, where the arbitrary type trees are all replaced by + * TypeTree's. + * @group Trees + * @template + */ type TypeTree >: Null <: TypTree with TypeTreeApi /** A tag that preserves the identity of the `TypeTree` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeTreeTag: ClassTag[TypeTree] - /** The constructor/deconstructor for `TypeTree` instances. */ + /** The constructor/deconstructor for `TypeTree` instances. + * @group Extractors + */ val TypeTree: TypeTreeExtractor /** An extractor class to create and pattern match with syntax `TypeTree()`. * This AST node does not have direct correspondence to Scala code, * and is emitted by everywhere when we want to wrap a `Type` in a `Tree`. + * @group Extractors */ abstract class TypeTreeExtractor { def apply(): TypeTree def unapply(typeTree: TypeTree): Boolean } - /** The API that all type trees support */ + /** The API that all type trees support + * @group API + */ trait TypeTreeApi extends TypTreeApi { this: TypeTree => + /** The precursor of this tree. + * Is equal to `EmptyTree` if this type tree doesn't have precursors. + */ def original: Tree } @@ -1720,156 +2345,415 @@ trait Trees { self: Universe => * val _: _ * This is used as a placeholder in the `self` parameter Template if there is * no definition of a self value of self type. + * @group Trees */ val emptyValDef: ValDef // ---------------------- factories ---------------------------------------------- - /** @param sym the class symbol - * @param impl the implementation template + /** A factory method for `ClassDef` nodes. + * @group Factories */ def ClassDef(sym: Symbol, impl: Template): ClassDef - /** - * @param sym the class symbol - * @param impl the implementation template + /** A factory method for `ModuleDef` nodes. + * @group Factories */ def ModuleDef(sym: Symbol, impl: Template): ModuleDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def ValDef(sym: Symbol, rhs: Tree): ValDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def ValDef(sym: Symbol): ValDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def DefDef(sym: Symbol, mods: Modifiers, vparamss: List[List[ValDef]], rhs: Tree): DefDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def DefDef(sym: Symbol, vparamss: List[List[ValDef]], rhs: Tree): DefDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def DefDef(sym: Symbol, mods: Modifiers, rhs: Tree): DefDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def DefDef(sym: Symbol, rhs: Tree): DefDef + /** A factory method for `ValDef` nodes. + * @group Factories + */ def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef - /** A TypeDef node which defines given `sym` with given tight hand side `rhs`. */ + /** A factory method for `TypeDef` nodes. + * @group Factories + */ def TypeDef(sym: Symbol, rhs: Tree): TypeDef - /** A TypeDef node which defines abstract type or type parameter for given `sym` */ + /** A factory method for `TypeDef` nodes. + * @group Factories + */ def TypeDef(sym: Symbol): TypeDef + /** A factory method for `LabelDef` nodes. + * @group Factories + */ def LabelDef(sym: Symbol, params: List[Symbol], rhs: Tree): LabelDef - /** Block factory that flattens directly nested blocks. + /** A factory method for `Block` nodes. + * Flattens directly nested blocks. + * @group Factories */ def Block(stats: Tree*): Block - /** casedef shorthand */ + /** A factory method for `CaseDef` nodes. + * @group Factories + */ def CaseDef(pat: Tree, body: Tree): CaseDef + /** A factory method for `Bind` nodes. + * @group Factories + */ def Bind(sym: Symbol, body: Tree): Bind + /** A factory method for `Try` nodes. + * @group Factories + */ def Try(body: Tree, cases: (Tree, Tree)*): Try + /** A factory method for `Throw` nodes. + * @group Factories + */ def Throw(tpe: Type, args: Tree*): Throw /** Factory method for object creation `new tpt(args_1)...(args_n)` * A `New(t, as)` is expanded to: `(new t).<init>(as)` + * @group Factories */ def New(tpt: Tree, argss: List[List[Tree]]): Tree /** 0-1 argument list new, based on a type. + * @group Factories */ def New(tpe: Type, args: Tree*): Tree + /** 0-1 argument list new, based on a symbol. + * @group Factories + */ def New(sym: Symbol, args: Tree*): Tree + /** A factory method for `Apply` nodes. + * @group Factories + */ def Apply(sym: Symbol, args: Tree*): Tree + /** 0-1 argument list new, based on a type tree. + * @group Factories + */ def ApplyConstructor(tpt: Tree, args: List[Tree]): Tree + /** A factory method for `Super` nodes. + * @group Factories + */ def Super(sym: Symbol, mix: TypeName): Tree + /** A factory method for `This` nodes. + * @group Factories + */ def This(sym: Symbol): Tree + /** A factory method for `Select` nodes. + * The string `name` argument is assumed to represent a [[scala.reflect.api.Names#TermName `TermName`]]. + * @group Factories + */ def Select(qualifier: Tree, name: String): Select + /** A factory method for `Select` nodes. + * @group Factories + */ def Select(qualifier: Tree, sym: Symbol): Select + /** A factory method for `Ident` nodes. + * @group Factories + */ def Ident(name: String): Ident + /** A factory method for `Ident` nodes. + * @group Factories + */ def Ident(sym: Symbol): Ident + /** A factory method for `TypeTree` nodes. + * @group Factories + */ def TypeTree(tp: Type): TypeTree // ---------------------- copying ------------------------------------------------ - /** The standard (lazy) tree copier + /** The type of standard (lazy) tree copiers. + * @template + * @group Copying */ type TreeCopier <: TreeCopierOps + + /** The standard (lazy) tree copier. + * @group Copying + */ val treeCopy: TreeCopier = newLazyTreeCopier + /** Creates a strict tree copier. + * @group Copying + */ def newStrictTreeCopier: TreeCopier + + /** Creates a lazy tree copier. + * @group Copying + */ def newLazyTreeCopier: TreeCopier - /** The API of a tree copier - * tree copiers are made available by an implicit conversion in reflect.ops + /** The API of a tree copier. + * @group API */ abstract class TreeCopierOps { + /** Creates a `ClassDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template): ClassDef + + /** Creates a `PackageDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def PackageDef(tree: Tree, pid: RefTree, stats: List[Tree]): PackageDef + + /** Creates a `ModuleDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template): ModuleDef + + /** Creates a `ValDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree): ValDef + + /** Creates a `DefDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree): DefDef + + /** Creates a `TypeDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def TypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], rhs: Tree): TypeDef + + /** Creates a `LabelDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree): LabelDef + + /** Creates a `Import` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Import(tree: Tree, expr: Tree, selectors: List[ImportSelector]): Import + + /** Creates a `Template` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Template(tree: Tree, parents: List[Tree], self: ValDef, body: List[Tree]): Template + + /** Creates a `Block` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Block(tree: Tree, stats: List[Tree], expr: Tree): Block + + /** Creates a `CaseDef` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree): CaseDef + + /** Creates a `Alternative` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Alternative(tree: Tree, trees: List[Tree]): Alternative + + /** Creates a `Star` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Star(tree: Tree, elem: Tree): Star + + /** Creates a `Bind` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Bind(tree: Tree, name: Name, body: Tree): Bind + + /** Creates a `UnApply` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def UnApply(tree: Tree, fun: Tree, args: List[Tree]): UnApply + + /** Creates a `Function` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Function(tree: Tree, vparams: List[ValDef], body: Tree): Function + + /** Creates a `Assign` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Assign(tree: Tree, lhs: Tree, rhs: Tree): Assign + + /** Creates a `AssignOrNamedArg` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def AssignOrNamedArg(tree: Tree, lhs: Tree, rhs: Tree): AssignOrNamedArg + + /** Creates a `If` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree): If + + /** Creates a `Match` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Match(tree: Tree, selector: Tree, cases: List[CaseDef]): Match + + /** Creates a `Return` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Return(tree: Tree, expr: Tree): Return + + /** Creates a `Try` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Try(tree: Tree, block: Tree, catches: List[CaseDef], finalizer: Tree): Try + + /** Creates a `Throw` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Throw(tree: Tree, expr: Tree): Throw + + /** Creates a `New` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def New(tree: Tree, tpt: Tree): New + + /** Creates a `Typed` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Typed(tree: Tree, expr: Tree, tpt: Tree): Typed + + /** Creates a `TypeApply` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def TypeApply(tree: Tree, fun: Tree, args: List[Tree]): TypeApply + + /** Creates a `Apply` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Apply(tree: Tree, fun: Tree, args: List[Tree]): Apply + + /** Creates a `Super` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Super(tree: Tree, qual: Tree, mix: TypeName): Super + + /** Creates a `This` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def This(tree: Tree, qual: Name): This + + /** Creates a `Select` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Select(tree: Tree, qualifier: Tree, selector: Name): Select + + /** Creates a `Ident` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Ident(tree: Tree, name: Name): Ident + + /** Creates a `ReferenceToBoxed` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def ReferenceToBoxed(tree: Tree, idt: Ident): ReferenceToBoxed + + /** Creates a `Literal` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Literal(tree: Tree, value: Constant): Literal + + /** Creates a `TypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def TypeTree(tree: Tree): TypeTree + + /** Creates a `Annotated` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def Annotated(tree: Tree, annot: Tree, arg: Tree): Annotated + + /** Creates a `SingletonTypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def SingletonTypeTree(tree: Tree, ref: Tree): SingletonTypeTree + + /** Creates a `SelectFromTypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name): SelectFromTypeTree + + /** Creates a `CompoundTypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def CompoundTypeTree(tree: Tree, templ: Template): CompoundTypeTree + + /** Creates a `AppliedTypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]): AppliedTypeTree + + /** Creates a `TypeBoundsTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def TypeBoundsTree(tree: Tree, lo: Tree, hi: Tree): TypeBoundsTree + + /** Creates a `ExistentialTypeTree` node from the given components, having a given `tree` as a prototype. + * Having a tree as a prototype means that the tree's attachments, type and symbol will be copied into the result. + */ def ExistentialTypeTree(tree: Tree, tpt: Tree, whereClauses: List[Tree]): ExistentialTypeTree } // ---------------------- traversing and transforming ------------------------------ + /** A class that implement a default tree traversal strategy: breadth-first component-wise. + * @group Traversal + */ class Traverser { protected[scala] var currentOwner: Symbol = rootMirror.RootClass + /** Traverses a single tree. */ def traverse(tree: Tree): Unit = itraverse(this, tree) + /** Traverses a list of trees. */ def traverseTrees(trees: List[Tree]) { trees foreach traverse } + + /** Traverses a list of lists of trees. */ def traverseTreess(treess: List[List[Tree]]) { treess foreach traverseTrees } + + /** Traverses a list of trees with a given owner symbol. */ def traverseStats(stats: List[Tree], exprOwner: Symbol) { stats foreach (stat => if (exprOwner != currentOwner) atOwner(exprOwner)(traverse(stat)) @@ -1877,6 +2761,7 @@ trait Trees { self: Universe => ) } + /** Performs a traversal with a given owner symbol. */ def atOwner(owner: Symbol)(traverse: => Unit) { val prevOwner = currentOwner currentOwner = owner @@ -1889,49 +2774,81 @@ trait Trees { self: Universe => def apply[T <: Tree](tree: T): T = { traverse(tree); tree } } + /** Delegates the traversal strategy to `scala.reflect.internal.Trees`, + * because pattern matching on abstract types we have here degrades performance. + * @group Traversal + */ protected def itraverse(traverser: Traverser, tree: Tree): Unit = throw new MatchError(tree) + /** Provides an extension hook for the traversal strategy. + * Future-proofs against new node types. + * @group Traversal + */ protected def xtraverse(traverser: Traverser, tree: Tree): Unit = throw new MatchError(tree) + /** A class that implement a default tree transformation strategy: breadth-first component-wise cloning. + * @group Traversal + */ abstract class Transformer { + /** The underlying tree copier. */ val treeCopy: TreeCopier = newLazyTreeCopier + + /** The current owner symbol. */ protected[scala] var currentOwner: Symbol = rootMirror.RootClass + + /** The enclosing method of the currently transformed tree. */ protected def currentMethod = { def enclosingMethod(sym: Symbol): Symbol = if (sym.isMethod || sym == NoSymbol) sym else enclosingMethod(sym.owner) enclosingMethod(currentOwner) } + + /** The enclosing class of the currently transformed tree. */ protected def currentClass = { def enclosingClass(sym: Symbol): Symbol = if (sym.isClass || sym == NoSymbol) sym else enclosingClass(sym.owner) enclosingClass(currentOwner) } + // protected def currentPackage = currentOwner.enclosingTopLevelClass.owner + + /** Transforms a single tree. */ def transform(tree: Tree): Tree = itransform(this, tree) - def transformTrees(trees: List[Tree]): List[Tree] = - trees mapConserve (transform(_)) + /** Transforms a list of trees. */ + def transformTrees(trees: List[Tree]): List[Tree] = trees mapConserve (transform(_)) + + /** Transforms a `Template`. */ def transformTemplate(tree: Template): Template = transform(tree: Tree).asInstanceOf[Template] + /** Transforms a list of `TypeDef` trees. */ def transformTypeDefs(trees: List[TypeDef]): List[TypeDef] = trees mapConserve (tree => transform(tree).asInstanceOf[TypeDef]) + /** Transforms a `ValDef`. */ def transformValDef(tree: ValDef): ValDef = if (tree.isEmpty) tree else transform(tree).asInstanceOf[ValDef] + /** Transforms a list of `ValDef` nodes. */ def transformValDefs(trees: List[ValDef]): List[ValDef] = trees mapConserve (transformValDef(_)) + /** Transforms a list of lists of `ValDef` nodes. */ def transformValDefss(treess: List[List[ValDef]]): List[List[ValDef]] = treess mapConserve (transformValDefs(_)) + /** Transforms a list of `CaseDef` nodes. */ def transformCaseDefs(trees: List[CaseDef]): List[CaseDef] = trees mapConserve (tree => transform(tree).asInstanceOf[CaseDef]) + /** Transforms a list of `Ident` nodes. */ def transformIdents(trees: List[Ident]): List[Ident] = trees mapConserve (tree => transform(tree).asInstanceOf[Ident]) + /** Traverses a list of trees with a given owner symbol. */ def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = stats mapConserve (stat => if (exprOwner != currentOwner && stat.isTerm) atOwner(exprOwner)(transform(stat)) else transform(stat)) filter (EmptyTree != _) + /** Transforms `Modifiers`. */ def transformModifiers(mods: Modifiers): Modifiers = mods.mapAnnotations(transformTrees) + /** Transforms a tree with a given owner symbol. */ def atOwner[A](owner: Symbol)(trans: => A): A = { val prevOwner = currentOwner currentOwner = owner @@ -1941,39 +2858,83 @@ trait Trees { self: Universe => } } + /** Delegates the transformation strategy to `scala.reflect.internal.Trees`, + * because pattern matching on abstract types we have here degrades performance. + * @group Traversal + */ protected def itransform(transformer: Transformer, tree: Tree): Tree = throw new MatchError(tree) + /** Provides an extension hook for the transformation strategy. + * Future-proofs against new node types. + * @group Traversal + */ protected def xtransform(transformer: Transformer, tree: Tree): Tree = throw new MatchError(tree) - - /** ... */ + /** The type of tree modifiers. + * @group Traversal + */ type Modifiers >: Null <: AnyRef with ModifiersApi /** A tag that preserves the identity of the `Modifiers` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Traversal */ implicit val ModifiersTag: ClassTag[Modifiers] - /** ... */ + /** The API that all Modifiers support + * @group API + */ abstract class ModifiersApi { - def flags: FlagSet // default: NoFlags + /** The underlying flags of the enclosing definition. + * Is equal to `NoFlags` if none are specified explicitly. + */ + def flags: FlagSet + def hasFlag(flag: FlagSet): Boolean - def privateWithin: Name // default: EmptyTypeName - def annotations: List[Tree] // default: List() + + /** The visibility scope of the enclosing definition. + * Is equal to `tpnme.EMPTY` if none is specified explicitly. + */ + def privateWithin: Name + + /** The annotations of the enclosing definition. + * Empty list if none are specified explicitly. + */ + def annotations: List[Tree] + + /** Creates a new instance of `Modifiers` with + * the annotations transformed according to the given function. + */ def mapAnnotations(f: List[Tree] => List[Tree]): Modifiers = Modifiers(flags, privateWithin, f(annotations)) } + /** The constructor/deconstructor for `Modifiers` instances. + * @group Traversal + */ val Modifiers: ModifiersCreator + /** An extractor class to create and pattern match with syntax `Modifiers(flags, privateWithin, annotations)`. + * Modifiers encapsulate flags, visibility annotations and Scala annotations for member definitions. + * @group Traversal + */ abstract class ModifiersCreator { - def apply(): Modifiers = Modifiers(NoFlags, EmptyTypeName, List()) + def apply(): Modifiers = Modifiers(NoFlags, tpnme.EMPTY, List()) def apply(flags: FlagSet, privateWithin: Name, annotations: List[Tree]): Modifiers } + /** The factory for `Modifiers` instances. + * @group Traversal + */ def Modifiers(flags: FlagSet, privateWithin: Name): Modifiers = Modifiers(flags, privateWithin, List()) - def Modifiers(flags: FlagSet): Modifiers = Modifiers(flags, EmptyTypeName) - /** ... */ + /** The factory for `Modifiers` instances. + * @group Traversal + */ + def Modifiers(flags: FlagSet): Modifiers = Modifiers(flags, tpnme.EMPTY) + + /** An empty `Modifiers` object: no flags, empty visibility annotation and no Scala annotations. + * @group Traversal + */ lazy val NoMods = Modifiers() } diff --git a/src/reflect/scala/reflect/api/TypeCreator.scala b/src/reflect/scala/reflect/api/TypeCreator.scala index cc6d38c548..9c386f2939 100644 --- a/src/reflect/scala/reflect/api/TypeCreator.scala +++ b/src/reflect/scala/reflect/api/TypeCreator.scala @@ -3,24 +3,8 @@ package api /** A mirror-aware factory for types. * - * In the reflection API, artifacts are specific to universes and - * symbolic references used in artifacts (e.g. `scala.Int`) are resolved by mirrors. - * - * Therefore to build a type one needs to know a universe that the type is going to be bound to - * and a mirror that is going to resolve symbolic references (e.g. to determine that `scala.Int` - * points to a core class `Int` from scala-library.jar). - * - * `TypeCreator` implements this notion by providing a standalone type factory. - * - * This is immediately useful for type tags. When the compiler creates a type tag, - * the end result needs to make sense in any mirror. That's because the compiler knows - * the universe it's creating a type tag for (since `TypeTag` is path-dependent on a universe), - * but it cannot know in advance the mirror to instantiate the result in (e.g. on JVM - * it doesn't know what classloader use to resolve symbolic names in the type tag). - * - * Due to a typechecker restriction (no eta-expansion for dependent method types), - * `TypeCreator` can't have a functional type, so it's implemented as class with an apply method. + * This class is used internally by Scala Reflection, and is not recommended for use in client code. */ abstract class TypeCreator { - def apply[U <: Universe with Singleton](m: MirrorOf[U]): U # Type + def apply[U <: Universe with Singleton](m: scala.reflect.api.Mirror[U]): U # Type } diff --git a/src/reflect/scala/reflect/api/TypeTags.scala b/src/reflect/scala/reflect/api/TypeTags.scala index a7e58d2bcb..812d5199fc 100644 --- a/src/reflect/scala/reflect/api/TypeTags.scala +++ b/src/reflect/scala/reflect/api/TypeTags.scala @@ -18,170 +18,200 @@ import scala.language.implicitConversions * Backwards compat item1: [Eugene++] it might be useful, though, to guard against abstractness of the incoming type. */ /** - * A type tag encapsulates a representation of type T. - * - * Type tags replace the pre-2.10 concept of a [[scala.reflect.Manifest]] and are integrated with reflection. - * - * === Overview and examples === - * - * Type tags are organized in a hierarchy of three classes: - * [[scala.reflect.ClassTag]], [[scala.reflect.api.Universe#TypeTag]] and [[scala.reflect.api.Universe#WeakTypeTag]]. - * - * @see [[scala.reflect.ClassTag]], [[scala.reflect.api.Universe#TypeTag]], [[scala.reflect.api.Universe#WeakTypeTag]] - * - * Examples: - * {{{ - * scala> class Person - * scala> class Container[T] - * scala> import scala.reflect.ClassTag - * scala> import scala.reflect.runtime.universe.TypeTag - * scala> import scala.reflect.runtime.universe.WeakTypeTag - * scala> def firstTypeArg( tag: WeakTypeTag[_] ) = (tag.tpe match {case TypeRef(_,_,typeArgs) => typeArgs})(0) - * }}} - * TypeTag contains concrete type arguments: - * {{{ - * scala> firstTypeArg( implicitly[TypeTag[Container[Person]]] ) - * res0: reflect.runtime.universe.Type = Person - * }}} - * TypeTag guarantees concrete type arguments (fails for references to unbound type arguments): - * {{{ - * scala> def foo1[T] = implicitly[TypeTag[Container[T]]] - * <console>:11: error: No TypeTag available for Container[T] - * def foo1[T] = implicitly[TypeTag[Container[T]]] - * }}} - * WeakTypeTag allows references to unbound type arguments: - * {{{ - * scala> def foo2[T] = firstTypeArg( implicitly[WeakTypeTag[Container[T]]] ) - * foo2: [T]=> reflect.runtime.universe.Type - * scala> foo2[Person] - * res1: reflect.runtime.universe.Type = T - * }}} - * TypeTag allows unbound type arguments for which type tags are available: - * {{{ - * scala> def foo3[T:TypeTag] = firstTypeArg( implicitly[TypeTag[Container[T]]] ) - * foo3: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type - * scala> foo3[Person] - * res1: reflect.runtime.universe.Type = Person - * }}} - * WeakTypeTag contains concrete type arguments if available via existing tags: - * {{{ - * scala> def foo4[T:WeakTypeTag] = firstTypeArg( implicitly[WeakTypeTag[Container[T]]] ) - * foo4: [T](implicit evidence$1: reflect.runtime.universe.WeakTypeTag[T])reflect.runtime.universe.Type - * scala> foo4[Person] - * res1: reflect.runtime.universe.Type = Person - * }}} - * - * - * [[scala.reflect.api.Universe#TypeTag]] and [[scala.reflect.api.Universe#WeakTypeTag]] are path dependent on their universe. - * - * The default universe is [[scala.reflect.runtime.universe]] - * - * Type tags can be migrated to another universe given the corresponding mirror using - * - * {{{ - * tag.in( other_mirror ) - * }}} - * - * See [[scala.reflect.api.TypeTags#WeakTypeTag.in]] - * - * === WeakTypeTag vs TypeTag === - * - * Be careful with WeakTypeTag, because it will reify types even if these types are abstract. - * This makes it easy to forget to tag one of the methods in the call chain and discover it much later in the runtime - * by getting cryptic errors far away from their source. For example, consider the following snippet: + * A `TypeTag[T]` encapsulates the runtime type representation of some type `T`. + * Like [[scala.reflect.Manifest]], the prime use case of `TypeTag`s is to give access + * to erased types. However, `TypeTag`s should be considered to be a richer + * replacement of the pre-2.10 notion of a [[scala.reflect.Manifest Manifest]], that + * are, in addition, fully integrated with Scala reflection. + * + * There exist three different types of `TypeTags`: + * + * <ul> + * <li>[[scala.reflect.api.TypeTags#TypeTag]]. <br/>A full type descriptor of a Scala type. + * For example, a `TypeTag[List[String]]` contains all type information, + * in this case, of type `scala.List[String]`.</li> + * + * <li>[[scala.reflect.ClassTag]]. <br/>A partial type descriptor of a Scala type. For + * example, a `ClassTag[List[String]]` contains only the erased class + * type information, in this case, of type `scala.collection.immutable.List`. + * `ClassTag`s provide access only to the runtime class of a type. + * Analogous to [[scala.reflect.ClassManifest]]</li> + * + * <li>[[scala.reflect.api.TypeTags#WeakTypeTag]]. <br/>A type descriptor for abstract + * types (see description below).</li> + * </ul> + * + * Like [[scala.reflect.Manifest Manifest]]s, `TypeTag`s are always generated by the + * compiler, and can be obtained in three ways: + * + * === #1 Via the methods [[scala.reflect.api.TypeTags#typeTag typeTag]], + * [[scala.reflect#classTag classTag]], or [[scala.reflect.api.TypeTags#weakTypeTag weakTypeTag]] === + * + * For example: + * {{{ + * import scala.reflect.runtime.universe._ + * val tt = typeTag[Int] + * + * import scala.reflect._ + * val ct = classTag[String] + * }}} + * + * Each of these methods constructs a `TypeTag[T]` or `ClassTag[T]` for the given + * type argument `T`. + * + * === #2 Using an implicit parameter of type `TypeTag[T]`, `ClassTag[T]`, or `WeakTypeTag[T] + * + * For example: + * {{{ + * import scala.reflect.runtime.universe._ + * + * def paramInfo[T](x: T)(implicit tag: TypeTag[T]): Unit = { + * val targs = tag.tpe match { case TypeRef(_, _, args) => args } + * println(s"type of $x has type arguments $targs") + * } + * + * scala> paramInfo(42) + * type of 42 has type arguments List() + * + * scala> paramInfo(List(1, 2)) + * type of List(1, 2) has type arguments List(Int) + * }}} + * + * === #3 Context bound of a type parameter === + * + * ...on methods or classes. The above example can be implemented as follows: * * {{{ - * def bind[T: WeakTypeTag](name: String, value: T): IR.Result = bind((name, value)) - * def bind(p: NamedParam): IR.Result = bind(p.name, p.tpe, p.value) - * object NamedParam { - * implicit def namedValue[T: WeakTypeTag](name: String, x: T): NamedParam = apply(name, x) - * def apply[T: WeakTypeTag](name: String, x: T): NamedParam = new Typed[T](name, x) + * import scala.reflect.runtime.universe._ + * + * def paramInfo[T: TypeTag](x: T): Unit = { + * val targs = typeOf[T] match { case TypeRef(_, _, args) => args } + * println(s"type of $x has type arguments $targs") * } + * + * scala> paramInfo(42) + * type of 42 has type arguments List() + * + * scala> paramInfo(List(1, 2)) + * type of List(1, 2) has type arguments List(Int) * }}} + * + * === `WeakTypeTag`s === + * + *`WeakTypeTag[T]` generalizes `TypeTag[T]`. Unlike a regular `TypeTag`, components of + * its type representation can be references to type parameters or abstract types. + * However, `WeakTypeTag[T]` tries to be as concrete as possible, i.e. if type tags + * are available for the referenced type arguments or abstract types, they are used to + * embed the concrete types into the `WeakTypeTag[T]`. * - * This fragment of the Scala REPL implementation defines a `bind` function that carries a named value along with its type - * into the heart of the REPL. Using a [[scala.reflect.api.Universe#WeakTypeTag]] here is reasonable, because it is desirable - * to work with all types, even if they are type parameters or abstract type members. + * Continuing the example above: + * {{{ + * def weakParamInfo[T](x: T)(implicit tag: WeakTypeTag[T]): Unit = { + * val targs = tag.tpe match { case TypeRef(_, _, args) => args } + * println(s"type of $x has type arguments $targs") + * } + * + * scala> def foo[T] = weakParamInfo(List[T]()) + * foo: [T]=> Unit * - * However if any of the three `WeakTypeTag` context bounds is omitted, the resulting code will be incorrect, - * because the missing `WeakTypeTag` will be transparently generated by the compiler, carrying meaningless information. - * Most likely, this problem will manifest itself elsewhere, making debugging complicated. - * If `WeakTypeTag` context bounds were replaced with `TypeTag`, then such errors would be reported statically. - * But in that case we wouldn't be able to use `bind` in arbitrary contexts. + * scala> foo[Int] + * type of List() has type arguments List(T) + * }}} * - * === Backward compatibility with Manifests === + * === TypeTags and Manifests === * - * Type tags correspond loosely to manifests. + * `TypeTag`s correspond loosely to the pre-2.10 notion of + * [[scala.reflect.Manifest]]s. While [[scala.reflect.ClassTag]] corresponds to + * [[scala.reflect.ClassManifest]] and [[scala.reflect.api.TypeTags#TypeTag]] mostly + * corresponds to [[scala.reflect.Manifest]], other pre-2.10 `Manifest` types do not + * have a direct correspondence with a 2.10 "`Tag`" type. * - * More precisely: - * The previous notion of a [[scala.reflect.ClassManifest]] corresponds to a scala.reflect.ClassTag, - * The previous notion of a [[scala.reflect.Manifest]] corresponds to scala.reflect.runtime.universe.TypeTag, + * <ul> + * <li>'''[[scala.reflect.OptManifest]] is not supported.''' <br/>This is because `Tag`s + * can reify arbitrary types, so they are always available.<li> * - * In Scala 2.10, manifests are deprecated, so it's advisable to migrate them to tags, - * because manifests will probably be removed in the next major release. + * <li>'''There is no equivalent for [[scala.reflect.AnyValManifest]].''' <br/>Instead, one + * can compare their `Tag` with one of the base `Tag`s (defined in the corresponding + * companion objects) in order to find out whether or not it represents a primitive + * value class. Additionally, it's possible to simply use + * `<tag>.tpe.typeSymbol.isPrimitiveValueClass`.</li> * - * In most cases it will be enough to replace ClassManifest with ClassTag and Manifest with TypeTag. - * There are however a few caveats: + * <li>'''There are no replacement for factory methods defined in the `Manifest` + * companion objects'''. <br/>Instead, one could generate corresponding types using the + * reflection APIs provided by Java (for classes) and Scala (for types).</li> * - * 1) The notion of OptManifest is no longer supported. Tags can reify arbitrary types, so they are always available. + * <li>'''Certain manifest operations(i.e., <:<, >:> and typeArguments) are not + * supported.''' <br/>Instead, one culd use the reflection APIs provided by Java (for + * classes) and Scala (for types).</li> + *</ul> * - * 2) There's no equivalent for AnyValManifest. Consider comparing your tag with one of the base tags - * (defined in the corresponding companion objects) to find out whether it represents a primitive value class. - * You can also use `<tag>.tpe.typeSymbol.isPrimitiveValueClass` for that purpose (requires scala-reflect.jar). + * In Scala 2.10, [[scala.reflect.ClassManifest]]s are deprecated, and it is planned + * to deprecate [[scala.reflect.Manifest]] in favor of `TypeTag`s and `ClassTag`s in + * an upcoming point release. Thus, it is advisable to migrate any `Manifest`-based + * APIs to use `Tag`s. * - * 3) There's no replacement for factory methods defined in `ClassManifest` and `Manifest` companion objects. - * Consider assembling corresponding types using the reflection APIs provided by Java (for classes) and Scala (for types). + * For more information about `TypeTag`s, see the + * [[http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html Reflection Guide: TypeTags]] * - * 4) Certain manifest functions (such as `<:<`, `>:>` and `typeArguments`) weren't included in the tag API. - * Consider using the reflection APIs provided by Java (for classes) and Scala (for types) instead. + * @see [[scala.reflect.ClassTag]], [[scala.reflect.api.TypeTags#TypeTag]], [[scala.reflect.api.TypeTags#WeakTypeTag]] + * @group TypeTags Type Tags */ trait TypeTags { self: Universe => import definitions._ /** - * If an implicit value of type WeakTypeTag[T] is required, the compiler will create one. - * A reflective representation of T can be accessed via the tpe field. - * Components of T can be references to type parameters or abstract types. WeakTypeTag makes an effort to - * be as concrete as possible, i.e. if type tags are available for the referenced type arguments or abstract types, - * they are used to embed the concrete types into the WeakTypeTag. Otherwise the WeakTypeTag will contain a reference - * to an abstract type. This behavior can be useful, when one expects T to be possibly partially abstract, but - * requires special care to handle this case. If however T is expected to be fully known, use - * [[scala.reflect.api.Universe#TypeTag]] instead, which statically guarantees this property. + * If an implicit value of type `WeakTypeTag[T]` is required, the compiler will create one, + * and the reflective representation of `T` can be accessed via the `tpe` field. + * Components of `T` can be references to type parameters or abstract types. Note that `WeakTypeTag` + * makes an effort to be as concrete as possible, i.e. if `TypeTag`s are available for the referenced type arguments + * or abstract types, they are used to embed the concrete types into the WeakTypeTag. Otherwise the WeakTypeTag will + * contain a reference to an abstract type. This behavior can be useful, when one expects `T` to be perhaps be partially + * abstract, but requires special care to handle this case. However, if `T` is expected to be fully known, use + * [[scala.reflect.api.TypeTags#TypeTag]] instead, which statically guarantees this property. + * + * For more information about `TypeTag`s, see the + * [[http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html Reflection Guide: TypeTags]] * * @see [[scala.reflect.api.TypeTags]] + * @group TypeTags */ @annotation.implicitNotFound(msg = "No WeakTypeTag available for ${T}") trait WeakTypeTag[T] extends Equals with Serializable { /** - * Mirror corresponding to the universe of this WeakTypeTag. + * The underlying `Mirror` of this type tag. */ val mirror: Mirror + /** - * Migrates type tag to another universe. - * - * Type tags are path dependent on their universe. This methods allows migration - * given the mirror corresponding to the target universe. + * Migrates the expression into another mirror, jumping into a different universe if necessary. * * Migration means that all symbolic references to classes/objects/packages in the expression * will be re-resolved within the new mirror (typically using that mirror's classloader). */ - def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # WeakTypeTag[T] + def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # WeakTypeTag[T] /** * Reflective representation of type T. */ def tpe: Type - // case class accessories + // TODO how do I doc this? override def canEqual(x: Any) = x.isInstanceOf[WeakTypeTag[_]] + + // TODO how do I doc this? override def equals(x: Any) = x.isInstanceOf[WeakTypeTag[_]] && this.mirror == x.asInstanceOf[WeakTypeTag[_]].mirror && this.tpe == x.asInstanceOf[WeakTypeTag[_]].tpe + + // TODO how do I doc this? override def hashCode = mirror.hashCode * 31 + tpe.hashCode + + // TODO how do I doc this? override def toString = "WeakTypeTag[" + tpe + "]" } /** * Type tags corresponding to primitive types and constructor/extractor for WeakTypeTags. + * @group TypeTags */ object WeakTypeTag { val Byte : WeakTypeTag[scala.Byte] = TypeTag.Byte @@ -201,7 +231,7 @@ trait TypeTags { self: Universe => val Null : WeakTypeTag[scala.Null] = TypeTag.Null - def apply[T](mirror1: MirrorOf[self.type], tpec1: TypeCreator): WeakTypeTag[T] = + def apply[T](mirror1: scala.reflect.api.Mirror[self.type], tpec1: TypeCreator): WeakTypeTag[T] = tpec1(mirror1) match { case ByteTpe => WeakTypeTag.Byte.asInstanceOf[WeakTypeTag[T]] case ShortTpe => WeakTypeTag.Short.asInstanceOf[WeakTypeTag[T]] @@ -224,36 +254,48 @@ trait TypeTags { self: Universe => def unapply[T](ttag: WeakTypeTag[T]): Option[Type] = Some(ttag.tpe) } + /* @group TypeTags */ private class WeakTypeTagImpl[T](val mirror: Mirror, val tpec: TypeCreator) extends WeakTypeTag[T] { lazy val tpe: Type = tpec(mirror) - def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # WeakTypeTag[T] = { - val otherMirror1 = otherMirror.asInstanceOf[MirrorOf[otherMirror.universe.type]] + def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # WeakTypeTag[T] = { + val otherMirror1 = otherMirror.asInstanceOf[scala.reflect.api.Mirror[otherMirror.universe.type]] otherMirror.universe.WeakTypeTag[T](otherMirror1, tpec) } private def writeReplace(): AnyRef = new SerializedTypeTag(tpec, concrete = false) } /** - * A `TypeTag` is a [[scala.reflect.api.Universe#WeakTypeTag]] with the additional + * A `TypeTag` is a [[scala.reflect.api.TypeTags#WeakTypeTag]] with the additional * static guarantee that all type references are concrete, i.e. it does <b>not</b> contain any references to * unresolved type parameters or abstract types. * * @see [[scala.reflect.api.TypeTags]] + * @group TypeTags */ @annotation.implicitNotFound(msg = "No TypeTag available for ${T}") trait TypeTag[T] extends WeakTypeTag[T] with Equals with Serializable { /** * @inheritdoc */ - override def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # TypeTag[T] + override def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # TypeTag[T] - // case class accessories + /** TODO how do I doc this? */ override def canEqual(x: Any) = x.isInstanceOf[TypeTag[_]] + + /** TODO how do I doc this? */ override def equals(x: Any) = x.isInstanceOf[TypeTag[_]] && this.mirror == x.asInstanceOf[TypeTag[_]].mirror && this.tpe == x.asInstanceOf[TypeTag[_]].tpe + + /** TODO how do I doc this? */ override def hashCode = mirror.hashCode * 31 + tpe.hashCode + + /** TODO how do I doc this? */ override def toString = "TypeTag[" + tpe + "]" } + /** + * Type tags corresponding to primitive types and constructor/extractor for WeakTypeTags. + * @group TypeTags + */ object TypeTag { val Byte: TypeTag[scala.Byte] = new PredefTypeTag[scala.Byte] (ByteTpe, _.TypeTag.Byte) val Short: TypeTag[scala.Short] = new PredefTypeTag[scala.Short] (ShortTpe, _.TypeTag.Short) @@ -271,7 +313,7 @@ trait TypeTags { self: Universe => val Nothing: TypeTag[scala.Nothing] = new PredefTypeTag[scala.Nothing] (NothingTpe, _.TypeTag.Nothing) val Null: TypeTag[scala.Null] = new PredefTypeTag[scala.Null] (NullTpe, _.TypeTag.Null) - def apply[T](mirror1: MirrorOf[self.type], tpec1: TypeCreator): TypeTag[T] = + def apply[T](mirror1: scala.reflect.api.Mirror[self.type], tpec1: TypeCreator): TypeTag[T] = tpec1(mirror1) match { case ByteTpe => TypeTag.Byte.asInstanceOf[TypeTag[T]] case ShortTpe => TypeTag.Short.asInstanceOf[TypeTag[T]] @@ -294,20 +336,23 @@ trait TypeTags { self: Universe => def unapply[T](ttag: TypeTag[T]): Option[Type] = Some(ttag.tpe) } + /* @group TypeTags */ private class TypeTagImpl[T](mirror: Mirror, tpec: TypeCreator) extends WeakTypeTagImpl[T](mirror, tpec) with TypeTag[T] { - override def in[U <: Universe with Singleton](otherMirror: MirrorOf[U]): U # TypeTag[T] = { - val otherMirror1 = otherMirror.asInstanceOf[MirrorOf[otherMirror.universe.type]] + override def in[U <: Universe with Singleton](otherMirror: scala.reflect.api.Mirror[U]): U # TypeTag[T] = { + val otherMirror1 = otherMirror.asInstanceOf[scala.reflect.api.Mirror[otherMirror.universe.type]] otherMirror.universe.TypeTag[T](otherMirror1, tpec) } private def writeReplace(): AnyRef = new SerializedTypeTag(tpec, concrete = true) } + /* @group TypeTags */ private class PredefTypeCreator[T](copyIn: Universe => Universe#TypeTag[T]) extends TypeCreator { - def apply[U <: Universe with Singleton](m: MirrorOf[U]): U # Type = { + def apply[U <: Universe with Singleton](m: scala.reflect.api.Mirror[U]): U # Type = { copyIn(m.universe).asInstanceOf[U # TypeTag[T]].tpe } } + /* @group TypeTags */ private class PredefTypeTag[T](_tpe: Type, copyIn: Universe => Universe#TypeTag[T]) extends TypeTagImpl[T](rootMirror, new PredefTypeCreator(copyIn)) { override lazy val tpe: Type = _tpe private def writeReplace(): AnyRef = new SerializedTypeTag(tpec, concrete = true) @@ -315,22 +360,26 @@ trait TypeTags { self: Universe => /** * Shortcut for `implicitly[WeakTypeTag[T]]` + * @group TypeTags */ def weakTypeTag[T](implicit attag: WeakTypeTag[T]) = attag /** * Shortcut for `implicitly[TypeTag[T]]` + * @group TypeTags */ def typeTag[T](implicit ttag: TypeTag[T]) = ttag // big thanks to Viktor Klang for this brilliant idea! /** * Shortcut for `implicitly[WeakTypeTag[T]].tpe` + * @group TypeTags */ def weakTypeOf[T](implicit attag: WeakTypeTag[T]): Type = attag.tpe /** * Shortcut for `implicitly[TypeTag[T]].tpe` + * @group TypeTags */ def typeOf[T](implicit ttag: TypeTag[T]): Type = ttag.tpe } diff --git a/src/reflect/scala/reflect/api/Types.scala b/src/reflect/scala/reflect/api/Types.scala index af70c9e761..2267f21609 100644 --- a/src/reflect/scala/reflect/api/Types.scala +++ b/src/reflect/scala/reflect/api/Types.scala @@ -1,37 +1,102 @@ package scala.reflect package api -/** - * Defines the type hierachy for types. +/** A trait that defines types and operations on them. * - * Note: Because of implementation details, some type factories have return type `Type` - * instead of a more precise type. + * Type instances represent information about the type of a corresponding symbol. This includes its members + * (methods, fields, type parameters, nested classes, traits, etc) either declared directly or inherited, its base types, + * its erasure and so on. Types also provide operation to test for type conformance or euqivalence or for widening. * - * @see [[scala.reflect]] for a description on how the class hierarchy is encoded here. + * === Instantiating types === + * + * There are three ways to instantiate types. The simplest one involves the [[scala.reflect.api.TypeTags#typeOf]] method, + * which takes a type argument and produces a `Type` instance that represents that argument. For example, `typeOf[List[Int]]` + * produces a [[scala.reflect.api.Types#TypeRef]], which corresponds to a type `List` applied to a type argument `Int`. + * Method `typeOf` does not work for types with type parameters, such as `typeOf[List[A]]` where `A` is a type variable. + * In this case, use [[scala.reflect.api.TypeTags#weakTypeOf]] instead. Refer to [[scala.reflect.api.TypeTags the type tags page]] to find out + * more about this distinction. + * + * `typeOf` requires spelling out a type explicitly, but there's also a way to capture types implicitly with the [[scala.reflect.api.TypeTags#TypeTag]] + * context bound. See [[scala.reflect.api.TypeTags the type tags page]] for details. + * + * Finally, types can be instantiated manually using factory methods such as `typeRef` or `polyType`. + * This is necessary only in cases when `typeOf` or `typeTag` cannot be applied because the type cannot be spelt out + * in a Scala snippet, usually when writing macros. Manual construction requires deep knowledge of Scala compiler internals + * and should be avoided if possible. + * + * === Using types === + * + * Common operations on types are querying them for inner declarations or type conformance tests. + * + * Every type has `members` and `declarations` methods (along with their singular counterparts `member` and `declaration`), + * which provide the list of definitions associated with that type. For example, to look up the `map` method of `List`, one can + * write `typeOf[List[_]].member("map": TermName)`, getting a `MethodSymbol` + * + * Types expose `<:<` and `weak_<:<` methods to test for subtype relationships. The latter is an extension of the former - it also works + * with numeric types (for example, `Int <:< Long` is false, but `Int weak_<:< Long` is true). Unlike the subtype tests implemented by + * type tags, tests provided by `Type`s are aware of all the intricacies of the Scala type system and work correctly even for involved types. + * + * The vanilla `==` method should not be used to compare types for equality. Instead, one should always use the `=:=` method. + * Operator `=:=` knows about type aliases, e.g., `typeOf[scala.List[_]] =:= typeOf[scala.collection.immutable.List[_]]`. + * + * === Exploring types === + * + * {{{ + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> typeOf[List[_]].members.sorted take 5 foreach println + * constructor List + * method companion + * method :: + * method ::: + * method reverse_::: + * + * scala> def test[T: TypeTag](x: T) = s"I've been called for an x typed as \${typeOf[T]}" + * test: [T](x: T)(implicit evidence\$1: reflect.runtime.universe.TypeTag[T])String + * + * scala> test(2) + * res0 @ 3fc80fae: String = I've been called for an x typed as Int + * + * scala> test(List(2, "x")) + * res1 @ 10139edf: String = I've been called for an x typed as List[Any] + * }}} + * + * @groupname TypeCreators Types - Creation + * @groupname TypeOps Types - Operations + * + * @contentDiagram hideNodes "*Api" */ trait Types { self: Universe => /** The type of Scala types, and also Scala type signatures. * (No difference is internally made between the two). + * @template + * @group Types */ type Type >: Null <: TypeApi /** A tag that preserves the identity of the `Type` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeTagg: ClassTag[Type] /** This constant is used as a special value that indicates that no meaningful type exists. + * @group Types */ val NoType: Type /** This constant is used as a special value denoting the empty prefix in a path dependent type. * For instance `x.type` is represented as `SingleType(NoPrefix, <x>)`, where `<x>` stands for * the symbol for `x`. + * @group Types */ val NoPrefix: Type - /** The API of types + /** The API of types. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API */ abstract class TypeApi { /** The term symbol associated with the type, or `NoSymbol` for types @@ -92,7 +157,8 @@ trait Types { self: Universe => /** Does this type conform to given type argument `that`? */ def <:< (that: Type): Boolean - /** Is this type a weak subtype of that type? True also for numeric types, i.e. Int weak_<:< Long. + /** Does this type weakly conform to given type argument `that`, i.e., either conforms in terms of `<:<` or both are primitive number types + * that conform according to Section "Weak Conformance" in the spec. For example, Int weak_<:< Long. */ def weak_<:<(that: Type): Boolean @@ -186,11 +252,14 @@ trait Types { self: Universe => * x.type * }}} * as well as [[ConstantType constant types]]. + * @template + * @group Types */ type SingletonType >: Null <: Type /** A tag that preserves the identity of the `SingletonType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SingletonTypeTag: ClassTag[SingletonType] @@ -199,19 +268,25 @@ trait Types { self: Universe => * {{{ * C.this.type ThisType(C) * }}} + * @template + * @group Types */ type ThisType >: Null <: AnyRef with SingletonType with ThisTypeApi /** A tag that preserves the identity of the `ThisType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ThisTypeTag: ClassTag[ThisType] - /** The constructor/deconstructor for `ThisType` instances. */ + /** The constructor/deconstructor for `ThisType` instances. + * @group Extractors + */ val ThisType: ThisTypeExtractor /** An extractor class to create and pattern match with syntax `ThisType(sym)` * where `sym` is the class prefix of the this type. + * @group Extractors */ abstract class ThisTypeExtractor { /** @@ -221,8 +296,12 @@ trait Types { self: Universe => def unapply(tpe: ThisType): Option[Symbol] } - /** The API that all this types support */ + /** The API that all this types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait ThisTypeApi extends TypeApi { this: ThisType => + /** The underlying class symbol. */ val sym: Symbol } @@ -233,29 +312,41 @@ trait Types { self: Universe => * p.x.type SingleType(p.type, x) * x.type SingleType(NoPrefix, x) * }}} + * @template + * @group Types */ type SingleType >: Null <: AnyRef with SingletonType with SingleTypeApi /** A tag that preserves the identity of the `SingleType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SingleTypeTag: ClassTag[SingleType] - /** The constructor/deconstructor for `SingleType` instances. */ + /** The constructor/deconstructor for `SingleType` instances. + * @group Extractors + */ val SingleType: SingleTypeExtractor /** An extractor class to create and pattern match with syntax `SingleType(pre, sym)` * Here, `pre` is the prefix of the single-type, and `sym` is the stable value symbol * referred to by the single-type. + * @group Extractors */ abstract class SingleTypeExtractor { def apply(pre: Type, sym: Symbol): Type // not SingleTypebecause of implementation details def unapply(tpe: SingleType): Option[(Type, Symbol)] } - /** The API that all single types support */ + /** The API that all single types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait SingleTypeApi extends TypeApi { this: SingleType => + /** The type of the qualifier. */ val pre: Type + + /** The underlying symbol. */ val sym: Symbol } /** The `SuperType` type is not directly written, but arises when `C.super` is used @@ -266,27 +357,43 @@ trait Types { self: Universe => * Here, `thistpe` is the type of the corresponding this-type. For instance, * in the type arising from C.super, the `thistpe` part would be `ThisType(C)`. * `supertpe` is the type of the super class referred to by the `super`. + * @template + * @group Types */ type SuperType >: Null <: AnyRef with SingletonType with SuperTypeApi /** A tag that preserves the identity of the `SuperType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val SuperTypeTag: ClassTag[SuperType] - /** The constructor/deconstructor for `SuperType` instances. */ + /** The constructor/deconstructor for `SuperType` instances. + * @group Extractors + */ val SuperType: SuperTypeExtractor /** An extractor class to create and pattern match with syntax `SingleType(thistpe, supertpe)` + * @group Extractors */ abstract class SuperTypeExtractor { def apply(thistpe: Type, supertpe: Type): Type // not SuperTypebecause of implementation details def unapply(tpe: SuperType): Option[(Type, Type)] } - /** The API that all super types support */ + /** The API that all super types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait SuperTypeApi extends TypeApi { this: SuperType => + /** The type of the qualifier. + * See the example for [[scala.reflect.api.Trees#SuperExtractor]]. + */ val thistpe: Type + + /** The type of the selector. + * See the example for [[scala.reflect.api.Trees#SuperExtractor]]. + */ val supertpe: Type } /** The `ConstantType` type is not directly written in user programs, but arises as the type of a constant. @@ -295,27 +402,37 @@ trait Types { self: Universe => * 1 ConstantType(Constant(1)) * "abc" ConstantType(Constant("abc")) * }}} + * @template + * @group Types */ type ConstantType >: Null <: AnyRef with SingletonType with ConstantTypeApi /** A tag that preserves the identity of the `ConstantType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ConstantTypeTag: ClassTag[ConstantType] - /** The constructor/deconstructor for `ConstantType` instances. */ + /** The constructor/deconstructor for `ConstantType` instances. + * @group Extractors + */ val ConstantType: ConstantTypeExtractor /** An extractor class to create and pattern match with syntax `ConstantType(constant)` * Here, `constant` is the constant value represented by the type. + * @group Extractors */ abstract class ConstantTypeExtractor { def apply(value: Constant): ConstantType def unapply(tpe: ConstantType): Option[Constant] } - /** The API that all constant types support */ + /** The API that all constant types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait ConstantTypeApi extends TypeApi { this: ConstantType => + /** The compile-time constant underlying this type. */ val value: Constant } @@ -329,40 +446,61 @@ trait Types { self: Universe => * p.C TypeRef(p.type, C, Nil) * C TypeRef(NoPrefix, C, Nil) * }}} + * @template + * @group Types */ type TypeRef >: Null <: AnyRef with Type with TypeRefApi /** A tag that preserves the identity of the `TypeRef` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeRefTag: ClassTag[TypeRef] - /** The constructor/deconstructor for `TypeRef` instances. */ + /** The constructor/deconstructor for `TypeRef` instances. + * @group Extractors + */ val TypeRef: TypeRefExtractor /** An extractor class to create and pattern match with syntax `TypeRef(pre, sym, args)` * Here, `pre` is the prefix of the type reference, `sym` is the symbol * referred to by the type reference, and `args` is a possible empty list of * type argumenrts. + * @group Extractors */ abstract class TypeRefExtractor { def apply(pre: Type, sym: Symbol, args: List[Type]): Type // not TypeRefbecause of implementation details def unapply(tpe: TypeRef): Option[(Type, Symbol, List[Type])] } - /** The API that all type refs support */ + /** The API that all type refs support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait TypeRefApi extends TypeApi { this: TypeRef => + /** The prefix of the type reference. + * Is equal to `NoPrefix` if the prefix is not applicable. + */ val pre: Type + + /** The underlying symbol of the type reference. */ val sym: Symbol + + /** The arguments of the type reference. + * Is equal to `Nil` if the arguments are not provided. + */ val args: List[Type] } /** A subtype of Type representing refined types as well as `ClassInfo` signatures. + * @template + * @group Types */ type CompoundType >: Null <: AnyRef with Type /** A tag that preserves the identity of the `CompoundType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val CompoundTypeTag: ClassTag[CompoundType] @@ -373,20 +511,26 @@ trait Types { self: Universe => * P_1 with ... with P_m RefinedType(List(P_1, ..., P_m), Scope()) * { D_1; ...; D_n} RefinedType(List(AnyRef), Scope(D_1, ..., D_n)) * }}} + * @template + * @group Types */ type RefinedType >: Null <: AnyRef with CompoundType with RefinedTypeApi /** A tag that preserves the identity of the `RefinedType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val RefinedTypeTag: ClassTag[RefinedType] - /** The constructor/deconstructor for `RefinedType` instances. */ + /** The constructor/deconstructor for `RefinedType` instances. + * @group Extractors + */ val RefinedType: RefinedTypeExtractor /** An extractor class to create and pattern match with syntax `RefinedType(parents, decls)` * Here, `parents` is the list of parent types of the class, and `decls` is the scope * containing all declarations in the class. + * @group Extractors */ abstract class RefinedTypeExtractor { def apply(parents: List[Type], decls: Scope): RefinedType @@ -398,9 +542,15 @@ trait Types { self: Universe => def unapply(tpe: RefinedType): Option[(List[Type], Scope)] } - /** The API that all refined types support */ + /** The API that all refined types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait RefinedTypeApi extends TypeApi { this: RefinedType => + /** The superclasses of the type. */ val parents: List[Type] + + /** The scope that holds the definitions comprising the type. */ val decls: Scope } @@ -413,44 +563,63 @@ trait Types { self: Universe => * {{{ * ClassInfo(List(P_1, ..., P_m), Scope(D_1, ..., D_n), C) * }}} + * @template + * @group Types */ type ClassInfoType >: Null <: AnyRef with CompoundType with ClassInfoTypeApi /** A tag that preserves the identity of the `ClassInfoType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ClassInfoTypeTag: ClassTag[ClassInfoType] - /** The constructor/deconstructor for `ClassInfoType` instances. */ + /** The constructor/deconstructor for `ClassInfoType` instances. + * @group Extractors + */ val ClassInfoType: ClassInfoTypeExtractor /** An extractor class to create and pattern match with syntax `ClassInfo(parents, decls, clazz)` * Here, `parents` is the list of parent types of the class, `decls` is the scope * containing all declarations in the class, and `clazz` is the symbol of the class * itself. + * @group Extractors */ abstract class ClassInfoTypeExtractor { def apply(parents: List[Type], decls: Scope, typeSymbol: Symbol): ClassInfoType def unapply(tpe: ClassInfoType): Option[(List[Type], Scope, Symbol)] } - /** The API that all class info types support */ + /** The API that all class info types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait ClassInfoTypeApi extends TypeApi { this: ClassInfoType => + /** The superclasses of the class type. */ val parents: List[Type] + + /** The scope that holds the definitions comprising the class type. */ val decls: Scope + + /** The symbol underlying the class type. */ val typeSymbol: Symbol } /** The `MethodType` type signature is used to indicate parameters and result type of a method + * @template + * @group Types */ type MethodType >: Null <: AnyRef with Type with MethodTypeApi /** A tag that preserves the identity of the `MethodType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val MethodTypeTag: ClassTag[MethodType] - /** The constructor/deconstructor for `MethodType` instances. */ + /** The constructor/deconstructor for `MethodType` instances. + * @group Extractors + */ val MethodType: MethodTypeExtractor /** An extractor class to create and pattern match with syntax `MethodType(params, respte)` @@ -466,128 +635,183 @@ trait Types { self: Universe => * def f: Int * }}} * its type is a `NullaryMethodType`. + * @group Extractors */ abstract class MethodTypeExtractor { def apply(params: List[Symbol], resultType: Type): MethodType def unapply(tpe: MethodType): Option[(List[Symbol], Type)] } - /** The API that all method types support */ + /** The API that all method types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait MethodTypeApi extends TypeApi { this: MethodType => + /** The symbols that correspond to the parameters of the method. */ val params: List[Symbol] + + /** The result type of the method. */ val resultType: Type } /** The `NullaryMethodType` type signature is used for parameterless methods * with declarations of the form `def foo: T` + * @template + * @group Types */ type NullaryMethodType >: Null <: AnyRef with Type with NullaryMethodTypeApi /** A tag that preserves the identity of the `NullaryMethodType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val NullaryMethodTypeTag: ClassTag[NullaryMethodType] - /** The constructor/deconstructor for `NullaryMethodType` instances. */ + /** The constructor/deconstructor for `NullaryMethodType` instances. + * @group Extractors + */ val NullaryMethodType: NullaryMethodTypeExtractor /** An extractor class to create and pattern match with syntax `NullaryMethodType(resultType)`. * Here, `resultType` is the result type of the parameterless method. + * @group Extractors */ abstract class NullaryMethodTypeExtractor { def apply(resultType: Type): NullaryMethodType def unapply(tpe: NullaryMethodType): Option[(Type)] } - /** The API that all nullary method types support */ + /** The API that all nullary method types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait NullaryMethodTypeApi extends TypeApi { this: NullaryMethodType => + /** The result type of the method. */ val resultType: Type } /** The `PolyType` type signature is used for polymorphic methods * that have at least one type parameter. + * @template + * @group Types */ type PolyType >: Null <: AnyRef with Type with PolyTypeApi /** A tag that preserves the identity of the `PolyType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val PolyTypeTag: ClassTag[PolyType] - /** The constructor/deconstructor for `PolyType` instances. */ + /** The constructor/deconstructor for `PolyType` instances. + * @group Extractors + */ val PolyType: PolyTypeExtractor /** An extractor class to create and pattern match with syntax `PolyType(typeParams, resultType)`. * Here, `typeParams` are the type parameters of the method and `resultType` * is the type signature following the type parameters. + * @group Extractors */ abstract class PolyTypeExtractor { def apply(typeParams: List[Symbol], resultType: Type): PolyType def unapply(tpe: PolyType): Option[(List[Symbol], Type)] } - /** The API that all polymorphic types support */ + /** The API that all polymorphic types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait PolyTypeApi extends TypeApi { this: PolyType => + /** The symbols corresponding to the type parameters. */ val typeParams: List[Symbol] + + /** The underlying type. */ val resultType: Type } /** The `ExistentialType` type signature is used for existential types and * wildcard types. + * @template + * @group Types */ type ExistentialType >: Null <: AnyRef with Type with ExistentialTypeApi /** A tag that preserves the identity of the `ExistentialType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val ExistentialTypeTag: ClassTag[ExistentialType] - /** The constructor/deconstructor for `ExistentialType` instances. */ + /** The constructor/deconstructor for `ExistentialType` instances. + * @group Extractors + */ val ExistentialType: ExistentialTypeExtractor /** An extractor class to create and pattern match with syntax * `ExistentialType(quantified, underlying)`. * Here, `quantified` are the type variables bound by the existential type and `underlying` * is the type that's existentially quantified. + * @group Extractors */ abstract class ExistentialTypeExtractor { def apply(quantified: List[Symbol], underlying: Type): ExistentialType def unapply(tpe: ExistentialType): Option[(List[Symbol], Type)] } - /** The API that all existential types support */ + /** The API that all existential types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait ExistentialTypeApi extends TypeApi { this: ExistentialType => + /** The symbols corresponding to the `forSome` clauses of the existential type. */ val quantified: List[Symbol] + + /** The underlying type of the existential type. */ val underlying: Type } /** The `AnnotatedType` type signature is used for annotated types of the * for `<type> @<annotation>`. + * @template + * @group Types */ type AnnotatedType >: Null <: AnyRef with Type with AnnotatedTypeApi /** A tag that preserves the identity of the `AnnotatedType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val AnnotatedTypeTag: ClassTag[AnnotatedType] - /** The constructor/deconstructor for `AnnotatedType` instances. */ + /** The constructor/deconstructor for `AnnotatedType` instances. + * @group Extractors + */ val AnnotatedType: AnnotatedTypeExtractor /** An extractor class to create and pattern match with syntax * `AnnotatedType(annotations, underlying, selfsym)`. * Here, `annotations` are the annotations decorating the underlying type `underlying`. * `selfSym` is a symbol representing the annotated type itself. + * @group Extractors */ abstract class AnnotatedTypeExtractor { def apply(annotations: List[Annotation], underlying: Type, selfsym: Symbol): AnnotatedType def unapply(tpe: AnnotatedType): Option[(List[Annotation], Type, Symbol)] } - /** The API that all annotated types support */ + /** The API that all annotated types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait AnnotatedTypeApi extends TypeApi { this: AnnotatedType => + /** The annotations. */ val annotations: List[Annotation] + + /** The annotee. */ val underlying: Type + + /** A symbol that represents the annotated type itself. */ val selfsym: Symbol } @@ -600,34 +824,51 @@ trait Types { self: Universe => * T >: L TypeBounds(L, Any) * T <: U TypeBounds(Nothing, U) * }}} + * @template + * @group Types */ type TypeBounds >: Null <: AnyRef with Type with TypeBoundsApi /** A tag that preserves the identity of the `TypeBounds` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val TypeBoundsTag: ClassTag[TypeBounds] - /** The constructor/deconstructor for `TypeBounds` instances. */ + /** The constructor/deconstructor for `TypeBounds` instances. + * @group Extractors + */ val TypeBounds: TypeBoundsExtractor /** An extractor class to create and pattern match with syntax `TypeBound(lower, upper)` * Here, `lower` is the lower bound of the `TypeBounds` pair, and `upper` is * the upper bound. + * @group Extractors */ abstract class TypeBoundsExtractor { def apply(lo: Type, hi: Type): TypeBounds def unapply(tpe: TypeBounds): Option[(Type, Type)] } - /** The API that all type bounds support */ + /** The API that all type bounds support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait TypeBoundsApi extends TypeApi { this: TypeBounds => + /** The lower bound. + * Is equal to `definitions.NothingTpe` if not specified explicitly. + */ val lo: Type + + /** The upper bound. + * Is equal to `definitions.AnyTpe` if not specified explicitly. + */ val hi: Type } /** An object representing an unknown type, used during type inference. * If you see WildcardType outside of inference it is almost certainly a bug. + * @group Types */ val WildcardType: Type @@ -640,55 +881,77 @@ trait Types { self: Universe => * the name of a method in the converted type, a HasMethodMatching * type is created: a MethodType with parameters typed as * BoundedWildcardTypes. + * @template + * @group Types */ type BoundedWildcardType >: Null <: AnyRef with Type with BoundedWildcardTypeApi /** A tag that preserves the identity of the `BoundedWildcardType` abstract type from erasure. * Can be used for pattern matching, instance tests, serialization and likes. + * @group Tags */ implicit val BoundedWildcardTypeTag: ClassTag[BoundedWildcardType] - /** The constructor/deconstructor for `BoundedWildcardType` instances. */ + /** The constructor/deconstructor for `BoundedWildcardType` instances. + * @group Extractors + */ val BoundedWildcardType: BoundedWildcardTypeExtractor /** An extractor class to create and pattern match with syntax `BoundedWildcardTypeExtractor(bounds)` * with `bounds` denoting the type bounds. + * @group Extractors */ abstract class BoundedWildcardTypeExtractor { def apply(bounds: TypeBounds): BoundedWildcardType def unapply(tpe: BoundedWildcardType): Option[TypeBounds] } - /** The API that all this types support */ + /** The API that all this types support. + * The main source of information about types is the [[scala.reflect.api.Types]] page. + * @group API + */ trait BoundedWildcardTypeApi extends TypeApi { this: BoundedWildcardType => + /** Type bounds for the wildcard type. */ val bounds: TypeBounds } - /** The least upper bound of a list of types, as determined by `<:<`. */ + /** The least upper bound of a list of types, as determined by `<:<`. + * @group TypeOps + */ def lub(xs: List[Type]): Type - /** The greatest lower bound of a list of types, as determined by `<:<`. */ + /** The greatest lower bound of a list of types, as determined by `<:<`. + * @group TypeOps + */ def glb(ts: List[Type]): Type // Creators --------------------------------------------------------------- // too useful and too non-trivial to be left out of public API - /** The canonical creator for single-types */ + /** The canonical creator for single-types + * @group TypeCreators + */ def singleType(pre: Type, sym: Symbol): Type - /** the canonical creator for a refined type with a given scope */ + /** the canonical creator for a refined type with a given scope + * @group TypeCreators + */ def refinedType(parents: List[Type], owner: Symbol, decls: Scope, pos: Position): Type /** The canonical creator for a refined type with an initially empty scope. + * @group TypeCreators */ def refinedType(parents: List[Type], owner: Symbol): Type /** The canonical creator for typerefs + * @group TypeCreators */ def typeRef(pre: Type, sym: Symbol, args: List[Type]): Type /** A creator for intersection type where intersections of a single type are - * replaced by the type itself. */ + * replaced by the type itself. + * @group TypeCreators + */ def intersectionType(tps: List[Type]): Type /** A creator for intersection type where intersections of a single type are @@ -696,15 +959,19 @@ trait Types { self: Universe => * * !!! Repeated parent classes are not merged - is this a bug in the * comment or in the code? + * @group TypeCreators */ def intersectionType(tps: List[Type], owner: Symbol): Type - /** A creator for type applications */ + /** A creator for type applications + * @group Types + */ def appliedType(tycon: Type, args: List[Type]): Type /** A creator for type parameterizations that strips empty type parameter lists. * Use this factory method to indicate the type has kind * (it's a polymorphic value) * until we start tracking explicit kinds equivalent to typeFun (except that the latter requires tparams nonEmpty). + * @group Types */ def polyType(tparams: List[Symbol], tpe: Type): Type @@ -725,6 +992,7 @@ trait Types { self: Universe => * The abstraction drops all type parameters that are not directly or * indirectly referenced by type `tpe1`. If there are no remaining type * parameters, simply returns result type `tpe`. + * @group TypeCreators */ def existentialAbstraction(tparams: List[Symbol], tpe0: Type): Type } diff --git a/src/reflect/scala/reflect/api/Universe.scala b/src/reflect/scala/reflect/api/Universe.scala index 7d0f6cf0d6..7d1f5c9df1 100644 --- a/src/reflect/scala/reflect/api/Universe.scala +++ b/src/reflect/scala/reflect/api/Universe.scala @@ -1,6 +1,58 @@ package scala.reflect package api +/** + * `Universe` provides a complete set of reflection operations which make it possible for one + * to reflectively inspect Scala type relations, such as membership or subtyping. + * + * [[scala.reflect.api.Universe]] has two specialized sub-universes for different scenarios. + * [[scala.reflect.api.JavaUniverse]] adds operations that link symbols and types to the underlying + * classes and runtime values of a JVM instance-- this can be thought of as the `Universe` that + * should be used for all typical use-cases of Scala reflection. [[scala.reflect.macros.Universe]] + * adds operations which allow macros to access selected compiler data structures and operations-- + * this type of `Universe` should only ever exist within the implementation of a Scala macro. + * + * `Universe` can be thought of as the entry point to Scala reflection. It mixes-in, and thus provides + * an interface to the following main types: + * + * - [[scala.reflect.api.Types#Type Types]] represent types + * - [[scala.reflect.api.Symbols#Symbol Symbols]] represent definitions + * - [[scala.reflect.api.Trees#Tree Trees]] represent abstract syntax trees + * - [[scala.reflect.api.Names#Name Names]] represent term and type names + * - [[scala.reflect.api.Annotations#Annotation Annotations]] represent annotations + * - [[scala.reflect.api.Positions#Position Positions]] represent source positions of tree nodes + * - [[scala.reflect.api.FlagSets#FlagSet FlagSet]] represent sets of flags that apply to symbols and + * definition trees + * - [[scala.reflect.api.Constants#Constant Constants]] represent compile-time constants. + * + * To obtain a `Universe` to use with Scala runtime reflection, simply make sure to use or import + * `scala.reflect.runtime.universe._` + * {{{ + * scala> import scala.reflect.runtime.universe._ + * import scala.reflect.runtime.universe._ + * + * scala> typeOf[List[Int]] + * res0: reflect.runtime.universe.Type = scala.List[Int] + * + * scala> typeOf[Either[String, Int]] + * res1: reflect.runtime.universe.Type = scala.Either[String,Int] + * }}} + * + * To obtain a `Universe` for use within a Scala macro, use [[scala.reflect.macros.Context#universe]]. For example: + * {{{ + * def printf(format: String, params: Any*): Unit = macro impl + * def impl(c: Context)(format: c.Expr[String], params: c.Expr[Any]*): c.Expr[Unit] = { + * import c.universe._ + * ... + * } + * }}} + * + * For more information about `Universe`s, see the [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Universes]] + * + * @groupprio Universe -1 + * + * @contentDiagram hideNodes "*Api" + */ abstract class Universe extends Symbols with Types with FlagSets @@ -20,61 +72,20 @@ abstract class Universe extends Symbols with Printers with Importers { - /** Produce the abstract syntax tree representing the given Scala expression. + /** Use `refiy` to produce the abstract syntax tree representing a given Scala expression. * - * For example + * For example: * * {{{ * val five = reify{ 5 } // Literal(Constant(5)) - * reify{ 2 + 4 } // Apply( Select( Literal(Constant(2)), newTermName("$plus")), List( Literal(Constant(4)) ) ) - * reify{ five.splice + 4 } // Apply( Select( Literal(Constant(5)), newTermName("$plus")), List( Literal(Constant(4)) ) ) + * reify{ 2 + 4 } // Apply( Select( Literal(Constant(2)), newTermName("\$plus")), List( Literal(Constant(4)) ) ) + * reify{ five.splice + 4 } // Apply( Select( Literal(Constant(5)), newTermName("\$plus")), List( Literal(Constant(4)) ) ) * }}} * * The produced tree is path dependent on the Universe `reify` was called from. * - * Use [[scala.reflect.api.Exprs#Expr.splice]] to embed an existing expression into a reify call. Use [[Expr]] to turn a [[Tree]] into an expression that can be spliced. - * - * == Further info and implementation details == - * - * `reify` is implemented as a macro, which given an expression, generates a tree that when compiled and executed produces the original tree. - * - * For instance in `reify{ x + 1 }` the macro `reify` receives the abstract syntax tree of `x + 1` as its argument, which is - * - * {{{ - * Apply(Select(Ident("x"), "+"), List(Literal(Constant(1)))) - * }}} - * - * and returns a tree, which produces the tree above, when compiled and executed. So in other terms, the refiy call expands to something like - * - * {{{ - * val $u: u.type = u // where u is a reference to the Universe that calls the reify - * $u.Expr[Int]($u.Apply($u.Select($u.Ident($u.newFreeVar("x", <Int>, x), "+"), List($u.Literal($u.Constant(1)))))) - * }}} - * - * ------ - * - * Reification performs expression splicing (when processing Expr.splice) - * and type splicing (for every type T that has a TypeTag[T] implicit in scope): - * - * {{{ - * val two = mirror.reify(2) // Literal(Constant(2)) - * val four = mirror.reify(two.splice + two.splice) // Apply(Select(two.tree, newTermName("$plus")), List(two.tree)) - * - * def macroImpl[T](c: Context) = { - * ... - * // T here is just a type parameter, so the tree produced by reify won't be of much use in a macro expansion - * // however, if T were annotated with c.WeakTypeTag (which would declare an implicit parameter for macroImpl) - * // then reification would substitute T with the TypeTree that was used in a TypeApply of this particular macro invocation - * val factory = c.reify{ new Queryable[T] } - * ... - * } - * }}} - * - * The transformation looks mostly straightforward, but it has its tricky parts: - * - Reifier retains symbols and types defined outside the reified tree, however - * locally defined entities get erased and replaced with their original trees - * - Free variables are detected and wrapped in symbols of the type `FreeTermSymbol` or `FreeTypeSymbol` - * - Mutable variables that are accessed from a local function are wrapped in refs + * Use [[scala.reflect.api.Exprs#Expr.splice]] to embed an existing expression into a `reify` call. Use [[Expr]] to turn a [[Tree]] into an expression that can be spliced. + * @group Universe */ // implementation is hardwired to `scala.reflect.reify.Taggers` // using the mechanism implemented in `scala.tools.reflect.FastTrack` diff --git a/src/reflect/scala/reflect/api/package.scala b/src/reflect/scala/reflect/api/package.scala index 0b2a43936e..bd9c72a839 100644 --- a/src/reflect/scala/reflect/api/package.scala +++ b/src/reflect/scala/reflect/api/package.scala @@ -2,72 +2,35 @@ package scala.reflect import scala.reflect.api.{Universe => ApiUniverse} -/** - * The main package of Scala's reflection library. - * - * The reflection library is structured according to the 'cake pattern'. The main layer - * resides in package [[scala.reflect.api]] and defines an interface to the following main types: - * - * - [[scala.reflect.api.Types#Type Types]] represent types - * - [[scala.reflect.api.Symbols#Symbol Symbols]] represent definitions - * - [[scala.reflect.api.Trees#Tree Trees]] represent abstract syntax trees - * - [[scala.reflect.api.Names#Name Names]] represent term and type names - * - [[scala.reflect.api.Annotations#Annotation Annotations]] represent annotations - * - [[scala.reflect.api.Positions#Position Positions]] represent source positions of tree nodes - * - [[scala.reflect.api.FlagSets#FlagSet FlagSet]] represent sets of flags that apply to symbols and - * definition trees - * - [[scala.reflect.api.Constants#Constant Constants]] represent compile-time constants. - * - * Each of these types are defined in their own enclosing traits, which are ultimately all inherited by class - * [[scala.reflect.api.Universe Universe]]. The main universe defines a minimal interface to the above types. - * Universes that provide additional functionality such as deeper introspection or runtime code generation, - * are defined in packages [[scala.reflect.api]] and `scala.tools.reflect`. - * - * The cake pattern employed here requires to write certain Scala idioms with more indirections that usual. - * What follows is a description of these indirections, which will help to navigate the Scaladocs easily. - * - * For instance, consider the base type of all abstract syntax trees: [[scala.reflect.api.Trees#Tree]]. - * This type is not a class but is abstract and has an upper bound of [[scala.reflect.api.Trees#TreeApi]], - * which is a class defining the minimal base interface for all trees. - * - * For a more interesting tree type, consider [[scala.reflect.api.Trees#If]] representing if-expressions. - * It is defined next to a value `If` of type [[scala.reflect.api.Trees#IfExtractor]]. - * This value serves as the companion object defining a factory method `apply` and a corresponding `unapply` - * for pattern matching. - * - * {{{ - * import scala.reflect.runtime.universe._ - * val cond = reify{ condition }.tree // <- just some tree representing a condition - * val body = Literal(Constant(1)) - * val other = Literal(Constant(2)) - * val iftree = If(cond,body,other) - * }}} - * - * is equivalent to - * - * {{{ - * import scala.reflect.runtime.universe._ - * val iftree = reify{ if( condition ) 1 else 2 }.tree - * }}} - * - * and can be pattern matched as - * - * {{{ - * iftree match { case If(cond,body,other) => ... } - * }}} - * - * Moreover, there is an implicit value [[scala.reflect.api.Trees#IfTag]] of type - * `ClassTag[If]` that is used by the Scala compiler so that we can indeed pattern match on `If`: - * {{{ - * iftree match { case _:If => ... } - * }}} - * Without the given implicit value, this pattern match would raise an "unchecked" warning at compile time - * since `If` is an abstract type that gets erased at runtime. See [[scala.reflect.ClassTag]] for details. - * - * To summarize: each tree type `X` (and similarly for other types such as `Type` or `Symbol`) is represented - * by an abstract type `X`, optionally together with a class `XApi` that defines `X`'s' interface. - * `X`'s companion object, if it exists, is represented by a value `X` that is of type `XExtractor`. - * Moreover, for each type `X`, there is a value `XTag` of type `ClassTag[X]` that allows to pattern match on `X`. +/** The Scala Reflection API (located in scala-reflect.jar). + * + * In Scala 2.10.0, the Scala Reflection API and its implementation have an "experimental" status. + * This means that the API and the docs are not complete and can be changed in binary- and source-incompatible + * manner in 2.10.1. This also means that the implementation has some known issues. + * + * The following types are the backbone of the Scala Reflection API, and serve as a good starting point + * for information about Scala Reflection: + * + * - [[scala.reflect.api.Symbols]] + * - [[scala.reflect.api.Types]] + * - [[scala.reflect.api.Mirrors]] + * - [[scala.reflect.api.Universe]] + * + * For more information about Scala Reflection, see the + * [[http://docs.scala-lang.org/overviews/reflection/overview.html Reflection Guide]] + * + * @groupprio API 9 + * @groupprio Extractors 10 + * @groupprio Tags 11 + * @groupdesc API The methods available for each reflection entity, without the implementation. Since the + * reflection entities are later overridden by runtime reflection and macros, their API + * counterparts guarantee a minimum set of methods that are implemented. + * @groupdesc Extractors Extractors provide the machinery necessary to allow pattern matching and construction of + * reflection entities that is similar to case classes, although the entities are only abstract + * types that are later overridden. + * @groupdesc Tags Implicit values that provide [[scala.reflect.ClassTag `ClassTags`]] for the reflection + * classes. These are abstract in the interface but are later filled in to provide ClassTags + * for the either the runtime reflection or macros entities, depending on the use. */ package object api { diff --git a/src/reflect/scala/reflect/internal/AnnotationCheckers.scala b/src/reflect/scala/reflect/internal/AnnotationCheckers.scala index 9f102c5712..05f80c8a0c 100644 --- a/src/reflect/scala/reflect/internal/AnnotationCheckers.scala +++ b/src/reflect/scala/reflect/internal/AnnotationCheckers.scala @@ -47,6 +47,13 @@ trait AnnotationCheckers { * before. If the implementing class cannot do the adaptiong, it * should return the tree unchanged.*/ def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = tree + + /** Adapt the type of a return expression. The decision of an annotation checker + * whether the type should be adapted is based on the type of the expression + * which is returned, as well as the result type of the method (pt). + * By default, this method simply returns the passed `default` type. + */ + def adaptTypeOfReturn(tree: Tree, pt: Type, default: => Type): Type = default } // Syncnote: Annotation checkers inaccessible to reflection, so no sync in var necessary. @@ -118,4 +125,23 @@ trait AnnotationCheckers { annotationCheckers.foldLeft(tree)((tree, checker) => checker.adaptAnnotations(tree, mode, pt)) } + + /** Let a registered annotation checker adapt the type of a return expression. + * Annotation checkers that cannot do the adaptation should simply return + * the `default` argument. + * + * Note that the result is undefined if more than one annotation checker + * returns an adapted type which is not a subtype of `default`. + */ + def adaptTypeOfReturn(tree: Tree, pt: Type, default: => Type): Type = { + val adaptedTypes = annotationCheckers flatMap { checker => + val adapted = checker.adaptTypeOfReturn(tree, pt, default) + if (!(adapted <:< default)) List(adapted) + else List() + } + adaptedTypes match { + case fst :: _ => fst + case List() => default + } + } } diff --git a/src/reflect/scala/reflect/internal/AnnotationInfos.scala b/src/reflect/scala/reflect/internal/AnnotationInfos.scala index 3bd7f4f4fa..46e4329b2e 100644 --- a/src/reflect/scala/reflect/internal/AnnotationInfos.scala +++ b/src/reflect/scala/reflect/internal/AnnotationInfos.scala @@ -30,7 +30,7 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => /** Symbols of any @throws annotations on this symbol. */ def throwsAnnotations(): List[Symbol] = annotations collect { - case AnnotationInfo(tp, Literal(Constant(tpe: Type)) :: Nil, _) if tp.typeSymbol == ThrowsClass => tpe.typeSymbol + case ThrownException(exc) => exc } /** Tests for, get, or remove an annotation */ @@ -325,4 +325,23 @@ trait AnnotationInfos extends api.Annotations { self: SymbolTable => implicit val AnnotationTag = ClassTag[AnnotationInfo](classOf[AnnotationInfo]) object UnmappableAnnotation extends CompleteAnnotationInfo(NoType, Nil, Nil) + + /** Extracts symbol of thrown exception from AnnotationInfo. + * + * Supports both “old-style” `@throws(classOf[Exception])` + * as well as “new-stye” `@throws[Exception]("cause")` annotations. + */ + object ThrownException { + def unapply(ann: AnnotationInfo): Option[Symbol] = + ann match { + case AnnotationInfo(tpe, _, _) if tpe.typeSymbol != ThrowsClass => + None + // old-style: @throws(classOf[Exception]) (which is throws[T](classOf[Exception])) + case AnnotationInfo(_, List(Literal(Constant(tpe: Type))), _) => + Some(tpe.typeSymbol) + // new-style: @throws[Exception], @throws[Exception]("cause") + case AnnotationInfo(TypeRef(_, _, args), _, _) => + Some(args.head.typeSymbol) + } + } } diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index b607f8cad9..2bc9f02758 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -517,7 +517,7 @@ trait Definitions extends api.StandardDefinitions { def ApiUniverseReify = if (ApiUniverseClass != NoSymbol) getMemberMethod(ApiUniverseClass, nme.reify) else NoSymbol lazy val JavaUniverseClass = getClassIfDefined("scala.reflect.api.JavaUniverse") // defined in scala-reflect.jar, so we need to be careful - lazy val MirrorOfClass = getClassIfDefined("scala.reflect.api.MirrorOf") // defined in scala-reflect.jar, so we need to be careful + lazy val MirrorClass = getClassIfDefined("scala.reflect.api.Mirror") // defined in scala-reflect.jar, so we need to be careful lazy val TypeCreatorClass = getClassIfDefined("scala.reflect.api.TypeCreator") // defined in scala-reflect.jar, so we need to be careful lazy val TreeCreatorClass = getClassIfDefined("scala.reflect.api.TreeCreator") // defined in scala-reflect.jar, so we need to be careful @@ -954,7 +954,7 @@ trait Definitions extends api.StandardDefinitions { lazy val ScalaNoInlineClass = requiredClass[scala.noinline] lazy val SerialVersionUIDAttr = requiredClass[scala.SerialVersionUID] lazy val SpecializedClass = requiredClass[scala.specialized] - lazy val ThrowsClass = requiredClass[scala.throws] + lazy val ThrowsClass = requiredClass[scala.throws[_]] lazy val TransientAttr = requiredClass[scala.transient] lazy val UncheckedClass = requiredClass[scala.unchecked] lazy val UnspecializedClass = requiredClass[scala.annotation.unspecialized] diff --git a/src/reflect/scala/reflect/internal/FlagSets.scala b/src/reflect/scala/reflect/internal/FlagSets.scala index 6270416d4f..6a3b6870a0 100644 --- a/src/reflect/scala/reflect/internal/FlagSets.scala +++ b/src/reflect/scala/reflect/internal/FlagSets.scala @@ -17,8 +17,6 @@ trait FlagSets extends api.FlagSets { self: SymbolTable => val NoFlags: FlagSet = 0L - trait FlagValues extends FlagValuesApi - object Flag extends FlagValues { val TRAIT : FlagSet = Flags.TRAIT val INTERFACE : FlagSet = Flags.INTERFACE diff --git a/src/reflect/scala/reflect/internal/Flags.scala b/src/reflect/scala/reflect/internal/Flags.scala index 0eb839479a..bb454b1df7 100644 --- a/src/reflect/scala/reflect/internal/Flags.scala +++ b/src/reflect/scala/reflect/internal/Flags.scala @@ -296,6 +296,12 @@ class Flags extends ModifierFlags { /** These flags are pickled */ final val PickledFlags = InitialFlags & ~FlagsNotPickled + /** If we have a top-level class or module + * and someone asks us for a flag not in TopLevelPickledFlags, + * then we don't need unpickling to give a definite answer. + */ + final val TopLevelPickledFlags = PickledFlags & ~(MODULE | METHOD | PACKAGE | PARAM | EXISTENTIAL) + def getterFlags(fieldFlags: Long): Long = ACCESSOR + ( if ((fieldFlags & MUTABLE) != 0) fieldFlags & ~MUTABLE & ~PRESUPER else fieldFlags & ~PRESUPER | STABLE diff --git a/src/reflect/scala/reflect/internal/HasFlags.scala b/src/reflect/scala/reflect/internal/HasFlags.scala index 62c8ed702b..4a3663b8ea 100644 --- a/src/reflect/scala/reflect/internal/HasFlags.scala +++ b/src/reflect/scala/reflect/internal/HasFlags.scala @@ -99,6 +99,7 @@ trait HasFlags { def isLabel = hasAllFlags(LABEL | METHOD) && !hasAccessorFlag def isLazy = hasFlag(LAZY) def isLifted = hasFlag(LIFTED) + def isMacro = hasFlag(MACRO) def isMutable = hasFlag(MUTABLE) def isOverride = hasFlag(OVERRIDE) def isParamAccessor = hasFlag(PARAMACCESSOR) @@ -109,6 +110,7 @@ trait HasFlags { def isProtectedLocal = hasAllFlags(ProtectedLocal) def isPublic = hasNoFlags(PRIVATE | PROTECTED) && !hasAccessBoundary def isSealed = hasFlag(SEALED) + def isSpecialized = hasFlag(SPECIALIZED) def isSuperAccessor = hasFlag(SUPERACCESSOR) def isSynthetic = hasFlag(SYNTHETIC) def isTrait = hasFlag(TRAIT) && !hasFlag(PARAM) diff --git a/src/reflect/scala/reflect/internal/Importers.scala b/src/reflect/scala/reflect/internal/Importers.scala index c116928d37..43902c1930 100644 --- a/src/reflect/scala/reflect/internal/Importers.scala +++ b/src/reflect/scala/reflect/internal/Importers.scala @@ -1,6 +1,8 @@ package scala.reflect package internal + import scala.collection.mutable.WeakHashMap +import scala.ref.WeakReference // SI-6241: move importers to a mirror trait Importers extends api.Importers { self: SymbolTable => @@ -26,8 +28,12 @@ trait Importers extends api.Importers { self: SymbolTable => val from: SymbolTable - lazy val symMap: WeakHashMap[from.Symbol, Symbol] = new WeakHashMap - lazy val tpeMap: WeakHashMap[from.Type, Type] = new WeakHashMap + protected lazy val symMap = new Cache[from.Symbol, Symbol]() + protected lazy val tpeMap = new Cache[from.Type, Type]() + protected class Cache[K <: AnyRef, V <: AnyRef] extends WeakHashMap[K, WeakReference[V]] { + def weakGet(key: K): Option[V] = this get key flatMap WeakReference.unapply + def weakUpdate(key: K, value: V) = this.update(key, WeakReference(value)) + } // fixups and maps prevent stackoverflows in importer var pendingSyms = 0 @@ -44,8 +50,10 @@ trait Importers extends api.Importers { self: SymbolTable => object reverse extends from.StandardImporter { val from: self.type = self - for ((fromsym, mysym) <- StandardImporter.this.symMap) symMap += ((mysym, fromsym)) - for ((fromtpe, mytpe) <- StandardImporter.this.tpeMap) tpeMap += ((mytpe, fromtpe)) + // FIXME this and reverse should be constantly kept in sync + // not just synced once upon the first usage of reverse + for ((fromsym, WeakReference(mysym)) <- StandardImporter.this.symMap) symMap += ((mysym, WeakReference(fromsym))) + for ((fromtpe, WeakReference(mytpe)) <- StandardImporter.this.tpeMap) tpeMap += ((mytpe, WeakReference(fromtpe))) } // todo. careful import of positions @@ -53,70 +61,70 @@ trait Importers extends api.Importers { self: SymbolTable => pos.asInstanceOf[Position] def importSymbol(sym0: from.Symbol): Symbol = { - def doImport(sym: from.Symbol): Symbol = { - if (symMap.contains(sym)) - return symMap(sym) - - val myowner = importSymbol(sym.owner) - val mypos = importPosition(sym.pos) - val myname = importName(sym.name).toTermName - val myflags = sym.flags - def linkReferenced(mysym: TermSymbol, x: from.TermSymbol, op: from.Symbol => Symbol): Symbol = { - symMap(x) = mysym - mysym.referenced = op(x.referenced) - mysym - } - val mysym = sym match { - case x: from.MethodSymbol => - linkReferenced(myowner.newMethod(myname, mypos, myflags), x, importSymbol) - case x: from.ModuleSymbol => - linkReferenced(myowner.newModuleSymbol(myname, mypos, myflags), x, importSymbol) - case x: from.FreeTermSymbol => - newFreeTermSymbol(importName(x.name).toTermName, x.value, x.flags, x.origin) setInfo importType(x.info) - case x: from.FreeTypeSymbol => - newFreeTypeSymbol(importName(x.name).toTypeName, x.flags, x.origin) - case x: from.TermSymbol => - linkReferenced(myowner.newValue(myname, mypos, myflags), x, importSymbol) - case x: from.TypeSkolem => - val origin = x.unpackLocation match { - case null => null - case y: from.Tree => importTree(y) - case y: from.Symbol => importSymbol(y) + def doImport(sym: from.Symbol): Symbol = + symMap weakGet sym match { + case Some(result) => result + case _ => + val myowner = importSymbol(sym.owner) + val mypos = importPosition(sym.pos) + val myname = importName(sym.name).toTermName + val myflags = sym.flags + def linkReferenced(mysym: TermSymbol, x: from.TermSymbol, op: from.Symbol => Symbol): Symbol = { + symMap.weakUpdate(x, mysym) + mysym.referenced = op(x.referenced) + mysym } - myowner.newTypeSkolemSymbol(myname.toTypeName, origin, mypos, myflags) - case x: from.ModuleClassSymbol => - val mysym = myowner.newModuleClass(myname.toTypeName, mypos, myflags) - symMap(x) = mysym - mysym.sourceModule = importSymbol(x.sourceModule) - mysym - case x: from.ClassSymbol => - val mysym = myowner.newClassSymbol(myname.toTypeName, mypos, myflags) - symMap(x) = mysym - if (sym.thisSym != sym) { - mysym.typeOfThis = importType(sym.typeOfThis) - mysym.thisSym setName importName(sym.thisSym.name) + val mysym = sym match { + case x: from.MethodSymbol => + linkReferenced(myowner.newMethod(myname, mypos, myflags), x, importSymbol) + case x: from.ModuleSymbol => + linkReferenced(myowner.newModuleSymbol(myname, mypos, myflags), x, importSymbol) + case x: from.FreeTermSymbol => + newFreeTermSymbol(importName(x.name).toTermName, x.value, x.flags, x.origin) setInfo importType(x.info) + case x: from.FreeTypeSymbol => + newFreeTypeSymbol(importName(x.name).toTypeName, x.flags, x.origin) + case x: from.TermSymbol => + linkReferenced(myowner.newValue(myname, mypos, myflags), x, importSymbol) + case x: from.TypeSkolem => + val origin = x.unpackLocation match { + case null => null + case y: from.Tree => importTree(y) + case y: from.Symbol => importSymbol(y) + } + myowner.newTypeSkolemSymbol(myname.toTypeName, origin, mypos, myflags) + case x: from.ModuleClassSymbol => + val mysym = myowner.newModuleClass(myname.toTypeName, mypos, myflags) + symMap.weakUpdate(x, mysym) + mysym.sourceModule = importSymbol(x.sourceModule) + mysym + case x: from.ClassSymbol => + val mysym = myowner.newClassSymbol(myname.toTypeName, mypos, myflags) + symMap.weakUpdate(x, mysym) + if (sym.thisSym != sym) { + mysym.typeOfThis = importType(sym.typeOfThis) + mysym.thisSym setName importName(sym.thisSym.name) + } + mysym + case x: from.TypeSymbol => + myowner.newTypeSymbol(myname.toTypeName, mypos, myflags) } - mysym - case x: from.TypeSymbol => - myowner.newTypeSymbol(myname.toTypeName, mypos, myflags) - } - symMap(sym) = mysym - mysym setFlag Flags.LOCKED - mysym setInfo { - val mytypeParams = sym.typeParams map importSymbol - new LazyPolyType(mytypeParams) { - override def complete(s: Symbol) { - val result = sym.info match { - case from.PolyType(_, res) => res - case result => result + symMap.weakUpdate(sym, mysym) + mysym setFlag Flags.LOCKED + mysym setInfo { + val mytypeParams = sym.typeParams map importSymbol + new LazyPolyType(mytypeParams) with FlagAgnosticCompleter { + override def complete(s: Symbol) { + val result = sym.info match { + case from.PolyType(_, res) => res + case result => result + } + s setInfo GenPolyType(mytypeParams, importType(result)) + s setAnnotations (sym.annotations map importAnnotationInfo) + } } - s setInfo GenPolyType(mytypeParams, importType(result)) - s setAnnotations (sym.annotations map importAnnotationInfo) } - } - } - mysym resetFlag Flags.LOCKED - } // end doImport + mysym resetFlag Flags.LOCKED + } // end doImport def importOrRelink: Symbol = { val sym = sym0 // makes sym visible in the debugger @@ -186,17 +194,18 @@ trait Importers extends api.Importers { self: SymbolTable => } // end importOrRelink val sym = sym0 - if (symMap contains sym) { - symMap(sym) - } else { - pendingSyms += 1 - - try { - symMap getOrElseUpdate (sym, importOrRelink) - } finally { - pendingSyms -= 1 - tryFixup() - } + symMap.weakGet(sym) match { + case Some(result) => result + case None => + pendingSyms += 1 + try { + val result = importOrRelink + symMap.weakUpdate(sym, result) + result + } finally { + pendingSyms -= 1 + tryFixup() + } } } @@ -258,17 +267,18 @@ trait Importers extends api.Importers { self: SymbolTable => def importOrRelink: Type = doImport(tpe) - if (tpeMap contains tpe) { - tpeMap(tpe) - } else { - pendingTpes += 1 - - try { - tpeMap getOrElseUpdate (tpe, importOrRelink) - } finally { - pendingTpes -= 1 - tryFixup() - } + tpeMap.weakGet(tpe) match { + case Some(result) => result + case None => + pendingTpes += 1 + try { + val result = importOrRelink + tpeMap.weakUpdate(tpe, result) + result + } finally { + pendingTpes -= 1 + tryFixup() + } } } diff --git a/src/reflect/scala/reflect/internal/Mirrors.scala b/src/reflect/scala/reflect/internal/Mirrors.scala index 4836db5db0..019cf7f908 100644 --- a/src/reflect/scala/reflect/internal/Mirrors.scala +++ b/src/reflect/scala/reflect/internal/Mirrors.scala @@ -19,7 +19,7 @@ trait Mirrors extends api.Mirrors { // if there are any symbols created by that mirror trait RootSymbol extends Symbol { def mirror: Mirror } - abstract class RootsBase(rootOwner: Symbol) extends MirrorOf[Mirrors.this.type] { thisMirror => + abstract class RootsBase(rootOwner: Symbol) extends scala.reflect.api.Mirror[Mirrors.this.type] { thisMirror => protected[scala] def rootLoader: LazyType diff --git a/src/reflect/scala/reflect/internal/Printers.scala b/src/reflect/scala/reflect/internal/Printers.scala index 4c423e0bc2..fd5a7cf88b 100644 --- a/src/reflect/scala/reflect/internal/Printers.scala +++ b/src/reflect/scala/reflect/internal/Printers.scala @@ -534,17 +534,16 @@ trait Printers extends api.Printers { self: SymbolTable => depth += 1 args foreach { + case expr: Expr[_] => + print("Expr") + if (printTypes) print(expr.staticType) + print("(") + print(expr.tree) + print(")") case EmptyTree => print("EmptyTree") case emptyValDef: AnyRef if emptyValDef eq self.emptyValDef => print("emptyValDef") - case Literal(Constant(value)) => - def print(s: String) = this.print("Literal(Constant(" + s + "))") - value match { - case s: String => print("\"" + s + "\"") - case null => print(null) - case _ => print(value.toString) - } case tree: Tree => val hasSymbol = tree.hasSymbol && tree.symbol != NoSymbol val isError = hasSymbol && tree.symbol.name.toString == nme.ERROR.toString @@ -568,6 +567,12 @@ trait Printers extends api.Printers { self: SymbolTable => } else { print(name) } + case Constant(s: String) => + print("Constant(\"" + s + "\")") + case Constant(null) => + print("Constant(null)") + case Constant(value) => + print("Constant(" + value + ")") case arg => print(arg) }, @@ -576,19 +581,24 @@ trait Printers extends api.Printers { self: SymbolTable => case _ => // do nothing }) case sym: Symbol => - if (sym.isStatic && (sym.isClass || sym.isModule)) print(sym.fullName) + if (sym == NoSymbol) print("NoSymbol") + else if (sym.isStatic && (sym.isClass || sym.isModule)) print(sym.fullName) else print(sym.name) if (printIds) print("#", sym.id) if (printKinds) print("#", sym.abbreviatedKindString) - if (printMirrors) print("%M", footnotes.put[MirrorOf[_]](mirrorThatLoaded(sym))) - case NoType => - print("NoType") - case NoPrefix => - print("NoPrefix") + if (printMirrors) print("%M", footnotes.put[scala.reflect.api.Mirror[_]](mirrorThatLoaded(sym))) + case tag: TypeTag[_] => + print("TypeTag(", tag.tpe, ")") + case tag: WeakTypeTag[_] => + print("WeakTypeTag(", tag.tpe, ")") case tpe: Type => val defer = printTypesInFootnotes && !printingFootnotes if (defer) print("[", footnotes.put(tpe), "]") - else printProduct(tpe.asInstanceOf[Product]) + else tpe match { + case NoType => print("NoType") + case NoPrefix => print("NoPrefix") + case _ => printProduct(tpe.asInstanceOf[Product]) + } case mods: Modifiers => print("Modifiers(") if (mods.flags != NoFlags || mods.privateWithin != tpnme.EMPTY || mods.annotations.nonEmpty) print(show(mods.flags)) @@ -597,6 +607,9 @@ trait Printers extends api.Printers { self: SymbolTable => print(")") case name: Name => print(show(name)) + case scope: Scope => + print("Scope") + printIterable(scope.toList) case list: List[_] => print("List") printIterable(list) @@ -609,7 +622,7 @@ trait Printers extends api.Printers { self: SymbolTable => if (depth == 0 && !printingFootnotes) { printingFootnotes = true footnotes.print[Type](this) - footnotes.print[MirrorOf[_]](this) + footnotes.print[scala.reflect.api.Mirror[_]](this) printingFootnotes = false } } @@ -644,16 +657,15 @@ trait Printers extends api.Printers { self: SymbolTable => } def show(name: Name): String = name match { + case tpnme.WILDCARD => "tpnme.WILDCARD" case tpnme.EMPTY => "tpnme.EMPTY" - case tpnme.ROOT => "tpnme.ROOT" + case tpnme.ERROR => "tpnme.ERROR" case tpnme.PACKAGE => "tpnme.PACKAGE" - case tpnme.EMPTY_PACKAGE_NAME => "tpnme.EMPTY_PACKAGE_NAME" - case tpnme.WILDCARD => "tpnme.WILDCARD" + case tpnme.WILDCARD_STAR => "tpnme.WILDCARD_STAR" + case nme.WILDCARD => "nme.WILDCARD" case nme.EMPTY => "nme.EMPTY" - case nme.ROOT => "nme.ROOT" + case nme.ERROR => "tpnme.ERROR" case nme.PACKAGE => "nme.PACKAGE" - case nme.EMPTY_PACKAGE_NAME => "nme.EMPTY_PACKAGE_NAME" - case nme.WILDCARD => "nme.WILDCARD" case nme.CONSTRUCTOR => "nme.CONSTRUCTOR" case nme.ROOTPKG => "nme.ROOTPKG" case _ => diff --git a/src/reflect/scala/reflect/internal/StdAttachments.scala b/src/reflect/scala/reflect/internal/StdAttachments.scala index 5c4d1f7e28..9fe443bf50 100644 --- a/src/reflect/scala/reflect/internal/StdAttachments.scala +++ b/src/reflect/scala/reflect/internal/StdAttachments.scala @@ -8,7 +8,7 @@ trait StdAttachments { * Common code between reflect-internal Symbol and Tree related to Attachments. */ trait Attachable { - protected var rawatt: scala.reflect.api.Attachments { type Pos = Position } = NoPosition + protected var rawatt: scala.reflect.macros.Attachments { type Pos = Position } = NoPosition def attachments = rawatt def updateAttachment[T: ClassTag](attachment: T): this.type = { rawatt = rawatt.update(attachment); this } def removeAttachment[T: ClassTag]: this.type = { rawatt = rawatt.remove[T]; this } diff --git a/src/reflect/scala/reflect/internal/StdCreators.scala b/src/reflect/scala/reflect/internal/StdCreators.scala index eba583d4b5..5e5e4f9043 100644 --- a/src/reflect/scala/reflect/internal/StdCreators.scala +++ b/src/reflect/scala/reflect/internal/StdCreators.scala @@ -7,14 +7,14 @@ import scala.reflect.api.{Universe => ApiUniverse} trait StdCreators { self: SymbolTable => - case class FixedMirrorTreeCreator(mirror: MirrorOf[StdCreators.this.type], tree: Tree) extends TreeCreator { - def apply[U <: ApiUniverse with Singleton](m: MirrorOf[U]): U # Tree = + case class FixedMirrorTreeCreator(mirror: scala.reflect.api.Mirror[StdCreators.this.type], tree: Tree) extends TreeCreator { + def apply[U <: ApiUniverse with Singleton](m: scala.reflect.api.Mirror[U]): U # Tree = if (m eq mirror) tree.asInstanceOf[U # Tree] else throw new IllegalArgumentException(s"Expr defined in $mirror cannot be migrated to other mirrors.") } - case class FixedMirrorTypeCreator(mirror: MirrorOf[StdCreators.this.type], tpe: Type) extends TypeCreator { - def apply[U <: ApiUniverse with Singleton](m: MirrorOf[U]): U # Type = + case class FixedMirrorTypeCreator(mirror: scala.reflect.api.Mirror[StdCreators.this.type], tpe: Type) extends TypeCreator { + def apply[U <: ApiUniverse with Singleton](m: scala.reflect.api.Mirror[U]): U # Type = if (m eq mirror) tpe.asInstanceOf[U # Type] else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.") } diff --git a/src/reflect/scala/reflect/internal/StdNames.scala b/src/reflect/scala/reflect/internal/StdNames.scala index 2cdfb05e77..eacbf6a0cc 100644 --- a/src/reflect/scala/reflect/internal/StdNames.scala +++ b/src/reflect/scala/reflect/internal/StdNames.scala @@ -346,6 +346,16 @@ trait StdNames { def isSingletonName(name: Name) = name endsWith SINGLETON_SUFFIX def isModuleName(name: Name) = name endsWith MODULE_SUFFIX_NAME + /** Is name a variable name? */ + def isVariableName(name: Name): Boolean = { + val first = name.startChar + ( ((first.isLower && first.isLetter) || first == '_') + && (name != nme.false_) + && (name != nme.true_) + && (name != nme.null_) + ) + } + def isDeprecatedIdentifierName(name: Name) = name.toTermName match { case nme.`then` | nme.`macro` => true case _ => false diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index a0e28bf735..a6f156f947 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -55,6 +55,16 @@ trait Symbols extends api.Symbols { self: SymbolTable => def newFreeTypeSymbol(name: TypeName, flags: Long = 0L, origin: String): FreeTypeSymbol = new FreeTypeSymbol(name, origin) initFlags flags + /** Determines whether the given information request should trigger the given symbol's completer. + * See comments to `Symbol.needsInitialize` for details. + */ + protected def shouldTriggerCompleter(symbol: Symbol, completer: Type, isFlagRelated: Boolean, mask: Long) = + completer match { + case null => false + case _: FlagAgnosticCompleter => !isFlagRelated + case _ => abort(s"unsupported completer: $completer of class ${if (completer != null) completer.getClass else null} for symbol ${symbol.fullName}") + } + /** The original owner of a class. Used by the backend to generate * EnclosingMethod attributes. */ @@ -67,7 +77,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => def isParamWithDefault: Boolean = this.hasDefault def isByNameParam: Boolean = this.isValueParameter && (this hasFlag BYNAMEPARAM) def isImplementationArtifact: Boolean = (this hasFlag BRIDGE) || (this hasFlag VBRIDGE) || (this hasFlag ARTIFACT) - def isJava: Boolean = this hasFlag JAVA + def isJava: Boolean = isJavaDefined def isVal: Boolean = isTerm && !isModule && !isMethod && !isMutable def isVar: Boolean = isTerm && !isModule && !isMethod && isMutable @@ -81,14 +91,13 @@ trait Symbols extends api.Symbols { self: SymbolTable => def module = sourceModule def thisPrefix: Type = thisType def selfType: Type = typeOfThis - def typeSignature: Type = info - def typeSignatureIn(site: Type): Type = site memberInfo this + def typeSignature: Type = { fullyInitializeSymbol(this); info } + def typeSignatureIn(site: Type): Type = { fullyInitializeSymbol(this); site memberInfo this } def toType: Type = tpe def toTypeIn(site: Type): Type = site.memberType(this) def toTypeConstructor: Type = typeConstructor def setTypeSignature(tpe: Type): this.type = { setInfo(tpe); this } - def getAnnotations: List[AnnotationInfo] = { initialize; annotations } def setAnnotations(annots: AnnotationInfo*): this.type = { setAnnotations(annots.toList); this } def getter: Symbol = getter(owner) @@ -218,9 +227,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => val m = newModuleSymbol(clazz.name.toTermName, clazz.pos, MODULE | newFlags) connectModuleToClass(m, clazz.asInstanceOf[ClassSymbol]) } - final def newModule(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = { - val m = newModuleSymbol(name, pos, newFlags | MODULE) - val clazz = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags) + final def newModule(name: TermName, pos: Position = NoPosition, newFlags0: Long = 0L): ModuleSymbol = { + val newFlags = newFlags0 | MODULE + val m = newModuleSymbol(name, pos, newFlags) + val clazz = newModuleClass(name.toTypeName, pos, newFlags & ModuleToClassFlags) connectModuleToClass(m, clazz) } @@ -238,9 +248,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => final def newModuleSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol] - final def newModuleAndClassSymbol(name: Name, pos: Position, flags: FlagSet): (ModuleSymbol, ClassSymbol) = { - val m = newModuleSymbol(name, pos, flags | MODULE) - val c = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags) + final def newModuleAndClassSymbol(name: Name, pos: Position, flags0: FlagSet): (ModuleSymbol, ClassSymbol) = { + val flags = flags0 | MODULE + val m = newModuleSymbol(name, pos, flags) + val c = newModuleClass(name.toTypeName, pos, flags & ModuleToClassFlags) connectModuleToClass(m, c) (m, c) } @@ -489,14 +500,12 @@ trait Symbols extends api.Symbols { self: SymbolTable => def isAliasType = false def isAbstractType = false def isSkolem = false - def isMacro = this hasFlag MACRO /** A Type, but not a Class. */ def isNonClassType = false /** The bottom classes are Nothing and Null, found in Definitions. */ def isBottomClass = false - def isSpecialized = this hasFlag SPECIALIZED /** These are all tests for varieties of ClassSymbol, which has these subclasses: * - ModuleClassSymbol @@ -585,11 +594,20 @@ trait Symbols extends api.Symbols { self: SymbolTable => && owner.isPackageClass && nme.isReplWrapperName(name) ) - final def getFlag(mask: Long): Long = flags & mask + final def getFlag(mask: Long): Long = { + if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize + flags & mask + } /** Does symbol have ANY flag in `mask` set? */ - final def hasFlag(mask: Long): Boolean = (flags & mask) != 0 + final def hasFlag(mask: Long): Boolean = { + if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize + (flags & mask) != 0 + } /** Does symbol have ALL the flags in `mask` set? */ - final def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask + final def hasAllFlags(mask: Long): Boolean = { + if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize + (flags & mask) == mask + } def setFlag(mask: Long): this.type = { _rawflags |= mask ; this } def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this } @@ -636,7 +654,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => info.firstParent.typeSymbol == AnyValClass && !isPrimitiveValueClass final def isMethodWithExtension = - isMethod && owner.isDerivedValueClass && !isParamAccessor && !isConstructor && !hasFlag(SUPERACCESSOR) + isMethod && owner.isDerivedValueClass && !isParamAccessor && !isConstructor && !hasFlag(SUPERACCESSOR) && !isTermMacro final def isAnonymousFunction = isSynthetic && (name containsName tpnme.ANON_FUN_NAME) final def isDefinedInPackage = effectiveOwner.isPackageClass @@ -1138,7 +1156,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** See comment in HasFlags for how privateWithin combines with flags. */ private[this] var _privateWithin: Symbol = _ - def privateWithin = _privateWithin + def privateWithin = { + if (!isCompilerUniverse && needsInitialize(isFlagRelated = false, mask = 0)) initialize + _privateWithin + } def privateWithin_=(sym: Symbol) { _privateWithin = sym } def setPrivateWithin(sym: Symbol): this.type = { privateWithin_=(sym) ; this } @@ -1329,6 +1350,46 @@ trait Symbols extends api.Symbols { self: SymbolTable => this } + /** Called when the programmer requests information that might require initialization of the underlying symbol. + * + * `isFlagRelated` and `mask` describe the nature of this information. + * isFlagRelated = true means that the programmer needs particular bits in flags. + * isFlagRelated = false means that the request is unrelated to flags (annotations or privateWithin). + * + * In our current architecture, symbols for top-level classes and modules + * are created as dummies. Package symbols just call newClass(name) or newModule(name) and + * consider their job done. + * + * In order for such a dummy to provide meaningful info (e.g. a list of its members), + * it needs to go through unpickling. Unpickling is a process of reading Scala metadata + * from ScalaSignature annotations and assigning it to symbols and types. + * + * A single unpickling session takes a top-level class or module, parses the ScalaSignature annotation + * and then reads metadata for the unpicklee, its companion (if any) and all their members recursively + * (i.e. the pickle not only contains info about directly nested classes/modules, but also about + * classes/modules nested into those and so on). + * + * Unpickling is triggered automatically whenever typeSignature (info in compiler parlance) is called. + * This happens because package symbols assign completer thunks to the dummies they create. + * Therefore metadata loading happens lazily and transparently. + * + * Almost transparently. Unfortunately metadata isn't limited to just signatures (i.e. lists of members). + * It also includes flags (which determine e.g. whether a class is sealed or not), annotations and privateWithin. + * This gives rise to unpleasant effects like in SI-6277, when a flag test called on an uninitialize symbol + * produces incorrect results. + * + * One might think that the solution is simple: automatically call the completer whenever one needs + * flags, annotations and privateWithin - just like it's done for typeSignature. Unfortunately, this + * leads to weird crashes in scalac, and currently we can't attempt to fix the core of the compiler + * risk stability a few weeks before the final release. + * + * However we do need to fix this for runtime reflection, since it's not something we'd like to + * expose to reflection users. Therefore a proposed solution is to check whether we're in a + * runtime reflection universe and if yes then to commence initialization. + */ + protected def needsInitialize(isFlagRelated: Boolean, mask: Long) = + !isInitialized && (flags & LOCKED) == 0 && shouldTriggerCompleter(this, if (infos ne null) infos.info else null, isFlagRelated, mask) + /** Was symbol's type updated during given phase? */ final def isUpdatedAt(pid: Phase#Id): Boolean = { assert(isCompilerUniverse) @@ -1469,7 +1530,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => def makeSerializable() { info match { case ci @ ClassInfoType(_, _, _) => - updateInfo(ci.copy(parents = ci.parents :+ SerializableClass.tpe)) + setInfo(ci.copy(parents = ci.parents :+ SerializableClass.tpe)) case i => abort("Only ClassInfoTypes can be made serializable: "+ i) } @@ -1491,8 +1552,10 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** After the typer phase (before, look at the definition's Modifiers), contains * the annotations attached to member a definition (class, method, type, field). */ - def annotations: List[AnnotationInfo] = + def annotations: List[AnnotationInfo] = { + if (!isCompilerUniverse && needsInitialize(isFlagRelated = false, mask = 0)) initialize _annotations + } def setAnnotations(annots: List[AnnotationInfo]): this.type = { _annotations = annots @@ -2536,8 +2599,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => res } - override def params: List[List[Symbol]] = paramss - override def isVarargs: Boolean = definitions.isVarArgsList(paramss.flatten) override def returnType: Type = { @@ -2936,7 +2997,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => } override def derivedValueClassUnbox = - (info.decl(nme.unbox)) orElse + // (info.decl(nme.unbox)) orElse uncomment once we accept unbox methods (info.decls.find(_ hasAllFlags PARAMACCESSOR | METHOD) getOrElse NoSymbol) diff --git a/src/reflect/scala/reflect/internal/TreeInfo.scala b/src/reflect/scala/reflect/internal/TreeInfo.scala index 6ef4c3f660..68decc27f5 100644 --- a/src/reflect/scala/reflect/internal/TreeInfo.scala +++ b/src/reflect/scala/reflect/internal/TreeInfo.scala @@ -247,7 +247,7 @@ abstract class TreeInfo { /** Is tree a variable pattern? */ def isVarPattern(pat: Tree): Boolean = pat match { - case x: Ident => !x.isBackquoted && isVariableName(x.name) + case x: Ident => !x.isBackquoted && nme.isVariableName(x.name) case _ => false } def isDeprecatedIdentifier(tree: Tree): Boolean = tree match { @@ -312,14 +312,6 @@ abstract class TreeInfo { /** Is name a left-associative operator? */ def isLeftAssoc(operator: Name) = operator.nonEmpty && (operator.endChar != ':') - private val reserved = Set[Name](nme.false_, nme.true_, nme.null_) - - /** Is name a variable name? */ - def isVariableName(name: Name): Boolean = { - val first = name.startChar - ((first.isLower && first.isLetter) || first == '_') && !reserved(name) - } - /** Is tree a `this` node which belongs to `enclClass`? */ def isSelf(tree: Tree, enclClass: Symbol): Boolean = tree match { case This(_) => tree.symbol == enclClass diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index 7ec9f7086d..d6b4f18855 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -1300,25 +1300,26 @@ trait Trees extends api.Trees { self: SymbolTable => } class ChangeOwnerTraverser(val oldowner: Symbol, val newowner: Symbol) extends Traverser { - def changeOwner(tree: Tree) = tree match { - case Return(expr) => - if (tree.symbol == oldowner) { - // SI-5612 - if (newowner hasTransOwner oldowner) - log("NOT changing owner of %s because %s is nested in %s".format(tree, newowner, oldowner)) - else { - log("changing owner of %s: %s => %s".format(tree, oldowner, newowner)) - tree.symbol = newowner - } - } - case _: DefTree | _: Function => - if (tree.symbol != NoSymbol && tree.symbol.owner == oldowner) { - tree.symbol.owner = newowner - } - case _ => + final def change(sym: Symbol) = { + if (sym != NoSymbol && sym.owner == oldowner) + sym.owner = newowner } override def traverse(tree: Tree) { - changeOwner(tree) + tree match { + case _: Return => + if (tree.symbol == oldowner) { + // SI-5612 + if (newowner hasTransOwner oldowner) + log("NOT changing owner of %s because %s is nested in %s".format(tree, newowner, oldowner)) + else { + log("changing owner of %s: %s => %s".format(tree, oldowner, newowner)) + tree.symbol = newowner + } + } + case _: DefTree | _: Function => + change(tree.symbol) + case _ => + } super.traverse(tree) } } diff --git a/src/reflect/scala/reflect/internal/Types.scala b/src/reflect/scala/reflect/internal/Types.scala index 4311f1dd4f..ab33c29153 100644 --- a/src/reflect/scala/reflect/internal/Types.scala +++ b/src/reflect/scala/reflect/internal/Types.scala @@ -66,9 +66,9 @@ import util.ThreeValues._ // a type variable // Replace occurrences of type parameters with type vars, where // inst is the instantiation and constr is a list of bounds. - case DeBruijnIndex(level, index) + case DeBruijnIndex(level, index, args) // for dependent method types: a type referring to a method parameter. - case ErasedValueType(clazz, underlying) + case ErasedValueType(tref) // only used during erasure of derived value classes. */ @@ -3445,6 +3445,16 @@ trait Types extends api.Types { self: SymbolTable => override def kind = "LazyType" } + /** A marker trait representing an as-yet unevaluated type + * which doesn't assign flags to the underlying symbol. + */ + trait FlagAgnosticCompleter extends LazyType + + /** A marker trait representing an as-yet unevaluated type + * which assigns flags to the underlying symbol. + */ + trait FlagAssigningCompleter extends LazyType + abstract class LazyPolyType(override val typeParams: List[Symbol]) extends LazyType { override def safeToString = (if (typeParams.isEmpty) "" else typeParamsString(this)) + super.safeToString @@ -3613,9 +3623,20 @@ trait Types extends api.Types { self: SymbolTable => */ /** A creator for type applications */ - def appliedType(tycon: Type, args: List[Type]): Type = - if (args.isEmpty) tycon //@M! `if (args.isEmpty) tycon' is crucial (otherwise we create new types in phases after typer and then they don't get adapted (??)) - else tycon match { + def appliedType(tycon: Type, args: List[Type]): Type = { + if (args.isEmpty) + return tycon //@M! `if (args.isEmpty) tycon' is crucial (otherwise we create new types in phases after typer and then they don't get adapted (??)) + + /** Disabled - causes cycles in tcpoly tests. */ + if (false && isDefinitionsInitialized) { + assert(isUseableAsTypeArgs(args), { + val tapp_s = s"""$tycon[${args mkString ", "}]""" + val arg_s = args filterNot isUseableAsTypeArg map (t => t + "/" + t.getClass) mkString ", " + s"$tapp_s includes illegal type argument $arg_s" + }) + } + + tycon match { case TypeRef(pre, sym @ (NothingClass|AnyClass), _) => copyTypeRef(tycon, pre, sym, Nil) //@M drop type args to Any/Nothing case TypeRef(pre, sym, _) => copyTypeRef(tycon, pre, sym, args) case PolyType(tparams, restpe) => restpe.instantiateTypeParams(tparams, args) @@ -3629,6 +3650,7 @@ trait Types extends api.Types { self: SymbolTable => case WildcardType => tycon // needed for neg/t0226 case _ => abort(debugString(tycon)) } + } /** Very convenient. */ def appliedType(tyconSym: Symbol, args: Type*): Type = @@ -3900,7 +3922,17 @@ trait Types extends api.Types { self: SymbolTable => def avoidWiden: Boolean = avoidWidening def addLoBound(tp: Type, isNumericBound: Boolean = false) { - if (!lobounds.contains(tp)) { + // For some reason which is still a bit fuzzy, we must let Nothing through as + // a lower bound despite the fact that Nothing is always a lower bound. My current + // supposition is that the side-effecting type constraint accumulation mechanism + // depends on these subtype tests being performed to make forward progress when + // there are mutally recursive type vars. + // See pos/t6367 and pos/t6499 for the competing test cases. + val mustConsider = tp.typeSymbol match { + case NothingClass => true + case _ => !(lobounds contains tp) + } + if (mustConsider) { if (isNumericBound && isNumericValueType(tp)) { if (numlo == NoType || isNumericSubType(numlo, tp)) numlo = tp @@ -3920,7 +3952,13 @@ trait Types extends api.Types { self: SymbolTable => } def addHiBound(tp: Type, isNumericBound: Boolean = false) { - if (!hibounds.contains(tp)) { + // My current test case only demonstrates the need to let Nothing through as + // a lower bound, but I suspect the situation is symmetrical. + val mustConsider = tp.typeSymbol match { + case AnyClass => true + case _ => !(hibounds contains tp) + } + if (mustConsider) { checkWidening(tp) if (isNumericBound && isNumericValueType(tp)) { if (numhi == NoType || isNumericSubType(tp, numhi)) @@ -5722,6 +5760,107 @@ trait Types extends api.Types { self: SymbolTable => case _ => false } + /** This is defined and named as it is because the goal is to exclude source + * level types which are not value types (e.g. MethodType) without excluding + * necessary internal types such as WildcardType. There are also non-value + * types which can be used as type arguments (e.g. type constructors.) + */ + def isUseableAsTypeArg(tp: Type) = ( + isInternalTypeUsedAsTypeArg(tp) // the subset of internal types which can be type args + || isHKTypeRef(tp) // not a value type, but ok as a type arg + || isValueElseNonValue(tp) // otherwise only value types + ) + + private def isHKTypeRef(tp: Type) = tp match { + case TypeRef(_, sym, Nil) => tp.isHigherKinded + case _ => false + } + @tailrec final def isUseableAsTypeArgs(tps: List[Type]): Boolean = tps match { + case Nil => true + case x :: xs => isUseableAsTypeArg(x) && isUseableAsTypeArgs(xs) + } + + /** The "third way", types which are neither value types nor + * non-value types as defined in the SLS, further divided into + * types which are used internally in type applications and + * types which are not. + */ + private def isInternalTypeNotUsedAsTypeArg(tp: Type): Boolean = tp match { + case AntiPolyType(pre, targs) => true + case ClassInfoType(parents, defs, clazz) => true + case DeBruijnIndex(level, index, args) => true + case ErasedValueType(tref) => true + case NoPrefix => true + case NoType => true + case SuperType(thistpe, supertpe) => true + case TypeBounds(lo, hi) => true + case _ => false + } + private def isInternalTypeUsedAsTypeArg(tp: Type): Boolean = tp match { + case WildcardType => true + case BoundedWildcardType(_) => true + case ErrorType => true + case _: TypeVar => true + case _ => false + } + private def isAlwaysValueType(tp: Type) = tp match { + case RefinedType(_, _) => true + case ExistentialType(_, _) => true + case ConstantType(_) => true + case _ => false + } + private def isAlwaysNonValueType(tp: Type) = tp match { + case OverloadedType(_, _) => true + case NullaryMethodType(_) => true + case MethodType(_, _) => true + case PolyType(_, MethodType(_, _)) => true + case _ => false + } + /** Should be called only with types for which a clear true/false answer + * can be given: true == value type, false == non-value type. Otherwise, + * an exception is thrown. + */ + private def isValueElseNonValue(tp: Type): Boolean = tp match { + case tp if isAlwaysValueType(tp) => true + case tp if isAlwaysNonValueType(tp) => false + case AnnotatedType(_, underlying, _) => isValueElseNonValue(underlying) + case SingleType(_, sym) => sym.isValue // excludes packages and statics + case TypeRef(_, _, _) if tp.isHigherKinded => false // excludes type constructors + case ThisType(sym) => !sym.isPackageClass // excludes packages + case TypeRef(_, sym, _) => !sym.isPackageClass // excludes packages + case PolyType(_, _) => true // poly-methods excluded earlier + case tp => sys.error("isValueElseNonValue called with third-way type " + tp) + } + + /** SLS 3.2, Value Types + * Is the given type definitely a value type? A true result means + * it verifiably is, but a false result does not mean it is not, + * only that it cannot be assured. To avoid false positives, this + * defaults to false, but since Type is not sealed, one should take + * a false answer with a grain of salt. This method may be primarily + * useful as documentation; it is likely that !isNonValueType(tp) + * will serve better than isValueType(tp). + */ + def isValueType(tp: Type) = isValueElseNonValue(tp) + + /** SLS 3.3, Non-Value Types + * Is the given type definitely a non-value type, as defined in SLS 3.3? + * The specification-enumerated non-value types are method types, polymorphic + * method types, and type constructors. Supplements to the specified set of + * non-value types include: types which wrap non-value symbols (packages + * abd statics), overloaded types. Varargs and by-name types T* and (=>T) are + * not designated non-value types because there is code which depends on using + * them as type arguments, but their precise status is unclear. + */ + def isNonValueType(tp: Type) = !isValueElseNonValue(tp) + + def isNonRefinementClassType(tpe: Type) = tpe match { + case SingleType(_, sym) => sym.isModuleClass + case TypeRef(_, sym, _) => sym.isClass && !sym.isRefinementClass + case ErrorType => true + case _ => false + } + // @assume tp1.isHigherKinded || tp2.isHigherKinded def isHKSubType0(tp1: Type, tp2: Type, depth: Int): Boolean = ( tp1.typeSymbol == NothingClass @@ -6193,21 +6332,26 @@ trait Types extends api.Types { self: SymbolTable => }) if (!cyclic) { if (up) { - if (bound.typeSymbol != AnyClass) + if (bound.typeSymbol != AnyClass) { + log(s"$tvar addHiBound $bound.instantiateTypeParams($tparams, $tvars)") tvar addHiBound bound.instantiateTypeParams(tparams, tvars) + } for (tparam2 <- tparams) tparam2.info.bounds.lo.dealias match { case TypeRef(_, `tparam`, _) => + log(s"$tvar addHiBound $tparam2.tpeHK.instantiateTypeParams($tparams, $tvars)") tvar addHiBound tparam2.tpeHK.instantiateTypeParams(tparams, tvars) case _ => } } else { if (bound.typeSymbol != NothingClass && bound.typeSymbol != tparam) { + log(s"$tvar addLoBound $bound.instantiateTypeParams($tparams, $tvars)") tvar addLoBound bound.instantiateTypeParams(tparams, tvars) } for (tparam2 <- tparams) tparam2.info.bounds.hi.dealias match { case TypeRef(_, `tparam`, _) => + log(s"$tvar addLoBound $tparam2.tpeHK.instantiateTypeParams($tparams, $tvars)") tvar addLoBound tparam2.tpeHK.instantiateTypeParams(tparams, tvars) case _ => } @@ -6216,14 +6360,15 @@ trait Types extends api.Types { self: SymbolTable => tvar.constr.inst = NoType // necessary because hibounds/lobounds may contain tvar //println("solving "+tvar+" "+up+" "+(if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds)+((if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds) map (_.widen))) - - tvar setInst ( + val newInst = ( if (up) { if (depth != AnyDepth) glb(tvar.constr.hiBounds, depth) else glb(tvar.constr.hiBounds) } else { if (depth != AnyDepth) lub(tvar.constr.loBounds, depth) else lub(tvar.constr.loBounds) - }) - + } + ) + log(s"$tvar setInst $newInst") + tvar setInst newInst //Console.println("solving "+tvar+" "+up+" "+(if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds)+((if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds) map (_.widen))+" = "+tvar.constr.inst)//@MDEBUG } } diff --git a/src/reflect/scala/reflect/internal/package.scala b/src/reflect/scala/reflect/internal/package.scala deleted file mode 100644 index 63568f6a6b..0000000000 --- a/src/reflect/scala/reflect/internal/package.scala +++ /dev/null @@ -1,6 +0,0 @@ -package scala.reflect - -package object internal { - - type MirrorOf[U <: scala.reflect.api.Universe with Singleton] = scala.reflect.api.MirrorOf[U] -} diff --git a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala index a9994a037f..b158a1ac26 100644 --- a/src/reflect/scala/reflect/internal/pickling/UnPickler.scala +++ b/src/reflect/scala/reflect/internal/pickling/UnPickler.scala @@ -848,7 +848,7 @@ abstract class UnPickler /*extends scala.reflect.generic.UnPickler*/ { } /** A lazy type which when completed returns type at index `i`. */ - private class LazyTypeRef(i: Int) extends LazyType { + private class LazyTypeRef(i: Int) extends LazyType with FlagAgnosticCompleter { private val definedAtRunId = currentRunId private val p = phase override def complete(sym: Symbol) : Unit = try { diff --git a/src/reflect/scala/reflect/internal/util/Collections.scala b/src/reflect/scala/reflect/internal/util/Collections.scala index 14b5d3003d..201b4dfe0a 100644 --- a/src/reflect/scala/reflect/internal/util/Collections.scala +++ b/src/reflect/scala/reflect/internal/util/Collections.scala @@ -175,6 +175,20 @@ trait Collections { } false } + final def exists3[A, B, C](xs1: List[A], xs2: List[B], xs3: List[C])(f: (A, B, C) => Boolean): Boolean = { + var ys1 = xs1 + var ys2 = xs2 + var ys3 = xs3 + while (!ys1.isEmpty && !ys2.isEmpty && !ys3.isEmpty) { + if (f(ys1.head, ys2.head, ys3.head)) + return true + + ys1 = ys1.tail + ys2 = ys2.tail + ys3 = ys3.tail + } + false + } final def forall2[A, B](xs1: List[A], xs2: List[B])(f: (A, B) => Boolean): Boolean = { var ys1 = xs1 var ys2 = xs2 diff --git a/src/reflect/scala/reflect/internal/util/Position.scala b/src/reflect/scala/reflect/internal/util/Position.scala index 1621fb84d4..5456d66584 100644 --- a/src/reflect/scala/reflect/internal/util/Position.scala +++ b/src/reflect/scala/reflect/internal/util/Position.scala @@ -7,8 +7,7 @@ package scala.reflect.internal.util import scala.reflect.ClassTag -import scala.reflect.api.Attachments -import scala.reflect.api.PositionApi +import scala.reflect.macros.Attachments object Position { val tabInc = 8 @@ -36,7 +35,51 @@ object Position { } } -abstract class Position extends PositionApi { self => +/** The Position class and its subclasses represent positions of ASTs and symbols. + * Except for NoPosition and FakePos, every position refers to a SourceFile + * and to an offset in the sourcefile (its `point`). For batch compilation, + * that's all. For interactive IDE's there are also RangePositions + * and TransparentPositions. A RangePosition indicates a start and an end + * in addition to its point. TransparentPositions are a subclass of RangePositions. + * Range positions that are not transparent are called opaque. + * Trees with RangePositions need to satisfy the following invariants. + * + * INV1: A tree with an offset position never contains a child + * with a range position + * INV2: If the child of a tree with a range position also has a range position, + * then the child's range is contained in the parent's range. + * INV3: Opaque range positions of children of the same node are non-overlapping + * (this means their overlap is at most a single point). + * + * The following tests are useful on positions: + * + * pos.isDefined true if position is not a NoPosition nor a FakePosition + * pos.isRange true if position is a range + * pos.isOpaqueRange true if position is an opaque range + * + * The following accessor methods are provided: + * + * pos.source The source file of the position, which must be defined + * pos.point The offset of the position's point, which must be defined + * pos.start The start of the position, which must be a range + * pos.end The end of the position, which must be a range + * + * There are also convenience methods, such as + * + * pos.startOrPoint + * pos.endOrPoint + * pos.pointOrElse(default) + * + * These are less strict about the kind of position on which they can be applied. + * + * The following conversion methods are often used: + * + * pos.focus converts a range position to an offset position, keeping its point; + * returns all other positions unchanged. + * pos.makeTransparent converts an opaque range position into a transparent one. + * returns all other positions unchanged. + */ +abstract class Position extends scala.reflect.api.Position { self => type Pos = Position @@ -44,16 +87,6 @@ abstract class Position extends PositionApi { self => def withPos(newPos: Position): Attachments { type Pos = self.Pos } = newPos - /** Java file corresponding to the source file of this position. - */ - // necessary for conformance with scala.reflect.api.Position - def fileInfo: java.io.File = source.file.file - - /** Contents of the source file that contains this position. - */ - // necessary for conformance with scala.reflect.api.Position - def fileContent: Array[Char] = source.content - /** An optional value containing the source file referred to by this position, or * None if not defined. */ diff --git a/src/reflect/scala/reflect/macros/Aliases.scala b/src/reflect/scala/reflect/macros/Aliases.scala index eff7f34b02..7f7ab66848 100644 --- a/src/reflect/scala/reflect/macros/Aliases.scala +++ b/src/reflect/scala/reflect/macros/Aliases.scala @@ -1,28 +1,109 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that defines shorthands for the + * most frequently used types and functions of the underlying compiler universe. + */ trait Aliases { self: Context => + /** The type of symbols representing declarations. */ type Symbol = universe.Symbol + + /** The type of Scala types, and also Scala type signatures. + * (No difference is internally made between the two). + */ type Type = universe.Type + + /** The abstract type of names. */ type Name = universe.Name + + /** The abstract type of names representing terms. */ type TermName = universe.TermName + + /** The abstract type of names representing types. */ type TypeName = universe.TypeName + + /** The type of Scala abstract syntax trees. */ type Tree = universe.Tree - // type Position = universe.Position + + /** Defines a universe-specific notion of positions. */ + type Position = universe.Position + + /** The base type of all scopes. */ type Scope = universe.Scope + + /** The type of tree modifiers. */ type Modifiers = universe.Modifiers + /** The type of compilation runs. */ + type Run = universe.Run + + /** The type of compilation units. */ + type CompilationUnit = universe.CompilationUnit + + /** Expr wraps an abstract syntax tree and tags it with its type. */ type Expr[+T] = universe.Expr[T] + + /** Constructor/Extractor for `Expr`. */ val Expr = universe.Expr + /** A shorthand to create an expr. + * + * Unlike the conventional expr factory, which requires a [[scala.reflect.api.TreeCreator]], + * this one accepts a regular tree, but the resulting exprs are unable of being migrated + * to other universes/mirrors (the functionality normally not needed for macros, since there is + * only one compile-time universe and only one compile-time mirror). + */ + def Expr[T: WeakTypeTag](tree: Tree): Expr[T] + + /** The type of weak type tags. */ type WeakTypeTag[T] = universe.WeakTypeTag[T] + + /** The type of type tags. */ type TypeTag[T] = universe.TypeTag[T] + + /** Constructor/Extractor for `WeakTypeTag`. */ val WeakTypeTag = universe.WeakTypeTag + + /** Constructor/Extractor for `TypeTag`. */ val TypeTag = universe.TypeTag + + /** A shorthand to create a weak type tag. + * + * Unlike the conventional type tag factory, which requires a [[scala.reflect.api.TypeCreator]], + * this one accepts a regular type, but the resulting type tags are unable of being migrated + * to other universes/mirrors (the functionality normally not needed for macros, since there is + * only one compile-time universe and only one compile-time mirror). + */ + def WeakTypeTag[T](tpe: Type): WeakTypeTag[T] + + /** A shorthand to create a type tag. + * + * Unlike the conventional type tag factory, which requires a [[scala.reflect.api.TypeCreator]], + * this one accepts a regular type, but the resulting type tags are unable of being migrated + * to other universes/mirrors (the functionality normally not needed for macros, since there is + * only one compile-time universe and only one compile-time mirror). + */ + def TypeTag[T](tpe: Type): TypeTag[T] + + /** + * Shortcut for `implicitly[WeakTypeTag[T]]` + */ def weakTypeTag[T](implicit attag: WeakTypeTag[T]) = attag + + /** + * Shortcut for `implicitly[TypeTag[T]]` + */ def typeTag[T](implicit ttag: TypeTag[T]) = ttag + + /** + * Shortcut for `implicitly[WeakTypeTag[T]].tpe` + */ def weakTypeOf[T](implicit attag: WeakTypeTag[T]): Type = attag.tpe + + /** + * Shortcut for `implicitly[TypeTag[T]].tpe` + */ def typeOf[T](implicit ttag: TypeTag[T]): Type = ttag.tpe } diff --git a/src/reflect/scala/reflect/api/Attachments.scala b/src/reflect/scala/reflect/macros/Attachments.scala index edbb0131ca..ba5ccf88f1 100644 --- a/src/reflect/scala/reflect/api/Attachments.scala +++ b/src/reflect/scala/reflect/macros/Attachments.scala @@ -1,12 +1,20 @@ package scala.reflect -package api +package macros -/** Attachments is a generalization of Position. Typically it stores a Position of a tree, but this can be extended to +/** Attachments provide a way to associate custom metadata with symbols and trees. + * + * Along with `symbol` and `tpe`, which represent core metadata of trees, each tree + * carries the `attachments` field that can store other metadata: compiler-defined (e.g. positions) or user-defined. + * Same story is true for symbols, which also have extensible metadata by the virtue + * of the same `attachments` field. + * + * Typically attachments just store a [[scala.reflect.api.Position]], but they can be extended to * encompass arbitrary payloads. Payloads are stored in type-indexed slots, which can be read with `get[T]` and written * with `update[T]` and `remove[T]`. * - * Attachments always carry positions because we don't want to introduce an additional field for attachments in `Tree` - * imposing an unnecessary memory tax because of something that will not be used in most cases. + * This API doesn't have much use in the runtime reflection API (the [[scala.reflect.api]] package), but it might be of help + * for macro writers, providing a way to coordinate multiple macros operating on the same code. Therefore the `attachments` + * field is only declared in trees and symbols belonging to [[scala.reflect.macros.Universe]]. */ abstract class Attachments { self => @@ -30,8 +38,7 @@ abstract class Attachments { self => (all filter matchesTag[T]).headOption.asInstanceOf[Option[T]] /** Creates a copy of this attachment with the payload slot of T added/updated with the provided value. - * - * Replaces an existing payload of the same type, if exists. + * Replaces an existing payload of the same type, if exists. */ def update[T: ClassTag](attachment: T): Attachments { type Pos = self.Pos } = new NonemptyAttachments(this.pos, remove[T].all + attachment) diff --git a/src/reflect/scala/reflect/macros/CapturedVariables.scala b/src/reflect/scala/reflect/macros/CapturedVariables.scala deleted file mode 100644 index 60ed6f5e7b..0000000000 --- a/src/reflect/scala/reflect/macros/CapturedVariables.scala +++ /dev/null @@ -1,21 +0,0 @@ -package scala.reflect -package macros - -trait CapturedVariables { - self: Context => - - import mirror._ - - /** Mark a variable as captured; i.e. force boxing in a *Ref type. - */ - def captureVariable(vble: Symbol): Unit - - /** Mark given identifier as a reference to a captured variable itself - * suppressing dereferencing with the `elem` field. - */ - def referenceCapturedVariable(vble: Symbol): Tree - - /** Convert type of a captured variable to *Ref type. - */ - def capturedVariableType(vble: Symbol): Type -}
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/Context.scala b/src/reflect/scala/reflect/macros/Context.scala index 37c8f9057e..1f6e97adbc 100644 --- a/src/reflect/scala/reflect/macros/Context.scala +++ b/src/reflect/scala/reflect/macros/Context.scala @@ -5,30 +5,83 @@ package macros // the most lightweight context should just expose the stuff from the SIP // the full context should include all traits from scala.reflect.macros (and probably reside in scala-compiler.jar) +/** The Scala macros context. + * + * See [[scala.reflect.macros.package the overview page]] for a description of how macros work. This documentation + * entry provides information on the API available to macro writers. + * + * A macro context wraps a compiler universe exposed in `universe` and having type [[scala.reflect.macros.Universe]]. + * This type is a refinement over the generic reflection API provided in [[scala.reflect.api.Universe]]. The + * extended Universe provides mutability for reflection artifacts (e.g. macros can change types of compiler trees, + * add annotation to symbols representing definitions, etc) and exposes some internal compiler functionality + * such as `Symbol.deSkolemize` or `Tree.attachments`. + * + * Another fundamental part of a macro context is `macroApplication`, which provides access to the tree undergoing + * macro expansion. Parts of this tree can be found in arguments of the corresponding macro implementations and + * in `prefix`, but `macroApplication` gives the full picture. + * + * Other than that, macro contexts provide facilities for typechecking, exploring the compiler's symbol table and + * enclosing trees and compilation units, evaluating trees, logging warnings/errors and much more. + * Refer to the documentation of top-level traits in this package to learn the details. + */ trait Context extends Aliases - with CapturedVariables with Enclosures - with Infrastructure with Names with Reifiers with FrontEnds - with Settings + with Infrastructure with Typers with Parsers - with Exprs - with TypeTags with Evals with ExprUtils { - /** The compile-time universe */ + /** The compile-time universe. */ val universe: Universe - /** The mirror of the compile-time universe */ - val mirror: MirrorOf[universe.type] + /** The mirror of the compile-time universe. */ + val mirror: universe.Mirror - /** The type of the prefix tree from which the macro is selected */ + /** The type of the prefix tree from which the macro is selected. + * See the documentation entry for `prefix` for an example. + */ type PrefixType - /** The prefix tree from which the macro is selected */ + /** The prefix tree from which the macro is selected. + * + * For a example, for a macro `filter` defined as an instance method on a collection `Coll`, + * `prefix` represents an equivalent of `this` for normal instance methods: + * + * {{{ + * scala> class Coll[T] { + * | def filter(p: T => Boolean): Coll[T] = macro M.filter[T] + * | }; object M { + * | def filter[T](c: Context { type PrefixType = Coll[T] }) + * | (p: c.Expr[T => Boolean]): c.Expr[Coll[T]] = + * | { + * | println(c.prefix.tree) + * | c.prefix + * | } + * | } + * defined class Coll + * defined module Macros + * + * scala> new Coll[Int]().filter(_ % 2 == 0) + * new Coll[Int]() + * res0: Coll[Int] = ... + * + * scala> val x = new Coll[String]() + * x: Coll[String] = ... + * + * scala> x.filter(_ != "") + * \$line11.\$read.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.\$iw.x + * res1 @ 35563b4b: x.type = ... + * }}} + * + * Note how the value of `prefix` changes depending on the qualifier of the macro call + * (i.e. the expression that is at the left-hand side of the dot). + * + * Another noteworthy thing about the snippet above is the `Context { type PrefixType = Coll[T] }` + * type that is used to stress that the macro implementation works with prefixes of type `Coll[T]`. + */ val prefix: Expr[PrefixType] } diff --git a/src/reflect/scala/reflect/macros/Enclosures.scala b/src/reflect/scala/reflect/macros/Enclosures.scala index a07ff85a08..41d6af94e3 100644 --- a/src/reflect/scala/reflect/macros/Enclosures.scala +++ b/src/reflect/scala/reflect/macros/Enclosures.scala @@ -1,6 +1,11 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that exposes + * enclosing trees (method, class, compilation unit and currently compiled application), + * the enclosing position of the macro expansion, as well as macros and implicits + * that are currently in-flight. + */ trait Enclosures { self: Context => @@ -47,4 +52,8 @@ trait Enclosures { /** Compilation unit that contains this macro application. */ val enclosingUnit: CompilationUnit + + /** Compilation run that contains this macro application. + */ + val enclosingRun: Run }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/Evals.scala b/src/reflect/scala/reflect/macros/Evals.scala index 3837d749da..6aab3d5b02 100644 --- a/src/reflect/scala/reflect/macros/Evals.scala +++ b/src/reflect/scala/reflect/macros/Evals.scala @@ -1,9 +1,54 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that provides + * a facility to evaluate trees. + */ trait Evals { self: Context => - /** .. */ + /** Takes a typed wrapper for a tree of type `T` and evaluates it to a value of type `T`. + * + * Can be used to perform compile-time computations on macro arguments to the extent + * permitted by the shape of the arguments. + * + * Known issues: because of [[https://issues.scala-lang.org/browse/SI-5748 https://issues.scala-lang.org/browse/SI-5748]] + * trees being evaluated first need to undergo `resetAllAttrs`. Resetting symbols and types + * mutates the tree in place, therefore the conventional approach is to `duplicate` the tree first. + * + * {{{ + * scala> def impl(c: Context)(x: c.Expr[String]) = { + * | val x1 = c.Expr[String](c.resetAllAttrs(x.tree.duplicate)) + * | println(s"compile-time value is: \${c.eval(x1)}") + * | x + * | } + * impl: (c: Context)(x: c.Expr[String])c.Expr[String] + * + * scala> def test(x: String) = macro impl + * test: (x: String)String + * + * scala> test("x") + * compile-time value is: x + * res0: String = x + * + * scala> test("x" + "y") + * compile-time value is: xy + * res1: String = xy + * + * scala> val x = "x" + * x: String = x + * + * scala> test(x + "y") + * compile-time value is: xy + * res2: String = xy + * + * scala> { val x = "x"; test(x + "y") } + * error: exception during macro expansion: + * scala.tools.reflect.ToolBoxError: reflective compilation failed + * }}} + * + * Note that in the last case evaluation has failed, because the argument of a macro + * refers to a runtime value `x`, which is unknown at compile time. + */ def eval[T](expr: Expr[T]): T }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/ExprUtils.scala b/src/reflect/scala/reflect/macros/ExprUtils.scala index adcdc78c78..a9acc61735 100644 --- a/src/reflect/scala/reflect/macros/ExprUtils.scala +++ b/src/reflect/scala/reflect/macros/ExprUtils.scala @@ -1,32 +1,48 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that defines shorthands for the + * most common `Expr`-creating functions. + */ trait ExprUtils { self: Context => + /** Shorthand for `Literal(Constant(null))` in the underlying `universe`. */ def literalNull: Expr[Null] + /** Shorthand for `Literal(Constant(()))` in the underlying `universe`. */ def literalUnit: Expr[Unit] + /** Shorthand for `Literal(Constant(true))` in the underlying `universe`. */ def literalTrue: Expr[Boolean] + /** Shorthand for `Literal(Constant(false))` in the underlying `universe`. */ def literalFalse: Expr[Boolean] + /** Shorthand for `Literal(Constant(x: Boolean))` in the underlying `universe`. */ def literal(x: Boolean): Expr[Boolean] + /** Shorthand for `Literal(Constant(x: Byte))` in the underlying `universe`. */ def literal(x: Byte): Expr[Byte] + /** Shorthand for `Literal(Constant(x: Short))` in the underlying `universe`. */ def literal(x: Short): Expr[Short] + /** Shorthand for `Literal(Constant(x: Int))` in the underlying `universe`. */ def literal(x: Int): Expr[Int] + /** Shorthand for `Literal(Constant(x: Long))` in the underlying `universe`. */ def literal(x: Long): Expr[Long] + /** Shorthand for `Literal(Constant(x: Float))` in the underlying `universe`. */ def literal(x: Float): Expr[Float] + /** Shorthand for `Literal(Constant(x: Double))` in the underlying `universe`. */ def literal(x: Double): Expr[Double] + /** Shorthand for `Literal(Constant(x: String))` in the underlying `universe`. */ def literal(x: String): Expr[String] + /** Shorthand for `Literal(Constant(x: Char))` in the underlying `universe`. */ def literal(x: Char): Expr[Char] } diff --git a/src/reflect/scala/reflect/macros/Exprs.scala b/src/reflect/scala/reflect/macros/Exprs.scala deleted file mode 100644 index 280d5508c8..0000000000 --- a/src/reflect/scala/reflect/macros/Exprs.scala +++ /dev/null @@ -1,8 +0,0 @@ -package scala.reflect -package macros - -trait Exprs { - self: Context => - - def Expr[T: WeakTypeTag](tree: Tree): Expr[T] -} diff --git a/src/reflect/scala/reflect/macros/FrontEnds.scala b/src/reflect/scala/reflect/macros/FrontEnds.scala index d15db0725f..8c47202342 100644 --- a/src/reflect/scala/reflect/macros/FrontEnds.scala +++ b/src/reflect/scala/reflect/macros/FrontEnds.scala @@ -1,42 +1,44 @@ package scala.reflect package macros -trait FrontEnds extends scala.reflect.api.FrontEnds { +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * provides facilities to communicate with the compiler's front end + * (emit warnings, errors and other sorts of messages). + */ +trait FrontEnds { self: Context => - import mirror._ - - type Position = universe.Position - - /** Exposes means to control the compiler UI */ - def frontEnd: FrontEnd - def setFrontEnd(frontEnd: FrontEnd): this.type - def withFrontEnd[T](frontEnd: FrontEnd)(op: => T): T - /** For sending a message which should not be labeled as a warning/error, * but also shouldn't require -verbose to be visible. - * Use ``enclosingPosition'' if you're in doubt what position to pass to ``pos''. + * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. */ def echo(pos: Position, msg: String): Unit - /** Informational messages, suppressed unless -verbose or force=true. - * Use ``enclosingPosition'' if you're in doubt what position to pass to ``pos''. + /** Emits an informational message, suppressed unless `-verbose` or `force=true`. + * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. */ def info(pos: Position, msg: String, force: Boolean): Unit - /** Warnings and errors. - * Use ``enclosingPosition'' if you're in doubt what position to pass to ``pos''. + /** Does the compilation session have any warnings? */ def hasWarnings: Boolean - def hasErrors: Boolean + + /** Emits a warning. + * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. + */ def warning(pos: Position, msg: String): Unit + + /** Does the compilation session have any errors? + */ + def hasErrors: Boolean + + /** Emits a compilation error. + * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. + */ def error(pos: Position, msg: String): Unit /** Abruptly terminates current macro expansion leaving a note about what happened. - * Use ``enclosingPosition'' if you're in doubt what position to pass to ``pos''. + * Use `enclosingPosition` if you're in doubt what position to pass to `pos`. */ def abort(pos: Position, msg: String): Nothing - - /** Drops into interactive mode if supported by the compiler UI */ - def interactive(): Unit }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/Infrastructure.scala b/src/reflect/scala/reflect/macros/Infrastructure.scala index 80153ff257..2f3b8e8d19 100644 --- a/src/reflect/scala/reflect/macros/Infrastructure.scala +++ b/src/reflect/scala/reflect/macros/Infrastructure.scala @@ -1,80 +1,22 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * provides facilities to communicate with the compiler's infrastructure. + */ trait Infrastructure { self: Context => - /** Determines whether the compiler expanding a macro targets JVM. + /** Exposes macro-specific settings as a list of strings. + * These settings are passed to the compiler via the "-Xmacro-settings:setting1,setting2...,settingN" command-line option. */ - val forJVM: Boolean + def settings: List[String] - /** Determines whether the compiler expanding a macro targets CLR. + /** Exposes current compiler settings as a list of options. + * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. */ - val forMSIL: Boolean + def compilerSettings: List[String] - /** Determines whether the compiler expanding a macro is a presentation compiler. - */ - val forInteractive: Boolean - - /** Determines whether the compiler expanding a macro is a Scaladoc compiler. - */ - val forScaladoc: Boolean - - /** Exposes current compilation run. - */ - val currentRun: Run - - /** Exposes library classpath. - */ - val libraryClassPath: List[java.net.URL] - - /** Exposes a classloader that corresponds to the library classpath. - * - * With this classloader you can perform on-the-fly evaluation of macro arguments. - * For example, consider this code snippet: - * - * def staticEval[T](x: T) = macro staticEval[T] - * - * def staticEval[T](c: Context)(x: c.Expr[T]) = { - * import scala.reflect.runtime.{universe => ru} - * val mirror = ru.runtimeMirror(c.libraryClassLoader) - * import scala.tools.reflect.ToolBox - * val toolBox = mirror.mkToolBox() - * val importer = ru.mkImporter(c.universe).asInstanceOf[ru.Importer { val from: c.universe.type }] - * val tree = c.resetAllAttrs(x.tree.duplicate) - * val imported = importer.importTree(tree) - * val valueOfX = toolBox.eval(imported).asInstanceOf[T] - * ... - * } - */ - def libraryClassLoader: ClassLoader - - /** As seen by macro API, compilation run is an opaque type that can be deconstructed into: - * 1) Current compilation unit - * 2) List of all compilation units that comprise the run - */ - type Run - - val Run: RunExtractor - - abstract class RunExtractor { - def unapply(run: Run): Option[(CompilationUnit, List[CompilationUnit])] - } - - /** As seen by macro API, compilation unit is an opaque type that can be deconstructed into: - * 1) File that corresponds to the unit (if not applicable, null) - * 2) Content of the file (if not applicable, empty array) - * 3) Body, i.e. the AST that represents the compilation unit - */ - type CompilationUnit - - val CompilationUnit: CompilationUnitExtractor - - abstract class CompilationUnitExtractor { - def unapply(compilationUnit: CompilationUnit): Option[(java.io.File, Array[Char], Tree)] - } - - /** Returns a macro definition which triggered this macro expansion. - */ - val currentMacro: Symbol -} + /** Exposes current classpath. */ + def classPath: List[java.net.URL] +}
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/Names.scala b/src/reflect/scala/reflect/macros/Names.scala index fab9bbbca5..20e750b225 100644 --- a/src/reflect/scala/reflect/macros/Names.scala +++ b/src/reflect/scala/reflect/macros/Names.scala @@ -1,15 +1,20 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * provides functions that generate unique names. + */ trait Names { self: Context => - /** Creates a fresh string */ + /** Creates a unique string. */ def fresh(): String - /** Creates a fresh string from the provided string */ + /** Creates a unique string having a given prefix. */ def fresh(name: String): String - /** Creates a fresh name from the provided name */ + /** Creates a unique name having a given name as a prefix and + * having the same flavor (term name or type name) as the given name. + */ def fresh[NameType <: Name](name: NameType): NameType } diff --git a/src/reflect/scala/reflect/macros/Parsers.scala b/src/reflect/scala/reflect/macros/Parsers.scala index 1742d07b60..bf73c36b1b 100644 --- a/src/reflect/scala/reflect/macros/Parsers.scala +++ b/src/reflect/scala/reflect/macros/Parsers.scala @@ -1,18 +1,19 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * exposes functions to parse strings with Scala code into trees. + */ trait Parsers { self: Context => - /** .. */ - // todo. distinguish between `parse` and `parse` + /** Parses a string with a Scala expression into an abstract syntax tree. + * Only works for expressions, i.e. parsing a package declaration will fail. + * @throws [[scala.reflect.macros.ParseException]] + */ def parse(code: String): Tree +} - /** Represents an error during parsing - */ - type ParseError <: Throwable - val ParseError: ParseErrorExtractor - abstract class ParseErrorExtractor { - def unapply(error: ParseError): Option[(Position, String)] - } -}
\ No newline at end of file +/** Indicates an error during [[scala.reflect.macros.Parsers#parse]]. + */ +case class ParseException(val pos: scala.reflect.api.Position, val msg: String) extends Exception(msg) diff --git a/src/reflect/scala/reflect/macros/Reifiers.scala b/src/reflect/scala/reflect/macros/Reifiers.scala index c2a6c5be05..d7ee30c7d9 100644 --- a/src/reflect/scala/reflect/macros/Reifiers.scala +++ b/src/reflect/scala/reflect/macros/Reifiers.scala @@ -1,21 +1,17 @@ package scala.reflect package macros -import scala.reflect.api.PositionApi - +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * exposes functions to save reflection artifacts for runtime. + */ trait Reifiers { self: Context => - /** Reification prefix that refers to the runtime reflexive universe, ``scala.reflect.runtime.universe''. - * Providing it for the ``prefix'' parameter of ``reifyTree'' or ``reifyType'' will create a full-fledged tree that can be inspected at runtime. - */ - val runtimeUniverse: Tree - /** Given a tree, generate a tree that when compiled and executed produces the original tree. * For more information and examples see the documentation for ``Universe.reify''. * * The produced tree will be bound to the specified ``universe'' and ``mirror''. - * Possible values for ``universe'' include ``runtimeUniverse''. + * Possible values for ``universe'' include ``universe.treeBuild.mkRuntimeUniverseRef''. * Possible values for ``mirror'' include ``EmptyTree'' (in that case the reifier will automatically pick an appropriate mirror). * * This function is deeply connected to ``Universe.reify'', a macro that reifies arbitrary expressions into runtime trees. @@ -83,6 +79,14 @@ trait Reifiers { // made these guys non path-dependent, otherwise exception handling quickly becomes a mess -case class ReificationError(val pos: PositionApi, val msg: String) extends Throwable(msg) +/** Indicates an expected error during one of the `reifyXXX` methods in [[scala.reflect.macros.Reifiers]]. + * Such errors represent one of the standard ways for reification to go wrong, e.g. + * an attempt to create a `TypeTag` from a weak type. + */ +case class ReificationException(val pos: scala.reflect.api.Position, val msg: String) extends Exception(msg) -case class UnexpectedReificationError(val pos: PositionApi, val msg: String, val cause: Throwable = null) extends Throwable(msg, cause) +/** Indicates an unexpected expected error during one of the `reifyXXX` methods in [[scala.reflect.macros.Reifiers]]. + * Such errors wrap random crashes in reification logic and are distinguished from expected [[scala.reflect.macros.ReificationException]]s + * so that the latter can be reported as compilation errors, while the former manifest themselves as compiler crashes. + */ +case class UnexpectedReificationException(val pos: scala.reflect.api.Position, val msg: String, val cause: Throwable = null) extends Exception(msg, cause) diff --git a/src/reflect/scala/reflect/macros/Settings.scala b/src/reflect/scala/reflect/macros/Settings.scala deleted file mode 100644 index a2cdb4c8e1..0000000000 --- a/src/reflect/scala/reflect/macros/Settings.scala +++ /dev/null @@ -1,36 +0,0 @@ -package scala.reflect -package macros - -trait Settings { - self: Context => - - /** Exposes macro-specific settings as a list of strings. - * These settings are passed to the compiler via the "-Xmacro-settings:setting1,setting2...,settingN" command-line option. - */ - def settings: List[String] - - /** Exposes current compiler settings as a list of options. - * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. - */ - def compilerSettings: List[String] - - /** Updates current compiler settings with an option string. - * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. - */ - def setCompilerSettings(options: String): this.type - - /** Updates current compiler settings with a list of options. - * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. - */ - def setCompilerSettings(options: List[String]): this.type - - /** Temporarily sets compiler settings to a given option string and executes a given closure. - * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. - */ - def withCompilerSettings[T](options: String)(op: => T): T - - /** Temporarily sets compiler settings to a given list of options and executes a given closure. - * Use `scalac -help`, `scalac -X` and `scalac -Y` to learn about currently supported options. - */ - def withCompilerSettings[T](options: List[String])(op: => T): T -}
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/TreeBuilder.scala b/src/reflect/scala/reflect/macros/TreeBuilder.scala index ca29194859..727387c5af 100644 --- a/src/reflect/scala/reflect/macros/TreeBuilder.scala +++ b/src/reflect/scala/reflect/macros/TreeBuilder.scala @@ -1,6 +1,9 @@ package scala.reflect package macros +/** A helper available in [[scala.reflect.macros.Universe]] that defines shorthands for the + * most common tree-creating functions. + */ abstract class TreeBuilder { val global: Universe @@ -46,11 +49,28 @@ abstract class TreeBuilder { * @return the newly created trees. */ def mkMethodCall(receiver: Symbol, methodName: Name, targs: List[Type], args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(method: Symbol, targs: List[Type], args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(method: Symbol, args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(target: Tree, args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(receiver: Symbol, methodName: Name, args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(receiver: Tree, method: Symbol, targs: List[Type], args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkMethodCall(target: Tree, targs: List[Type], args: List[Tree]): Tree + + /** TODO how to refer to the main `mkMethodCall`? */ def mkNullaryCall(method: Symbol, targs: List[Type]): Tree + + /** A tree that refers to the runtime reflexive universe, ``scala.reflect.runtime.universe''. */ + def mkRuntimeUniverseRef: Tree } diff --git a/src/reflect/scala/reflect/macros/TypeTags.scala b/src/reflect/scala/reflect/macros/TypeTags.scala deleted file mode 100644 index 2f15e37f6a..0000000000 --- a/src/reflect/scala/reflect/macros/TypeTags.scala +++ /dev/null @@ -1,9 +0,0 @@ -package scala.reflect -package macros - -trait TypeTags { - self: Context => - - def WeakTypeTag[T](tpe: Type): WeakTypeTag[T] - def TypeTag[T](tpe: Type): TypeTag[T] -} diff --git a/src/reflect/scala/reflect/macros/Typers.scala b/src/reflect/scala/reflect/macros/Typers.scala index eef6507418..016a08bd01 100644 --- a/src/reflect/scala/reflect/macros/Typers.scala +++ b/src/reflect/scala/reflect/macros/Typers.scala @@ -1,6 +1,9 @@ package scala.reflect package macros +/** A slice of [[scala.reflect.macros.Context the Scala macros context]] that + * partially exposes the type checker to macro writers. + */ trait Typers { self: Context => @@ -24,11 +27,11 @@ trait Typers { * Unlike `enclosingImplicits`, this is a def, which means that it gets recalculated on every invocation, * so it might change depending on what is going on during macro expansion. */ - def openImplicits: List[(Type, Tree)] + def openImplicits: List[(Type, Tree)] /** Typechecks the provided tree against the expected type `pt` in the macro callsite context. * - * If `silent` is false, `TypeError` will be thrown in case of a typecheck error. + * If `silent` is false, `TypecheckException` will be thrown in case of a typecheck error. * If `silent` is true, the typecheck is silent and will return `EmptyTree` if an error occurs. * Such errors don't vanish and can be inspected by turning on -Ymacro-debug-verbose. * Unlike in `inferImplicitValue` and `inferImplicitView`, `silent` is false by default. @@ -36,26 +39,32 @@ trait Typers { * Typechecking can be steered with the following optional parameters: * `withImplicitViewsDisabled` recursively prohibits implicit views (though, implicit vals will still be looked up and filled in), default value is false * `withMacrosDisabled` recursively prohibits macro expansions and macro-based implicits, default value is false + * + * @throws [[scala.reflect.macros.TypecheckException]] */ def typeCheck(tree: Tree, pt: Type = WildcardType, silent: Boolean = false, withImplicitViewsDisabled: Boolean = false, withMacrosDisabled: Boolean = false): Tree /** Infers an implicit value of the expected type `pt` in the macro callsite context. * Optional `pos` parameter provides a position that will be associated with the implicit search. * - * If `silent` is false, `TypeError` will be thrown in case of an inference error. + * If `silent` is false, `TypecheckException` will be thrown in case of an inference error. * If `silent` is true, the typecheck is silent and will return `EmptyTree` if an error occurs. * Such errors don't vanish and can be inspected by turning on -Xlog-implicits. * Unlike in `typeCheck`, `silent` is true by default. + * + * @throws [[scala.reflect.macros.TypecheckException]] */ def inferImplicitValue(pt: Type, silent: Boolean = true, withMacrosDisabled: Boolean = false, pos: Position = enclosingPosition): Tree /** Infers an implicit view from the provided tree `tree` of the type `from` to the type `to` in the macro callsite context. * Optional `pos` parameter provides a position that will be associated with the implicit search. * - * If `silent` is false, `TypeError` will be thrown in case of an inference error. + * If `silent` is false, `TypecheckException` will be thrown in case of an inference error. * If `silent` is true, the typecheck is silent and will return `EmptyTree` if an error occurs. * Such errors don't vanish and can be inspected by turning on -Xlog-implicits. * Unlike in `typeCheck`, `silent` is true by default. + * + * @throws [[scala.reflect.macros.TypecheckException]] */ def inferImplicitView(tree: Tree, from: Type, to: Type, silent: Boolean = true, withMacrosDisabled: Boolean = false, pos: Position = enclosingPosition): Tree @@ -72,12 +81,8 @@ trait Typers { * For more info, read up https://issues.scala-lang.org/browse/SI-5464. */ def resetLocalAttrs(tree: Tree): Tree +} - /** Represents an error during typechecking - */ - type TypeError <: Throwable - val TypeError: TypeErrorExtractor - abstract class TypeErrorExtractor { - def unapply(error: TypeError): Option[(Position, String)] - } -}
\ No newline at end of file +/** Indicates an error during one of the methods in [[scala.reflect.macros.Typers]]. + */ +case class TypecheckException(val pos: scala.reflect.api.Position, val msg: String) extends Exception(msg) diff --git a/src/reflect/scala/reflect/macros/Universe.scala b/src/reflect/scala/reflect/macros/Universe.scala index f84c11ee63..86bc37b4c9 100644 --- a/src/reflect/scala/reflect/macros/Universe.scala +++ b/src/reflect/scala/reflect/macros/Universe.scala @@ -1,69 +1,125 @@ package scala.reflect package macros +/** The refinement of [[scala.reflect.api.Universe]] for the use by macro writers. + * + * This universe provides mutability for reflection artifacts (e.g. macros can change types of compiler trees, + * add annotation to symbols representing definitions, etc) and exposes some internal compiler functionality + * such as `Symbol.deSkolemize` or `Tree.attachments`. + * @groupname Macros Macro Specific Additions + * @groupprio Macros -1 + * + * @contentDiagram hideNodes "*Api" + */ abstract class Universe extends scala.reflect.api.Universe { + /** A factory that encapsulates common tree-building functions. + * @group Macros + */ val treeBuild: TreeBuilder { val global: Universe.this.type } + /** The API of reflection artifacts that support [[scala.reflect.macros.Attachments]]. + * These artifacts are trees and symbols. + * @group Macros + */ trait AttachableApi { - /** ... */ - def attachments: scala.reflect.api.Attachments { type Pos = Position } + /** The attachment of the reflection artifact. */ + def attachments: Attachments { type Pos = Position } - /** ... */ + /** Updates the attachment with the payload slot of T added/updated with the provided value. + * Replaces an existing payload of the same type, if exists. + * Returns the reflection artifact itself. + */ def updateAttachment[T: ClassTag](attachment: T): AttachableApi.this.type - /** ... */ + /** Update the attachment with the payload of the given class type `T` removed. + * Returns the reflection artifact itself. + */ def removeAttachment[T: ClassTag]: AttachableApi.this.type } // Symbol extensions --------------------------------------------------------------- + /** The `Symbol` API is extended for macros: See [[SymbolContextApi]] for details. + * + * @group Macros + */ override type Symbol >: Null <: SymbolContextApi /** The extended API of symbols that's supported in macro context universes + * @group API */ trait SymbolContextApi extends SymbolApi with AttachableApi { self: Symbol => + /** If this symbol is a skolem, its corresponding type parameter, otherwise the symbol itself. + * + * [[https://groups.google.com/forum/#!msg/scala-internals/0j8laVNTQsI/kRXMF_c8bGsJ To quote Martin Odersky]], + * skolems are synthetic type "constants" that are copies of existentially bound or universally + * bound type variables. E.g. if one is inside the right-hand side of a method: + * + * {{{ + * def foo[T](x: T) = ... foo[List[T]].... + * }}} + * + * the skolem named `T` refers to the unknown type instance of `T` when `foo` is called. It needs to be different + * from the type parameter because in a recursive call as in the `foo[List[T]]` above the type parameter gets + * substituted with `List[T]`, but the ''type skolem'' stays what it is. + * + * The other form of skolem is an ''existential skolem''. Say one has a function + * + * {{{ + * def bar(xs: List[T] forSome { type T }) = xs.head + * }}} + * + * then each occurrence of `xs` on the right will have type `List[T']` where `T'` is a fresh copy of `T`. + */ def deSkolemize: Symbol - /** The position of this symbol - */ + /** The position of this symbol. */ def pos: Position + /** Sets the `typeSignature` of the symbol. */ def setTypeSignature(tpe: Type): Symbol + /** Sets the `annotations` of the symbol. */ def setAnnotations(annots: Annotation*): Symbol + /** Sets the `name` of the symbol. */ def setName(name: Name): Symbol + /** Sets the `privateWithin` of the symbol. */ def setPrivateWithin(sym: Symbol): Symbol } // Tree extensions --------------------------------------------------------------- + /** The `Tree` API is extended for macros: See [[TreeContextApi]] for details. + * + * @group Macros + */ override type Tree >: Null <: TreeContextApi /** The extended API of trees that's supported in macro context universes + * @group API */ trait TreeContextApi extends TreeApi with AttachableApi { self: Tree => - /** ... */ + /** Sets the `pos` of the tree. Returns `Unit`. */ def pos_=(pos: Position): Unit - /** ... */ + /** Sets the `pos` of the tree. Returns the tree itself. */ def setPos(newpos: Position): Tree - /** ... */ + /** Sets the `tpe` of the tree. Returns `Unit`. */ def tpe_=(t: Type): Unit - /** Set tpe to give `tp` and return this. - */ + /** Sets the `tpe` of the tree. Returns the tree itself. */ def setType(tp: Type): Tree /** Like `setType`, but if this is a previously empty TypeTree that * fact is remembered so that resetAllAttrs will snap back. * - * @PP: Attempting to elaborate on the above, I find: If defineType + * \@PP: Attempting to elaborate on the above, I find: If defineType * is called on a TypeTree whose type field is null or NoType, * this is recorded as "wasEmpty = true". That value is used in * ResetAttrsTraverser, which nulls out the type field of TypeTrees @@ -79,34 +135,104 @@ abstract class Universe extends scala.reflect.api.Universe { */ def defineType(tp: Type): Tree - /** ... */ + /** Sets the `symbol` of the tree. Returns `Unit`. */ def symbol_=(sym: Symbol): Unit - /** ... */ + /** Sets the `symbol` of the tree. Returns the tree itself. */ def setSymbol(sym: Symbol): Tree } + /** @inheritdoc */ override type SymTree >: Null <: Tree with SymTreeContextApi /** The extended API of sym trees that's supported in macro context universes + * @group API */ trait SymTreeContextApi extends SymTreeApi { this: SymTree => + /** Sets the `symbol` field of the sym tree. */ var symbol: Symbol } + /** @inheritdoc */ override type TypeTree >: Null <: TypTree with TypeTreeContextApi /** The extended API of sym trees that's supported in macro context universes + * @group API */ trait TypeTreeContextApi extends TypeTreeApi { this: TypeTree => + /** Sets the `original` field of the type tree. */ def setOriginal(tree: Tree): this.type } + /** @inheritdoc */ override type Ident >: Null <: RefTree with IdentContextApi /** The extended API of idents that's supported in macro context universes + * @group API */ trait IdentContextApi extends IdentApi { this: Ident => + /** Was this ident created from a backquoted identifier? */ def isBackquoted: Boolean } + + /** Mark a variable as captured; i.e. force boxing in a *Ref type. + * @group Macros + */ + def captureVariable(vble: Symbol): Unit + + /** Mark given identifier as a reference to a captured variable itself + * suppressing dereferencing with the `elem` field. + * @group Macros + */ + def referenceCapturedVariable(vble: Symbol): Tree + + /** Convert type of a captured variable to *Ref type. + * @group Macros + */ + def capturedVariableType(vble: Symbol): Type + + /** The type of compilation runs. + * @template + * @group Macros + */ + type Run <: RunContextApi + + /** Compilation run uniquely identifies current invocation of the compiler + * (e.g. can be used to implement per-run caches for macros) and provides access to units of work + * of the invocation (currently processed unit of work and the list of all units). + * @group API + */ + trait RunContextApi { + /** Currently processed unit of work (a real or a virtual file). */ + def currentUnit: CompilationUnit + + /** All units of work comprising this compilation run. */ + def units: Iterator[CompilationUnit] + } + + /** The type of compilation units. + * @template + * @group Macros + */ + type CompilationUnit <: CompilationUnitContextApi + + /** Compilation unit describes a unit of work of the compilation run. + * It provides such information as file name, textual representation of the unit and the underlying AST. + * @group API + */ + trait CompilationUnitContextApi { + /** Source file corresponding to this compilation unit. + * + * Exposes information about the file as a part of a real or virtual file system + * along with the contents of that file. + * + * The return type is `scala.reflect.io.AbstractFile`, which belongs to an experimental part of Scala reflection. + * It should not be used unless you know what you are doing. In subsequent releases, this API will be refined + * and exposed as a part of scala.reflect.api. + */ + def source: scala.reflect.internal.util.SourceFile + + /** The AST that corresponds to this compilation unit. */ + def body: Tree + } }
\ No newline at end of file diff --git a/src/reflect/scala/reflect/macros/package.scala b/src/reflect/scala/reflect/macros/package.scala index df93785d40..3a2f04bcf2 100644 --- a/src/reflect/scala/reflect/macros/package.scala +++ b/src/reflect/scala/reflect/macros/package.scala @@ -1,6 +1,12 @@ package scala.reflect +/** The base package for Scala macros. + * + * Macros are functions that are called by the compiler during compilation. + * Within these functions the programmer has access to compiler APIs exposed in [[scala.reflect.macros.Context]]. + * For example, it is possible to generate, analyze and typecheck code. + * + * See the [[http://docs.scala-lang.org/overviews/macros.html Macros Guide]] on how to get started with Scala macros. + */ package object macros { - - type MirrorOf[U <: scala.reflect.api.Universe with Singleton] = scala.reflect.api.MirrorOf[U] -} +}
\ No newline at end of file diff --git a/src/reflect/scala/reflect/runtime/JavaMirrors.scala b/src/reflect/scala/reflect/runtime/JavaMirrors.scala index 2f12ba59a2..2d08cd887b 100644 --- a/src/reflect/scala/reflect/runtime/JavaMirrors.scala +++ b/src/reflect/scala/reflect/runtime/JavaMirrors.scala @@ -24,7 +24,7 @@ import scala.language.existentials import scala.runtime.{ScalaRunTime, BoxesRunTime} import scala.reflect.internal.util.Collections._ -trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUniverse: SymbolTable => +private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUniverse: SymbolTable => private lazy val mirrors = new WeakHashMap[ClassLoader, WeakReference[JavaMirror]]() @@ -44,6 +44,8 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive // overriden by ReflectGlobal def rootClassLoader: ClassLoader = this.getClass.getClassLoader + trait JavaClassCompleter extends FlagAssigningCompleter + def init() = { definitions.AnyValClass // force it. @@ -71,7 +73,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive /** The lazy type for root. */ - override lazy val rootLoader = new LazyType { + override lazy val rootLoader = new LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) = sym setInfo new LazyPackageType } @@ -96,7 +98,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive private val fieldCache = new TwoWayCache[jField, TermSymbol] private val tparamCache = new TwoWayCache[jTypeVariable[_ <: GenericDeclaration], TypeSymbol] - def toScala[J: HasJavaClass, S](cache: TwoWayCache[J, S], key: J)(body: (JavaMirror, J) => S): S = + private[runtime] def toScala[J: HasJavaClass, S](cache: TwoWayCache[J, S], key: J)(body: (JavaMirror, J) => S): S = cache.toScala(key){ val jclazz = implicitly[HasJavaClass[J]] getClazz key body(mirrorDefining(jclazz), key) @@ -298,7 +300,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive def showTparams(tparams: List[Symbol]) = "[" + (tparams map showTparam mkString ", ") + "]" sig += showTparams(symbol.typeParams) } - if (symbol.params.nonEmpty) { + if (symbol.paramss.nonEmpty) { def showParam(param: Symbol) = s"${param.name}: ${param.typeSignature}" def showParams(params: List[Symbol]) = { val s_mods = if (params.nonEmpty && params(0).hasFlag(IMPLICIT)) "implicit " else "" @@ -306,7 +308,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive "(" + s_mods + s_params + ")" } def showParamss(paramss: List[List[Symbol]]) = paramss map showParams mkString "" - sig += showParamss(symbol.params) + sig += showParamss(symbol.paramss) } sig += s": ${symbol.returnType}" sig @@ -314,7 +316,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive // the "symbol == Any_getClass || symbol == Object_getClass" test doesn't cut it // because both AnyVal and its primitive descendants define their own getClass methods - private def isGetClass(meth: MethodSymbol) = meth.name.toString == "getClass" && meth.params.flatten.isEmpty + private def isGetClass(meth: MethodSymbol) = meth.name.toString == "getClass" && meth.paramss.flatten.isEmpty private def isStringConcat(meth: MethodSymbol) = meth == String_+ || (meth.owner.isPrimitiveValueClass && meth.returnType =:= StringClass.toType) lazy val bytecodelessMethodOwners = Set[Symbol](AnyClass, AnyValClass, AnyRefClass, ObjectClass, ArrayClass) ++ ScalaPrimitiveValueClasses lazy val bytecodefulObjectMethods = Set[Symbol](Object_clone, Object_equals, Object_finalize, Object_hashCode, Object_toString, @@ -330,7 +332,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive // rather than have them on a hot path them in a unified implementation of the `apply` method private def mkJavaMethodMirror[T: ClassTag](receiver: T, symbol: MethodSymbol): JavaMethodMirror = { if (isBytecodelessMethod(symbol)) new JavaBytecodelessMethodMirror(receiver, symbol) - else if (symbol.params.flatten exists (p => isByNameParamType(p.info))) new JavaByNameMethodMirror(receiver, symbol) + else if (symbol.paramss.flatten exists (p => isByNameParamType(p.info))) new JavaByNameMethodMirror(receiver, symbol) else new JavaVanillaMethodMirror(receiver, symbol) } @@ -359,7 +361,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive private class JavaByNameMethodMirror(val receiver: Any, symbol: MethodSymbol) extends JavaMethodMirror(symbol) { def apply(args: Any*): Any = { - val transformed = map2(args.toList, symbol.params.flatten)((arg, param) => if (isByNameParamType(param.info)) () => arg else arg) + val transformed = map2(args.toList, symbol.paramss.flatten)((arg, param) => if (isByNameParamType(param.info)) () => arg else arg) jinvoke(jmeth, receiver, transformed) } } @@ -444,8 +446,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive extends TemplateMirror { def outer: AnyRef def erasure: ClassSymbol - lazy val runtimeClass = classToJava(erasure) - lazy val signature = typeToScala(runtimeClass) + lazy val signature = typeToScala(classToJava(erasure)) } private class JavaClassMirror(val outer: AnyRef, val symbol: ClassSymbol) @@ -456,10 +457,6 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive checkConstructorOf(constructor, symbol) new JavaConstructorMirror(outer, constructor) } - def companion: Option[ModuleMirror] = symbol.companionModule match { - case module: ModuleSymbol => Some(new JavaModuleMirror(outer, module)) - case _ => None - } override def toString = s"class mirror for ${symbol.fullName} (bound to $outer)" } @@ -474,10 +471,6 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive if (outer == null) staticSingletonInstance(classToJava(symbol.moduleClass.asClass)) else innerSingletonInstance(outer, symbol.name) } - def companion: Option[ClassMirror] = symbol.companionClass match { - case cls: ClassSymbol => Some(new JavaClassMirror(outer, cls)) - case _ => None - } override def toString = s"module mirror for ${symbol.fullName} (bound to $outer)" } @@ -609,7 +602,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive * A completer that fills in the type of a Scala type parameter from the bounds of a Java type variable. * @param jtvar The Java type variable */ - private class TypeParamCompleter(jtvar: jTypeVariable[_ <: GenericDeclaration]) extends LazyType { + private class TypeParamCompleter(jtvar: jTypeVariable[_ <: GenericDeclaration]) extends LazyType with FlagAgnosticCompleter { override def load(sym: Symbol) = complete(sym) override def complete(sym: Symbol) = { sym setInfo TypeBounds.upper(glb(jtvar.getBounds.toList map typeToScala map objToAny)) @@ -634,7 +627,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive * @param module The Scala companion object for which info is copied * @param jclazz The Java class */ - private class FromJavaClassCompleter(clazz: Symbol, module: Symbol, jclazz: jClass[_]) extends LazyType { + private class FromJavaClassCompleter(clazz: Symbol, module: Symbol, jclazz: jClass[_]) extends LazyType with JavaClassCompleter with FlagAssigningCompleter { /** used to avoid cycles while initializing classes */ private var parentsLevel = 0 @@ -710,7 +703,7 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive } } - class LazyPolyType(override val typeParams: List[Symbol]) extends LazyType { + class LazyPolyType(override val typeParams: List[Symbol]) extends LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) { completeRest() } @@ -1277,6 +1270,6 @@ trait JavaMirrors extends internal.SymbolTable with api.JavaUniverse { thisUnive } } -class ReflectError(msg: String) extends java.lang.Error(msg) +private[reflect] class ReflectError(msg: String) extends java.lang.Error(msg) -class HasJavaClass[J](val getClazz: J => java.lang.Class[_]) +private[reflect] class HasJavaClass[J](val getClazz: J => java.lang.Class[_]) diff --git a/src/reflect/scala/reflect/runtime/JavaUniverse.scala b/src/reflect/scala/reflect/runtime/JavaUniverse.scala index 1d875b10f1..e18435d5b0 100644 --- a/src/reflect/scala/reflect/runtime/JavaUniverse.scala +++ b/src/reflect/scala/reflect/runtime/JavaUniverse.scala @@ -3,8 +3,11 @@ package runtime import internal.{SomePhase, NoPhase, Phase, TreeGen} -/** The universe for standard runtime reflection from Java. - * This type implements all abstract term members in internal.SymbolTable. +/** An implementation of [[scala.reflect.api.Universe]] for runtime reflection using JVM classloaders. + * + * Should not be instantiated directly, use [[scala.reflect.runtime.universe]] instead. + * + * @contentDiagram hideNodes "*Api" "*Extractor" */ class JavaUniverse extends internal.SymbolTable with ReflectSetup with runtime.SymbolTable { self => diff --git a/src/reflect/scala/reflect/runtime/ReflectionUtils.scala b/src/reflect/scala/reflect/runtime/ReflectionUtils.scala index 44d9d94a46..73425bae55 100644 --- a/src/reflect/scala/reflect/runtime/ReflectionUtils.scala +++ b/src/reflect/scala/reflect/runtime/ReflectionUtils.scala @@ -10,7 +10,7 @@ import java.lang.reflect.{ Method, InvocationTargetException, UndeclaredThrowabl /** A few java-reflection oriented utility functions useful during reflection bootstrapping. */ -object ReflectionUtils { +private[scala] object ReflectionUtils { // Unwraps some chained exceptions which arise during reflective calls. def unwrapThrowable(x: Throwable): Throwable = x match { case _: InvocationTargetException | // thrown by reflectively invoked method or constructor diff --git a/src/reflect/scala/reflect/runtime/Settings.scala b/src/reflect/scala/reflect/runtime/Settings.scala index da4f4fbda1..0e0cf3fc40 100644 --- a/src/reflect/scala/reflect/runtime/Settings.scala +++ b/src/reflect/scala/reflect/runtime/Settings.scala @@ -7,7 +7,7 @@ import scala.reflect.internal.settings.MutableSettings * This should be refined, so that settings are settable via command * line options or properties. */ -class Settings extends MutableSettings { +private[reflect] class Settings extends MutableSettings { trait Setting extends SettingValue { } diff --git a/src/reflect/scala/reflect/runtime/SymbolLoaders.scala b/src/reflect/scala/reflect/runtime/SymbolLoaders.scala index f3473d46a7..61663f6181 100644 --- a/src/reflect/scala/reflect/runtime/SymbolLoaders.scala +++ b/src/reflect/scala/reflect/runtime/SymbolLoaders.scala @@ -5,7 +5,7 @@ import internal.Flags import java.lang.{Class => jClass, Package => jPackage} import scala.collection.mutable -trait SymbolLoaders { self: SymbolTable => +private[reflect] trait SymbolLoaders { self: SymbolTable => /** The standard completer for top-level classes * @param clazz The top-level class @@ -14,7 +14,7 @@ trait SymbolLoaders { self: SymbolTable => * by unpickling information from the corresponding Java class. If no Java class * is found, a package is created instead. */ - class TopClassCompleter(clazz: Symbol, module: Symbol) extends SymLoader { + class TopClassCompleter(clazz: Symbol, module: Symbol) extends SymLoader with FlagAssigningCompleter { // def makePackage() { // println("wrong guess; making package "+clazz) // val ptpe = newPackageType(module.moduleClass) @@ -80,7 +80,7 @@ trait SymbolLoaders { self: SymbolTable => /** The type completer for packages. */ - class LazyPackageType extends LazyType { + class LazyPackageType extends LazyType with FlagAgnosticCompleter { override def complete(sym: Symbol) { assert(sym.isPackageClass) sym setInfo new ClassInfoType(List(), new PackageScope(sym), sym) diff --git a/src/reflect/scala/reflect/runtime/SymbolTable.scala b/src/reflect/scala/reflect/runtime/SymbolTable.scala index 5b9090dae5..5c08e9a508 100644 --- a/src/reflect/scala/reflect/runtime/SymbolTable.scala +++ b/src/reflect/scala/reflect/runtime/SymbolTable.scala @@ -1,12 +1,14 @@ package scala.reflect package runtime +import scala.reflect.internal.Flags._ + /** * This symbol table trait fills in the definitions so that class information is obtained by refection. * It can be used either from a reflexive universe (class scala.reflect.runtime.JavaUniverse), or else from * a runtime compiler that uses reflection to get a class information (class scala.tools.reflect.ReflectGlobal) */ -trait SymbolTable extends internal.SymbolTable with JavaMirrors with SymbolLoaders with SynchronizedOps { +private[scala] trait SymbolTable extends internal.SymbolTable with JavaMirrors with SymbolLoaders with SynchronizedOps { def info(msg: => String) = if (settings.verbose.value) println("[reflect-compiler] "+msg) @@ -14,4 +16,30 @@ trait SymbolTable extends internal.SymbolTable with JavaMirrors with SymbolLoade def debugInfo(msg: => String) = if (settings.debug.value) info(msg) + /** Declares that this is a runtime reflection universe. + * + * This means that we can make certain assumptions to optimize the universe. + * For example, we may auto-initialize symbols on flag and annotation requests + * (see `shouldTriggerCompleter` below for more details). + * + * On the other hand, this also means that usage scenarios of the universe + * will differ from the conventional ones. For example, we have to do additional cleanup + * in order to prevent memory leaks: http://groups.google.com/group/scala-internals/browse_thread/thread/eabcf3d406dab8b2. + */ + override def isCompilerUniverse = false + + /** Unlike compiler universes, reflective universes can auto-initialize symbols on flag requests. + * + * scalac wasn't designed with such auto-initialization in mind, and quite often it makes assumptions + * that flag requests won't cause initialization. Therefore enabling auto-init leads to cyclic errors. + * We could probably fix those, but at the moment it's too risky. + * + * Reflective universes share codebase with scalac, but their surface is much smaller, which means less assumptions. + * These assumptions are taken care of in this overriden `shouldTriggerCompleter` method. + */ + override protected def shouldTriggerCompleter(symbol: Symbol, completer: Type, isFlagRelated: Boolean, mask: Long) = + completer match { + case _: TopClassCompleter | _: JavaClassCompleter => !isFlagRelated || (mask & TopLevelPickledFlags) != 0 + case _ => super.shouldTriggerCompleter(symbol, completer, isFlagRelated, mask) + } } diff --git a/src/reflect/scala/reflect/runtime/SynchronizedOps.scala b/src/reflect/scala/reflect/runtime/SynchronizedOps.scala index 1a17dd12d2..7b280e59b9 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedOps.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedOps.scala @@ -2,7 +2,7 @@ package scala.reflect package runtime // SI-6240: test thread-safety, make trees synchronized as well -trait SynchronizedOps extends internal.SymbolTable +private[reflect] trait SynchronizedOps extends internal.SymbolTable with SynchronizedSymbols with SynchronizedTypes { self: SymbolTable => diff --git a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala index 3c2885a9f4..00f6952dc1 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedSymbols.scala @@ -3,7 +3,7 @@ package runtime import scala.reflect.io.AbstractFile -trait SynchronizedSymbols extends internal.Symbols { self: SymbolTable => +private[reflect] trait SynchronizedSymbols extends internal.Symbols { self: SymbolTable => override protected def nextId() = synchronized { super.nextId() } @@ -110,7 +110,7 @@ trait SynchronizedSymbols extends internal.Symbols { self: SymbolTable => trait SynchronizedMethodSymbol extends MethodSymbol with SynchronizedTermSymbol { override def typeAsMemberOf(pre: Type): Type = synchronized { super.typeAsMemberOf(pre) } - override def params: List[List[Symbol]] = synchronized { super.params } + override def paramss: List[List[Symbol]] = synchronized { super.paramss } override def returnType: Type = synchronized { super.returnType } } diff --git a/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala b/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala index b9b140a2fd..a3e7c28ca4 100644 --- a/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala +++ b/src/reflect/scala/reflect/runtime/SynchronizedTypes.scala @@ -7,7 +7,7 @@ import java.lang.ref.WeakReference /** This trait overrides methods in reflect.internal, bracketing * them in synchronized { ... } to make them thread-safe */ -trait SynchronizedTypes extends internal.Types { self: SymbolTable => +private[reflect] trait SynchronizedTypes extends internal.Types { self: SymbolTable => // No sharing of map objects: override protected def commonOwnerMap = new CommonOwnerMap @@ -24,7 +24,8 @@ trait SynchronizedTypes extends internal.Types { self: SymbolTable => // i.e. they have their caches cleaned up automatically on per-run basis, // therefore they should use vanilla uniques, which are faster if (!isCompilerUniverse) { - val result = if (uniques contains tp) uniques(tp).get else null + val inCache = uniques get tp + val result = if (inCache.isDefined) inCache.get.get else null if (result ne null) result.asInstanceOf[T] else { uniques(tp) = new WeakReference(tp) diff --git a/src/reflect/scala/reflect/runtime/package.scala b/src/reflect/scala/reflect/runtime/package.scala index 7b9f69e657..b97913daf0 100644 --- a/src/reflect/scala/reflect/runtime/package.scala +++ b/src/reflect/scala/reflect/runtime/package.scala @@ -1,17 +1,30 @@ package scala.reflect +/** Entry points into runtime reflection. + * See [[scala.reflect.api.package the overview page]] for details on how to use them. + */ package object runtime { - // type is api.JavaUniverse because we only want to expose the `scala.reflect.api.*` subset of reflection + /** The entry point into Scala runtime reflection. + * + * To use Scala runtime reflection, simply use or import `scala.reflect.runtime.universe._` + * + * See [[scala.reflect.api.Universe]] or the + * [[http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html Reflection Guide: Universes]] + * for more details. + */ lazy val universe: api.JavaUniverse = new runtime.JavaUniverse + /** The runtime reflection mirror that corresponds to the current lexical context. + * It's typically equivalent to `universe.runtimeMirror(getClass.getClassLoader)` invoked at the call site. + */ // implementation hardwired to the `currentMirror` method below // using the mechanism implemented in `scala.tools.reflect.FastTrack` def currentMirror: universe.Mirror = ??? // macro } package runtime { - object Macros { + private[scala] object Macros { def currentMirror(c: scala.reflect.macros.Context): c.Expr[universe.Mirror] = { import c.universe._ val runtimeClass = c.reifyEnclosingRuntimeClass diff --git a/src/swing/scala/swing/ColorChooser.scala b/src/swing/scala/swing/ColorChooser.scala new file mode 100644 index 0000000000..9bd71e1df0 --- /dev/null +++ b/src/swing/scala/swing/ColorChooser.scala @@ -0,0 +1,45 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2012, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + + + +package scala.swing + +import javax.swing.JColorChooser +import event._ + +/** + * Wrapper for JColorChooser. Publishes `ColorChanged` events, when the color selection changes. + * + * @author andy@hicks.net + * @author Ingo Maier + * @see javax.swing.JColorChooser + */ +object ColorChooser { + def showDialog(parent: Component, title: String, color: Color): scala.Option[Color] = { + toOption[Color](javax.swing.JColorChooser.showDialog(parent.peer, title, color)) + } +} + +class ColorChooser(color0: Color) extends Component { + def this() = this(java.awt.Color.white) + + override lazy val peer: JColorChooser = new JColorChooser(color0) with SuperMixin + + peer.getSelectionModel.addChangeListener(new javax.swing.event.ChangeListener { + def stateChanged(e: javax.swing.event.ChangeEvent) { + publish(ColorChanged(ColorChooser.this, peer.getColor)) + } + }) + + def color: Color = peer.getColor + def color_=(c: Color) = peer.setColor(c) + + def dragEnabled: Boolean = peer.getDragEnabled + def dragEnabled_=(b: Boolean) = peer.setDragEnabled(b) +}
\ No newline at end of file diff --git a/src/swing/scala/swing/PopupMenu.scala b/src/swing/scala/swing/PopupMenu.scala new file mode 100644 index 0000000000..0f292b11a2 --- /dev/null +++ b/src/swing/scala/swing/PopupMenu.scala @@ -0,0 +1,65 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2012, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + + + +package scala.swing + +import javax.swing.JPopupMenu +import javax.swing.event.{PopupMenuListener, PopupMenuEvent} +import event._ + +/** + * A popup menu. + * + * Example usage: + * + * {{{ + * val popupMenu = new PopupMenu { + * contents += new Menu("menu 1") { + * contents += new RadioMenuItem("radio 1.1") + * contents += new RadioMenuItem("radio 1.2") + * } + * contents += new Menu("menu 2") { + * contents += new RadioMenuItem("radio 2.1") + * contents += new RadioMenuItem("radio 2.2") + * } + * } + * val button = new Button("Show Popup Menu") + * reactions += { + * case e: ButtonClicked => popupMenu.show(button, 0, button.bounds.height) + * } + * listenTo(button) + * }}} + * + * @author John Sullivan + * @author Ingo Maier + * @see javax.swing.JPopupMenu + */ +class PopupMenu extends Component with SequentialContainer.Wrapper with Publisher { + override lazy val peer: JPopupMenu = new JPopupMenu with SuperMixin + + peer.addPopupMenuListener(new PopupMenuListener { + def popupMenuCanceled(e: PopupMenuEvent) { + publish(PopupMenuCanceled(PopupMenu.this)) + } + def popupMenuWillBecomeInvisible(e: PopupMenuEvent) { + publish(PopupMenuWillBecomeInvisible(PopupMenu.this)) + } + def popupMenuWillBecomeVisible(e: PopupMenuEvent) { + publish(PopupMenuWillBecomeVisible(PopupMenu.this)) + } + }) + + def show(invoker: Component, x: Int, y: Int): Unit = peer.show(invoker.peer, x, y) + + def margin: Insets = peer.getMargin + def label: String = peer.getLabel + def label_=(s: String) { peer.setLabel(s) } +} + diff --git a/src/swing/scala/swing/event/ColorChanged.scala b/src/swing/scala/swing/event/ColorChanged.scala new file mode 100644 index 0000000000..44387aa864 --- /dev/null +++ b/src/swing/scala/swing/event/ColorChanged.scala @@ -0,0 +1,14 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2011, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + + + +package scala.swing +package event + +case class ColorChanged(source: Component, c: Color) extends ComponentEvent with SelectionEvent diff --git a/src/swing/scala/swing/event/PopupMenuEvent.scala b/src/swing/scala/swing/event/PopupMenuEvent.scala new file mode 100644 index 0000000000..f7083c06de --- /dev/null +++ b/src/swing/scala/swing/event/PopupMenuEvent.scala @@ -0,0 +1,18 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2007-2012, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + + + +package scala.swing +package event + +abstract class PopupMenuEvent extends ComponentEvent + +case class PopupMenuCanceled(source: PopupMenu) extends PopupMenuEvent +case class PopupMenuWillBecomeInvisible(source: PopupMenu) extends PopupMenuEvent +case class PopupMenuWillBecomeVisible(source: PopupMenu) extends PopupMenuEvent
\ No newline at end of file diff --git a/test/files/continuations-neg/lazy.check b/test/files/continuations-neg/lazy.check index b8c6887409..3c460546be 100644 --- a/test/files/continuations-neg/lazy.check +++ b/test/files/continuations-neg/lazy.check @@ -1,6 +1,4 @@ -lazy.scala:5: error: type mismatch; - found : Unit @scala.util.continuations.cpsParam[Unit,Unit] - required: Unit - def foo() = { - ^ +lazy.scala:6: error: implementation restriction: cps annotations not allowed on lazy value definitions + lazy val x = shift((k:Unit=>Unit)=>k()) + ^ one error found diff --git a/test/files/continuations-neg/t5314-missing-result-type.check b/test/files/continuations-neg/t5314-missing-result-type.check new file mode 100644 index 0000000000..341e580cf3 --- /dev/null +++ b/test/files/continuations-neg/t5314-missing-result-type.check @@ -0,0 +1,4 @@ +t5314-missing-result-type.scala:6: error: method bar has return statement; needs result type + def bar(x:Int) = return foo(x) + ^ +one error found diff --git a/test/files/continuations-neg/t5314-missing-result-type.scala b/test/files/continuations-neg/t5314-missing-result-type.scala new file mode 100644 index 0000000000..d7c5043a86 --- /dev/null +++ b/test/files/continuations-neg/t5314-missing-result-type.scala @@ -0,0 +1,13 @@ +import scala.util.continuations._ + +object Test extends App { + def foo(x:Int): Int @cps[Int] = x + + def bar(x:Int) = return foo(x) + + reset { + val res = bar(8) + println(res) + res + } +} diff --git a/test/files/continuations-neg/t5314-npe.check b/test/files/continuations-neg/t5314-npe.check new file mode 100644 index 0000000000..b5f024aa89 --- /dev/null +++ b/test/files/continuations-neg/t5314-npe.check @@ -0,0 +1,4 @@ +t5314-npe.scala:2: error: method bar has return statement; needs result type + def bar(x:Int) = { return x; x } // NPE + ^ +one error found diff --git a/test/files/continuations-neg/t5314-npe.scala b/test/files/continuations-neg/t5314-npe.scala new file mode 100644 index 0000000000..2b5966e07c --- /dev/null +++ b/test/files/continuations-neg/t5314-npe.scala @@ -0,0 +1,3 @@ +object Test extends App { + def bar(x:Int) = { return x; x } // NPE +} diff --git a/test/files/continuations-neg/t5314-return-reset.check b/test/files/continuations-neg/t5314-return-reset.check new file mode 100644 index 0000000000..4c817ae14d --- /dev/null +++ b/test/files/continuations-neg/t5314-return-reset.check @@ -0,0 +1,4 @@ +t5314-return-reset.scala:14: error: return expression not allowed, since method calls CPS method + if (rnd.nextInt(100) > 50) return 5 // not allowed, since method is calling `reset` + ^ +one error found diff --git a/test/files/continuations-neg/t5314-return-reset.scala b/test/files/continuations-neg/t5314-return-reset.scala new file mode 100644 index 0000000000..df9d58e4cb --- /dev/null +++ b/test/files/continuations-neg/t5314-return-reset.scala @@ -0,0 +1,21 @@ +import scala.util.continuations._ +import scala.util.Random + +object Test extends App { + val rnd = new Random + + def foo(x: Int): Int @cps[Int] = shift { k => k(x) } + + def bar(x: Int): Int @cps[Int] = return foo(x) + + def caller(): Int = { + val v: Int = reset { + val res: Int = bar(8) + if (rnd.nextInt(100) > 50) return 5 // not allowed, since method is calling `reset` + 42 + } + v + } + + caller() +} diff --git a/test/files/continuations-neg/t5314-type-error.check b/test/files/continuations-neg/t5314-type-error.check new file mode 100644 index 0000000000..1f4e46a7f2 --- /dev/null +++ b/test/files/continuations-neg/t5314-type-error.check @@ -0,0 +1,6 @@ +t5314-type-error.scala:7: error: type mismatch; + found : Int @util.continuations.cps[Int] + required: Int @util.continuations.cps[String] + def bar(x:Int): Int @cps[String] = return foo(x) + ^ +one error found diff --git a/test/files/continuations-neg/t5314-type-error.scala b/test/files/continuations-neg/t5314-type-error.scala new file mode 100644 index 0000000000..e36ce6c203 --- /dev/null +++ b/test/files/continuations-neg/t5314-type-error.scala @@ -0,0 +1,17 @@ +import scala.util.continuations._ + +object Test extends App { + def foo(x:Int): Int @cps[Int] = shift { k => k(x) } + + // should be a type error + def bar(x:Int): Int @cps[String] = return foo(x) + + def caller(): Unit = { + val v: String = reset { + val res: Int = bar(8) + "hello" + } + } + + caller() +} diff --git a/test/files/continuations-run/t5314-2.check b/test/files/continuations-run/t5314-2.check new file mode 100644 index 0000000000..35b3c93780 --- /dev/null +++ b/test/files/continuations-run/t5314-2.check @@ -0,0 +1,5 @@ +8 +hi +8 +from try +8 diff --git a/test/files/continuations-run/t5314-2.scala b/test/files/continuations-run/t5314-2.scala new file mode 100644 index 0000000000..8a896dec2c --- /dev/null +++ b/test/files/continuations-run/t5314-2.scala @@ -0,0 +1,44 @@ +import scala.util.continuations._ + +class ReturnRepro { + def s1: Int @cps[Any] = shift { k => k(5) } + def caller = reset { println(p(3)) } + def caller2 = reset { println(p2(3)) } + def caller3 = reset { println(p3(3)) } + + def p(i: Int): Int @cps[Any] = { + val v= s1 + 3 + return v + } + + def p2(i: Int): Int @cps[Any] = { + val v = s1 + 3 + if (v > 0) { + println("hi") + return v + } else { + println("hi") + return 8 + } + } + + def p3(i: Int): Int @cps[Any] = { + val v = s1 + 3 + try { + println("from try") + return v + } catch { + case e: Exception => + println("from catch") + return 7 + } + } + +} + +object Test extends App { + val repro = new ReturnRepro + repro.caller + repro.caller2 + repro.caller3 +} diff --git a/test/files/continuations-run/t5314-3.check b/test/files/continuations-run/t5314-3.check new file mode 100644 index 0000000000..71489f097c --- /dev/null +++ b/test/files/continuations-run/t5314-3.check @@ -0,0 +1,4 @@ +enter return expr +8 +hi +8 diff --git a/test/files/continuations-run/t5314-3.scala b/test/files/continuations-run/t5314-3.scala new file mode 100644 index 0000000000..62c547f5a2 --- /dev/null +++ b/test/files/continuations-run/t5314-3.scala @@ -0,0 +1,27 @@ +import scala.util.continuations._ + +class ReturnRepro { + def s1: Int @cpsParam[Any, Unit] = shift { k => k(5) } + def caller = reset { println(p(3)) } + def caller2 = reset { println(p2(3)) } + + def p(i: Int): Int @cpsParam[Unit, Any] = { + val v= s1 + 3 + return { println("enter return expr"); v } + } + + def p2(i: Int): Int @cpsParam[Unit, Any] = { + val v = s1 + 3 + if (v > 0) { + return { println("hi"); v } + } else { + return { println("hi"); 8 } + } + } +} + +object Test extends App { + val repro = new ReturnRepro + repro.caller + repro.caller2 +} diff --git a/test/files/continuations-run/t5314-with-if.check b/test/files/continuations-run/t5314-with-if.check new file mode 100644 index 0000000000..7f8f011eb7 --- /dev/null +++ b/test/files/continuations-run/t5314-with-if.check @@ -0,0 +1 @@ +7 diff --git a/test/files/continuations-run/t5314-with-if.scala b/test/files/continuations-run/t5314-with-if.scala new file mode 100644 index 0000000000..5840199a3c --- /dev/null +++ b/test/files/continuations-run/t5314-with-if.scala @@ -0,0 +1,17 @@ +import scala.util.continuations._ + +object Test extends App { + + def foo(x:Int): Int @cps[Int] = 7 + + def bar(x:Int): Int @cps[Int] = { + val v = foo(x) + if (v > 0) + return v + else + return 10 + } + + println(reset { bar(10) }) + +} diff --git a/test/files/continuations-run/t5314.check b/test/files/continuations-run/t5314.check new file mode 100644 index 0000000000..4b35d8e6d0 --- /dev/null +++ b/test/files/continuations-run/t5314.check @@ -0,0 +1,8 @@ +7 +7 +7 +8 +8 +hi +8 +8 diff --git a/test/files/continuations-run/t5314.scala b/test/files/continuations-run/t5314.scala new file mode 100644 index 0000000000..d611016ce4 --- /dev/null +++ b/test/files/continuations-run/t5314.scala @@ -0,0 +1,52 @@ +import scala.util.continuations._ + +class ReturnRepro { + def s1: Int @cpsParam[Any, Unit] = shift { k => k(5) } + def caller = reset { println(p(3)) } + def caller2 = reset { println(p2(3)) } + + def p(i: Int): Int @cpsParam[Unit, Any] = { + val v= s1 + 3 + return v + } + + def p2(i: Int): Int @cpsParam[Unit, Any] = { + val v = s1 + 3 + if (v > 0) { + println("hi") + return v + } else { + println("hi") + return 8 + } + } +} + +object Test extends App { + def foo(x:Int): Int @cps[Int] = shift { k => k(x) } + + def bar(x:Int): Int @cps[Int] = return foo(x) + + def nocps(x: Int): Int = { return x; x } + + def foo2(x:Int): Int @cps[Int] = 7 + def bar2(x:Int): Int @cps[Int] = { foo2(x); return 7 } + def bar3(x:Int): Int @cps[Int] = { foo2(x); if (x == 7) return 7 else return foo2(x) } + def bar4(x:Int): Int @cps[Int] = { foo2(x); if (x == 7) return 7 else foo2(x) } + def bar5(x:Int): Int @cps[Int] = { foo2(x); if (x == 7) return 7 else 8 } + println(reset { bar2(10) }) + println(reset { bar3(10) }) + println(reset { bar4(10) }) + println(reset { bar5(10) }) + + /* original test case */ + val repro = new ReturnRepro + repro.caller + repro.caller2 + + reset { + val res = bar(8) + println(res) + res + } +} diff --git a/test/files/jvm/actmig-PinS_1.scala b/test/files/jvm/actmig-PinS_1.scala index 876688ca75..495852e812 100644 --- a/test/files/jvm/actmig-PinS_1.scala +++ b/test/files/jvm/actmig-PinS_1.scala @@ -9,7 +9,7 @@ import scala.concurrent.{ Promise, Await } object SillyActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SillyActor, "akka.actor.default-stash-dispatcher")) + val ref = ActorDSL.actor(new SillyActor) } /* PinS, Listing 32.1: A simple actor @@ -27,7 +27,7 @@ class SillyActor extends Actor { object SeriousActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SeriousActor, "akka.actor.default-stash-dispatcher")) + val ref = ActorDSL.actor(new SeriousActor) } class SeriousActor extends Actor { @@ -72,7 +72,7 @@ object Test extends App { /* PinS, Listing 32.2: An actor that calls receive */ - def makeEchoActor(): ActorRef = MigrationSystem.actorOf(Props(() => new Actor { + def makeEchoActor(): ActorRef = ActorDSL.actor(new Actor { def act() { while (true) { receive { @@ -83,20 +83,20 @@ object Test extends App { } } } - }, "akka.actor.default-stash-dispatcher")) + }) /* PinS, page 696 */ - def makeIntActor(): ActorRef = MigrationSystem.actorOf(Props(() => new Actor { + def makeIntActor(): ActorRef = ActorDSL.actor(new Actor { def act() { receive { case x: Int => // I only want Ints println("Got an Int: " + x) } } - }, "akka.actor.default-stash-dispatcher")) + }) - MigrationSystem.actorOf(Props(() => new Actor { + ActorDSL.actor(new Actor { def act() { trapExit = true link(SillyActor.ref) @@ -109,15 +109,14 @@ object Test extends App { case Exit(_: SeriousActor, _) => val seriousPromise2 = Promise[Boolean]() // PinS, page 694 - val seriousActor2 = MigrationSystem.actorOf(Props(() => + val seriousActor2 = ActorDSL.actor( new Actor { def act() { for (i <- 1 to 5) println("That is the question.") seriousPromise2.success(true) } - } - , "akka.actor.default-stash-dispatcher")) + }) Await.ready(seriousPromise2.future, 5 seconds) val echoActor = makeEchoActor() @@ -136,5 +135,5 @@ object Test extends App { } } } - }, "akka.actor.default-stash-dispatcher")) + }) } diff --git a/test/files/jvm/actmig-PinS_2.scala b/test/files/jvm/actmig-PinS_2.scala index 7d12578f71..508525463f 100644 --- a/test/files/jvm/actmig-PinS_2.scala +++ b/test/files/jvm/actmig-PinS_2.scala @@ -9,7 +9,7 @@ import scala.concurrent.{ Promise, Await } object SillyActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SillyActor, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new SillyActor) } /* PinS, Listing 32.1: A simple actor @@ -29,7 +29,7 @@ class SillyActor extends StashingActor { object SeriousActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SeriousActor, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new SeriousActor) } class SeriousActor extends StashingActor { @@ -44,7 +44,7 @@ class SeriousActor extends StashingActor { /* PinS, Listing 32.3: An actor that calls react */ object NameResolver { - val ref = MigrationSystem.actorOf(Props(() => new NameResolver, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new NameResolver) } class NameResolver extends StashingActor { @@ -80,7 +80,7 @@ object Test extends App { /* PinS, Listing 32.2: An actor that calls receive */ - def makeEchoActor(): ActorRef = MigrationSystem.actorOf(Props(() => + def makeEchoActor(): ActorRef = ActorDSL.actor( new StashingActor { def receive = { case _ => println("Nop") } @@ -94,11 +94,11 @@ object Test extends App { } } } - }, "default-stash-dispatcher")) + }) /* PinS, page 696 */ - def makeIntActor(): ActorRef = MigrationSystem.actorOf(Props(() =>new StashingActor { + def makeIntActor(): ActorRef = ActorDSL.actor(new StashingActor { def receive = { case _ => println("Nop") } @@ -108,9 +108,9 @@ object Test extends App { println("Got an Int: " + x) } } - }, "default-stash-dispatcher")) + }) - MigrationSystem.actorOf(Props(() => new StashingActor { + ActorDSL.actor(new StashingActor { def receive = { case _ => println("Nop") } @@ -126,7 +126,7 @@ object Test extends App { case Exit(_: SeriousActor, _) => val seriousPromise2 = Promise[Boolean]() // PinS, page 694 - val seriousActor2 = MigrationSystem.actorOf(Props(() =>{ + val seriousActor2 = ActorDSL.actor( new StashingActor { def receive = { case _ => println("Nop") } @@ -136,8 +136,7 @@ object Test extends App { println("That is the question.") seriousPromise2.success(true) } - } - }, "default-stash-dispatcher")) + }) Await.ready(seriousPromise2.future, 5 seconds) val echoActor = makeEchoActor() @@ -156,5 +155,5 @@ object Test extends App { } } } - }, "default-stash-dispatcher")) + }) } diff --git a/test/files/jvm/actmig-PinS_3.scala b/test/files/jvm/actmig-PinS_3.scala index c2943008b0..6c6ec6789b 100644 --- a/test/files/jvm/actmig-PinS_3.scala +++ b/test/files/jvm/actmig-PinS_3.scala @@ -7,10 +7,9 @@ import scala.actors.migration._ import scala.concurrent.duration._ import scala.concurrent.{ Promise, Await } - object SillyActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SillyActor, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new SillyActor) } /* PinS, Listing 32.1: A simple actor @@ -32,7 +31,7 @@ class SillyActor extends StashingActor { object SeriousActor { val startPromise = Promise[Boolean]() - val ref = MigrationSystem.actorOf(Props(() => new SeriousActor, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new SeriousActor) } class SeriousActor extends StashingActor { @@ -48,7 +47,7 @@ class SeriousActor extends StashingActor { /* PinS, Listing 32.3: An actor that calls react */ object NameResolver { - val ref = MigrationSystem.actorOf(Props(() => new NameResolver, "default-stash-dispatcher")) + val ref = ActorDSL.actor(new NameResolver) } class NameResolver extends StashingActor { @@ -78,7 +77,7 @@ object Test extends App { /* PinS, Listing 32.2: An actor that calls receive */ - def makeEchoActor(): ActorRef = MigrationSystem.actorOf(Props(() => new StashingActor { + def makeEchoActor(): ActorRef = ActorDSL.actor(new StashingActor { def receive = { // how to handle receive case 'stop => @@ -86,11 +85,11 @@ object Test extends App { case msg => println("received message: " + msg) } - }, "default-stash-dispatcher")) + }) /* PinS, page 696 */ - def makeIntActor(): ActorRef = MigrationSystem.actorOf(Props(() => new StashingActor { + def makeIntActor(): ActorRef = ActorDSL.actor(new StashingActor { def receive = { case x: Int => // I only want Ints @@ -99,9 +98,9 @@ object Test extends App { context.stop(self) case _ => stash() } - }, "default-stash-dispatcher")) + }) - MigrationSystem.actorOf(Props(() => new StashingActor { + ActorDSL.actor(new StashingActor { val silly = SillyActor.ref override def preStart() { @@ -119,7 +118,7 @@ object Test extends App { case Terminated(`serious`) => val seriousPromise2 = Promise[Boolean]() // PinS, page 694 - val seriousActor2 = MigrationSystem.actorOf(Props(() => { + val seriousActor2 = ActorDSL.actor( new StashingActor { def receive = { case _ => context.stop(self) } @@ -130,8 +129,7 @@ object Test extends App { seriousPromise2.success(true) context.stop(self) } - } - }, "default-stash-dispatcher")) + }) Await.ready(seriousPromise2.future, 5 seconds) val echoActor = makeEchoActor() @@ -162,5 +160,5 @@ object Test extends App { println("Stash 3 " + m) stash(m) } - }, "default-stash-dispatcher")) + }) } diff --git a/test/files/jvm/actmig-instantiation.check b/test/files/jvm/actmig-instantiation.check index 4c13d5c0a1..08ef979794 100644 --- a/test/files/jvm/actmig-instantiation.check +++ b/test/files/jvm/actmig-instantiation.check @@ -1,5 +1,5 @@ -OK error: java.lang.RuntimeException: In order to create StashingActor one must use actorOf. -OK error: java.lang.RuntimeException: Only one actor can be created per actorOf call. +OK error: java.lang.RuntimeException: In order to create a StashingActor one must use the ActorDSL object +OK error: java.lang.RuntimeException: Cannot create more than one actor 0 100 200 diff --git a/test/files/jvm/actmig-instantiation.scala b/test/files/jvm/actmig-instantiation.scala index d54dff9558..2e3ffc3c30 100644 --- a/test/files/jvm/actmig-instantiation.scala +++ b/test/files/jvm/actmig-instantiation.scala @@ -2,7 +2,6 @@ * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov. */ -import scala.actors.migration.MigrationSystem._ import scala.actors.migration._ import scala.actors.Actor._ import scala.actors._ @@ -35,53 +34,53 @@ object Test { a1 ! 100 // simple instantiation - val a2 = MigrationSystem.actorOf(Props(() => new TestStashingActor, "akka.actor.default-stash-dispatcher")) + val a2 = ActorDSL.actor(new TestStashingActor) a2 ! 200 toStop += a2 // actor of with scala actor - val a3 = MigrationSystem.actorOf(Props(() => actor { + val a3 = ActorDSL.actor(actor { react { case v: Int => Test.append(v); Test.latch.countDown() } - }, "akka.actor.default-stash-dispatcher")) + }) a3 ! 300 // using the manifest - val a4 = MigrationSystem.actorOf(Props(() => new TestStashingActor, "akka.actor.default-stash-dispatcher")) + val a4 = ActorDSL.actor(new TestStashingActor) a4 ! 400 toStop += a4 // deterministic part of a test - // creation without actorOf + // creation without actor try { val a3 = new TestStashingActor a3 ! -1 } catch { - case e => println("OK error: " + e) + case e: Throwable => println("OK error: " + e) } - // actorOf double creation + // actor double creation try { - val a3 = MigrationSystem.actorOf(Props(() => { + val a3 = ActorDSL.actor({ new TestStashingActor new TestStashingActor - }, "akka.actor.default-stash-dispatcher")) + }) a3 ! -1 } catch { - case e => println("OK error: " + e) + case e: Throwable => println("OK error: " + e) } - // actorOf nesting + // actor nesting try { - val a5 = MigrationSystem.actorOf(Props(() => { - val a6 = MigrationSystem.actorOf(Props(() => new TestStashingActor, "akka.actor.default-stash-dispatcher")) + val a5 = ActorDSL.actor({ + val a6 = ActorDSL.actor(new TestStashingActor) toStop += a6 new TestStashingActor - }, "akka.actor.default-stash-dispatcher")) + }) a5 ! 500 toStop += a5 } catch { - case e => println("Should not throw an exception: " + e) + case e: Throwable => println("Should not throw an exception: " + e) } // output @@ -93,4 +92,4 @@ object Test { buff.sorted.foreach(println) toStop.foreach(_ ! PoisonPill) } -}
\ No newline at end of file +} diff --git a/test/files/jvm/actmig-loop-react.scala b/test/files/jvm/actmig-loop-react.scala index 7f4c6f96dc..c9a3664526 100644 --- a/test/files/jvm/actmig-loop-react.scala +++ b/test/files/jvm/actmig-loop-react.scala @@ -2,7 +2,6 @@ * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov. */ -import scala.actors.migration.MigrationSystem._ import scala.actors.Actor._ import scala.actors._ import scala.actors.migration._ @@ -40,7 +39,7 @@ object Test { Await.ready(finishedLWCR1.future, 5 seconds) // Loop with Condition Snippet - migrated - val myAkkaActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myAkkaActor = ActorDSL.actor(new StashingActor { def receive = { case x: Int => @@ -51,7 +50,7 @@ object Test { context.stop(self) } } - }, "default-stashing-dispatcher")) + }) myAkkaActor ! 1 myAkkaActor ! 42 } @@ -88,7 +87,7 @@ object Test { Await.ready(finishedTNR1.future, 5 seconds) // Loop with Condition Snippet - migrated - val myAkkaActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myAkkaActor = ActorDSL.actor(new StashingActor { def receive = { case x: Int => @@ -107,7 +106,7 @@ object Test { context.unbecome() }).orElse { case x => stash() }) } - }, "default-stashing-dispatcher")) + }) myAkkaActor ! 1 myAkkaActor ! "I am a String" @@ -117,7 +116,7 @@ object Test { def exceptionHandling() = { // Stashing actor with act and exception handler - val myActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myActor = ActorDSL.actor(new StashingActor { def receive = { case _ => println("Dummy method.") } override def act() = { @@ -138,7 +137,7 @@ object Test { case x: Exception => println("scala got exception") } - }, "default-stashing-dispatcher")) + }) myActor ! "work" myActor ! "fail" @@ -146,7 +145,7 @@ object Test { Await.ready(finishedEH1.future, 5 seconds) // Stashing actor in Akka style - val myAkkaActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myAkkaActor = ActorDSL.actor(new StashingActor { def receive = PFCatch({ case "fail" => throw new Exception("failed") @@ -156,14 +155,14 @@ object Test { finishedEH.success(true) context.stop(self) }, { case x: Exception => println("akka got exception") }) - }, "default-stashing-dispatcher")) + }) myAkkaActor ! "work" myAkkaActor ! "fail" myAkkaActor ! "die" } - def main(args: Array[String]) = { + def main(args: Array[String]): Unit = { testLoopWithConditionReact() Await.ready(finishedLWCR.future, 5 seconds) exceptionHandling() diff --git a/test/files/jvm/actmig-public-methods.scala b/test/files/jvm/actmig-public-methods.scala index 58d7a1a9d4..8891c80668 100644 --- a/test/files/jvm/actmig-public-methods.scala +++ b/test/files/jvm/actmig-public-methods.scala @@ -5,7 +5,6 @@ import scala.collection.mutable.ArrayBuffer import scala.actors.Actor._ import scala.actors._ -import scala.actors.migration.MigrationSystem import scala.util.continuations._ import java.util.concurrent.{ TimeUnit, CountDownLatch } @@ -71,4 +70,4 @@ object Test { buff.sorted.foreach(println) toStop.foreach(_ ! 'stop) } -}
\ No newline at end of file +} diff --git a/test/files/jvm/actmig-public-methods_1.scala b/test/files/jvm/actmig-public-methods_1.scala index 15516a5d51..db21ab983c 100644 --- a/test/files/jvm/actmig-public-methods_1.scala +++ b/test/files/jvm/actmig-public-methods_1.scala @@ -28,7 +28,7 @@ object Test { def main(args: Array[String]) = { - val respActor = MigrationSystem.actorOf(Props(() => actor { + val respActor = ActorDSL.actor(actor { loop { react { case (x: String, time: Long) => @@ -41,7 +41,7 @@ object Test { exit() } } - }, "akka.actor.default-stash-dispatcher")) + }) toStop += respActor diff --git a/test/files/jvm/actmig-react-receive.scala b/test/files/jvm/actmig-react-receive.scala index 6adeac8b52..bf70ce0c46 100644 --- a/test/files/jvm/actmig-react-receive.scala +++ b/test/files/jvm/actmig-react-receive.scala @@ -2,7 +2,6 @@ * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov. */ -import scala.actors.migration.MigrationSystem._ import scala.actors.Actor._ import scala.actors._ import scala.actors.migration._ @@ -39,7 +38,7 @@ object Test { Await.ready(finishedRSC1.future, 5 seconds) // React Snippet - migrated - val myAkkaActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myAkkaActor = ActorDSL.actor(new StashingActor { override def preStart() = { println("do before") } @@ -63,7 +62,7 @@ object Test { finishedRSC.success(true) } - }, "default-stashing-dispatcher")) + }) myAkkaActor ! 1 myAkkaActor ! "1" Await.ready(finishedRSC.future, 5 seconds) @@ -88,7 +87,7 @@ object Test { Await.ready(finishedRS1.future, 5 seconds) // React Snippet - migrated - val myAkkaActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myAkkaActor = ActorDSL.actor(new StashingActor { override def preStart() = { println("do before") } @@ -105,7 +104,7 @@ object Test { finishedRS.success(true) } - }, "default-stashing-dispatcher")) + }) myAkkaActor ! 1 Await.ready(finishedRS.future, 5 seconds) diff --git a/test/files/jvm/actmig-react-within.scala b/test/files/jvm/actmig-react-within.scala index 43350ef120..3057398cb5 100644 --- a/test/files/jvm/actmig-react-within.scala +++ b/test/files/jvm/actmig-react-within.scala @@ -2,7 +2,6 @@ * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov. */ -import scala.actors.migration.MigrationSystem._ import scala.actors.Actor._ import scala.actors._ import scala.actors.migration._ @@ -27,7 +26,7 @@ object Test { } } - val myActor = MigrationSystem.actorOf(Props(() => new StashingActor { + val myActor = ActorDSL.actor(new StashingActor { context.setReceiveTimeout(1 millisecond) def receive = { case ReceiveTimeout => @@ -37,7 +36,7 @@ object Test { case _ => println("Should not occur.") } - }, "default-stashing-dispatcher")) + }) } def main(args: Array[String]) = { diff --git a/test/files/jvm/actmig-receive.scala b/test/files/jvm/actmig-receive.scala index 03dc1be63b..308643cf41 100644 --- a/test/files/jvm/actmig-receive.scala +++ b/test/files/jvm/actmig-receive.scala @@ -2,7 +2,6 @@ * NOTE: Code snippets from this test are included in the Actor Migration Guide. In case you change * code in these tests prior to the 2.10.0 release please send the notification to @vjovanov. */ -import scala.actors.migration.MigrationSystem._ import scala.actors.Actor._ import scala.actors._ import scala.actors.migration._ diff --git a/test/files/neg/anytrait.check b/test/files/neg/anytrait.check index 9dd970b58c..fabe74d379 100644 --- a/test/files/neg/anytrait.check +++ b/test/files/neg/anytrait.check @@ -1,7 +1,7 @@ -anytrait.scala:3: error: this statement is not allowed in universal trait extending from class Any: private[this] var x: Int = 1 +anytrait.scala:3: error: field definition is not allowed in universal trait extending from class Any var x = 1 ^ -anytrait.scala:5: error: this statement is not allowed in universal trait extending from class Any: T.this.x_=(T.this.x.+(1)) +anytrait.scala:5: error: this statement is not allowed in universal trait extending from class Any { x += 1 } ^ two errors found diff --git a/test/files/neg/classmanifests_new_deprecations.check b/test/files/neg/classmanifests_new_deprecations.check index e10308a66f..12428c7626 100644 --- a/test/files/neg/classmanifests_new_deprecations.check +++ b/test/files/neg/classmanifests_new_deprecations.check @@ -28,34 +28,4 @@ classmanifests_new_deprecations.scala:10: error: type ClassManifest in object Pr classmanifests_new_deprecations.scala:15: error: type ClassManifest in package reflect is deprecated: Use scala.reflect.ClassTag instead type RCM[T] = scala.reflect.ClassManifest[T] ^ -classmanifests_new_deprecations.scala:20: error: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - def m1[T: Manifest] = ??? - ^ -classmanifests_new_deprecations.scala:21: error: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - def m2[T](implicit evidence$1: Manifest[T]) = ??? - ^ -classmanifests_new_deprecations.scala:22: error: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - val m3: Manifest[Int] = null - ^ -classmanifests_new_deprecations.scala:22: error: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - val m3: Manifest[Int] = null - ^ -classmanifests_new_deprecations.scala:24: error: trait Manifest in package reflect is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - def rm1[T: scala.reflect.Manifest] = ??? - ^ -classmanifests_new_deprecations.scala:25: error: trait Manifest in package reflect is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - def rm2[T](implicit evidence$1: scala.reflect.Manifest[T]) = ??? - ^ -classmanifests_new_deprecations.scala:26: error: trait Manifest in package reflect is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - val rm3: scala.reflect.Manifest[Int] = null - ^ -classmanifests_new_deprecations.scala:26: error: trait Manifest in package reflect is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - val rm3: scala.reflect.Manifest[Int] = null - ^ -classmanifests_new_deprecations.scala:28: error: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - type M[T] = Manifest[T] - ^ -classmanifests_new_deprecations.scala:33: error: trait Manifest in package reflect is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - type RM[T] = scala.reflect.Manifest[T] - ^ -20 errors found +10 errors found diff --git a/test/files/neg/patmat-type-check.check b/test/files/neg/patmat-type-check.check index e045841ce1..721217c314 100644 --- a/test/files/neg/patmat-type-check.check +++ b/test/files/neg/patmat-type-check.check @@ -1,3 +1,12 @@ +patmat-type-check.scala:11: warning: fruitless type test: a value of type Test.Bop4[T] cannot also be a Seq[A] + def s3[T](x: Bop4[T]) = x match { case Seq('b', 'o', 'b') => true } + ^ +patmat-type-check.scala:15: warning: fruitless type test: a value of type Test.Bop5[_$1,T1,T2] cannot also be a Seq[A] + def s4[T1, T2](x: Bop5[_, T1, T2]) = x match { case Seq('b', 'o', 'b') => true } + ^ +patmat-type-check.scala:19: warning: fruitless type test: a value of type Test.Bop3[T] cannot also be a Seq[A] + def f4[T](x: Bop3[T]) = x match { case Seq('b', 'o', 'b') => true } + ^ patmat-type-check.scala:22: error: scrutinee is incompatible with pattern type; found : Seq[A] required: String @@ -18,4 +27,5 @@ patmat-type-check.scala:30: error: scrutinee is incompatible with pattern type; required: Test.Bop3[Char] def f4[T](x: Bop3[Char]) = x match { case Seq('b', 'o', 'b') => true } // fail ^ +three warnings found four errors found diff --git a/test/files/neg/t1872.check b/test/files/neg/t1872.check index ef84ef79e0..c5dc2a8080 100644 --- a/test/files/neg/t1872.check +++ b/test/files/neg/t1872.check @@ -1,4 +1,8 @@ +t1872.scala:3: warning: fruitless type test: a value of type Int cannot also be a scala.util.Random + def f(x: Int) = x.isInstanceOf[util.Random] + ^ t1872.scala:3: error: isInstanceOf cannot test if value types are references. def f(x: Int) = x.isInstanceOf[util.Random] ^ +one warning found one error found diff --git a/test/files/neg/t3692-old.check b/test/files/neg/t3692-old.check index 950f82951c..9f3ae516aa 100644 --- a/test/files/neg/t3692-old.check +++ b/test/files/neg/t3692-old.check @@ -7,14 +7,8 @@ t3692-old.scala:14: warning: non-variable type argument Int in type pattern Map[ t3692-old.scala:15: warning: non-variable type argument Int in type pattern Map[T,Int] is unchecked since it is eliminated by erasure case m2: Map[T, Int] => new java.util.HashMap[T, Integer] ^ -t3692-old.scala:11: warning: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - private final def toJavaMap[T, V](map: Map[T, V])(implicit m1: Manifest[T], m2: Manifest[V]): java.util.Map[_, _] = { - ^ -t3692-old.scala:11: warning: type Manifest in object Predef is deprecated: Use scala.reflect.ClassTag (to capture erasures) or scala.reflect.runtime.universe.TypeTag (to capture types) or both instead - private final def toJavaMap[T, V](map: Map[T, V])(implicit m1: Manifest[T], m2: Manifest[V]): java.util.Map[_, _] = { - ^ t3692-old.scala:15: error: unreachable code case m2: Map[T, Int] => new java.util.HashMap[T, Integer] ^ -5 warnings found +three warnings found one error found diff --git a/test/files/neg/t4302.check b/test/files/neg/t4302.check index 327425acb0..450d28bbc5 100644 --- a/test/files/neg/t4302.check +++ b/test/files/neg/t4302.check @@ -1,4 +1,4 @@ -t4302.scala:2: error: abstract type T in type T is unchecked since it is eliminated by erasure +t4302.scala:2: error: abstract type T is unchecked since it is eliminated by erasure def hasMatch[T](x: AnyRef) = x.isInstanceOf[T] ^ one error found diff --git a/test/files/neg/t5762.check b/test/files/neg/t5762.check new file mode 100644 index 0000000000..10064032aa --- /dev/null +++ b/test/files/neg/t5762.check @@ -0,0 +1,13 @@ +t5762.scala:6: error: non-variable type argument Int in type pattern D[Int] is unchecked since it is eliminated by erasure + case _: D[Int] if bippy => 1 + ^ +t5762.scala:7: error: non-variable type argument String in type pattern D[String] is unchecked since it is eliminated by erasure + case _: D[String] => 2 + ^ +t5762.scala:20: error: non-variable type argument D[Int] in type pattern D[D[Int]] is unchecked since it is eliminated by erasure + case _: D[D[Int]] if bippy => 1 + ^ +t5762.scala:21: error: non-variable type argument D[String] in type pattern D[D[String]] is unchecked since it is eliminated by erasure + case _: D[D[String]] => 2 + ^ +four errors found diff --git a/test/files/neg/t5762.flags b/test/files/neg/t5762.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/t5762.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/t5762.scala b/test/files/neg/t5762.scala new file mode 100644 index 0000000000..fb73552b12 --- /dev/null +++ b/test/files/neg/t5762.scala @@ -0,0 +1,24 @@ +class D[-A] + +object Test { + var bippy: Boolean = true + def f1(x: D[Int with String]) = x match { + case _: D[Int] if bippy => 1 + case _: D[String] => 2 + } + // Correctly warns: + // + // a.scala:5: warning: non variable type-argument Int in type pattern D[Int] is unchecked since it is eliminated by erasure + // case _: D[Int] => 1 + // ^ + // a.scala:6: warning: non variable type-argument String in type pattern D[String] is unchecked since it is eliminated by erasure + // case _: D[String] => 2 + // ^ + // two warnings found + + def f2(x: D[D[Int] with D[String]]) = x match { + case _: D[D[Int]] if bippy => 1 + case _: D[D[String]] => 2 + } + // No warnings! +} diff --git a/test/files/neg/t5799.check b/test/files/neg/t5799.check index 10e2658d56..3b43d06a94 100644 --- a/test/files/neg/t5799.check +++ b/test/files/neg/t5799.check @@ -1,4 +1,4 @@ -t5799.scala:2: error: value class may not have secondary constructors +t5799.scala:2: error: secondary constructor is not allowed in value class def this(s: String) = this(s.toDouble) ^ one error found diff --git a/test/files/neg/t5845.check b/test/files/neg/t5845.check index c0b402fccb..8c6100d6de 100644 --- a/test/files/neg/t5845.check +++ b/test/files/neg/t5845.check @@ -1,4 +1,7 @@ +t5845.scala:9: error: value +++ is not a member of Int + println(5 +++ 5) + ^ t5845.scala:15: error: value +++ is not a member of Int println(5 +++ 5) ^ -one error found +two errors found diff --git a/test/files/neg/t5882.check b/test/files/neg/t5882.check index df01c7bc0a..e0958e19d9 100644 --- a/test/files/neg/t5882.check +++ b/test/files/neg/t5882.check @@ -1,15 +1,9 @@ -t5882.scala:2: warning: case classes without a parameter list have been deprecated; -use either case objects or case classes with `()' as parameter list. - case class Scope - ^ -t5882.scala:2: error: value class may not have nested class definitions - case class Scope +t5882.scala:4: error: implementation restriction: nested class is not allowed in value class +This restriction is planned to be removed in subsequent releases. + case class Scope() ^ -t5882.scala:3: error: value class may not have nested class definitions - class Foo - ^ -t5882.scala:4: error: value class may not have nested module definitions +t5882.scala:5: error: implementation restriction: nested object is not allowed in value class +This restriction is planned to be removed in subsequent releases. object Bar ^ -one warning found -three errors found +two errors found diff --git a/test/files/neg/t5882.scala b/test/files/neg/t5882.scala index 1233eb636f..3a55abdc9a 100644 --- a/test/files/neg/t5882.scala +++ b/test/files/neg/t5882.scala @@ -1,5 +1,6 @@ +// SIP-15 was changed to allow nested classes. See run/t5882.scala + class NodeOps(val n: Any) extends AnyVal { - case class Scope - class Foo + case class Scope() object Bar } diff --git a/test/files/neg/t6359.check b/test/files/neg/t6359.check index 2aa1ac5035..5bcdc57331 100644 --- a/test/files/neg/t6359.check +++ b/test/files/neg/t6359.check @@ -1,7 +1,9 @@ -t6359.scala:3: error: value class may not have nested module definitions +t6359.scala:3: error: implementation restriction: nested object is not allowed in value class +This restriction is planned to be removed in subsequent releases. object X ^ -t6359.scala:4: error: value class may not have nested class definitions +t6359.scala:4: error: implementation restriction: nested class is not allowed in value class +This restriction is planned to be removed in subsequent releases. class Y ^ two errors found diff --git a/test/files/neg/t6436.check b/test/files/neg/t6436.check new file mode 100644 index 0000000000..ecb28f9100 --- /dev/null +++ b/test/files/neg/t6436.check @@ -0,0 +1,10 @@ +t6436.scala:8: error: type mismatch; + found : StringContext + required: ?{def q: ?} +Note that implicit conversions are not applicable because they are ambiguous: + both method foo1 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + and method foo2 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + are possible conversion functions from StringContext to ?{def q: ?} + println(q"a") + ^ +one error found diff --git a/test/files/neg/t6436.scala b/test/files/neg/t6436.scala new file mode 100644 index 0000000000..2c40502538 --- /dev/null +++ b/test/files/neg/t6436.scala @@ -0,0 +1,9 @@ +object quasiquotes { + implicit def foo1(ctx: StringContext) = new { def q = ??? } + implicit def foo2(ctx: StringContext) = new { def q = ??? } +} + +object Test extends App { + import quasiquotes._ + println(q"a") +} diff --git a/test/files/neg/t6436b.check b/test/files/neg/t6436b.check new file mode 100644 index 0000000000..b3c2d73739 --- /dev/null +++ b/test/files/neg/t6436b.check @@ -0,0 +1,10 @@ +t6436b.scala:8: error: type mismatch; + found : StringContext + required: ?{def q: ?} +Note that implicit conversions are not applicable because they are ambiguous: + both method foo1 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + and method foo2 in object quasiquotes of type (ctx: StringContext)Object{def q: Nothing} + are possible conversion functions from StringContext to ?{def q: ?} + println(StringContext("a").q()) + ^ +one error found diff --git a/test/files/neg/t6436b.scala b/test/files/neg/t6436b.scala new file mode 100644 index 0000000000..8023329e90 --- /dev/null +++ b/test/files/neg/t6436b.scala @@ -0,0 +1,9 @@ +object quasiquotes { + implicit def foo1(ctx: StringContext) = new { def q = ??? } + implicit def foo2(ctx: StringContext) = new { def q = ??? } +} + +object Test extends App { + import quasiquotes._ + println(StringContext("a").q()) +} diff --git a/test/files/neg/t6483.check b/test/files/neg/t6483.check new file mode 100644 index 0000000000..66e3507107 --- /dev/null +++ b/test/files/neg/t6483.check @@ -0,0 +1,9 @@ +t6483.scala:7: error: implementation restriction: qualified super reference is not allowed in value class +This restriction is planned to be removed in subsequent releases. + override def foo = super[T].foo // error + ^ +t6483.scala:20: error: implementation restriction: nested class is not allowed in value class +This restriction is planned to be removed in subsequent releases. + class Inner extends T { + ^ +two errors found diff --git a/test/files/neg/t6483.scala b/test/files/neg/t6483.scala new file mode 100644 index 0000000000..bd99f68fa4 --- /dev/null +++ b/test/files/neg/t6483.scala @@ -0,0 +1,24 @@ +trait T extends Any { + def foo = 1 + type X +} + +class C1(val a: Any) extends AnyVal with T { + override def foo = super[T].foo // error +} + +class C2(val a: Int) extends AnyVal with T { + override def foo = super.foo + a // okay +} + +class C3(val a: Int) extends AnyVal with T { + override def foo = C3.super.foo + a // okay +} + +class C4(val a: Int) extends AnyVal with T { + def foo { + class Inner extends T { + override def foo = super[T].foo + a // no (direct) error, other than that a nested class is currently illegal. + } + } +} diff --git a/test/files/neg/unchecked-abstract.check b/test/files/neg/unchecked-abstract.check new file mode 100644 index 0000000000..6e811dc156 --- /dev/null +++ b/test/files/neg/unchecked-abstract.check @@ -0,0 +1,25 @@ +unchecked-abstract.scala:16: error: abstract type H in type Contravariant[M.this.H] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Contravariant[H]]) + ^ +unchecked-abstract.scala:21: error: abstract type H in type Contravariant[M.this.H] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Contravariant[H]]) + ^ +unchecked-abstract.scala:27: error: abstract type T in type Invariant[M.this.T] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[T]]) + ^ +unchecked-abstract.scala:28: error: abstract type L in type Invariant[M.this.L] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[L]]) + ^ +unchecked-abstract.scala:31: error: abstract type H in type Invariant[M.this.H] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[H]]) + ^ +unchecked-abstract.scala:33: error: abstract type L in type Invariant[M.this.L] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[L]]) + ^ +unchecked-abstract.scala:36: error: abstract type H in type Invariant[M.this.H] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[H]]) + ^ +unchecked-abstract.scala:37: error: abstract type T in type Invariant[M.this.T] is unchecked since it is eliminated by erasure + /* warn */ println(x.isInstanceOf[Invariant[T]]) + ^ +8 errors found diff --git a/test/files/neg/unchecked-abstract.flags b/test/files/neg/unchecked-abstract.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/unchecked-abstract.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/unchecked-abstract.scala b/test/files/neg/unchecked-abstract.scala new file mode 100644 index 0000000000..23c8281ca8 --- /dev/null +++ b/test/files/neg/unchecked-abstract.scala @@ -0,0 +1,93 @@ +trait Contravariant[-X] +trait Invariant[X] +trait Covariant[+X] + +abstract class M { + type H + type L <: H + type T >: L <: H + + def h1(x: Contravariant[H]) = { + /* nowarn */ println(x.isInstanceOf[Contravariant[H]]) + /* nowarn */ println(x.isInstanceOf[Contravariant[T]]) + /* nowarn */ println(x.isInstanceOf[Contravariant[L]]) + } + def h2(x: Contravariant[T]) = { + /* warn */ println(x.isInstanceOf[Contravariant[H]]) + /* nowarn */ println(x.isInstanceOf[Contravariant[T]]) + /* nowarn */ println(x.isInstanceOf[Contravariant[L]]) + } + def h3(x: Contravariant[L]) = { + /* warn */ println(x.isInstanceOf[Contravariant[H]]) + /* warn */ println(x.isInstanceOf[Contravariant[T]]) + /* nowarn */ println(x.isInstanceOf[Contravariant[L]]) + } + def h4(x: Invariant[H]) = { + /* nowarn */ println(x.isInstanceOf[Invariant[H]]) + /* warn */ println(x.isInstanceOf[Invariant[T]]) + /* warn */ println(x.isInstanceOf[Invariant[L]]) + } + def h5(x: Invariant[T]) = { + /* warn */ println(x.isInstanceOf[Invariant[H]]) + /* nowarn */ println(x.isInstanceOf[Invariant[T]]) + /* warn */ println(x.isInstanceOf[Invariant[L]]) + } + def h6(x: Invariant[L]) = { + /* warn */ println(x.isInstanceOf[Invariant[H]]) + /* warn */ println(x.isInstanceOf[Invariant[T]]) + /* nowarn */ println(x.isInstanceOf[Invariant[L]]) + } + def h7(x: Covariant[H]) = { + /* nowarn */ println(x.isInstanceOf[Covariant[H]]) + /* warn */ println(x.isInstanceOf[Covariant[T]]) + /* warn */ println(x.isInstanceOf[Covariant[L]]) + } + def h8(x: Covariant[T]) = { + /* nowarn */ println(x.isInstanceOf[Covariant[H]]) + /* nowarn */ println(x.isInstanceOf[Covariant[T]]) + /* warn */ println(x.isInstanceOf[Covariant[L]]) + } + def h9(x: Covariant[L]) = { + /* nowarn */ println(x.isInstanceOf[Covariant[H]]) + /* nowarn */ println(x.isInstanceOf[Covariant[T]]) + /* nowarn */ println(x.isInstanceOf[Covariant[L]]) + } +} + +object Test extends M { + type H = Any + type T = Int + type L = Nothing + + val conh = new Contravariant[H] { } + val cont = new Contravariant[T] { } + val conl = new Contravariant[L] { } + + val invh = new Invariant[H] { } + val invt = new Invariant[T] { } + val invl = new Invariant[L] { } + + val covh = new Covariant[H] { } + val covt = new Covariant[T] { } + val covl = new Covariant[L] { } + + def main(args: Array[String]): Unit = { + h1(conh) + h2(conh) + h2(cont) + h3(conh) + h3(cont) + h3(conl) + + h4(invh) + h5(invt) + h6(invl) + + h7(covh) + h7(covt) + h7(covl) + h8(covt) + h8(covl) + h9(covl) + } +} diff --git a/test/files/neg/unchecked-impossible.check b/test/files/neg/unchecked-impossible.check new file mode 100644 index 0000000000..0ab371dbaa --- /dev/null +++ b/test/files/neg/unchecked-impossible.check @@ -0,0 +1,4 @@ +unchecked-impossible.scala:5: error: fruitless type test: a value of type T2[Int,Int] cannot also be a Seq[A] + case Seq(x) => + ^ +one error found diff --git a/test/files/neg/unchecked-impossible.flags b/test/files/neg/unchecked-impossible.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/unchecked-impossible.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/unchecked-impossible.scala b/test/files/neg/unchecked-impossible.scala new file mode 100644 index 0000000000..985a2d0b08 --- /dev/null +++ b/test/files/neg/unchecked-impossible.scala @@ -0,0 +1,16 @@ +final case class T2[+A, +B](a: A, b: B) + +class A { + def f1 = T2(1, 2) match { + case Seq(x) => + case _ => + } + def f2 = T2(1, 2) match { + case _: T2[Int, Int] => /* nowarn */ + case _ => + } + def f3 = T2(1, 2) match { + case _: T2[_, Int] => /* nowarn */ + case _ => + } +} diff --git a/test/files/neg/unchecked-knowable.check b/test/files/neg/unchecked-knowable.check new file mode 100644 index 0000000000..3a6ef994b5 --- /dev/null +++ b/test/files/neg/unchecked-knowable.check @@ -0,0 +1,4 @@ +unchecked-knowable.scala:17: error: fruitless type test: a value of type Bippy cannot also be a A1 + /* warn */ (new Bippy).isInstanceOf[A1] + ^ +one error found diff --git a/test/files/neg/unchecked-knowable.flags b/test/files/neg/unchecked-knowable.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/unchecked-knowable.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/unchecked-knowable.scala b/test/files/neg/unchecked-knowable.scala new file mode 100644 index 0000000000..667b47f504 --- /dev/null +++ b/test/files/neg/unchecked-knowable.scala @@ -0,0 +1,20 @@ +/** Knowable - only final leaves */ +sealed abstract class A1 +sealed abstract class A2 extends A1 +final class A3 extends A1 +final class A4 extends A2 + +/** Unknowable */ +sealed abstract class B1 +sealed abstract class B2 extends B1 +final class B3 extends B1 +trait B4 extends B2 + +class Bippy +trait Dingus + +class A { + /* warn */ (new Bippy).isInstanceOf[A1] + /* nowarn */ (new Bippy).isInstanceOf[B1] + /* nowarn */ ((new Bippy): Any).isInstanceOf[A1] +} diff --git a/test/files/neg/unchecked-refinement.check b/test/files/neg/unchecked-refinement.check new file mode 100644 index 0000000000..d81517464f --- /dev/null +++ b/test/files/neg/unchecked-refinement.check @@ -0,0 +1,13 @@ +unchecked-refinement.scala:17: error: abstract type U in type pattern Foo[U,U,V] is unchecked since it is eliminated by erasure + /* warn */ case _: Foo[U, U, V] if b => () + ^ +unchecked-refinement.scala:19: error: non-variable type argument Any in type pattern Foo[Any,U,V] is unchecked since it is eliminated by erasure + /* warn */ case _: Foo[Any, U, V] if b => () + ^ +unchecked-refinement.scala:23: error: a pattern match on a refinement type is unchecked + /* nowarn - todo */ case x: AnyRef { def bippy: Int } if b => x.bippy // this could/should do an instance check and not warn + ^ +unchecked-refinement.scala:24: error: a pattern match on a refinement type is unchecked + /* nowarn - todo */ case x: AnyRef { def size: Int } if b => x.size // this could/should do a static conformance test and not warn + ^ +four errors found diff --git a/test/files/neg/unchecked-refinement.flags b/test/files/neg/unchecked-refinement.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/unchecked-refinement.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/unchecked-refinement.scala b/test/files/neg/unchecked-refinement.scala new file mode 100644 index 0000000000..79ed7f13c1 --- /dev/null +++ b/test/files/neg/unchecked-refinement.scala @@ -0,0 +1,27 @@ +// a.scala +// Thu Sep 27 09:42:16 PDT 2012 + +trait Bar[-T1, T2, +T3] { } +trait Foo[-T1, T2, +T3] extends Bar[T1, T2, T3] + +class A { + var b = true + + def f1(x: Foo[Int, Int, Int]) = x match { + /* nowarn */ case _: Foo[Nothing, Int, Any] => true + } + def f2[T, U, V](x: Foo[T, U, V]) = x match { + /* nowarn */ case _: Foo[Nothing, U, Any] => true + } + def f3[T, U, V](x: Foo[T, U, V]) = x match { + /* warn */ case _: Foo[U, U, V] if b => () + /* nowarn */ case _: Foo[Nothing, U, V] if b => () + /* warn */ case _: Foo[Any, U, V] if b => () + } + + def f4(xs: List[Int]) = xs match { + /* nowarn - todo */ case x: AnyRef { def bippy: Int } if b => x.bippy // this could/should do an instance check and not warn + /* nowarn - todo */ case x: AnyRef { def size: Int } if b => x.size // this could/should do a static conformance test and not warn + /* nowarn */ case x: ((AnyRef { def size: Int }) @unchecked) if b => x.size + } +} diff --git a/test/files/neg/unchecked.check b/test/files/neg/unchecked.check index 34a11db1a0..2883b716c9 100644 --- a/test/files/neg/unchecked.check +++ b/test/files/neg/unchecked.check @@ -2,7 +2,7 @@ unchecked.scala:18: error: non-variable type argument String in type pattern Ite case xs: Iterable[String] => xs.head // unchecked ^ unchecked.scala:22: error: non-variable type argument Any in type pattern Set[Any] is unchecked since it is eliminated by erasure - case xs: Set[Any] => xs.head // unchecked + case xs: Set[Any] => xs.head // unchecked ^ unchecked.scala:26: error: non-variable type argument Any in type pattern Map[Any,Any] is unchecked since it is eliminated by erasure case xs: Map[Any, Any] => xs.head // unchecked diff --git a/test/files/neg/unchecked.scala b/test/files/neg/unchecked.scala index b50cdf9d7a..e491b253ba 100644 --- a/test/files/neg/unchecked.scala +++ b/test/files/neg/unchecked.scala @@ -19,8 +19,8 @@ object Test { case _ => 0 } def f3(x: Any) = x match { - case xs: Set[Any] => xs.head // unchecked - case _ => 0 + case xs: Set[Any] => xs.head // unchecked + case _ => 0 } def f4(x: Any) = x match { case xs: Map[Any, Any] => xs.head // unchecked diff --git a/test/files/neg/unchecked2.check b/test/files/neg/unchecked2.check index e37865928e..68fdfa82ac 100644 --- a/test/files/neg/unchecked2.check +++ b/test/files/neg/unchecked2.check @@ -1,19 +1,43 @@ -unchecked2.scala:2: error: non-variable type argument Int in type Option[Int] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[Int]] - ^ -unchecked2.scala:3: error: non-variable type argument String in type Option[String] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[String]] - ^ -unchecked2.scala:4: error: non-variable type argument List[String] in type Option[List[String]] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[List[String]]] - ^ -unchecked2.scala:5: error: non-variable type argument List[Int => String] in type Option[List[Int => String]] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[List[Int => String]]] - ^ -unchecked2.scala:6: error: non-variable type argument (String, Double) in type Option[(String, Double)] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[(String, Double)]] - ^ -unchecked2.scala:7: error: non-variable type argument String => Double in type Option[String => Double] is unchecked since it is eliminated by erasure - Some(123).isInstanceOf[Option[String => Double]] - ^ -6 errors found +unchecked2.scala:4: error: fruitless type test: a value of type Some[List[Int]] cannot also be a Option[List[String]] (but still might match its erasure) + /* warn */ Some(List(1)).isInstanceOf[Option[List[String]]] + ^ +unchecked2.scala:5: error: non-variable type argument Option[_] in type Option[Option[_]] is unchecked since it is eliminated by erasure + /* warn */ Some(123).isInstanceOf[Option[Option[_]]] + ^ +unchecked2.scala:6: error: fruitless type test: a value of type Some[Int] cannot also be a Option[String] (but still might match its erasure) + /* warn */ Some(123).isInstanceOf[Option[String]] + ^ +unchecked2.scala:7: error: fruitless type test: a value of type Some[Int] cannot also be a Option[List[String]] (but still might match its erasure) + /* warn */ Some(123).isInstanceOf[Option[List[String]]] + ^ +unchecked2.scala:8: error: fruitless type test: a value of type Some[Int] cannot also be a Option[List[Int => String]] (but still might match its erasure) + /* warn */ Some(123).isInstanceOf[Option[List[Int => String]]] + ^ +unchecked2.scala:9: error: fruitless type test: a value of type Some[Int] cannot also be a Option[(String, Double)] (but still might match its erasure) + /* warn */ Some(123).isInstanceOf[Option[(String, Double)]] + ^ +unchecked2.scala:10: error: fruitless type test: a value of type Some[Int] cannot also be a Option[String => Double] (but still might match its erasure) + /* warn */ Some(123).isInstanceOf[Option[String => Double]] + ^ +unchecked2.scala:14: error: non-variable type argument List[String] in type Option[List[String]] is unchecked since it is eliminated by erasure + /* warn */ (Some(List(1)): Any).isInstanceOf[Option[List[String]]] + ^ +unchecked2.scala:15: error: non-variable type argument Int in type Option[Int] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[Int]] + ^ +unchecked2.scala:16: error: non-variable type argument String in type Option[String] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[String]] + ^ +unchecked2.scala:17: error: non-variable type argument List[String] in type Option[List[String]] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[List[String]]] + ^ +unchecked2.scala:18: error: non-variable type argument List[Int => String] in type Option[List[Int => String]] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[List[Int => String]]] + ^ +unchecked2.scala:19: error: non-variable type argument (String, Double) in type Option[(String, Double)] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[(String, Double)]] + ^ +unchecked2.scala:20: error: non-variable type argument String => Double in type Option[String => Double] is unchecked since it is eliminated by erasure + /* warn */ (Some(123): Any).isInstanceOf[Option[String => Double]] + ^ +14 errors found diff --git a/test/files/neg/unchecked2.scala b/test/files/neg/unchecked2.scala index a2e757e1dc..616b05aad8 100644 --- a/test/files/neg/unchecked2.scala +++ b/test/files/neg/unchecked2.scala @@ -1,8 +1,33 @@ object Test { - Some(123).isInstanceOf[Option[Int]] - Some(123).isInstanceOf[Option[String]] - Some(123).isInstanceOf[Option[List[String]]] - Some(123).isInstanceOf[Option[List[Int => String]]] - Some(123).isInstanceOf[Option[(String, Double)]] - Some(123).isInstanceOf[Option[String => Double]] + // These warn because it can be statically shown they won't match. + + /* warn */ Some(List(1)).isInstanceOf[Option[List[String]]] + /* warn */ Some(123).isInstanceOf[Option[Option[_]]] + /* warn */ Some(123).isInstanceOf[Option[String]] + /* warn */ Some(123).isInstanceOf[Option[List[String]]] + /* warn */ Some(123).isInstanceOf[Option[List[Int => String]]] + /* warn */ Some(123).isInstanceOf[Option[(String, Double)]] + /* warn */ Some(123).isInstanceOf[Option[String => Double]] + + // These warn because you can't check at runtime. + + /* warn */ (Some(List(1)): Any).isInstanceOf[Option[List[String]]] + /* warn */ (Some(123): Any).isInstanceOf[Option[Int]] + /* warn */ (Some(123): Any).isInstanceOf[Option[String]] + /* warn */ (Some(123): Any).isInstanceOf[Option[List[String]]] + /* warn */ (Some(123): Any).isInstanceOf[Option[List[Int => String]]] + /* warn */ (Some(123): Any).isInstanceOf[Option[(String, Double)]] + /* warn */ (Some(123): Any).isInstanceOf[Option[String => Double]] + + // These don't warn. + + /* nowarn */ Some(List(1)).isInstanceOf[Option[List[Int]]] + /* nowarn */ Some(123).isInstanceOf[Option[Int]] + /* nowarn */ Some(123).isInstanceOf[Some[Int]] + /* nowarn */ Some(123).isInstanceOf[AnyRef] + + /* nowarn */ (Some(List(1)): Any).isInstanceOf[Option[_]] + /* nowarn */ (Some(123): Any).isInstanceOf[Option[_]] + /* nowarn */ (Some(123): Any).isInstanceOf[Some[_]] + /* nowarn */ (Some(123): Any).isInstanceOf[AnyRef] } diff --git a/test/files/neg/unchecked3.check b/test/files/neg/unchecked3.check new file mode 100644 index 0000000000..f4f0c74257 --- /dev/null +++ b/test/files/neg/unchecked3.check @@ -0,0 +1,37 @@ +unchecked3.scala:24: error: non-variable type argument Double in type pattern E1[Double] is unchecked since it is eliminated by erasure + /* warn */ def peerTypes2(x: B1[Int]) = x match { case _: E1[Double] => true } + ^ +unchecked3.scala:25: error: non-variable type argument Double in type pattern F1[Double] is unchecked since it is eliminated by erasure + /* warn */ def peerTypes3(x: B1[_]) = x match { case _: F1[Double] => true } + ^ +unchecked3.scala:28: error: non-variable type argument Int in type pattern A2[Int] is unchecked since it is eliminated by erasure + /* warn */ def twotypes1[T](x: B2[T, Int]) = x match { case _: A2[Int] => true } + ^ +unchecked3.scala:32: error: non-variable type argument Int in type pattern B2[_,Int] is unchecked since it is eliminated by erasure + /* warn */ def twotypes5[T](x: A2[T]) = x match { case _: B2[_, Int] => true } + ^ +unchecked3.scala:40: error: non-variable type argument String in type pattern Array[List[String]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[List[String]] => () + ^ +unchecked3.scala:43: error: non-variable type argument String in type pattern Array[Array[List[String]]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[Array[List[String]]] => () + ^ +unchecked3.scala:50: error: non-variable type argument String in type pattern Array[List[String]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[List[String]] => () + ^ +unchecked3.scala:53: error: non-variable type argument String in type pattern Array[Array[List[String]]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[Array[List[String]]] => () + ^ +unchecked3.scala:60: error: non-variable type argument String in type pattern Array[List[String]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[List[String]] => () + ^ +unchecked3.scala:62: error: non-variable type argument Array[String] in type pattern Array[List[Array[String]]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[List[Array[String]]] => () + ^ +unchecked3.scala:63: error: non-variable type argument String in type pattern Array[Array[List[String]]] is unchecked since it is eliminated by erasure + /* warn */ case _: Array[Array[List[String]]] => () + ^ +unchecked3.scala:75: error: abstract type A in type pattern Set[Q.this.A] is unchecked since it is eliminated by erasure + /* warn */ case xs: Set[A] => xs.head + ^ +12 errors found diff --git a/test/files/neg/unchecked3.flags b/test/files/neg/unchecked3.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/neg/unchecked3.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/neg/unchecked3.scala b/test/files/neg/unchecked3.scala new file mode 100644 index 0000000000..7b8c13e8f8 --- /dev/null +++ b/test/files/neg/unchecked3.scala @@ -0,0 +1,83 @@ +sealed trait A2[T1] +final class B2[T1, T2] extends A2[T1] + +sealed trait A[T] +final class B[T] extends A[T] + +sealed trait A1[T] +trait B1[T] extends A1[T] +trait C1[T] extends A1[T] +trait D1[T] extends A1[Int] +trait E1[T] extends B1[Int] +trait F1[T] extends B1[T] + +object MiscUnchecked { + /* nowarn */ def knownType1(x: A[Int]) = x match { case _: B[Int] if true => 1 } + /* nowarn */ def knownType2(x: B[Int]) = x match { case _: A[Int] if true => 1 } + /* nowarn */ def tparamLeakage1(x: Any) = x match { case Array() => 1 } + /* nowarn */ def tparamLeakage2(x: Any) = x match { case List() => 1 } + + // E1[Double] implies B1[Int], but B1[Int] does not imply E1[Double], even if .isInstanceOf[E1[_]] + // F1[Int] implies B1[Int], and B1[Int] implies F1[Int] + + /* nowarn */ def peerTypes1(x: B1[Int]) = x match { case _: C1[Int] => true } + /* warn */ def peerTypes2(x: B1[Int]) = x match { case _: E1[Double] => true } + /* warn */ def peerTypes3(x: B1[_]) = x match { case _: F1[Double] => true } + /* nowarn */ def peerTypes4(x: B1[Int]) = x match { case _: F1[Int] => true } + + /* warn */ def twotypes1[T](x: B2[T, Int]) = x match { case _: A2[Int] => true } + /* nowarn */ def twotypes2[T](x: B2[Int, T]) = x match { case _: A2[Int] => true } + /* nowarn */ def twotypes3(x: A2[Int]) = x match { case _: B2[Int, _] => true } + /* nowarn */ def twotypes4[T](x: A2[T]) = x match { case _: B2[T, _] => true } + /* warn */ def twotypes5[T](x: A2[T]) = x match { case _: B2[_, Int] => true } +} + +object Arrays { + def f1(x: Any) = x match { + /* nowarn */ case _: Array[Int] => () + /* nowarn */ case _: Array[Boolean] => () + /* nowarn */ case _: Array[String] => () + /* warn */ case _: Array[List[String]] => () + /* nowarn */ case _: Array[Array[String]] => () + /* nowarn */ case _: Array[Array[Array[String]]] => () + /* warn */ case _: Array[Array[List[String]]] => () + } + + def f2(x: Array[_]) = x match { + /* nowarn */ case _: Array[Int] => () + /* nowarn */ case _: Array[Boolean] => () + /* nowarn */ case _: Array[String] => () + /* warn */ case _: Array[List[String]] => () + /* nowarn */ case _: Array[Array[String]] => () + /* nowarn */ case _: Array[Array[Array[String]]] => () + /* warn */ case _: Array[Array[List[String]]] => () + } + + def f3[T](x: Array[T]) = x match { + /* nowarn */ case _: Array[Int] => () + /* nowarn */ case _: Array[Boolean] => () + /* nowarn */ case _: Array[String] => () + /* warn */ case _: Array[List[String]] => () + /* nowarn */ case _: Array[Array[String]] => () + /* warn */ case _: Array[List[Array[String]]] => () + /* warn */ case _: Array[Array[List[String]]] => () + } +} + +object Matching { + class Q { + type A + type B <: A + + def f(xs: Traversable[B]) = xs match { + /* nowarn */ case xs: List[A] => xs.head + /* nowarn */ case xs: Seq[B] => xs.head + /* warn */ case xs: Set[A] => xs.head + } + def f2[T <: B](xs: Traversable[T]) = xs match { + /* nowarn */ case xs: List[B with T] => xs.head + /* nowarn */ case xs: Seq[A] => xs.head + /* nowarn */ case xs: Set[T] => xs.head + } + } +} diff --git a/test/files/neg/valueclasses-impl-restrictions.check b/test/files/neg/valueclasses-impl-restrictions.check new file mode 100644 index 0000000000..63924493aa --- /dev/null +++ b/test/files/neg/valueclasses-impl-restrictions.check @@ -0,0 +1,17 @@ +valueclasses-impl-restrictions.scala:3: error: implementation restriction: nested object is not allowed in value class +This restriction is planned to be removed in subsequent releases. + object X + ^ +valueclasses-impl-restrictions.scala:9: error: implementation restriction: nested trait is not allowed in value class +This restriction is planned to be removed in subsequent releases. + trait I2 { + ^ +valueclasses-impl-restrictions.scala:15: error: implementation restriction: nested class is not allowed in value class +This restriction is planned to be removed in subsequent releases. + val i2 = new I2 { val q = x.s } + ^ +valueclasses-impl-restrictions.scala:21: error: implementation restriction: nested class is not allowed in value class +This restriction is planned to be removed in subsequent releases. + private[this] class I2(val q: String) + ^ +four errors found diff --git a/test/files/neg/valueclasses-impl-restrictions.scala b/test/files/neg/valueclasses-impl-restrictions.scala new file mode 100644 index 0000000000..137f3f854c --- /dev/null +++ b/test/files/neg/valueclasses-impl-restrictions.scala @@ -0,0 +1,27 @@ +class M(val t: Int) extends AnyVal { + def lazyString = { + object X + () => X + } +} + +class X1(val s: String) extends AnyVal { + trait I2 { + val q: String + def z = s + q + } + + def y(x: X1) = { + val i2 = new I2 { val q = x.s } + i2.z + } +} + +class X2(val s: String) extends AnyVal { + private[this] class I2(val q: String) + + def y(i: Int) = { + val i2 = new I2(i.toString) + i2.q + s + } +} diff --git a/test/files/neg/valueclasses.check b/test/files/neg/valueclasses.check index 4f042faded..3b82a8358c 100644 --- a/test/files/neg/valueclasses.check +++ b/test/files/neg/valueclasses.check @@ -25,13 +25,13 @@ class V5(private val x: Int) extends AnyVal // fail valueclasses.scala:19: error: value class needs to have exactly one public val parameter class V6(val x: Int, val y: String) extends AnyVal // fail ^ -valueclasses.scala:20: error: illegal parameter for value class +valueclasses.scala:20: error: field definition is not allowed in value class class V7(val x: Int, private[this] val y: String) extends AnyVal // fail ^ valueclasses.scala:21: error: value class needs to have exactly one public val parameter class V8(var x: Int) extends AnyVal // fail ^ -valueclasses.scala:24: error: this statement is not allowed in value class: private[this] val y: Int = V9.this.x +valueclasses.scala:24: error: field definition is not allowed in value class val y = x // fail ^ valueclasses.scala:29: error: type parameter of value class may not be specialized diff --git a/test/files/pos/t1107/O.scala b/test/files/pos/t1107b/O.scala index aa605a6d09..aa605a6d09 100644 --- a/test/files/pos/t1107/O.scala +++ b/test/files/pos/t1107b/O.scala diff --git a/test/files/pos/t1107/T.scala b/test/files/pos/t1107b/T.scala index 1f3712d529..1f3712d529 100644 --- a/test/files/pos/t1107/T.scala +++ b/test/files/pos/t1107b/T.scala diff --git a/test/files/pos/t1203/J.java b/test/files/pos/t1203b/J.java index 7fae118e04..7fae118e04 100644 --- a/test/files/pos/t1203/J.java +++ b/test/files/pos/t1203b/J.java diff --git a/test/files/pos/t1203/S.scala b/test/files/pos/t1203b/S.scala index 68eac4bf6d..68eac4bf6d 100644 --- a/test/files/pos/t1203/S.scala +++ b/test/files/pos/t1203b/S.scala diff --git a/test/files/pos/t4881.scala b/test/files/pos/t4881.scala deleted file mode 100644 index 46cfad9793..0000000000 --- a/test/files/pos/t4881.scala +++ /dev/null @@ -1,31 +0,0 @@ -class Contra[-T] -trait A -trait B extends A -trait C extends B - -// test improved variance inference: first try formals to see in which variance positions the type param appears; -// only when that fails to determine variance, look at result type -object Test { - def contraLBUB[a >: C <: A](): Contra[a] = null - def contraLB[a >: C](): Contra[a] = null - -{ - val x = contraLBUB() //inferred Contra[C] instead of Contra[A] - val x1: Contra[A] = x -} - -{ - val x = contraLB() //inferred Contra[C] instead of Contra[Any] - val x1: Contra[Any] = x -} - -{ - val x = contraLBUB // make sure it does the same thing as its ()-less counterpart - val x1: Contra[A] = x -} - -{ - val x = contraLB - val x1: Contra[Any] = x -} -} diff --git a/test/files/pos/t6215.scala b/test/files/pos/t6215.scala new file mode 100644 index 0000000000..2f66892b69 --- /dev/null +++ b/test/files/pos/t6215.scala @@ -0,0 +1 @@ +class Foo(val v: String) extends AnyVal { private def len = v.length ; def f = len } diff --git a/test/files/pos/t6275.flags b/test/files/pos/t6275.flags new file mode 100644 index 0000000000..85d8eb2ba2 --- /dev/null +++ b/test/files/pos/t6275.flags @@ -0,0 +1 @@ +-Xfatal-warnings diff --git a/test/files/pos/t6275.scala b/test/files/pos/t6275.scala new file mode 100644 index 0000000000..6b5ec7dceb --- /dev/null +++ b/test/files/pos/t6275.scala @@ -0,0 +1,11 @@ + +sealed trait A[T] +final class B[T] extends A[T] + +object ParsedAxis { + type BI = B[Int] + + def f1(a: A[Int]) = a match { case b: B[Int] => 3 } + def f2(a: A[Int]) = a match { case b: BI => 3 } + def f3(a: A[Int]) = a match { case b: B[t] => 3 } +} diff --git a/test/files/pos/t6311.scala b/test/files/pos/t6311.scala new file mode 100644 index 0000000000..d27ad2f502 --- /dev/null +++ b/test/files/pos/t6311.scala @@ -0,0 +1,5 @@ +class A { + def fooMinimal[T, Coll <: Traversable[T]](msg: String)(param1: Traversable[T])(param2: Coll): Traversable[T] = throw new Exception() + + fooMinimal("")(List(1))(List(2)) +} diff --git a/test/files/pos/t6358.scala b/test/files/pos/t6358.scala new file mode 100644 index 0000000000..25539c885e --- /dev/null +++ b/test/files/pos/t6358.scala @@ -0,0 +1,6 @@ +class L(val t: Int) extends AnyVal { + def lazyString = { + lazy val x = t.toString + () => x + } +} diff --git a/test/files/pos/t6358_2.scala b/test/files/pos/t6358_2.scala new file mode 100644 index 0000000000..7c2beb60d0 --- /dev/null +++ b/test/files/pos/t6358_2.scala @@ -0,0 +1,6 @@ +class Y[T](val i: Option[T]) extends AnyVal { + def q: List[T] = { + lazy val e: List[T] = i.toList + e + } +} diff --git a/test/files/pos/t6485a/Macros_1.scala b/test/files/pos/t6485a/Macros_1.scala new file mode 100644 index 0000000000..85c2d5dbdb --- /dev/null +++ b/test/files/pos/t6485a/Macros_1.scala @@ -0,0 +1,5 @@ +import scala.reflect.macros.Context + +object Macros { + def crash(c: Context): c.Expr[Unit] = c.universe.reify(()) +}
\ No newline at end of file diff --git a/test/files/pos/t6485a/Test_2.scala b/test/files/pos/t6485a/Test_2.scala new file mode 100644 index 0000000000..54e260ac74 --- /dev/null +++ b/test/files/pos/t6485a/Test_2.scala @@ -0,0 +1,5 @@ +import scala.language.experimental.macros + +final class Ops[T](val x: T) extends AnyVal { + def f = macro Macros.crash +} diff --git a/test/files/pos/t6485b/Test.scala b/test/files/pos/t6485b/Test.scala new file mode 100644 index 0000000000..382df1c453 --- /dev/null +++ b/test/files/pos/t6485b/Test.scala @@ -0,0 +1,10 @@ +import scala.language.experimental.macros +import scala.reflect.macros.Context + +final class Ops[T](val x: T) extends AnyVal { + def f = macro Macros.crash +} + +object Macros { + def crash(c: Context): c.Expr[Unit] = c.universe.reify(()) +}
\ No newline at end of file diff --git a/test/files/pos/t6499.scala b/test/files/pos/t6499.scala new file mode 100644 index 0000000000..db376572ee --- /dev/null +++ b/test/files/pos/t6499.scala @@ -0,0 +1,3 @@ +object Test { + Map(): Map[_, Int] with Map[_, Int] +} diff --git a/test/files/presentation/forgotten-ask.scala b/test/files/presentation/forgotten-ask.scala new file mode 100644 index 0000000000..358dd75e98 --- /dev/null +++ b/test/files/presentation/forgotten-ask.scala @@ -0,0 +1,33 @@ +import scala.tools.nsc.interactive._ +import tests._ + +/** Test that no ask calls are left unanswered after a compiler has shut down. */ +object Test extends InteractiveTest { + import compiler._ + + def askItem(): Response[Unit] = { + compiler.askForResponse { () => + Thread.sleep(100) + } + } + + final val Timeout = 5000 //ms + + override def main(args: Array[String]) { + val item1 = askItem() + + compiler.askShutdown() + + Thread.sleep(1000) // wait a bit, the compiler is shutting down + val item2 = askItem() + + item1.get(Timeout) match { + case None => println("TIMEOUT") + case _ => + } + item2.get(Timeout) match { + case None => println("TIMEOUT") + case _ => + } + } +}
\ No newline at end of file diff --git a/test/files/run/existentials3-new.check b/test/files/run/existentials3-new.check index bb6fe1a5e3..00614b19db 100644 --- a/test/files/run/existentials3-new.check +++ b/test/files/run/existentials3-new.check @@ -3,8 +3,8 @@ Bar, t=TypeRef, s=type Bar Test.ToS, t=RefinedType, s=f3 Test.ToS, t=RefinedType, s=f4 Test.ToS, t=RefinedType, s=f5 -() => Test.ToS, t=TypeRef, s=class Function0 -() => Test.ToS, t=TypeRef, s=class Function0 +() => Test.ToS, t=TypeRef, s=trait Function0 +() => Test.ToS, t=TypeRef, s=trait Function0 $anon, t=TypeRef, s=type $anon $anon, t=TypeRef, s=type $anon List[java.lang.Object{type T1}#T1], t=TypeRef, s=class List @@ -15,8 +15,8 @@ Bar, t=TypeRef, s=type Bar Test.ToS, t=RefinedType, s=g3 Test.ToS, t=RefinedType, s=g4 Test.ToS, t=RefinedType, s=g5 -() => Test.ToS, t=TypeRef, s=class Function0 -() => Test.ToS, t=TypeRef, s=class Function0 +() => Test.ToS, t=TypeRef, s=trait Function0 +() => Test.ToS, t=TypeRef, s=trait Function0 $anon, t=TypeRef, s=type $anon $anon, t=TypeRef, s=type $anon List[java.lang.Object{type T1}#T1], t=TypeRef, s=class List diff --git a/test/files/run/fail-non-value-types.check b/test/files/run/fail-non-value-types.check new file mode 100644 index 0000000000..714dce2c50 --- /dev/null +++ b/test/files/run/fail-non-value-types.check @@ -0,0 +1,3 @@ +[B, That](f: A => B)(implicit cbf: ImaginaryCanBuildFrom[CompletelyIndependentList.this.Repr,B,That])That +[B, That](f: Int => B)(implicit cbf: ImaginaryCanBuildFrom[CompletelyIndependentList[Int]#Repr,B,That])That +()CompletelyIndependentList[A] diff --git a/test/files/run/fail-non-value-types.scala b/test/files/run/fail-non-value-types.scala new file mode 100644 index 0000000000..51198a5f31 --- /dev/null +++ b/test/files/run/fail-non-value-types.scala @@ -0,0 +1,40 @@ +import scala.reflect.runtime.universe._ + +class ImaginaryCanBuildFrom[-From, -Elem, +To] +class CompletelyIndependentList[+A] { + type Repr <: CompletelyIndependentList[A] + def map[B, That](f: A => B)(implicit cbf: ImaginaryCanBuildFrom[Repr, B, That]): That = ??? + def distinct(): CompletelyIndependentList[A] = ??? +} + +object Test { + var failed = false + def expectFailure[T](body: => T): Boolean = { + try { val res = body ; failed = true ; println(res + " failed to fail.") ; false } + catch { case _: AssertionError => true } + } + + /** Attempt to use a method type as a type argument - expect failure. */ + def tcon[T: TypeTag](args: Type*) = appliedType(typeOf[T].typeConstructor, args.toList) + + def cil = typeOf[CompletelyIndependentList[Int]] + def map = cil.member("map": TermName).asMethod + def distinct = cil.member("distinct": TermName).asMethod + + def main(args: Array[String]): Unit = { + // Need the assert in there to fail. + // expectFailure(println(tcon[CompletelyIndependentList[Int]](map))) + // expectFailure(tcon[CompletelyIndependentList[Int]](distinct)) + + // Why is the first map signature printing showing an + // uninitialized symbol? + // + // [B <: <?>, That <: <?>](f: <?>)(implicit cbf: <?>)That + // + + println(map.typeSignature) + println(map.typeSignatureIn(cil)) + println(distinct.typeSignature) + if (failed) sys.exit(1) + } +} diff --git a/test/files/run/macro-openmacros/Impls_Macros_1.scala b/test/files/run/macro-openmacros/Impls_Macros_1.scala index 38d46c5185..b863ac048b 100644 --- a/test/files/run/macro-openmacros/Impls_Macros_1.scala +++ b/test/files/run/macro-openmacros/Impls_Macros_1.scala @@ -4,8 +4,7 @@ object Macros { def impl(c: Context): c.Expr[Unit] = { // we're macros, so we can reflect against our source path // so we don't need any partests to clean up after us! - val c.CompilationUnit(file, _, _) = c.enclosingUnit - val dir = file.getCanonicalFile.getParentFile + val dir = c.enclosingUnit.source.file.file.getCanonicalFile.getParentFile def normalizePaths(s: String) = { val base = (dir.getCanonicalPath + java.io.File.separator).replace('\\', '/') var regex = """\Q%s\E""" format base diff --git a/test/files/run/macro-reflective-mamd-normal-mi/Macros_Test_2.scala b/test/files/run/macro-reflective-mamd-normal-mi/Macros_Test_2.scala index 089f30f389..adecfcff17 100644 --- a/test/files/run/macro-reflective-mamd-normal-mi/Macros_Test_2.scala +++ b/test/files/run/macro-reflective-mamd-normal-mi/Macros_Test_2.scala @@ -11,7 +11,7 @@ object Test extends App { val macrobody = Select(Ident(newTermName("Impls")), newTermName("foo")) val macroparam = ValDef(NoMods, newTermName("x"), TypeTree(definitions.IntClass.toType), EmptyTree) val macrodef = DefDef(Modifiers(MACRO), newTermName("foo"), Nil, List(List(macroparam)), TypeTree(), macrobody) - val modulector = DefDef(NoMods, nme.CONSTRUCTOR, Nil, List(List()), TypeTree(), Block(Apply(Select(Super(This(EmptyTypeName), EmptyTypeName), nme.CONSTRUCTOR), List()))) + val modulector = DefDef(NoMods, nme.CONSTRUCTOR, Nil, List(List()), TypeTree(), Block(Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List()))) val module = ModuleDef(NoMods, newTermName("Macros"), Template(Nil, emptyValDef, List(modulector, macrodef))) val macroapp = Apply(Select(Ident("Macros"), newTermName("foo")), List(Literal(Constant(42)))) val tree = Block(macrodef, module, macroapp) diff --git a/test/files/run/macro-reify-nested-a/Impls_Macros_1.scala b/test/files/run/macro-reify-nested-a/Impls_Macros_1.scala index ae2def2d3e..b4351c2c53 100644 --- a/test/files/run/macro-reify-nested-a/Impls_Macros_1.scala +++ b/test/files/run/macro-reify-nested-a/Impls_Macros_1.scala @@ -23,9 +23,10 @@ case class Utils[C <: Context]( c:C ) { object QueryableMacros{ def _helper[C <: Context,S:c.WeakTypeTag]( c:C )( name:String, projection:c.Expr[_] ) = { import c.universe._ + import treeBuild._ val element_type = implicitly[c.WeakTypeTag[S]].tpe val foo = c.Expr[ru.Expr[Queryable[S]]]( - c.reifyTree( c.runtimeUniverse, EmptyTree, c.typeCheck( + c.reifyTree( mkRuntimeUniverseRef, EmptyTree, c.typeCheck( Utils[c.type](c).removeDoubleReify( Apply(Select(c.prefix.tree, newTermName( name )), List( projection.tree )) ).asInstanceOf[Tree] diff --git a/test/files/run/macro-reify-nested-b/Impls_Macros_1.scala b/test/files/run/macro-reify-nested-b/Impls_Macros_1.scala index ae2def2d3e..b4351c2c53 100644 --- a/test/files/run/macro-reify-nested-b/Impls_Macros_1.scala +++ b/test/files/run/macro-reify-nested-b/Impls_Macros_1.scala @@ -23,9 +23,10 @@ case class Utils[C <: Context]( c:C ) { object QueryableMacros{ def _helper[C <: Context,S:c.WeakTypeTag]( c:C )( name:String, projection:c.Expr[_] ) = { import c.universe._ + import treeBuild._ val element_type = implicitly[c.WeakTypeTag[S]].tpe val foo = c.Expr[ru.Expr[Queryable[S]]]( - c.reifyTree( c.runtimeUniverse, EmptyTree, c.typeCheck( + c.reifyTree( mkRuntimeUniverseRef, EmptyTree, c.typeCheck( Utils[c.type](c).removeDoubleReify( Apply(Select(c.prefix.tree, newTermName( name )), List( projection.tree )) ).asInstanceOf[Tree] diff --git a/test/files/run/macro-reify-splice-outside-reify/Impls_Macros_1.scala b/test/files/run/macro-reify-splice-outside-reify/Impls_Macros_1.scala index b23a5c70e1..5330d0e32b 100644 --- a/test/files/run/macro-reify-splice-outside-reify/Impls_Macros_1.scala +++ b/test/files/run/macro-reify-splice-outside-reify/Impls_Macros_1.scala @@ -4,18 +4,7 @@ object Impls { def foo(c: Ctx)(x: c.Expr[Int]) = { val x1 = c.Expr[Int](c.resetAllAttrs(x.tree)) // was: c.literal(x1.splice) - c.literal(eval(c)(x1)) - } - - private def eval[T](c: Ctx)(x: c.Expr[T]): T = { - import scala.reflect.runtime.{universe => ru} - val mirror = ru.runtimeMirror(c.libraryClassLoader) - import scala.tools.reflect.ToolBox - val toolBox = mirror.mkToolBox() - val importer = ru.mkImporter(c.universe).asInstanceOf[ru.Importer { val from: c.universe.type }] - val tree = c.resetAllAttrs(x.tree.duplicate) - val imported = importer.importTree(tree) - toolBox.eval(imported).asInstanceOf[T] + c.literal(c.eval(x1)) } } diff --git a/test/files/run/macro-reify-type.check b/test/files/run/macro-reify-type.check new file mode 100644 index 0000000000..ea5e70e10d --- /dev/null +++ b/test/files/run/macro-reify-type.check @@ -0,0 +1 @@ +[B, That](f: Int => B)(implicit bf: scala.collection.generic.CanBuildFrom[List[Int],B,That])That
\ No newline at end of file diff --git a/test/files/run/macro-reify-type.flags b/test/files/run/macro-reify-type.flags new file mode 100644 index 0000000000..cd66464f2f --- /dev/null +++ b/test/files/run/macro-reify-type.flags @@ -0,0 +1 @@ +-language:experimental.macros
\ No newline at end of file diff --git a/test/files/run/macro-reify-type/Macros_1.scala b/test/files/run/macro-reify-type/Macros_1.scala new file mode 100644 index 0000000000..06de05735d --- /dev/null +++ b/test/files/run/macro-reify-type/Macros_1.scala @@ -0,0 +1,27 @@ +import scala.reflect.macros.Context +import scala.reflect.runtime.{universe => ru} + +object StaticReflect { + def method[A](name: String): ru.Type = macro methodImpl[A] + + def methodImpl[A: c.WeakTypeTag](c: Context)(name: c.Expr[String]): c.Expr[ru.Type] = { + import c.universe._ + + val nameName: TermName = name.tree match { + case Literal(Constant(str: String)) => newTermName(str) + case _ => c.error(c.enclosingPosition, s"Method name not constant.") ; return reify(ru.NoType) + } + val clazz = weakTypeOf[A] + + clazz member nameName match { + case NoSymbol => c.error(c.enclosingPosition, s"No member called $nameName in $clazz.") ; reify(ru.NoType) + case member => + val mtpe = member typeSignatureIn clazz + val mtag = c.reifyType(treeBuild.mkRuntimeUniverseRef, Select(treeBuild.mkRuntimeUniverseRef, newTermName("rootMirror")), mtpe) + val mtree = Select(mtag, newTermName("tpe")) + + c.Expr[ru.Type](mtree) + } + } + +} diff --git a/test/files/run/macro-reify-type/Test_2.scala b/test/files/run/macro-reify-type/Test_2.scala new file mode 100644 index 0000000000..9beaf98681 --- /dev/null +++ b/test/files/run/macro-reify-type/Test_2.scala @@ -0,0 +1,21 @@ +import StaticReflect._ + +object Test extends App { + //println(method[List[Int]]("distinct")) + println(method[List[Int]]("map")) + //val $u: scala.reflect.runtime.universe.type = scala.reflect.runtime.universe; + //val $m: $u.Mirror = scala.reflect.runtime.universe.rootMirror; + //import $u._, $m._, Flag._ + //val tpe = { + // val symdef$B2 = build.newNestedSymbol(build.selectTerm(staticClass("scala.collection.TraversableLike"), "map"), newTypeName("B"), NoPosition, DEFERRED | PARAM, false); + // val symdef$That2 = build.newNestedSymbol(build.selectTerm(staticClass("scala.collection.TraversableLike"), "map"), newTypeName("That"), NoPosition, DEFERRED | PARAM, false); + // val symdef$f2 = build.newNestedSymbol(build.selectTerm(staticClass("scala.collection.TraversableLike"), "map"), newTermName("f"), NoPosition, PARAM, false); + // val symdef$bf2 = build.newNestedSymbol(build.selectTerm(staticClass("scala.collection.TraversableLike"), "map"), newTermName("bf"), NoPosition, IMPLICIT | PARAM, false); + // build.setTypeSignature(symdef$B2, TypeBounds(staticClass("scala.Nothing").asType.toTypeConstructor, staticClass("scala.Any").asType.toTypeConstructor)); + // build.setTypeSignature(symdef$That2, TypeBounds(staticClass("scala.Nothing").asType.toTypeConstructor, staticClass("scala.Any").asType.toTypeConstructor)); + // build.setTypeSignature(symdef$f2, TypeRef(ThisType(staticPackage("scala").asModule.moduleClass), staticClass("scala.Function1"), List(staticClass("scala.Int").asType.toTypeConstructor, TypeRef(NoPrefix, symdef$B2, List())))); + // build.setTypeSignature(symdef$bf2, TypeRef(ThisType(staticPackage("scala.collection.generic").asModule.moduleClass), staticClass("scala.collection.generic.CanBuildFrom"), List(TypeRef(ThisType(staticPackage("scala.collection.immutable").asModule.moduleClass), staticClass("scala.collection.immutable.List"), List(staticClass("scala.Int").asType.toTypeConstructor)), TypeRef(NoPrefix, symdef$B2, List()), TypeRef(NoPrefix, symdef$That2, List())))); + // PolyType(List(symdef$B2, symdef$That2), MethodType(List(symdef$f2), MethodType(List(symdef$bf2), TypeRef(NoPrefix, symdef$That2, List())))) + //} + //println(tpe) +}
\ No newline at end of file diff --git a/test/files/run/macro-reify-unreify/Macros_1.scala b/test/files/run/macro-reify-unreify/Macros_1.scala index 620a929210..9f04c13014 100644 --- a/test/files/run/macro-reify-unreify/Macros_1.scala +++ b/test/files/run/macro-reify-unreify/Macros_1.scala @@ -6,9 +6,10 @@ object Macros { object Impls { def foo(c: Ctx)(s: c.Expr[String]) = { import c.universe._ + import treeBuild._ - val world = c.reifyTree(c.runtimeUniverse, EmptyTree, s.tree) - val greeting = c.reifyTree(c.runtimeUniverse, EmptyTree, c.typeCheck(Apply(Select(Literal(Constant("hello ")), newTermName("$plus")), List(c.unreifyTree(world))))) + val world = c.reifyTree(mkRuntimeUniverseRef, EmptyTree, s.tree) + val greeting = c.reifyTree(mkRuntimeUniverseRef, EmptyTree, c.typeCheck(Apply(Select(Literal(Constant("hello ")), newTermName("$plus")), List(c.unreifyTree(world))))) val typedGreeting = c.Expr[String](greeting) c.universe.reify { diff --git a/test/files/run/macro-sip19-revised/Impls_Macros_1.scala b/test/files/run/macro-sip19-revised/Impls_Macros_1.scala index 0793696fd4..5f3f61ca3f 100644 --- a/test/files/run/macro-sip19-revised/Impls_Macros_1.scala +++ b/test/files/run/macro-sip19-revised/Impls_Macros_1.scala @@ -8,7 +8,7 @@ object Macros { val outer = c.Expr[SourceLocation](if (!inscope.isEmpty) inscope else Literal(Constant(null))) val Apply(fun, args) = c.enclosingImplicits(0)._2 - val fileName = fun.pos.fileInfo.getName + val fileName = fun.pos.source.file.file.getName val line = fun.pos.line val charOffset = fun.pos.point c.universe.reify { SourceLocation1(outer.splice, c.literal(fileName).splice, c.literal(line).splice, c.literal(charOffset).splice) } diff --git a/test/files/run/macro-sip19/Impls_Macros_1.scala b/test/files/run/macro-sip19/Impls_Macros_1.scala index f89e51f560..535ec2ccf0 100644 --- a/test/files/run/macro-sip19/Impls_Macros_1.scala +++ b/test/files/run/macro-sip19/Impls_Macros_1.scala @@ -4,7 +4,7 @@ object Macros { def impl(c: Context) = { import c.universe._ val Apply(fun, args) = c.enclosingImplicits(0)._2 - val fileName = fun.pos.fileInfo.getName + val fileName = fun.pos.source.file.file.getName val line = fun.pos.line val charOffset = fun.pos.point c.universe.reify { SourceLocation(c.literal(fileName).splice, c.literal(line).splice, c.literal(charOffset).splice) } diff --git a/test/files/run/macro-typecheck-implicitsdisabled.check b/test/files/run/macro-typecheck-implicitsdisabled.check index 6cf25076a7..c4fa2c5c28 100644 --- a/test/files/run/macro-typecheck-implicitsdisabled.check +++ b/test/files/run/macro-typecheck-implicitsdisabled.check @@ -1,2 +1,2 @@ scala.this.Predef.any2ArrowAssoc[Int](1).->[Int](2) -scala.reflect.internal.Types$TypeError: value -> is not a member of Int +scala.reflect.macros.TypecheckException: value -> is not a member of Int diff --git a/test/files/run/macro-typecheck-macrosdisabled.check b/test/files/run/macro-typecheck-macrosdisabled.check index 719c6a2ef2..29a881f8b1 100644 --- a/test/files/run/macro-typecheck-macrosdisabled.check +++ b/test/files/run/macro-typecheck-macrosdisabled.check @@ -7,7 +7,7 @@ $treecreator1.super.<init>(); () }; - def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Tree = { + def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Tree = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.Literal.apply($u.Constant.apply(2)) @@ -20,7 +20,7 @@ $typecreator2.super.<init>(); () }; - def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Type = { + def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.ConstantType.apply($u.Constant.apply(2)) diff --git a/test/files/run/macro-typecheck-macrosdisabled2.check b/test/files/run/macro-typecheck-macrosdisabled2.check index 1fd422083c..7bdd1d6a3a 100644 --- a/test/files/run/macro-typecheck-macrosdisabled2.check +++ b/test/files/run/macro-typecheck-macrosdisabled2.check @@ -7,7 +7,7 @@ $treecreator1.super.<init>(); () }; - def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Tree = { + def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Tree = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.Apply.apply($u.Select.apply($u.Select.apply($u.build.Ident($m.staticPackage("scala")), $u.newTermName("Array")), $u.newTermName("apply")), scala.collection.immutable.List.apply[$u.Literal]($u.Literal.apply($u.Constant.apply(2)))) @@ -20,7 +20,7 @@ $typecreator2.super.<init>(); () }; - def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Type = { + def apply[U >: Nothing <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.TypeRef.apply($u.ThisType.apply($m.staticPackage("scala").asModule.moduleClass), $m.staticClass("scala.Array"), scala.collection.immutable.List.apply[$u.Type]($m.staticClass("scala.Int").asType.toTypeConstructor)) diff --git a/test/files/run/manifests-undeprecated-in-2.10.0.flags b/test/files/run/manifests-undeprecated-in-2.10.0.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/run/manifests-undeprecated-in-2.10.0.flags @@ -0,0 +1 @@ +-Xfatal-warnings
\ No newline at end of file diff --git a/test/files/run/manifests-undeprecated-in-2.10.0.scala b/test/files/run/manifests-undeprecated-in-2.10.0.scala new file mode 100644 index 0000000000..82e90b3a89 --- /dev/null +++ b/test/files/run/manifests-undeprecated-in-2.10.0.scala @@ -0,0 +1,15 @@ +object Test extends App { + def m1a: scala.reflect.Manifest[Int] = scala.reflect.Manifest.Int + def m2a: scala.reflect.OptManifest[Int] = ??? + def m3a = scala.reflect.NoManifest + + def m1b: Manifest[Int] = Manifest.Int + def m2b: OptManifest[Int] = ??? + def m3b = NoManifest + + val m4a = manifest[Int] + val m5a = optManifest[Int] + + val m4b = implicitly[Manifest[Int]] + val m5b = implicitly[OptManifest[Int]] +}
\ No newline at end of file diff --git a/test/files/run/reflection-implicit.scala b/test/files/run/reflection-implicit.scala index 637ef24e14..0bcb0bc3a0 100644 --- a/test/files/run/reflection-implicit.scala +++ b/test/files/run/reflection-implicit.scala @@ -9,7 +9,7 @@ class C { object Test extends App { val decls = typeOf[C].typeSymbol.typeSignature.declarations.sorted.toList.filter(sym => !sym.isTerm || (sym.isMethod && !sym.asMethod.isConstructor)) println(decls map (_.isImplicit)) - val param = decls.find(_.name.toString == "d").get.asMethod.params.last.head + val param = decls.find(_.name.toString == "d").get.asMethod.paramss.last.head param.typeSignature println(param.isImplicit) }
\ No newline at end of file diff --git a/test/files/run/reflection-java-annotations.scala b/test/files/run/reflection-java-annotations.scala index 0b16c0d103..2e3fed48ce 100644 --- a/test/files/run/reflection-java-annotations.scala +++ b/test/files/run/reflection-java-annotations.scala @@ -2,6 +2,6 @@ object Test extends App { import scala.reflect.runtime.universe._ val sym = typeOf[JavaAnnottee].typeSymbol sym.typeSignature - sym.getAnnotations foreach (_.javaArgs) - println(sym.getAnnotations) + sym.annotations foreach (_.javaArgs) + println(sym.annotations) }
\ No newline at end of file diff --git a/test/files/run/reflection-magicsymbols-invoke.check b/test/files/run/reflection-magicsymbols-invoke.check index 520dc2bfbe..f5258efeb7 100644 --- a/test/files/run/reflection-magicsymbols-invoke.check +++ b/test/files/run/reflection-magicsymbols-invoke.check @@ -90,7 +90,7 @@ method $asInstanceOf: [T0]()T0 method $isInstanceOf: [T0]()Boolean method ==: (x$1: Any)Boolean method ==: (x$1: AnyRef)Boolean -method apply: (i: <?>)T +method apply: (i: Int)T method asInstanceOf: [T0]=> T0 method clone: ()Array[T] method eq: (x$1: AnyRef)Boolean @@ -105,7 +105,7 @@ method notify: ()Unit method notifyAll: ()Unit method synchronized: [T0](x$1: T0)T0 method toString: ()java.lang.String -method update: (i: <?>, x: <?>)Unit +method update: (i: Int, x: T)Unit method wait: ()Unit method wait: (x$1: Long)Unit method wait: (x$1: Long, x$2: Int)Unit diff --git a/test/files/run/reflection-magicsymbols-invoke.scala b/test/files/run/reflection-magicsymbols-invoke.scala index b38d1be7b2..5f39370708 100644 --- a/test/files/run/reflection-magicsymbols-invoke.scala +++ b/test/files/run/reflection-magicsymbols-invoke.scala @@ -2,6 +2,12 @@ import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe.definitions._ import scala.reflect.runtime.{currentMirror => cm} +package scala { + object ExceptionUtils { + def unwrapThrowable(ex: Throwable): Throwable = scala.reflect.runtime.ReflectionUtils.unwrapThrowable(ex) + } +} + object Test extends App { def key(sym: Symbol) = sym + ": " + sym.typeSignature def test(tpe: Type, receiver: Any, method: String, args: Any*) { @@ -13,7 +19,7 @@ object Test extends App { println(result) } catch { case ex: Throwable => - val realex = scala.reflect.runtime.ReflectionUtils.unwrapThrowable(ex) + val realex = scala.ExceptionUtils.unwrapThrowable(ex) println(realex.getClass + ": " + realex.getMessage) } print(s"testing ${tpe.typeSymbol.name}.$method: ") diff --git a/test/files/run/reflection-mem-typecheck.scala b/test/files/run/reflection-mem-typecheck.scala new file mode 100644 index 0000000000..a312c2c893 --- /dev/null +++ b/test/files/run/reflection-mem-typecheck.scala @@ -0,0 +1,26 @@ +import scala.tools.partest.MemoryTest + +trait A { type T <: A } +trait B { type T <: B } + +object Test extends MemoryTest { + lazy val tb = { + import scala.reflect.runtime.universe._ + import scala.reflect.runtime.{currentMirror => cm} + import scala.tools.reflect.ToolBox + cm.mkToolBox() + } + + override def maxDelta = 10 + override def calcsPerIter = 8 + override def calc() { + var snippet = """ + trait A { type T <: A } + trait B { type T <: B } + def foo[T](x: List[T]) = x + foo(List(new A {}, new B {})) + """.trim + snippet = snippet + "\n" + (List.fill(50)(snippet.split("\n").last) mkString "\n") + tb.typeCheck(tb.parse(snippet)) + } +}
\ No newline at end of file diff --git a/test/files/run/reflection-methodsymbol-params.scala b/test/files/run/reflection-methodsymbol-params.scala index 7174c6f49b..45b1f9628f 100644 --- a/test/files/run/reflection-methodsymbol-params.scala +++ b/test/files/run/reflection-methodsymbol-params.scala @@ -13,12 +13,12 @@ class C { } object Test extends App { - println(typeOf[C].member(newTermName("x1")).asMethod.params) - println(typeOf[C].member(newTermName("x2")).asMethod.params) - println(typeOf[C].member(newTermName("x3")).asMethod.params) - println(typeOf[C].member(newTermName("x4")).asMethod.params) - println(typeOf[C].member(newTermName("y1")).asMethod.params) - println(typeOf[C].member(newTermName("y2")).asMethod.params) - println(typeOf[C].member(newTermName("y3")).asMethod.params) - println(typeOf[C].member(newTermName("y4")).asMethod.params) + println(typeOf[C].member(newTermName("x1")).asMethod.paramss) + println(typeOf[C].member(newTermName("x2")).asMethod.paramss) + println(typeOf[C].member(newTermName("x3")).asMethod.paramss) + println(typeOf[C].member(newTermName("x4")).asMethod.paramss) + println(typeOf[C].member(newTermName("y1")).asMethod.paramss) + println(typeOf[C].member(newTermName("y2")).asMethod.paramss) + println(typeOf[C].member(newTermName("y3")).asMethod.paramss) + println(typeOf[C].member(newTermName("y4")).asMethod.paramss) }
\ No newline at end of file diff --git a/test/files/run/reflection-valueclasses-magic.scala b/test/files/run/reflection-valueclasses-magic.scala index f9feb2d504..c4a26e460a 100644 --- a/test/files/run/reflection-valueclasses-magic.scala +++ b/test/files/run/reflection-valueclasses-magic.scala @@ -3,11 +3,17 @@ import scala.reflect.runtime.universe.definitions._ import scala.reflect.runtime.{currentMirror => cm} import scala.reflect.ClassTag +package scala { + object ExceptionUtils { + def unwrapThrowable(ex: Throwable): Throwable = scala.reflect.runtime.ReflectionUtils.unwrapThrowable(ex) + } +} + object Test extends App { def key(sym: Symbol) = { sym match { // initialize parameter symbols - case meth: MethodSymbol => meth.params.flatten.map(_.typeSignature) + case meth: MethodSymbol => meth.paramss.flatten.map(_.typeSignature) } sym + ": " + sym.typeSignature } @@ -35,14 +41,14 @@ object Test extends App { println(s"[${result.getClass}] =======> $result") } catch { case ex: Throwable => - val realex = scala.reflect.runtime.ReflectionUtils.unwrapThrowable(ex) + val realex = scala.ExceptionUtils.unwrapThrowable(ex) println(realex.getClass + ": " + realex.getMessage) } val meth = tpe.declaration(newTermName(method).encodedName.toTermName) val testees = if (meth.isMethod) List(meth.asMethod) else meth.asTerm.alternatives.map(_.asMethod) testees foreach (testee => { - val convertedArgs = args.zipWithIndex.map { case (arg, i) => convert(arg, testee.params.flatten.apply(i).typeSignature) } - print(s"testing ${tpe.typeSymbol.name}.$method(${testee.params.flatten.map(_.typeSignature).mkString(','.toString)}) with receiver = $receiver and args = ${convertedArgs.map(arg => arg + ' '.toString + arg.getClass).toList}: ") + val convertedArgs = args.zipWithIndex.map { case (arg, i) => convert(arg, testee.paramss.flatten.apply(i).typeSignature) } + print(s"testing ${tpe.typeSymbol.name}.$method(${testee.paramss.flatten.map(_.typeSignature).mkString(','.toString)}) with receiver = $receiver and args = ${convertedArgs.map(arg => arg + ' '.toString + arg.getClass).toList}: ") wrap(cm.reflect(receiver).reflectMethod(testee)(convertedArgs: _*)) }) } diff --git a/test/files/run/reify_ann1a.scala b/test/files/run/reify_ann1a.scala index 88b4191195..c23048e463 100644 --- a/test/files/run/reify_ann1a.scala +++ b/test/files/run/reify_ann1a.scala @@ -21,7 +21,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_ann1b.scala b/test/files/run/reify_ann1b.scala index a8fb876023..29ce6021a2 100644 --- a/test/files/run/reify_ann1b.scala +++ b/test/files/run/reify_ann1b.scala @@ -21,7 +21,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_ann2a.scala b/test/files/run/reify_ann2a.scala index b7e5833584..53423e12c3 100644 --- a/test/files/run/reify_ann2a.scala +++ b/test/files/run/reify_ann2a.scala @@ -21,7 +21,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_ann3.scala b/test/files/run/reify_ann3.scala index 662d58aaf3..4162fa532f 100644 --- a/test/files/run/reify_ann3.scala +++ b/test/files/run/reify_ann3.scala @@ -15,7 +15,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_ann4.scala b/test/files/run/reify_ann4.scala index a85e5e3625..0aedb77b5e 100644 --- a/test/files/run/reify_ann4.scala +++ b/test/files/run/reify_ann4.scala @@ -19,7 +19,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_ann5.scala b/test/files/run/reify_ann5.scala index 877360180c..d27be3b6d5 100644 --- a/test/files/run/reify_ann5.scala +++ b/test/files/run/reify_ann5.scala @@ -16,7 +16,6 @@ object Test extends App { // test 2: import and typecheck val toolbox = cm.mkToolBox() val ttree = toolbox.typeCheck(tree) - ttree.foreach(sub => if (sub.hasSymbol) sub.symbol.typeSignature) println(ttree.toString) // test 3: import and compile diff --git a/test/files/run/reify_lazyunit.check b/test/files/run/reify_lazyunit.check new file mode 100644 index 0000000000..1b46c909be --- /dev/null +++ b/test/files/run/reify_lazyunit.check @@ -0,0 +1,3 @@ +12 +one +two diff --git a/test/files/run/reify_lazyunit.scala b/test/files/run/reify_lazyunit.scala new file mode 100644 index 0000000000..78b00cde28 --- /dev/null +++ b/test/files/run/reify_lazyunit.scala @@ -0,0 +1,13 @@ +import scala.reflect.runtime.universe._ +import scala.tools.reflect.Eval + +object Test extends App { + reify { + lazy val x = { 0; println("12")} + x + println("one") + x + println("two") + }.eval +} + diff --git a/test/files/run/showraw_nosymbol.check b/test/files/run/showraw_nosymbol.check new file mode 100644 index 0000000000..c54fe74717 --- /dev/null +++ b/test/files/run/showraw_nosymbol.check @@ -0,0 +1 @@ +NoSymbol diff --git a/test/files/run/showraw_nosymbol.scala b/test/files/run/showraw_nosymbol.scala new file mode 100644 index 0000000000..fbdc1591c9 --- /dev/null +++ b/test/files/run/showraw_nosymbol.scala @@ -0,0 +1,5 @@ +import scala.reflect.runtime.universe._ + +object Test extends App { + println(showRaw(NoSymbol)) +}
\ No newline at end of file diff --git a/test/files/run/t5423.scala b/test/files/run/t5423.scala index 9b8ba090fa..c1632126b2 100644 --- a/test/files/run/t5423.scala +++ b/test/files/run/t5423.scala @@ -7,5 +7,5 @@ final class table extends annotation.StaticAnnotation object Test extends App { val s = cm.classSymbol(classOf[A]) - println(s.getAnnotations) + println(s.annotations) }
\ No newline at end of file diff --git a/test/files/run/t576.scala b/test/files/run/t576.scala index dc09d8dc98..756a241572 100644 --- a/test/files/run/t576.scala +++ b/test/files/run/t576.scala @@ -12,7 +12,7 @@ object Dingus { object Test { val x1 = new A val x2 = new A - + val x3 = new { self => override def equals(other : Any) = other match { case that: self.type => true @@ -20,7 +20,7 @@ object Test { } } val x4 = new { self => - def f(x: Any) = x match { + def f(x: Any): Int = x match { case _: x1.type => 1 case _: x2.type => 2 case _: x3.type => 3 @@ -35,11 +35,11 @@ object Test { assert(x1 != x2) assert(x1 != ()) assert(x2 != x1) - + assert(x3 == x3) assert(x3 != x2) assert(x2 != x3) - + List(x1, x2, x3, x4, Dingus) map x4.f foreach println } -}
\ No newline at end of file +} diff --git a/test/files/run/t6277.check b/test/files/run/t6277.check new file mode 100644 index 0000000000..f32a5804e2 --- /dev/null +++ b/test/files/run/t6277.check @@ -0,0 +1 @@ +true
\ No newline at end of file diff --git a/test/files/run/t6277.scala b/test/files/run/t6277.scala new file mode 100644 index 0000000000..41feee8a8a --- /dev/null +++ b/test/files/run/t6277.scala @@ -0,0 +1,9 @@ +import scala.reflect.runtime.universe._ + +object Test extends App { + locally { + val sym = typeOf[List[_]].typeSymbol.asClass + val q = sym.isSealed + println(q) + } +}
\ No newline at end of file diff --git a/test/files/run/t6344.check b/test/files/run/t6344.check index 5ac04d0320..8d9adac849 100644 --- a/test/files/run/t6344.check +++ b/test/files/run/t6344.check @@ -101,14 +101,14 @@ public int ValueInt.x() public int ValueInt.x() public java.lang.Object ValueInt.x() public java.lang.Object ValueInt.x() -public static Gen ValueInt.extension$plus(int,Gen,Gen) -public static Gen<java.lang.Object> ValueInt.extension$plus(int,Gen<java.lang.Object>,Gen<java.lang.Object>) -public static boolean ValueInt.extension$equals(int,java.lang.Object) -public static boolean ValueInt.extension$equals(int,java.lang.Object) -public static int ValueInt.extension$hashCode(int) -public static int ValueInt.extension$hashCode(int) -public static int ValueInt.extension$iplus(int,int,int) -public static int ValueInt.extension$iplus(int,int,int) +public static Gen ValueInt.plus$extension(int,Gen,Gen) +public static Gen<java.lang.Object> ValueInt.plus$extension(int,Gen<java.lang.Object>,Gen<java.lang.Object>) +public static boolean ValueInt.equals$extension(int,java.lang.Object) +public static boolean ValueInt.equals$extension(int,java.lang.Object) +public static int ValueInt.hashCode$extension(int) +public static int ValueInt.hashCode$extension(int) +public static int ValueInt.iplus$extension(int,int,int) +public static int ValueInt.iplus$extension(int,int,int) RefInt public Gen RefInt.plus(Gen,Gen) diff --git a/test/files/run/t6380.check b/test/files/run/t6380.check new file mode 100644 index 0000000000..912525ed66 --- /dev/null +++ b/test/files/run/t6380.check @@ -0,0 +1,7 @@ +List(class java.lang.Exception) +List(class java.lang.Throwable) +List(class java.lang.RuntimeException) +List(class java.lang.IllegalArgumentException, class java.util.NoSuchElementException) +List(class java.lang.IndexOutOfBoundsException, class java.lang.IndexOutOfBoundsException) +List(class java.lang.IllegalStateException, class java.lang.IllegalStateException) +List(class java.lang.NullPointerException, class java.lang.NullPointerException) diff --git a/test/files/run/t6380.scala b/test/files/run/t6380.scala new file mode 100644 index 0000000000..0e264d9175 --- /dev/null +++ b/test/files/run/t6380.scala @@ -0,0 +1,20 @@ +object Test extends App { + classOf[Foo].getDeclaredMethods().sortBy(_.getName).map(_.getExceptionTypes.sortBy(_.getName).toList).toList.foreach(println) +} + +class Foo { + @throws[Exception] + def bar1 = ??? + @throws[Throwable]("always") + def bar2 = ??? + @throws(classOf[RuntimeException]) + def bar3 = ??? + @throws[IllegalArgumentException] @throws[NoSuchElementException] + def bar4 = ??? + @throws(classOf[IndexOutOfBoundsException]) @throws(classOf[IndexOutOfBoundsException]) + def bar5 = ??? + @throws[IllegalStateException]("Cause") @throws[IllegalStateException] + def bar6 = ??? + @throws[NullPointerException]("Cause A") @throws[NullPointerException]("Cause B") + def bar7 = ??? +}
\ No newline at end of file diff --git a/test/files/run/t6410.check b/test/files/run/t6410.check new file mode 100644 index 0000000000..051fe4995a --- /dev/null +++ b/test/files/run/t6410.check @@ -0,0 +1,2 @@ +ParMap(0 -> 4, 1 -> 5) +ParMap(0 -> 4, 1 -> 5)
\ No newline at end of file diff --git a/test/files/run/t6410.scala b/test/files/run/t6410.scala new file mode 100644 index 0000000000..2a001b47ab --- /dev/null +++ b/test/files/run/t6410.scala @@ -0,0 +1,9 @@ + + + +object Test extends App { + val x = collection.parallel.mutable.ParArray.range(1,10) groupBy { _ % 2 } mapValues { _.size } + println(x) + val y = collection.parallel.immutable.ParVector.range(1,10) groupBy { _ % 2 } mapValues { _.size } + println(y) +}
\ No newline at end of file diff --git a/test/files/run/t6440.check b/test/files/run/t6440.check new file mode 100644 index 0000000000..b5684daee4 --- /dev/null +++ b/test/files/run/t6440.check @@ -0,0 +1 @@ +Stream((), ?) diff --git a/test/files/run/t6440.scala b/test/files/run/t6440.scala new file mode 100644 index 0000000000..2b690f31e1 --- /dev/null +++ b/test/files/run/t6440.scala @@ -0,0 +1,7 @@ +object Test { + + def main(args: Array[String]): Unit = { + println(Stream.continually(()).filterNot(_ => false).take(2)) + } + +} diff --git a/test/files/run/toolbox_console_reporter.check b/test/files/run/toolbox_console_reporter.check index e69de29bb2..1395c68740 100644 --- a/test/files/run/toolbox_console_reporter.check +++ b/test/files/run/toolbox_console_reporter.check @@ -0,0 +1,8 @@ +hello +============compiler console============= +warning: method foo in object Utils is deprecated: test + +========================================= +============compiler messages============ +Info(NoPosition,method foo in object Utils is deprecated: test,WARNING) +========================================= diff --git a/test/files/run/toolbox_console_reporter.scala b/test/files/run/toolbox_console_reporter.scala index a57dea38a8..d672ccb9cb 100644 --- a/test/files/run/toolbox_console_reporter.scala +++ b/test/files/run/toolbox_console_reporter.scala @@ -1,16 +1,29 @@ import scala.reflect.runtime.universe._ +import scala.reflect.runtime.{universe => ru} +import scala.reflect.runtime.{currentMirror => cm} +import scala.tools.reflect.{ToolBox, mkConsoleFrontEnd} object Test extends App { - // todo. cannot test this unfortunately, because ConsoleFrontEnd grabs Console.out too early - // todo. and isn't affected by Console.setOut employed by partest to intercept output + val oldErr = Console.err; + val baos = new java.io.ByteArrayOutputStream(); + Console.setErr(new java.io.PrintStream(baos)); + try { + val toolbox = cm.mkToolBox(frontEnd = mkConsoleFrontEnd(), options = "-deprecation") + toolbox.eval(reify{ + object Utils { + @deprecated("test", "2.10.0") + def foo { println("hello") } + } - //val toolbox = mkToolBox(frontEnd = mkConsoleFrontEnd(), options = "-deprecation") - //toolbox.eval(reify{ - // object Utils { - // @deprecated("test", "2.10.0") - // def foo { println("hello") } - // } - // - // Utils.foo - //}) + Utils.foo + }.tree) + println("============compiler console=============") + println(baos.toString); + println("=========================================") + println("============compiler messages============") + toolbox.frontEnd.infos.foreach(println(_)) + println("=========================================") + } finally { + Console.setErr(oldErr); + } }
\ No newline at end of file diff --git a/test/files/run/toolbox_silent_reporter.scala b/test/files/run/toolbox_silent_reporter.scala index 15f559d605..03b1d6defa 100644 --- a/test/files/run/toolbox_silent_reporter.scala +++ b/test/files/run/toolbox_silent_reporter.scala @@ -1,10 +1,10 @@ import scala.reflect.runtime.universe._ import scala.reflect.runtime.{universe => ru} import scala.reflect.runtime.{currentMirror => cm} -import scala.tools.reflect.ToolBox +import scala.tools.reflect.{ToolBox, mkSilentFrontEnd} object Test extends App { - val toolbox = cm.mkToolBox(options = "-deprecation") + val toolbox = cm.mkToolBox(options = "-deprecation", frontEnd = mkSilentFrontEnd()) toolbox.eval(reify{ object Utils { @deprecated("test", "2.10.0") diff --git a/test/files/run/toolbox_typecheck_macrosdisabled.check b/test/files/run/toolbox_typecheck_macrosdisabled.check index 9e997dafed..688f37927c 100644 --- a/test/files/run/toolbox_typecheck_macrosdisabled.check +++ b/test/files/run/toolbox_typecheck_macrosdisabled.check @@ -16,7 +16,7 @@ $treecreator1.super.<init>(); () }; - def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Tree = { + def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Tree = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.Literal.apply($u.Constant.apply(2)) @@ -29,7 +29,7 @@ $typecreator2.super.<init>(); () }; - def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Type = { + def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.ConstantType.apply($u.Constant.apply(2)) diff --git a/test/files/run/toolbox_typecheck_macrosdisabled2.check b/test/files/run/toolbox_typecheck_macrosdisabled2.check index 16c8d6c397..f5c9b6eeab 100644 --- a/test/files/run/toolbox_typecheck_macrosdisabled2.check +++ b/test/files/run/toolbox_typecheck_macrosdisabled2.check @@ -16,7 +16,7 @@ $treecreator1.super.<init>(); () }; - def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Tree = { + def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Tree = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.Apply.apply($u.Select.apply($u.Select.apply($u.build.Ident($m.staticPackage("scala")), $u.newTermName("Array")), $u.newTermName("apply")), scala.collection.immutable.List.apply[$u.Literal]($u.Literal.apply($u.Constant.apply(2)))) @@ -29,7 +29,7 @@ $typecreator2.super.<init>(); () }; - def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.MirrorOf[U]): U#Type = { + def apply[U <: scala.reflect.api.Universe with Singleton]($m$untyped: scala.reflect.api.Mirror[U]): U#Type = { val $u: U = $m$untyped.universe; val $m: $u.Mirror = $m$untyped.asInstanceOf[$u.Mirror]; $u.TypeRef.apply($u.ThisType.apply($m.staticPackage("scala").asModule.moduleClass), $m.staticClass("scala.Array"), scala.collection.immutable.List.apply[$u.Type]($m.staticClass("scala.Int").asType.toTypeConstructor)) diff --git a/test/files/run/typetags_without_scala_reflect_manifest_lookup.scala b/test/files/run/typetags_without_scala_reflect_manifest_lookup.scala index 37047e7884..6fd3d2dc2b 100644 --- a/test/files/run/typetags_without_scala_reflect_manifest_lookup.scala +++ b/test/files/run/typetags_without_scala_reflect_manifest_lookup.scala @@ -2,7 +2,7 @@ import scala.tools.partest._ import scala.tools.nsc.Settings object Test extends DirectTest { - override def extraSettings = "-cp " + sys.props("partest.lib") + override def extraSettings = "-cp " + sys.props("partest.lib") + " -d \"" + testOutput.path + "\"" def code = """ object Test extends App { diff --git a/test/pending/pos/exhaust_2.scala b/test/pending/pos/exhaust_2.scala new file mode 100644 index 0000000000..4f4e47c43b --- /dev/null +++ b/test/pending/pos/exhaust_2.scala @@ -0,0 +1,54 @@ +object ExhaustivityWarnBugReportMinimal { + //sealed is needed for the warning + sealed trait FoundNode[T]/*presence of parameters is irrelevant*/ + // This also causes a warning: + // sealed abstract class FoundNode[T]/*presence of parameters is irrelevant*/ + case class FoundFilter[T](/*presence of parameters is irrelevant*/) extends FoundNode[T] + case class FoundTypeCase[T](/*presence of parameters is irrelevant*/) extends FoundNode[T] + val f: Some[_] = ??? + f match { + case x: Some[t] => //no warning + } + //With these variants, no warnings: + //val v: (Some[Int], FoundNode[_]) = (???, ???) + //val v: (Some[AnyRef], FoundNode[_]) = (???, ???) + //val v: (Some[String], FoundNode[_]) = (???, ???) + + val v: (Some[_], FoundNode[_]) = (???, ???) + //Warning here: + v match { + case (x: Some[t], _: FoundNode[_]) => + } + v match { + case (x: Some[t], _) => + } + + v match { + case (x: Some[_], _) => + } + case class Foo[T]() + + val vp: (Foo[_], FoundNode[_]) = (???, ???) + vp match { + case (x: Foo[_], _) => + } + + //No warning here: + v match { + case (Some(y), _) => + } + + v match { + case (x, _) => + } + + val v2: (Some[_], Int) = (???, ???) + v2 match { + case (x: Some[t], _) => + } + + val v3: (Option[_], FoundNode[_]) = (???, ???) + v match { + case (x: Option[_], _) => + } +} diff --git a/test/pending/run/reflection-mem-eval.scala b/test/pending/run/reflection-mem-eval.scala new file mode 100644 index 0000000000..9045c44cd6 --- /dev/null +++ b/test/pending/run/reflection-mem-eval.scala @@ -0,0 +1,26 @@ +import scala.tools.partest.MemoryTest + +trait A { type T <: A } +trait B { type T <: B } + +object Test extends MemoryTest { + lazy val tb = { + import scala.reflect.runtime.universe._ + import scala.reflect.runtime.{currentMirror => cm} + import scala.tools.reflect.ToolBox + cm.mkToolBox() + } + + override def maxDelta = 10 + override def calcsPerIter = 3 + override def calc() { + var snippet = """ + trait A { type T <: A } + trait B { type T <: B } + def foo[T](x: List[T]) = x + foo(List(new A {}, new B {})) + """.trim + snippet = snippet + "\n" + (List.fill(50)(snippet.split("\n").last) mkString "\n") + tb.eval(tb.parse(snippet)) + } +}
\ No newline at end of file diff --git a/test/pending/run/t5882.scala b/test/pending/run/t5882.scala new file mode 100644 index 0000000000..47996d3068 --- /dev/null +++ b/test/pending/run/t5882.scala @@ -0,0 +1,14 @@ +// SIP-15 was revised to allow nested classes in value classes. +// This test checks that their basic functionality. + +class NodeOps(val n: Any) extends AnyVal { self => + class Foo() { def show = self.show(n) } + def show(x: Any) = x.toString +} + + +object Test extends App { + + val n = new NodeOps("abc") + assert(new n.Foo().show == "abc") +} diff --git a/test/pending/run/t6408.scala b/test/pending/run/t6408.scala new file mode 100644 index 0000000000..ff17480b35 --- /dev/null +++ b/test/pending/run/t6408.scala @@ -0,0 +1,11 @@ +class X(val i: Int) extends AnyVal { + class Inner(val q: Int) { + def plus = i + q + } +} + +object Test extends App { + val x = new X(11) + val i = new x.Inner(22) + assert(i.plus == 33) +} diff --git a/test/scaladoc/resources/SI-6509.scala b/test/scaladoc/resources/SI-6509.scala new file mode 100644 index 0000000000..540ba243bd --- /dev/null +++ b/test/scaladoc/resources/SI-6509.scala @@ -0,0 +1,24 @@ +package test.scaladoc.template.owners + +trait X { + /** @template */ + type Symbol >: Null <: SymbolApi + + /** @template */ + type TypeSymbol >: Null <: Symbol with TypeSymbolApi + + /** @template */ + type TermSymbol >: Null <: Symbol with TermSymbolApi + + /** @template */ + type MethodSymbol >: Null <: TermSymbol with MethodSymbolApi + + trait SymbolApi { this: Symbol => def x: Int} + trait TermSymbolApi extends SymbolApi { this: TermSymbol => def y: Int} + trait TypeSymbolApi extends SymbolApi { this: TypeSymbol => def z: Int} + trait MethodSymbolApi extends TermSymbolApi { this: MethodSymbol => def t: Int } +} + +trait Y extends X +trait Z extends Y +trait T extends Z diff --git a/test/scaladoc/resources/SI-6511.scala b/test/scaladoc/resources/SI-6511.scala new file mode 100644 index 0000000000..1f153caeb0 --- /dev/null +++ b/test/scaladoc/resources/SI-6511.scala @@ -0,0 +1,24 @@ +package test.scaladoc.template.diagrams + +/** @contentDiagram hideNodes "*Api" */ +trait X { + /** @template */ + type Symbol >: Null <: SymbolApi + + /** @template */ + type TypeSymbol >: Null <: Symbol with TypeSymbolApi + + /** @template */ + type TermSymbol >: Null <: Symbol with TermSymbolApi + + /** @template */ + type MethodSymbol >: Null <: TermSymbol with MethodSymbolApi + + trait SymbolApi { this: Symbol => def x: Int} + trait TermSymbolApi extends SymbolApi { this: TermSymbol => def y: Int} + trait TypeSymbolApi extends SymbolApi { this: TypeSymbol => def z: Int} + trait MethodSymbolApi extends TermSymbolApi { this: MethodSymbol => def t: Int } +} + +/** @contentDiagram hideNodes "*Api" */ +trait Y extends X diff --git a/test/scaladoc/resources/links.scala b/test/scaladoc/resources/links.scala index 09a52a4334..bd69665357 100644 --- a/test/scaladoc/resources/links.scala +++ b/test/scaladoc/resources/links.scala @@ -3,6 +3,9 @@ // SI-4497 "Links in ScalaDoc - Spec and implementation unsufficient" // SI-4224 "Wiki-links should support method targets" // SI-3695 "support non-fully-qualified type links in scaladoc comments" +// SI-6487 "Scaladoc can't link to inner classes" +// SI-6495 "Scaladoc won't pick up group name, priority and description from owner chain" +// SI-6501 "Scaladoc won't link to a @template type T as a template but as a member" package scala.test.scaladoc.links { import language.higherKinds class C @@ -54,9 +57,18 @@ package scala.test.scaladoc.links { * - [[localMethod object TEST -> localMethod]] (should use the current template to resolve link instead of inTpl, that's the package) * - [[#localMethod object TEST -> localMethod]] (should exercise Java-style links to empty members) * - [[ImOutside class ImOutside (check correct lookup in EmptyPackage)]] + * - [[ImOutside.Inner#foo class ImOutside#class Inner#method foo (check correct lookup in EmptyPackage)]] + * - [[ImOutside.T class ImOutside#type T (check correct linking to templates)]] + * - [[ImOutside.T#foo class ImOutside#type T#method foo (check correct interaction between @template and links)]] */ object TEST { def localMethod = 3 } } -class ImOutside
\ No newline at end of file +trait ImOutside { + /** @template */ + type T <: Inner + class Inner { + def foo: Any + } +} diff --git a/test/scaladoc/run/SI-6509.check b/test/scaladoc/run/SI-6509.check new file mode 100644 index 0000000000..3925a0d464 --- /dev/null +++ b/test/scaladoc/run/SI-6509.check @@ -0,0 +1 @@ +Done.
\ No newline at end of file diff --git a/test/scaladoc/run/SI-6509.scala b/test/scaladoc/run/SI-6509.scala new file mode 100644 index 0000000000..3857949d14 --- /dev/null +++ b/test/scaladoc/run/SI-6509.scala @@ -0,0 +1,30 @@ +import scala.tools.nsc.doc.model._ +import scala.tools.partest.ScaladocModelTest + +object Test extends ScaladocModelTest { + + override def resourceFile: String = "SI-6509.scala" + + // no need for special settings + def scaladocSettings = "" + + def testModel(rootPackage: Package) = { + // get the quick access implicit defs in scope (_package(s), _class(es), _trait(s), object(s) _method(s), _value(s)) + import access._ + + val main = rootPackage._package("test")._package("scaladoc")._package("template")._package("owners") + val X = main._trait("X") + val Y = main._trait("Y") + val Z = main._trait("Z") + val T = main._trait("T") + + def checkTemplateOwner(d: DocTemplateEntity) = + for (mbr <- List("Symbol", "TypeSymbol", "TermSymbol", "MethodSymbol")) { + val tpl = d._absTypeTpl(mbr).inTemplate + assert(tpl == X, tpl + " == X") + } + + for (tpl <- List(X, Y, Z, T)) + checkTemplateOwner(tpl) + } +}
\ No newline at end of file diff --git a/test/scaladoc/run/SI-6511.check b/test/scaladoc/run/SI-6511.check new file mode 100644 index 0000000000..3925a0d464 --- /dev/null +++ b/test/scaladoc/run/SI-6511.check @@ -0,0 +1 @@ +Done.
\ No newline at end of file diff --git a/test/scaladoc/run/SI-6511.scala b/test/scaladoc/run/SI-6511.scala new file mode 100644 index 0000000000..cc950a98d6 --- /dev/null +++ b/test/scaladoc/run/SI-6511.scala @@ -0,0 +1,22 @@ +import scala.tools.nsc.doc.model._ +import scala.tools.partest.ScaladocModelTest + +object Test extends ScaladocModelTest { + + override def resourceFile: String = "SI-6511.scala" + + // no need for special settings + def scaladocSettings = "-diagrams" + + def testModel(rootPackage: Package) = { + // get the quick access implicit defs in scope (_package(s), _class(es), _trait(s), object(s) _method(s), _value(s)) + import access._ + + val main = rootPackage._package("test")._package("scaladoc")._package("template")._package("diagrams") + val X = main._trait("X") + val Y = main._trait("Y") + + testDiagram(X, X.contentDiagram, nodes = 4, edges = 3) + testDiagram(Y, Y.contentDiagram, nodes = 4, edges = 3) + } +}
\ No newline at end of file diff --git a/test/scaladoc/run/groups.scala b/test/scaladoc/run/groups.scala index 05324c2ec9..c9e4a8679b 100644 --- a/test/scaladoc/run/groups.scala +++ b/test/scaladoc/run/groups.scala @@ -4,49 +4,54 @@ import scala.tools.partest.ScaladocModelTest object Test extends ScaladocModelTest { override def code = """ - package test.scaladoc.groups { - - /** - * The trait A - * @groupdesc A Group A is the group that contains functions starting with f - * For example: - * {{{ - * this is an example - * }}} - * @groupdesc B Group B is the group that contains functions starting with b - * @groupname B Group B has a nice new name and a high priority - * @groupprio B -10 - * @group Traits - * @note This is a note - */ - trait A { - /** foo description - * @group A */ - def foo = 1 - - /** bar description - * @group B */ - def bar = 2 - } - - /** The trait B - * @group Traits - * @groupdesc C Group C is introduced by B - */ - trait B { - /** baz descriptopn - * @group C */ - def baz = 3 - } - - /** The class C which inherits from both A and B - * @group Classes - * @groupdesc B Look ma, I'm overriding group descriptions!!! - * @groupname B And names - */ - class C extends A with B { - /** Oh noes, I lost my group -- or did I?!? */ - override def baz = 4 + package test.scaladoc { + + /** @groupname Z From owner chain */ + package object `groups` + + package groups { + /** + * The trait A + * @groupdesc A Group A is the group that contains functions starting with f + * For example: + * {{{ + * this is an example + * }}} + * @groupdesc B Group B is the group that contains functions starting with b + * @groupname B Group B has a nice new name and a high priority + * @groupprio B -10 + * @group Traits + * @note This is a note + */ + trait A { + /** foo description + * @group A */ + def foo = 1 + + /** bar description + * @group B */ + def bar = 2 + } + + /** The trait B + * @group Traits + * @groupdesc C Group C is introduced by B + */ + trait B { + /** baz descriptopn + * @group C */ + def baz = 3 + } + + /** The class C which inherits from both A and B + * @group Classes + * @groupdesc B Look ma, I'm overriding group descriptions!!! + * @groupname B And names + */ + class C extends A with B { + /** Oh noes, I lost my group -- or did I?!? */ + override def baz = 4 + } } } """ @@ -101,10 +106,12 @@ object Test extends ScaladocModelTest { checkGroupDesc(A, "B", "Group B is the group that contains functions starting with b") checkGroupName(A, "B", "Group B has a nice new name and a high priority") checkGroupPrio(A, "B", -10) + checkGroupName(A, "Z", "From owner chain") checkGroupDesc(B, "C", "Group C is introduced by B") checkGroupName(B, "C", "C") checkGroupPrio(B, "C", 0) + checkGroupName(B, "Z", "From owner chain") checkGroupDesc(C, "A", "Group A is the group that contains functions starting with f") checkGroupName(C, "A", "A") @@ -115,5 +122,6 @@ object Test extends ScaladocModelTest { checkGroupDesc(C, "C", "Group C is introduced by B") checkGroupName(C, "C", "C") checkGroupPrio(C, "C", 0) + checkGroupName(C, "Z", "From owner chain") } }
\ No newline at end of file diff --git a/test/scaladoc/run/links.scala b/test/scaladoc/run/links.scala index de359539cf..0c67857e1c 100644 --- a/test/scaladoc/run/links.scala +++ b/test/scaladoc/run/links.scala @@ -5,6 +5,9 @@ import scala.tools.partest.ScaladocModelTest // SI-4497 "Links in ScalaDoc - Spec and implementation unsufficient" // SI-4224 "Wiki-links should support method targets" // SI-3695 "support non-fully-qualified type links in scaladoc comments" +// SI-6487 "Scaladoc can't link to inner classes" +// SI-6495 "Scaladoc won't pick up group name, priority and description from owner chain" +// SI-6501 "Scaladoc won't link to a @template type T as a template but as a member" object Test extends ScaladocModelTest { override def resourceFile = "links.scala" @@ -22,7 +25,7 @@ object Test extends ScaladocModelTest { val memberLinks = countLinks(TEST.comment.get, _.link.isInstanceOf[LinkToMember]) val templateLinks = countLinks(TEST.comment.get, _.link.isInstanceOf[LinkToTpl]) - assert(memberLinks == 15, memberLinks + " == 15 (the member links in object TEST)") - assert(templateLinks == 5, templateLinks + " == 5 (the template links in object TEST)") + assert(memberLinks == 17, memberLinks + " == 17 (the member links in object TEST)") + assert(templateLinks == 6, templateLinks + " == 6 (the template links in object TEST)") } }
\ No newline at end of file |