summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CONTRIBUTING.md66
-rw-r--r--build.number2
-rw-r--r--docs/examples/swing/ColorChooserDemo.scala61
-rw-r--r--docs/examples/swing/PopupDemo.scala33
-rw-r--r--src/compiler/scala/reflect/reify/Errors.scala15
-rw-r--r--src/compiler/scala/reflect/reify/phases/Reshape.scala60
-rw-r--r--src/compiler/scala/tools/nsc/ast/NodePrinters.scala2
-rw-r--r--src/compiler/scala/tools/nsc/ast/Trees.scala2
-rw-r--r--src/compiler/scala/tools/nsc/ast/parser/Parsers.scala2
-rw-r--r--src/compiler/scala/tools/nsc/doc/DocFactory.scala3
-rw-r--r--src/compiler/scala/tools/nsc/doc/Settings.scala32
-rw-r--r--src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala6
-rw-r--r--src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala53
-rw-r--r--src/compiler/scala/tools/nsc/doc/model/ModelFactoryTypeSupport.scala2
-rw-r--r--src/compiler/scala/tools/nsc/interactive/Global.scala41
-rw-r--r--src/compiler/scala/tools/nsc/transform/AddInterfaces.scala5
-rw-r--r--src/compiler/scala/tools/nsc/transform/Erasure.scala40
-rw-r--r--src/compiler/scala/tools/nsc/transform/LazyVals.scala3
-rw-r--r--src/compiler/scala/tools/nsc/transform/UnCurry.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala28
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Implicits.scala16
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Macros.scala13
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala73
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Namers.scala11
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala16
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/RefChecks.scala57
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala4
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala8
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Typers.scala127
-rwxr-xr-xsrc/compiler/scala/tools/nsc/util/DocStrings.scala26
-rw-r--r--src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala6
-rw-r--r--src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala9
-rw-r--r--src/library/scala/Symbol.scala5
-rw-r--r--src/library/scala/collection/IndexedSeq.scala10
-rw-r--r--src/library/scala/collection/generic/GenTraversableFactory.scala9
-rw-r--r--src/library/scala/collection/generic/IndexedSeqFactory.scala21
-rw-r--r--src/library/scala/collection/immutable/IndexedSeq.scala5
-rw-r--r--src/library/scala/collection/immutable/Vector.scala33
-rw-r--r--src/library/scala/collection/mutable/FlatHashTable.scala13
-rw-r--r--src/library/scala/collection/mutable/ListBuffer.scala98
-rw-r--r--src/library/scala/collection/mutable/MultiMap.scala35
-rw-r--r--src/library/scala/package.scala3
-rw-r--r--src/library/scala/sys/process/ProcessImpl.scala5
-rw-r--r--src/manual/scala/man1/scaladoc.scala5
-rw-r--r--src/reflect/scala/reflect/internal/Definitions.scala1
-rw-r--r--src/reflect/scala/reflect/internal/Printers.scala7
-rw-r--r--src/reflect/scala/reflect/internal/StdAttachments.scala17
-rw-r--r--src/reflect/scala/reflect/internal/SymbolTable.scala12
-rw-r--r--src/reflect/scala/reflect/internal/Symbols.scala7
-rw-r--r--src/reflect/scala/reflect/internal/Trees.scala52
-rw-r--r--src/reflect/scala/reflect/internal/Types.scala19
-rw-r--r--src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala40
-rw-r--r--src/reflect/scala/reflect/internal/util/package.scala9
-rw-r--r--src/reflect/scala/reflect/macros/compileTimeOnly.scala16
-rw-r--r--src/reflect/scala/reflect/runtime/JavaMirrors.scala17
-rw-r--r--src/swing/scala/swing/ColorChooser.scala45
-rw-r--r--src/swing/scala/swing/PopupMenu.scala65
-rw-r--r--src/swing/scala/swing/event/ColorChanged.scala14
-rw-r--r--src/swing/scala/swing/event/PopupMenuEvent.scala18
-rw-r--r--test/files/continuations-neg/lazy.check8
-rw-r--r--test/files/neg/gadts1.check4
-rw-r--r--test/files/neg/t5753.check4
-rw-r--r--test/files/neg/t5753.flags1
-rw-r--r--test/files/neg/t5753/Impls$class.classbin0 -> 626 bytes
-rw-r--r--test/files/neg/t5753/Impls.classbin0 -> 866 bytes
-rw-r--r--test/files/neg/t5753/Impls_Macros_1.scala6
-rw-r--r--test/files/neg/t5753/Test_2.scala11
-rw-r--r--test/files/neg/t6323a.check2
-rw-r--r--test/files/neg/t6357.check4
-rw-r--r--test/files/neg/t6357.scala6
-rw-r--r--test/files/neg/t6539.check10
-rw-r--r--test/files/neg/t6539/Macro_1.scala10
-rw-r--r--test/files/neg/t6539/Test_2.scala6
-rw-r--r--test/files/neg/t6597.check4
-rw-r--r--test/files/neg/t6597.scala5
-rw-r--r--test/files/neg/t6663.check6
-rw-r--r--test/files/neg/t6663.scala19
-rw-r--r--test/files/neg/valueclasses-impl-restrictions.check12
-rw-r--r--test/files/neg/valueclasses-impl-restrictions.scala1
-rw-r--r--test/files/pos/t5330.scala22
-rw-r--r--test/files/pos/t5330b.scala6
-rw-r--r--test/files/pos/t5330c.scala5
-rw-r--r--test/files/pos/t5726.scala17
-rw-r--r--test/files/pos/t6014.scala13
-rw-r--r--test/files/pos/t6358.scala6
-rw-r--r--test/files/pos/t6358_2.scala6
-rw-r--r--test/files/pos/t6551.scala13
-rw-r--r--test/files/pos/t6722.scala11
-rw-r--r--test/files/run/reify_lazyunit.check3
-rw-r--r--test/files/run/reify_lazyunit.scala13
-rw-r--r--test/files/run/showraw_aliases.check2
-rw-r--r--test/files/run/showraw_aliases.scala17
-rw-r--r--test/files/run/sm-interpolator.scala41
-rw-r--r--test/files/run/t5733.check2
-rw-r--r--test/files/run/t5733.scala53
-rw-r--r--test/files/run/t5753_1.check1
-rw-r--r--test/files/run/t5753_1.flags1
-rw-r--r--test/files/run/t5753_1/Impls_Macros_1.scala10
-rw-r--r--test/files/run/t5753_1/Test_2.scala4
-rw-r--r--test/files/run/t5753_2.check1
-rw-r--r--test/files/run/t5753_2.flags1
-rw-r--r--test/files/run/t5753_2/Impls_Macros_1.scala10
-rw-r--r--test/files/run/t5753_2/Test_2.scala4
-rw-r--r--test/files/run/t6023.check12
-rw-r--r--test/files/run/t6023.scala17
-rw-r--r--test/files/run/t6150.scala44
-rw-r--r--test/files/run/t6320.check17
-rw-r--r--test/files/run/t6320.scala9
-rw-r--r--test/files/run/t6488.check1
-rw-r--r--test/files/run/t6488.scala11
-rw-r--r--test/files/run/t6632.check3
-rw-r--r--test/files/run/t6632.scala29
-rw-r--r--test/files/run/t6633.check3
-rw-r--r--test/files/run/t6633.scala33
-rw-r--r--test/files/run/t6634.check31
-rw-r--r--test/files/run/t6634.scala80
-rw-r--r--test/files/run/t6662.check1
-rw-r--r--test/files/run/t6662/Macro_1.scala8
-rw-r--r--test/files/run/t6662/Test_2.scala8
-rw-r--r--test/files/run/t6663.check1
-rw-r--r--test/files/run/t6663.scala17
-rw-r--r--test/files/run/t6673.check1
-rw-r--r--test/files/run/t6673.scala5
-rw-r--r--test/files/run/t6677.scala28
-rw-r--r--test/files/run/t6677b.scala33
-rw-r--r--test/files/run/t6687.scala10
-rw-r--r--test/files/run/t6695.scala18
-rw-r--r--test/files/run/t6706.scala14
-rw-r--r--test/files/run/t6731.check40
-rw-r--r--test/files/run/t6731.scala143
-rwxr-xr-xtest/scaladoc/run/SI-191-deprecated.check1
-rwxr-xr-xtest/scaladoc/run/SI-191-deprecated.scala71
-rwxr-xr-xtest/scaladoc/run/SI-191.check1
-rwxr-xr-xtest/scaladoc/run/SI-191.scala76
134 files changed, 2141 insertions, 411 deletions
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..551100ae85
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,66 @@
+# Scala Project & Developer Guidelines
+
+These guidelines are meant to be a living document that should be changed and adapted as needed. We encourage changes that make it easier to achieve our goals in an efficient way.
+
+## General Workflow
+
+This is the process for committing code to the Scala project. There are of course exceptions to these rules, for example minor changes to comments and documentation, fixing a broken build etc.
+
+1. Make sure you have signed the [Scala CLA](http://www.scala-lang.org/sites/default/files/contributor_agreement.pdf), if not, sign it.
+2. Before starting to work on a feature or a fix, it's good practice to ensure that:
+ 1. There is a ticket for your work in the project's issue tracker. If not, create it first (perhaps given a thumbs up from the scala-internals mailing list first).
+ 2. The ticket has been discussed and prioritized by the team.
+3. You should always perform your work in its own Git branch. The branch should be given a descriptive name that explains its intent. Some teams also like adding the ticket number and/or the [GitHub](http://github.com) user ID to the branch name, these details is up to each of the individual teams. (See below for more details on branch naming.)
+4. When the feature or fix is completed you should open a [Pull Request](https://help.github.com/articles/using-pull-requests) on GitHub.
+5. The Pull Request should be reviewed by other maintainers (as many as feasible/practical). Note that a reviewer can also be an outside contributor-- members of Typesafe and independent contributors are encouraged to participate in the review process. It is not a closed process. Please try to avoid conflict of interest -- the spirit of the review process is to evenly distribute the understanding of our code base across its maintainers as well as to load balance quality assurance. Assigning a review to a "sure win" reviewer is not a good long-term solution.
+6. After the review, you should resolve issues brought up by the reviewers as needed (pushing a new commit to address reviewers' comments), iterating until the reviewers give their thumbs up, the "LGTM" (acronym for "Looks Good To Me").
+7. Once the code has passed review the Pull Request can be merged into the distribution.
+
+## Pull Request Requirements
+
+First, please have a look at and follow the [Pull Request Policy](https://github.com/scala/scala/wiki/Pull-Request-Policy) for guidelines on submitting a pull request to the Scala project.
+
+In order for a Pull Request to be considered, it has to meet these requirements:
+
+1. Live up to the current code standard:
+ - Not violate [DRY](http://programmer.97things.oreilly.com/wiki/index.php/Don%27t_Repeat_Yourself).
+ - [Boy Scout Rule](http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule) should be applied.
+2. Tests are of paramount importance.
+3. The code must be well documented in the project's standard documentation format (see the ‘Documentation’ section below).
+
+If *all* of these requirements are not met then the code should **not** be merged into the distribution, and need not even be reviewed.
+
+## Documentation
+
+All contributed code should come accompanied with documentation. Pull requests containing undocumented code will not be accepted. Both user-facing Scaladoc comments, as well as committer-facing internal documentation (i.e. important design decisions that other maintainers should know about should be placed inline with line comments `//`) should be accompanying all contributed code where possible.
+
+
+## Work In Progress
+
+It is ok to work on a public feature branch in the GitHub repository. Something that can sometimes be useful for early feedback etc. If so, then it is preferable to name the branch accordingly. This can be done by either prefixing the name with ``wip-`` as in ‘Work In Progress’, or use hierarchical names like ``wip/..``, ``feature/..`` or ``topic/..``. Either way is fine as long as it is clear that it is work in progress and not ready for merge. This work can temporarily have a lower standard. However, to be merged into master it will have to go through the regular process outlined above, with Pull Request, review etc..
+
+Also, to facilitate both well-formed commits and working together, the ``wip`` and ``feature``/``topic`` identifiers also have special meaning. Any branch labelled with ``wip`` is considered “git-unstable” and may be rebased and have its history rewritten. Any branch with ``feature``/``topic`` in the name is considered “stable” enough for others to depend on when a group is working on a feature.
+
+## Creating Commits And Writing Commit Messages
+
+Follow these guidelines when creating public commits and writing commit messages.
+
+1. If your work spans multiple local commits (for example; if you do safe point commits while working in a feature branch or work in a branch for long time doing merges/rebases etc.) then please do not commit it all but rewrite the history by squashing the commits into one large commit which is accompanied by a detailed commit message for (as discussed in the following sections). For more info, see the article: [Git Workflow](http://sandofsky.com/blog/git-workflow.html). Additionally, every commit should be able to be used in isolation-- that is, each commit must build and pass all tests.
+2. The first line should be a descriptive sentence about what the commit is doing. It should be possible to fully understand what the commit does by just reading this single line. It is **not ok** to only list the ticket number, type "minor fix" or similar. If the commit has a corresponding ticket, include a reference to the ticket number, prefixed with "SI-", at the beginning of the first line followed by the title of the ticket, assuming that it aptly and concisely summarizes the commit in a single line. If the commit is a small fix, then you are done. If not, go to 3.
+3. Following the single line description (ideally no more than 70 characters long) should be a blank line followed by an enumerated list with the details of the commit.
+4. Add keywords for your commit (depending on the degree of automation we reach, the list may change over time):
+ * ``Review by @githubuser`` - will notify the reviewer via GitHub. Everyone is encouraged to give feedback, however. (Remember that @-mentions will result in notifications also when pushing to a WIP branch, so please only include this in your commit message when you're ready for your pull request to be reviewed. Alternatively, you may request a review in the pull request's description.)
+ * ``Fix/Fixing/Fixes/Close/Closing/Refs #ticket`` - if you want to mark the ticket as fixed in the issue tracker (Assembla understands this).
+ * ``backport to _branch name_`` - if the fix needs to be cherry-picked to another branch (like 2.9.x, 2.10.x, etc)
+
+Example:
+
+ SI-4032 Implicit conversion visibility affected by presence of "this"
+
+ - Details 1
+ - Details 2
+ - Details 3
+
+## The Scala Improvement Process
+A new language feature requires a SIP (Scala Improvement Process) proposal. Note that significant additions to the standard library are also considered candidates for a SIP proposal.
+For more details on submitting SIPs, see (how to submit a SIP)[http://docs.scala-lang.org/sips/sip-submission.html].
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
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/compiler/scala/reflect/reify/Errors.scala b/src/compiler/scala/reflect/reify/Errors.scala
index c25112941c..7c66d5b9eb 100644
--- a/src/compiler/scala/reflect/reify/Errors.scala
+++ b/src/compiler/scala/reflect/reify/Errors.scala
@@ -28,15 +28,15 @@ trait Errors {
}
def CannotReifyWeakType(details: Any) = {
- val msg = "cannot create a TypeTag" + details
+ val msg = "cannot create a TypeTag" + details + ": use WeakTypeTag instead"
throw new ReificationException(defaultErrorPosition, msg)
}
def CannotConvertManifestToTagWithoutScalaReflect(tpe: Type, manifestInScope: Tree) = {
- val msg = s"""
- |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
+ val msg =
+ sm"""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."""
throw new ReificationException(defaultErrorPosition, msg)
}
@@ -71,4 +71,9 @@ trait Errors {
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 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/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/tools/nsc/ast/NodePrinters.scala b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
index 275cfcd123..deea4de707 100644
--- a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
+++ b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
@@ -102,7 +102,7 @@ abstract class NodePrinters {
buf.clear()
if (settings.XshowtreesStringified.value) buf.append(tree.toString + EOL)
if (settings.XshowtreesCompact.value) {
- buf.append(showRaw(tree))
+ buf.append(showRaw(tree, printIds = settings.uniqid.value, printTypes = settings.printtypes.value))
} else {
level = 0
traverse(tree)
diff --git a/src/compiler/scala/tools/nsc/ast/Trees.scala b/src/compiler/scala/tools/nsc/ast/Trees.scala
index ed73464c93..296d55fec5 100644
--- a/src/compiler/scala/tools/nsc/ast/Trees.scala
+++ b/src/compiler/scala/tools/nsc/ast/Trees.scala
@@ -56,7 +56,7 @@ trait Trees extends scala.reflect.internal.Trees { self: Global =>
* The class `C` is stored as a tree attachment.
*/
case class InjectDerivedValue(arg: Tree)
- extends SymTree
+ extends SymTree with TermTree
class PostfixSelect(qual: Tree, name: Name) extends Select(qual, name)
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
index a2a45d0684..074fcabec8 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
@@ -1933,7 +1933,7 @@ self =>
case _ =>
}
val typeAppliedTree = in.token match {
- case LBRACKET => atPos(start, in.offset)(TypeApply(convertToTypeId(t), typeArgs()))
+ case LBRACKET => atPos(start, in.offset)(AppliedTypeTree(convertToTypeId(t), typeArgs()))
case _ => t
}
in.token match {
diff --git a/src/compiler/scala/tools/nsc/doc/DocFactory.scala b/src/compiler/scala/tools/nsc/doc/DocFactory.scala
index 4c9a3178aa..642e330a57 100644
--- a/src/compiler/scala/tools/nsc/doc/DocFactory.scala
+++ b/src/compiler/scala/tools/nsc/doc/DocFactory.scala
@@ -39,9 +39,6 @@ class DocFactory(val reporter: Reporter, val settings: doc.Settings) { processor
phasesSet += analyzer.namerFactory
phasesSet += analyzer.packageObjects
phasesSet += analyzer.typerFactory
- phasesSet += superAccessors
- phasesSet += pickler
- phasesSet += refChecks
}
override def forScaladoc = true
}
diff --git a/src/compiler/scala/tools/nsc/doc/Settings.scala b/src/compiler/scala/tools/nsc/doc/Settings.scala
index 7cc99ba50e..10a0d8d879 100644
--- a/src/compiler/scala/tools/nsc/doc/Settings.scala
+++ b/src/compiler/scala/tools/nsc/doc/Settings.scala
@@ -7,6 +7,7 @@ package scala.tools.nsc
package doc
import java.io.File
+import java.net.URI
import java.lang.System
import scala.language.postfixOps
@@ -71,6 +72,12 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_))
""
)
+ val docExternalUris = MultiStringSetting (
+ "-doc-external-uris",
+ "external-doc",
+ "comma-separated list of file://classpath_entry_path#doc_URL URIs for external dependencies"
+ )
+
val useStupidTypes = BooleanSetting (
"-Yuse-stupid-types",
"Print the types of inherited members as seen from their original definition context. Hint: you don't want to do that!"
@@ -197,7 +204,7 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_))
val docExternalUrls = MultiStringSetting (
"-external-urls",
"externalUrl(s)",
- "comma-separated list of package_names=doc_URL for external dependencies, where package names are ':'-separated"
+ "(deprecated) comma-separated list of package_names=doc_URL for external dependencies, where package names are ':'-separated"
)
val docGroups = BooleanSetting (
@@ -244,22 +251,25 @@ class Settings(error: String => Unit, val printMsg: String => Unit = println(_))
}
}
- // TODO: Enable scaladoc to scoop up the package list from another scaladoc site, just as javadoc does
- // -external-urls 'http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library'
- // should trigger scaldoc to fetch the package-list file. The steps necessary:
- // 1 - list all packages generated in scaladoc in the package-list file, exactly as javadoc:
- // see http://docs.oracle.com/javase/6/docs/api/package-list for http://docs.oracle.com/javase/6/docs/api
- // 2 - download the file and add the packages to the list
- lazy val extUrlMapping: Map[String, String] = (Map.empty[String, String] /: docExternalUrls.value) {
+ def appendIndex(url: String): String = {
+ val index = "/index.html"
+ if (url.endsWith(index)) url else url + index
+ }
+
+ // Deprecated together with 'docExternalUrls' option.
+ lazy val extUrlPackageMapping: Map[String, String] = (Map.empty[String, String] /: docExternalUrls.value) {
case (map, binding) =>
val idx = binding indexOf "="
val pkgs = binding substring (0, idx) split ":"
- var url = binding substring (idx + 1)
- val index = "/index.html"
- url = if (url.endsWith(index)) url else url + index
+ val url = appendIndex(binding substring (idx + 1))
map ++ (pkgs map (_ -> url))
}
+ lazy val extUrlMapping: Map[String, String] = docExternalUris.value map { s =>
+ val uri = new URI(s)
+ uri.getSchemeSpecificPart -> appendIndex(uri.getFragment)
+ } toMap
+
/**
* This is the hardcoded area of Scaladoc. This is where "undesirable" stuff gets eliminated. I know it's not pretty,
* but ultimately scaladoc has to be useful. :)
diff --git a/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala b/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala
index 1c783a7d2c..5257db1610 100644
--- a/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala
+++ b/src/compiler/scala/tools/nsc/doc/model/MemberLookup.scala
@@ -48,9 +48,9 @@ trait MemberLookup {
}
if (sym.isClass || sym.isModule || sym.isTrait || sym.isPackage)
- findExternalLink(linkName(sym))
+ findExternalLink(sym, linkName(sym))
else if (owner.isClass || owner.isModule || owner.isTrait || owner.isPackage)
- findExternalLink(linkName(owner) + "@" + externalSignature(sym))
+ findExternalLink(sym, linkName(owner) + "@" + externalSignature(sym))
else
None
}
@@ -171,7 +171,7 @@ trait MemberLookup {
// and removing NoType classes
def cleanupBogusClasses(syms: List[Symbol]) = { syms.filter(_.info != NoType) }
- def syms(name: Name) = container.info.nonPrivateMember(name).alternatives
+ def syms(name: Name) = container.info.nonPrivateMember(name.encodedName).alternatives
def termSyms = cleanupBogusClasses(syms(newTermName(name)))
def typeSyms = cleanupBogusClasses(syms(newTypeName(name)))
diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
index b4df7b8354..3ae1210ebf 100644
--- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
+++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
@@ -28,7 +28,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) {
with MemberLookup =>
import global._
- import definitions.{ ObjectClass, NothingClass, AnyClass, AnyValClass, AnyRefClass }
+ import definitions.{ ObjectClass, NothingClass, AnyClass, AnyValClass, AnyRefClass, ListClass }
import rootMirror.{ RootPackage, RootClass, EmptyPackage }
// Defaults for member grouping, that may be overridden by the template
@@ -493,28 +493,16 @@ class ModelFactory(val global: Global, val settings: doc.Settings) {
def inheritanceDiagram = makeInheritanceDiagram(this)
def contentDiagram = makeContentDiagram(this)
- def groupSearch[T](extractor: Comment => T, default: T): T = {
- // query this template
- if (comment.isDefined) {
- val entity = extractor(comment.get)
- if (entity != default) return entity
+ def groupSearch[T](extractor: Comment => Option[T]): Option[T] = {
+ val comments = comment +: linearizationTemplates.collect { case dtpl: DocTemplateImpl => dtpl.comment }
+ comments.flatten.map(extractor).flatten.headOption orElse {
+ Option(inTpl) flatMap (_.groupSearch(extractor))
}
- // query linearization
- 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), 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)
+ def groupDescription(group: String): Option[Body] = groupSearch(_.groupDesc.get(group)) orElse { if (group == defaultGroup) defaultGroupDesc else None }
+ def groupPriority(group: String): Int = groupSearch(_.groupPrio.get(group)) getOrElse { if (group == defaultGroup) defaultGroupPriority else 0 }
+ def groupName(group: String): String = groupSearch(_.groupNames.get(group)) getOrElse { if (group == defaultGroup) defaultGroupName else group }
}
abstract class PackageImpl(sym: Symbol, inTpl: PackageImpl) extends DocTemplateImpl(sym, inTpl) with Package {
@@ -1097,12 +1085,27 @@ class ModelFactory(val global: Global, val settings: doc.Settings) {
{ val rawComment = global.expandedDocComment(bSym, inTpl.sym)
rawComment.contains("@template") || rawComment.contains("@documentable") }
- def findExternalLink(name: String): Option[LinkTo] =
- settings.extUrlMapping find {
- case (pkg, _) => name startsWith pkg
- } map {
- case (_, url) => LinkToExternal(name, url + "#" + name)
+ def findExternalLink(sym: Symbol, name: String): Option[LinkTo] = {
+ val sym1 =
+ if (sym == AnyClass || sym == AnyRefClass || sym == AnyValClass || sym == NothingClass) ListClass
+ else if (sym.isPackage)
+ /* Get package object which has associatedFile ne null */
+ sym.info.member(newTermName("package"))
+ else sym
+ Option(sym1.associatedFile) flatMap (_.underlyingSource) flatMap { src =>
+ val path = src.path
+ settings.extUrlMapping get path map { url =>
+ LinkToExternal(name, url + "#" + name)
+ }
+ } orElse {
+ // Deprecated option.
+ settings.extUrlPackageMapping find {
+ case (pkg, _) => name startsWith pkg
+ } map {
+ case (_, url) => LinkToExternal(name, url + "#" + name)
+ }
}
+ }
def externalSignature(sym: Symbol) = {
sym.info // force it, otherwise we see lazy types
diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryTypeSupport.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryTypeSupport.scala
index a07865f7a3..942ccaf1ba 100644
--- a/src/compiler/scala/tools/nsc/doc/model/ModelFactoryTypeSupport.scala
+++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactoryTypeSupport.scala
@@ -104,7 +104,7 @@ trait ModelFactoryTypeSupport {
if (!bSym.owner.isPackage)
Tooltip(name)
else
- findExternalLink(name).getOrElse (
+ findExternalLink(bSym, name).getOrElse (
// (3) if we couldn't find neither the owner nor external URL to link to, show a tooltip with the qualified name
Tooltip(name)
)
diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala
index 56617d0026..2ab389445f 100644
--- a/src/compiler/scala/tools/nsc/interactive/Global.scala
+++ b/src/compiler/scala/tools/nsc/interactive/Global.scala
@@ -20,18 +20,23 @@ import scala.tools.nsc.io.Pickler._
import scala.tools.nsc.typechecker.DivergentImplicit
import scala.annotation.tailrec
import symtab.Flags.{ACCESSOR, PARAMACCESSOR}
+import scala.annotation.elidable
import scala.language.implicitConversions
/** The main class of the presentation compiler in an interactive environment such as an IDE
*/
-class Global(settings: Settings, _reporter: Reporter, projectName: String = "")
- extends scala.tools.nsc.Global(settings, _reporter)
- with CompilerControl
- with RangePositions
- with ContextTrees
- with RichCompilationUnits
- with ScratchPadMaker
- with Picklers {
+class Global(settings: Settings, _reporter: Reporter, projectName: String = "") extends {
+ /* Is the compiler initializing? Early def, so that the field is true during the
+ * execution of the super constructor.
+ */
+ private var initializing = true
+} with scala.tools.nsc.Global(settings, _reporter)
+ with CompilerControl
+ with RangePositions
+ with ContextTrees
+ with RichCompilationUnits
+ with ScratchPadMaker
+ with Picklers {
import definitions._
@@ -51,6 +56,7 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "")
import log.logreplay
debugLog("logger: " + log.getClass + " writing to " + (new java.io.File(logName)).getAbsolutePath)
debugLog("classpath: "+classPath)
+ Console.err.println("\n ======= CHECK THREAD ACCESS compiler build ========\n")
private var curTime = System.nanoTime
private def timeStep = {
@@ -433,7 +439,18 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "")
private var threadId = 0
/** The current presentation compiler runner */
- @volatile private[interactive] var compileRunner = newRunnerThread()
+ @volatile private[interactive] var compileRunner: Thread = newRunnerThread()
+
+ /** Check that the currenyly executing thread is the presentation compiler thread.
+ *
+ * Compiler initialization may happen on a different thread (signalled by globalPhase being NoPhase)
+ */
+ @elidable(elidable.WARNING)
+ override def assertCorrectThread() {
+ assert(initializing || (Thread.currentThread() eq compileRunner),
+ "Race condition detected: You are running a presentation compiler method outside the PC thread.[phase: %s]".format(globalPhase) +
+ " Please file a ticket with the current stack trace at https://www.assembla.com/spaces/scala-ide/support/tickets")
+ }
/** Create a new presentation compiler runner.
*/
@@ -1110,6 +1127,12 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "")
alt
}
}
+
+ /** The compiler has been initialized. Constructors are evaluated in textual order,
+ * so this is set to true only after all super constructors and the primary constructor
+ * have been executed.
+ */
+ initializing = false
}
object CancelException extends Exception
diff --git a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
index 83f661e1de..bacd8c39e1 100644
--- a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
+++ b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
@@ -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/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala
index 7b45b3efe5..7b9b13ae1c 100644
--- a/src/compiler/scala/tools/nsc/transform/Erasure.scala
+++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala
@@ -437,19 +437,19 @@ abstract class Erasure extends AddInterfaces
noclash = false
unit.error(
if (member.owner == root) member.pos else root.pos,
- s"""bridge generated for member ${fulldef(member)}
- |which overrides ${fulldef(other)}
- |clashes with definition of $what;
- |both have erased type ${afterPostErasure(bridge.tpe)}""".stripMargin)
+ sm"""bridge generated for member ${fulldef(member)}
+ |which overrides ${fulldef(other)}
+ |clashes with definition of $what;
+ |both have erased type ${afterPostErasure(bridge.tpe)}""")
}
for (bc <- root.baseClasses) {
if (settings.debug.value)
afterPostErasure(println(
- s"""check bridge overrides in $bc
- ${bc.info.nonPrivateDecl(bridge.name)}
- ${site.memberType(bridge)}
- ${site.memberType(bc.info.nonPrivateDecl(bridge.name) orElse IntClass)}
- ${(bridge.matchingSymbol(bc, site))}""".stripMargin))
+ sm"""check bridge overrides in $bc
+ |${bc.info.nonPrivateDecl(bridge.name)}
+ |${site.memberType(bridge)}
+ |${site.memberType(bc.info.nonPrivateDecl(bridge.name) orElse IntClass)}
+ |${(bridge.matchingSymbol(bc, site))}"""))
def overriddenBy(sym: Symbol) =
sym.matchingSymbol(bc, site).alternatives filter (sym => !sym.isBridge)
@@ -693,7 +693,7 @@ abstract class Erasure extends AddInterfaces
adaptToType(unbox(tree, pt), pt)
else if (isPrimitiveValueType(tree.tpe) && !isPrimitiveValueType(pt)) {
adaptToType(box(tree, pt.toString), pt)
- } else if (tree.tpe.isInstanceOf[MethodType] && tree.tpe.params.isEmpty) {
+ } else if (isMethodTypeWithEmptyParams(tree.tpe)) {
// [H] this assert fails when trying to typecheck tree !(SomeClass.this.bitmap) for single lazy val
//assert(tree.symbol.isStable, "adapt "+tree+":"+tree.tpe+" to "+pt)
adaptToType(Apply(tree, List()) setPos tree.pos setType tree.tpe.resultType, pt)
@@ -783,16 +783,21 @@ abstract class Erasure extends AddInterfaces
else if (!isPrimitiveValueType(qual1.tpe) && isPrimitiveValueMember(tree.symbol))
qual1 = unbox(qual1, tree.symbol.owner.tpe)
- if (isPrimitiveValueMember(tree.symbol) && !isPrimitiveValueType(qual1.tpe))
+ def selectFrom(qual: Tree) = treeCopy.Select(tree, qual, name)
+
+ if (isPrimitiveValueMember(tree.symbol) && !isPrimitiveValueType(qual1.tpe)) {
tree.symbol = NoSymbol
- else if (qual1.tpe.isInstanceOf[MethodType] && qual1.tpe.params.isEmpty) {
+ selectFrom(qual1)
+ } else if (isMethodTypeWithEmptyParams(qual1.tpe)) {
assert(qual1.symbol.isStable, qual1.symbol);
- qual1 = Apply(qual1, List()) setPos qual1.pos setType qual1.tpe.resultType
+ val applied = Apply(qual1, List()) setPos qual1.pos setType qual1.tpe.resultType
+ adaptMember(selectFrom(applied))
} else if (!(qual1.isInstanceOf[Super] || (qual1.tpe.typeSymbol isSubClass tree.symbol.owner))) {
assert(tree.symbol.owner != ArrayClass)
- qual1 = cast(qual1, tree.symbol.owner.tpe)
+ selectFrom(cast(qual1, tree.symbol.owner.tpe))
+ } else {
+ selectFrom(qual1)
}
- treeCopy.Select(tree, qual1, name)
}
case SelectFromArray(qual, name, erasure) =>
var qual1 = typedQualifier(qual)
@@ -870,6 +875,11 @@ abstract class Erasure extends AddInterfaces
tree1
}
}
+
+ private def isMethodTypeWithEmptyParams(tpe: Type) = tpe match {
+ case MethodType(Nil, _) => true
+ case _ => false
+ }
}
/** The erasure transformer */
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 f6b55b6606..529009a058 100644
--- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala
+++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala
@@ -369,7 +369,7 @@ abstract class UnCurry extends InfoTransform
}
val isDefinedAtMethodDef = {
- val methSym = anonClass.newMethod(nme.isDefinedAt, fun.pos, FINAL)
+ val methSym = anonClass.newMethod(nme.isDefinedAt, fun.pos, FINAL | SYNTHETIC)
val params = methSym newSyntheticValueParams formals
methSym setInfoAndEnter MethodType(params, BooleanClass.tpe)
diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala
index 9e9b8b995b..faacb60d75 100644
--- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala
@@ -107,9 +107,9 @@ trait ContextErrors {
s"$name extends Any, not AnyRef"
)
if (isPrimitiveValueType(found) || isTrivialTopType(tp)) "" else "\n" +
- s"""|Note that $what.
- |Such types can participate in value classes, but instances
- |cannot appear in singleton types or in reference comparisons.""".stripMargin
+ sm"""|Note that $what.
+ |Such types can participate in value classes, but instances
+ |cannot appear in singleton types or in reference comparisons."""
}
import ErrorUtils._
@@ -1128,9 +1128,9 @@ trait ContextErrors {
(isView: Boolean, pt: Type, tree: Tree)(implicit context0: Context) = {
if (!info1.tpe.isErroneous && !info2.tpe.isErroneous) {
def coreMsg =
- s"""| $pre1 ${info1.sym.fullLocationString} of type ${info1.tpe}
- | $pre2 ${info2.sym.fullLocationString} of type ${info2.tpe}
- | $trailer""".stripMargin
+ sm"""| $pre1 ${info1.sym.fullLocationString} of type ${info1.tpe}
+ | $pre2 ${info2.sym.fullLocationString} of type ${info2.tpe}
+ | $trailer"""
def viewMsg = {
val found :: req :: _ = pt.typeArgs
def explanation = {
@@ -1141,19 +1141,19 @@ trait ContextErrors {
// involving Any, are further explained from foundReqMsg.
if (AnyRefClass.tpe <:< req) (
if (sym == AnyClass || sym == UnitClass) (
- s"""|Note: ${sym.name} is not implicitly converted to AnyRef. You can safely
- |pattern match `x: AnyRef` or cast `x.asInstanceOf[AnyRef]` to do so.""".stripMargin
+ sm"""|Note: ${sym.name} is not implicitly converted to AnyRef. You can safely
+ |pattern match `x: AnyRef` or cast `x.asInstanceOf[AnyRef]` to do so."""
)
else boxedClass get sym map (boxed =>
- s"""|Note: an implicit exists from ${sym.fullName} => ${boxed.fullName}, but
- |methods inherited from Object are rendered ambiguous. This is to avoid
- |a blanket implicit which would convert any ${sym.fullName} to any AnyRef.
- |You may wish to use a type ascription: `x: ${boxed.fullName}`.""".stripMargin
+ sm"""|Note: an implicit exists from ${sym.fullName} => ${boxed.fullName}, but
+ |methods inherited from Object are rendered ambiguous. This is to avoid
+ |a blanket implicit which would convert any ${sym.fullName} to any AnyRef.
+ |You may wish to use a type ascription: `x: ${boxed.fullName}`."""
) getOrElse ""
)
else
- s"""|Note that implicit conversions are not applicable because they are ambiguous:
- |${coreMsg}are possible conversion functions from $found to $req""".stripMargin
+ sm"""|Note that implicit conversions are not applicable because they are ambiguous:
+ |${coreMsg}are possible conversion functions from $found to $req"""
}
typeErrorMsg(found, req, infer.isPossiblyMissingArgs(found, req)) + (
if (explanation == "") "" else "\n" + explanation
diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
index 547d756888..fc10f68454 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
@@ -1306,17 +1306,17 @@ trait Implicits {
else {
if (ReflectRuntimeUniverse == NoSymbol) {
// todo. write a test for this
- context.error(pos, s"""
- |to create a manifest here, it is necessary to interoperate with the type tag `$tagInScope` in scope.
- |however typetag -> manifest 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)
+ context.error(pos,
+ sm"""to create a manifest here, it is necessary to interoperate with the type tag `$tagInScope` in scope.
+ |however typetag -> manifest conversion requires Scala reflection, which is not present on the classpath.
+ |to proceed put scala-reflect.jar on your compilation classpath and recompile.""")
return SearchFailure
}
if (resolveClassTag(pos, tp, allowMaterialization = true) == EmptyTree) {
- context.error(pos, s"""
- |to create a manifest here, it is necessary to interoperate with the type tag `$tagInScope` in scope.
- |however typetag -> manifest conversion requires a class tag for the corresponding type to be present.
- |to proceed add a class tag to the type `$tp` (e.g. by introducing a context bound) and recompile.""".trim.stripMargin)
+ context.error(pos,
+ sm"""to create a manifest here, it is necessary to interoperate with the type tag `$tagInScope` in scope.
+ |however typetag -> manifest conversion requires a class tag for the corresponding type to be present.
+ |to proceed add a class tag to the type `$tp` (e.g. by introducing a context bound) and recompile.""")
return SearchFailure
}
val cm = typed(Ident(ReflectRuntimeCurrentMirror))
diff --git a/src/compiler/scala/tools/nsc/typechecker/Macros.scala b/src/compiler/scala/tools/nsc/typechecker/Macros.scala
index bcc37e8b37..b20a9ea626 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Macros.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Macros.scala
@@ -122,16 +122,9 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces {
}
def pickle(macroImplRef: Tree): Tree = {
- val macroImpl = macroImplRef.symbol
+ val MacroImplReference(owner, macroImpl, targs) = macroImplRef
val paramss = macroImpl.paramss
- // this logic relies on the assumptions that were valid for the old macro prototype
- // namely that macro implementations can only be defined in top-level classes and modules
- // with the new prototype that materialized in a SIP, macros need to be statically accessible, which is different
- // for example, a macro def could be defined in a trait that is implemented by an object
- // there are some more clever cases when seemingly non-static method ends up being statically accessible
- // however, the code below doesn't account for these guys, because it'd take a look of time to get it right
- // for now I leave it as a todo and move along to more the important stuff
// todo. refactor when fixing SI-5498
def className: String = {
def loop(sym: Symbol): String = sym match {
@@ -143,7 +136,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces {
loop(sym.owner) + separator + sym.javaSimpleName.toString
}
- loop(macroImpl.owner.enclClass)
+ loop(owner)
}
def signature: List[Int] = {
@@ -164,7 +157,7 @@ trait Macros extends scala.tools.reflect.FastTrack with Traces {
// I just named it "macro", because it's macro-related, but I could as well name it "foobar"
val nucleus = Ident(newTermName("macro"))
val wrapped = Apply(nucleus, payload map { case (k, v) => Assign(pickleAtom(k), pickleAtom(v)) })
- val pickle = gen.mkTypeApply(wrapped, treeInfo.typeArguments(macroImplRef.duplicate))
+ val pickle = gen.mkTypeApply(wrapped, targs map (_.duplicate))
// assign NoType to all freshly created AST nodes
// otherwise pickler will choke on tree.tpe being null
diff --git a/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala b/src/compiler/scala/tools/nsc/typechecker/MethodSynthesis.scala
index 6448c28e21..acc4f7ff67 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
@@ -416,6 +426,7 @@ trait MethodSynthesis {
// spot that brand of them. In other words it's an artifact of the implementation.
val tpt = derivedSym.tpe.finalResultType match {
case ExistentialType(_, _) => TypeTree()
+ case _ if mods.isDeferred => TypeTree()
case tp => TypeTree(tp)
}
tpt setPos derivedSym.pos.focus
@@ -437,6 +448,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 +505,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/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala
index e3b1ae50e4..36edd46f25 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
@@ -400,7 +398,7 @@ trait Namers extends MethodSynthesis {
* a module definition or a class definition.
*/
def enterModuleSymbol(tree : ModuleDef): Symbol = {
- var m: Symbol = context.scope.lookup(tree.name)
+ var m: Symbol = context.scope lookupAll tree.name find (_.isModule) getOrElse NoSymbol
val moduleFlags = tree.mods.flags | MODULE
if (m.isModule && !m.isPackage && inCurrentScope(m) && (currentRun.canRedefine(m) || m.isSynthetic)) {
updatePosFlags(m, tree.pos, moduleFlags)
@@ -1291,7 +1289,8 @@ trait Namers extends MethodSynthesis {
if (clazz.isDerivedValueClass) {
log("Ensuring companion for derived value class " + name + " at " + cdef.pos.show)
clazz setFlag FINAL
- enclosingNamerWithScope(clazz.owner.info.decls).ensureCompanionObject(cdef)
+ // Don't force the owner's info lest we create cycles as in SI-6357.
+ enclosingNamerWithScope(clazz.owner.rawInfo.decls).ensureCompanionObject(cdef)
}
result
diff --git a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala
index 938866deef..834c64aaae 100644
--- a/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/PatternMatching.scala
@@ -1153,7 +1153,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL
// ExplicitOuter replaces `Select(q, outerSym) OBJ_EQ expectedPrefix` by `Select(q, outerAccessor(outerSym.owner)) OBJ_EQ expectedPrefix`
// if there's an outer accessor, otherwise the condition becomes `true` -- TODO: can we improve needsOuterTest so there's always an outerAccessor?
- val outer = expectedTp.typeSymbol.newMethod(vpmName.outer) setInfo expectedTp.prefix setFlag SYNTHETIC | ARTIFACT
+ val outer = expectedTp.typeSymbol.newMethod(vpmName.outer, newFlags = SYNTHETIC | ARTIFACT) setInfo expectedTp.prefix
(Select(codegen._asInstanceOf(testedBinder, expectedTp), outer)) OBJ_EQ expectedOuter
}
@@ -1386,10 +1386,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
@@ -1419,7 +1415,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL
// assert(owner ne null); assert(owner ne NoSymbol)
def freshSym(pos: Position, tp: Type = NoType, prefix: String = "x") =
- NoSymbol.newTermSymbol(freshName(prefix), pos) setInfo tp
+ NoSymbol.newTermSymbol(freshName(prefix), pos, newFlags = SYNTHETIC) setInfo tp
def newSynthCaseLabel(name: String) =
NoSymbol.newLabel(freshName(name), NoPosition) setFlag treeInfo.SYNTH_CASE_FLAGS
@@ -2051,9 +2047,9 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL
// CNF: a formula is a conjunction of clauses
type Formula = Array[Clause]
/** Override Array creation for efficiency (to not go through reflection). */
- private implicit val formulaTag: scala.reflect.ClassTag[Formula] = new scala.reflect.ClassTag[Formula] {
- def runtimeClass: java.lang.Class[Formula] = classOf[Formula]
- final override def newArray(len: Int): Array[Formula] = new Array[Formula](len)
+ private implicit val clauseTag: scala.reflect.ClassTag[Clause] = new scala.reflect.ClassTag[Clause] {
+ def runtimeClass: java.lang.Class[Clause] = classOf[Clause]
+ final override def newArray(len: Int): Array[Clause] = new Array[Clause](len)
}
def formula(c: Clause*): Formula = c.toArray
def andFormula(a: Formula, b: Formula): Formula = a ++ b
@@ -3615,7 +3611,7 @@ trait PatternMatching extends Transform with TypingTransformers with ast.TreeDSL
*/
def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Tree => Tree]): Tree = {
val matchEnd = newSynthCaseLabel("matchEnd")
- val matchRes = NoSymbol.newValueParameter(newTermName("x"), NoPosition, SYNTHETIC) setInfo restpe.withoutAnnotations
+ val matchRes = NoSymbol.newValueParameter(newTermName("x"), NoPosition, newFlags = SYNTHETIC) setInfo restpe.withoutAnnotations
matchEnd setInfo MethodType(List(matchRes), restpe)
def newCaseSym = newSynthCaseLabel("case") setInfo MethodType(Nil, restpe)
diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
index 9aec8c142b..78ec6508ed 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) {
@@ -1402,6 +1376,16 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans
)
}
+ private def checkCompileTimeOnly(sym: Symbol, pos: Position) = {
+ if (sym.isCompileTimeOnly) {
+ def defaultMsg =
+ sm"""Reference to ${sym.fullLocationString} should not have survived past type checking,
+ |it should have been processed and eliminated during expansion of an enclosing macro."""
+ // The getOrElse part should never happen, it's just here as a backstop.
+ unit.error(pos, sym.compileTimeOnlyMessage getOrElse defaultMsg)
+ }
+ }
+
private def lessAccessible(otherSym: Symbol, memberSym: Symbol): Boolean = (
(otherSym != NoSymbol)
&& !otherSym.isProtected
@@ -1588,6 +1572,7 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans
checkDeprecated(sym, tree.pos)
if (settings.Xmigration28.value)
checkMigration(sym, tree.pos)
+ checkCompileTimeOnly(sym, tree.pos)
if (sym eq NoSymbol) {
unit.warning(tree.pos, "Select node has NoSymbol! " + tree + " / " + tree.tpe)
diff --git a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
index c9e45b6348..fb8a111da1 100644
--- a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
@@ -527,8 +527,8 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
}
def isJavaProtected = host.isTrait && sym.isJavaDefined && {
restrictionError(pos, unit,
- s"""|$clazz accesses protected $sym inside a concrete trait method.
- |Add an accessor in a class extending ${sym.enclClass} as a workaround.""".stripMargin
+ sm"""$clazz accesses protected $sym inside a concrete trait method.
+ |Add an accessor in a class extending ${sym.enclClass} as a workaround."""
)
true
}
diff --git a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
index b4cdad70e2..48a5a36b00 100644
--- a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
@@ -280,11 +280,9 @@ abstract class TreeCheckers extends Analyzer {
if (sym.owner != currentOwner) {
val expected = currentOwner.ownerChain find (x => cond(x)) getOrElse fail("DefTree can't find owner: ")
if (sym.owner != expected)
- fail("""|
- | currentOwner chain: %s
- | symbol chain: %s""".stripMargin.format(
- currentOwner.ownerChain take 3 mkString " -> ",
- sym.ownerChain mkString " -> ")
+ fail(sm"""|
+ | currentOwner chain: ${currentOwner.ownerChain take 3 mkString " -> "}
+ | symbol chain: ${sym.ownerChain mkString " -> "}"""
)
}
}
diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
index b823e1ad0f..802b42f6c7 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
@@ -1100,6 +1100,10 @@ trait Typers extends Modes with Adaptations with Tags {
instantiateToMethodType(mt)
case _ =>
+ def shouldInsertApply(tree: Tree) = inAllModes(mode, EXPRmode | FUNmode) && (tree.tpe match {
+ case _: MethodType | _: OverloadedType | _: PolyType => false
+ case _ => applyPossible
+ })
def applyPossible = {
def applyMeth = member(adaptToName(tree, nme.apply), nme.apply)
dyna.acceptsApplyDynamic(tree.tpe) || (
@@ -1113,14 +1117,12 @@ trait Typers extends Modes with Adaptations with Tags {
adaptType()
else if (
inExprModeButNot(mode, FUNmode) && !tree.isDef && // typechecking application
- tree.symbol != null && tree.symbol.isTermMacro) // of a macro
+ tree.symbol != null && tree.symbol.isTermMacro && // of a macro
+ !tree.attachments.get[SuppressMacroExpansionAttachment.type].isDefined)
macroExpand(this, tree, mode, pt)
else if ((mode & (PATTERNmode | FUNmode)) == (PATTERNmode | FUNmode))
adaptConstrPattern()
- else if (inAllModes(mode, EXPRmode | FUNmode) &&
- !tree.tpe.isInstanceOf[MethodType] &&
- !tree.tpe.isInstanceOf[OverloadedType] &&
- applyPossible)
+ else if (shouldInsertApply(tree))
insertApply()
else if (!context.undetparams.isEmpty && !inPolyMode(mode)) { // (9)
assert(!inHKMode(mode), modeString(mode)) //@M
@@ -1423,9 +1425,6 @@ trait Typers extends Modes with Adaptations with Tags {
//see https://issues.scala-lang.org/browse/SI-6463
case _: ClassDef =>
implRestriction(tree, "nested class")
- case x: ValDef if x.mods.isLazy =>
- //see https://issues.scala-lang.org/browse/SI-6358
- implRestriction(tree, "lazy val")
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")
@@ -1911,7 +1910,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 {
@@ -2337,9 +2336,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
@@ -3075,7 +3080,7 @@ trait Typers extends Modes with Adaptations with Tags {
def checkNotMacro() = {
if (fun.symbol != null && fun.symbol.filter(sym => sym != null && sym.isTermMacro && !sym.isErroneous) != NoSymbol)
- duplErrorTree(NamedAndDefaultArgumentsNotSupportedForMacros(tree, fun))
+ tryTupleApply getOrElse duplErrorTree(NamedAndDefaultArgumentsNotSupportedForMacros(tree, fun))
}
if (mt.isErroneous) duplErrTree
@@ -3922,49 +3927,45 @@ trait Typers extends Modes with Adaptations with Tags {
*
*/
def mkInvoke(cxTree: Tree, tree: Tree, qual: Tree, name: Name): Option[Tree] = {
- debuglog(s"mkInvoke($cxTree, $tree, $qual, $name)")
+ log(s"dyna.mkInvoke($cxTree, $tree, $qual, $name)")
+ val treeSelection = treeInfo.methPart(tree)
+ def isDesugaredApply = treeSelection match {
+ case Select(`qual`, nme.apply) => true
+ case _ => false
+ }
acceptsApplyDynamicWithType(qual, name) map { tp =>
- // tp eq NoType => can call xxxDynamic, but not passing any type args (unless specified explicitly by the user)
- // in scala-virtualized, when not NoType, tp is passed as type argument (for selection on a staged Struct)
-
- // strip off type application -- we're not doing much with outer,
- // so don't bother preserving cxTree's attributes etc
- val cxTree1 = cxTree match {
- case t: ValOrDefDef => t.rhs
- case t => t
- }
- val (outer, explicitTargs) = cxTree1 match {
- case TypeApply(fun, targs) => (fun, targs)
- case Apply(TypeApply(fun, targs), args) => (Apply(fun, args), targs)
- case t => (t, Nil)
- }
- def hasNamedArg(as: List[Tree]) = as.collectFirst{case AssignOrNamedArg(lhs, rhs) =>}.nonEmpty
-
- def desugaredApply = tree match {
- case Select(`qual`, nme.apply) => true
- case _ => false
+ // If tp == NoType, pass only explicit type arguments to applyXXX. Not used at all
+ // here - it is for scala-virtualized, where tp will be passed as an argument (for
+ // selection on a staged Struct)
+ def hasNamed(args: List[Tree]): Boolean = args exists (_.isInstanceOf[AssignOrNamedArg])
+ // not supported: foo.bar(a1,..., an: _*)
+ def hasStar(args: List[Tree]) = treeInfo.isWildcardStarArgList(args)
+ def applyOp(args: List[Tree]) = if (hasNamed(args)) nme.applyDynamicNamed else nme.applyDynamic
+ def matches(t: Tree) = isDesugaredApply || treeInfo.methPart(t) == treeSelection
+
+ /** Note that the trees which arrive here are potentially some distance from
+ * the trees of direct interest. `cxTree` is some enclosing expression which
+ * may apparently be arbitrarily larger than `tree`; and `tree` itself is
+ * too small, having at least in some cases lost its explicit type parameters.
+ * This logic is designed to use `tree` to pinpoint the immediately surrounding
+ * Apply/TypeApply/Select node, and only then creates the dynamic call.
+ * See SI-6731 among others.
+ */
+ def findSelection(t: Tree): Option[(TermName, Tree)] = t match {
+ case Apply(fn, args) if hasStar(args) => DynamicVarArgUnsupported(tree, applyOp(args)) ; None
+ case Apply(fn, args) if matches(fn) => Some((applyOp(args), fn))
+ case Assign(lhs, _) if matches(lhs) => Some((nme.updateDynamic, lhs))
+ case _ if matches(t) => Some((nme.selectDynamic, t))
+ case _ => t.children flatMap findSelection headOption
}
- // note: context.tree includes at most one Apply node
- // thus, we can't use it to detect we're going to receive named args in expressions such as:
- // qual.sel(a)(a2, arg2 = "a2")
- val oper = outer match {
- case Apply(q, as) if q == tree || desugaredApply =>
- val oper =
- if (hasNamedArg(as)) nme.applyDynamicNamed
- else nme.applyDynamic
- // not supported: foo.bar(a1,..., an: _*)
- if (treeInfo.isWildcardStarArgList(as)) {
- DynamicVarArgUnsupported(tree, oper)
- return Some(setError(tree))
- } else oper
- case Assign(`tree`, _) => nme.updateDynamic
- case _ => nme.selectDynamic
+ findSelection(cxTree) match {
+ case Some((opName, tapply)) =>
+ val targs = treeInfo.typeArguments(tapply)
+ val fun = gen.mkTypeApply(Select(qual, opName), targs)
+ atPos(qual.pos)(Apply(fun, Literal(Constant(name.decode)) :: Nil))
+ case _ =>
+ setError(tree)
}
-
- val dynSel = Select(qual, oper)
- val tappSel = if (explicitTargs.nonEmpty) TypeApply(dynSel, explicitTargs) else dynSel
-
- atPos(qual.pos)(Apply(tappSel, List(Literal(Constant(name.decode)))))
}
}
@@ -3972,7 +3973,7 @@ trait Typers extends Modes with Adaptations with Tags {
silent(typeTree) match {
case SilentResultValue(r) => r
case SilentTypeError(err) => DynamicRewriteError(tree, err)
- }
+ }
}
}
@@ -4860,12 +4861,12 @@ trait Typers extends Modes with Adaptations with Tags {
defSym = pre.member(defEntry.sym.name)
if (defSym ne defEntry.sym) {
qual = gen.mkAttributedQualifier(pre)
- log(s"""
+ log(sm"""
| !!! Overloaded package object member resolved incorrectly.
| prefix: $pre
| Discarded: ${defEntry.sym.defString}
| Using: ${defSym.defString}
- """.stripMargin)
+ """)
}
}
else
@@ -5212,9 +5213,9 @@ trait Typers extends Modes with Adaptations with Tags {
// find out whether the programmer is trying to eta-expand a macro def
// to do that we need to typecheck the tree first (we need a symbol of the eta-expandee)
// that typecheck must not trigger macro expansions, so we explicitly prohibit them
- // Q: "but, " - you may ask - ", `typed1` doesn't call adapt, which does macro expansion, so why explicit check?"
- // A: solely for robustness reasons. this mechanism might change in the future, which might break unprotected code
- val exprTyped = context.withMacrosDisabled(typed1(expr, mode, pt))
+ // however we cannot do `context.withMacrosDisabled`
+ // because `expr` might contain nested macro calls (see SI-6673)
+ val exprTyped = typed1(expr updateAttachment SuppressMacroExpansionAttachment, mode, pt)
exprTyped match {
case macroDef if macroDef.symbol != null && macroDef.symbol.isTermMacro && !macroDef.symbol.isErroneous =>
MacroEtaError(exprTyped)
@@ -5358,8 +5359,14 @@ trait Typers extends Modes with Adaptations with Tags {
}
def typedTypeTree(tree: TypeTree) = {
- if (tree.original != null)
- tree setType typedType(tree.original, mode).tpe
+ if (tree.original != null) {
+ val newTpt = typedType(tree.original, mode)
+ tree setType newTpt.tpe
+ newTpt match {
+ case tt @ TypeTree() => tree setOriginal tt.original
+ case _ => tree
+ }
+ }
else
// we should get here only when something before failed
// and we try again (@see tryTypedApply). In that case we can assign
diff --git a/src/compiler/scala/tools/nsc/util/DocStrings.scala b/src/compiler/scala/tools/nsc/util/DocStrings.scala
index 66987d833b..dde53dc640 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/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala
index b373b3d0de..15025f85e3 100644
--- a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala
+++ b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala
@@ -496,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 ba87cadfeb..8b39bf3961 100644
--- a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala
+++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala
@@ -195,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)
}
diff --git a/src/library/scala/Symbol.scala b/src/library/scala/Symbol.scala
index 723c05a30c..4fead7a50c 100644
--- a/src/library/scala/Symbol.scala
+++ b/src/library/scala/Symbol.scala
@@ -69,6 +69,11 @@ private[scala] abstract class UniquenessCache[K, V >: Null]
val res = cached()
if (res != null) res
else {
+ // If we don't remove the old String key from the map, we can
+ // wind up with one String as the key and a different String as
+ // as the name field in the Symbol, which can lead to surprising
+ // GC behavior and duplicate Symbols. See SI-6706.
+ map remove name
val sym = valueFromKey(name)
map.put(name, new WeakReference(sym))
sym
diff --git a/src/library/scala/collection/IndexedSeq.scala b/src/library/scala/collection/IndexedSeq.scala
index e30d2f07bb..63e5adf428 100644
--- a/src/library/scala/collection/IndexedSeq.scala
+++ b/src/library/scala/collection/IndexedSeq.scala
@@ -28,8 +28,14 @@ trait IndexedSeq[+A] extends Seq[A]
* @define coll indexed sequence
* @define Coll `IndexedSeq`
*/
-object IndexedSeq extends SeqFactory[IndexedSeq] {
- implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
+object IndexedSeq extends IndexedSeqFactory[IndexedSeq] {
+ // A single CBF which can be checked against to identify
+ // an indexed collection type.
+ override val ReusableCBF: GenericCanBuildFrom[Nothing] = new GenericCanBuildFrom[Nothing] {
+ override def apply() = newBuilder[Nothing]
+ }
def newBuilder[A]: Builder[A, IndexedSeq[A]] = immutable.IndexedSeq.newBuilder[A]
+ implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] =
+ ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
}
diff --git a/src/library/scala/collection/generic/GenTraversableFactory.scala b/src/library/scala/collection/generic/GenTraversableFactory.scala
index d5edf5961e..a43862abaf 100644
--- a/src/library/scala/collection/generic/GenTraversableFactory.scala
+++ b/src/library/scala/collection/generic/GenTraversableFactory.scala
@@ -36,15 +36,12 @@ import scala.language.higherKinds
* @see GenericCanBuildFrom
*/
abstract class GenTraversableFactory[CC[X] <: GenTraversable[X] with GenericTraversableTemplate[X, CC]]
- extends GenericCompanion[CC] {
+extends GenericCompanion[CC] {
- // A default implementation of GenericCanBuildFrom which can be cast
- // to whatever is desired.
- private class ReusableCBF extends GenericCanBuildFrom[Nothing] {
+ private[this] val ReusableCBFInstance: GenericCanBuildFrom[Nothing] = new GenericCanBuildFrom[Nothing] {
override def apply() = newBuilder[Nothing]
}
- // Working around SI-4789 by using a lazy val instead of an object.
- lazy val ReusableCBF: GenericCanBuildFrom[Nothing] = new ReusableCBF
+ def ReusableCBF: GenericCanBuildFrom[Nothing] = ReusableCBFInstance
/** A generic implementation of the `CanBuildFrom` trait, which forwards
* all calls to `apply(from)` to the `genericBuilder` method of
diff --git a/src/library/scala/collection/generic/IndexedSeqFactory.scala b/src/library/scala/collection/generic/IndexedSeqFactory.scala
new file mode 100644
index 0000000000..200d033c2d
--- /dev/null
+++ b/src/library/scala/collection/generic/IndexedSeqFactory.scala
@@ -0,0 +1,21 @@
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
+\* */
+
+package scala.collection
+package generic
+
+import language.higherKinds
+
+/** A template for companion objects of IndexedSeq and subclasses thereof.
+ *
+ * @since 2.10
+ */
+abstract class IndexedSeqFactory[CC[X] <: IndexedSeq[X] with GenericTraversableTemplate[X, CC]] extends SeqFactory[CC] {
+ override def ReusableCBF: GenericCanBuildFrom[Nothing] =
+ scala.collection.IndexedSeq.ReusableCBF.asInstanceOf[GenericCanBuildFrom[Nothing]]
+}
diff --git a/src/library/scala/collection/immutable/IndexedSeq.scala b/src/library/scala/collection/immutable/IndexedSeq.scala
index e98df46c9b..bf4ba3a381 100644
--- a/src/library/scala/collection/immutable/IndexedSeq.scala
+++ b/src/library/scala/collection/immutable/IndexedSeq.scala
@@ -31,11 +31,12 @@ trait IndexedSeq[+A] extends Seq[A]
* @define coll indexed sequence
* @define Coll `IndexedSeq`
*/
-object IndexedSeq extends SeqFactory[IndexedSeq] {
+object IndexedSeq extends IndexedSeqFactory[IndexedSeq] {
class Impl[A](buf: ArrayBuffer[A]) extends AbstractSeq[A] with IndexedSeq[A] with Serializable {
def length = buf.length
def apply(idx: Int) = buf.apply(idx)
}
- implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
def newBuilder[A]: Builder[A, IndexedSeq[A]] = Vector.newBuilder[A]
+ implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] =
+ ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
}
diff --git a/src/library/scala/collection/immutable/Vector.scala b/src/library/scala/collection/immutable/Vector.scala
index dff221ad05..f083e80175 100644
--- a/src/library/scala/collection/immutable/Vector.scala
+++ b/src/library/scala/collection/immutable/Vector.scala
@@ -18,16 +18,10 @@ import scala.collection.parallel.immutable.ParVector
/** Companion object to the Vector class
*/
-object Vector extends SeqFactory[Vector] {
- private[collection] class VectorReusableCBF extends GenericCanBuildFrom[Nothing] {
- override def apply() = newBuilder[Nothing]
- }
-
- private val VectorReusableCBF: GenericCanBuildFrom[Nothing] = new VectorReusableCBF
-
- implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] =
- VectorReusableCBF.asInstanceOf[CanBuildFrom[Coll, A, Vector[A]]]
+object Vector extends IndexedSeqFactory[Vector] {
def newBuilder[A]: Builder[A, Vector[A]] = new VectorBuilder[A]
+ implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] =
+ ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
override def empty[A]: Vector[A] = NIL
}
@@ -137,20 +131,17 @@ override def companion: GenericCompanion[Vector] = Vector
// SeqLike api
- override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = bf match {
- case _: Vector.VectorReusableCBF => updateAt(index, elem).asInstanceOf[That] // just ignore bf
- case _ => super.updated(index, elem)(bf)
- }
+ override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
+ if (bf eq IndexedSeq.ReusableCBF) updateAt(index, elem).asInstanceOf[That] // just ignore bf
+ else super.updated(index, elem)(bf)
- override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = bf match {
- case _: Vector.VectorReusableCBF => appendFront(elem).asInstanceOf[That] // just ignore bf
- case _ => super.+:(elem)(bf)
- }
+ override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
+ if (bf eq IndexedSeq.ReusableCBF) appendFront(elem).asInstanceOf[That] // just ignore bf
+ else super.+:(elem)(bf)
- override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = bf match {
- case _: Vector.VectorReusableCBF => appendBack(elem).asInstanceOf[That] // just ignore bf
- case _ => super.:+(elem)(bf)
- }
+ override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That =
+ if (bf eq IndexedSeq.ReusableCBF) appendBack(elem).asInstanceOf[That] // just ignore bf
+ else super.:+(elem)(bf)
override def take(n: Int): Vector[A] = {
if (n <= 0)
diff --git a/src/library/scala/collection/mutable/FlatHashTable.scala b/src/library/scala/collection/mutable/FlatHashTable.scala
index c0299479f3..91e95e039b 100644
--- a/src/library/scala/collection/mutable/FlatHashTable.scala
+++ b/src/library/scala/collection/mutable/FlatHashTable.scala
@@ -110,24 +110,23 @@ trait FlatHashTable[A] extends FlatHashTable.HashUtils[A] {
/** Finds an entry in the hash table if such an element exists. */
protected def findEntry(elem: A): Option[A] = {
- var h = index(elemHashCode(elem))
- var entry = table(h)
- while (null != entry && entry != elem) {
- h = (h + 1) % table.length
- entry = table(h)
- }
+ val entry = findEntryImpl(elem)
if (null == entry) None else Some(entry.asInstanceOf[A])
}
/** Checks whether an element is contained in the hash table. */
protected def containsEntry(elem: A): Boolean = {
+ null != findEntryImpl(elem)
+ }
+
+ private def findEntryImpl(elem: A): AnyRef = {
var h = index(elemHashCode(elem))
var entry = table(h)
while (null != entry && entry != elem) {
h = (h + 1) % table.length
entry = table(h)
}
- null != entry
+ entry
}
/** Add entry if not yet in table.
diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala
index 53b2b57f50..67af4a6bd6 100644
--- a/src/library/scala/collection/mutable/ListBuffer.scala
+++ b/src/library/scala/collection/mutable/ListBuffer.scala
@@ -129,29 +129,27 @@ final class ListBuffer[A]
* @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
*/
def update(n: Int, x: A) {
- try {
- if (exported) copy()
- if (n == 0) {
- val newElem = new :: (x, start.tail);
- if (last0 eq start) {
- last0 = newElem
- }
- start = newElem
- } else {
- var cursor = start
- var i = 1
- while (i < n) {
- cursor = cursor.tail
- i += 1
- }
- val newElem = new :: (x, cursor.tail.tail)
- if (last0 eq cursor.tail) {
- last0 = newElem
- }
- cursor.asInstanceOf[::[A]].tl = newElem
+ // We check the bounds early, so that we don't trigger copying.
+ if (n < 0 || n >= len) throw new IndexOutOfBoundsException(n.toString)
+ if (exported) copy()
+ if (n == 0) {
+ val newElem = new :: (x, start.tail);
+ if (last0 eq start) {
+ last0 = newElem
+ }
+ start = newElem
+ } else {
+ var cursor = start
+ var i = 1
+ while (i < n) {
+ cursor = cursor.tail
+ i += 1
+ }
+ val newElem = new :: (x, cursor.tail.tail)
+ if (last0 eq cursor.tail) {
+ last0 = newElem
}
- } catch {
- case ex: Exception => throw new IndexOutOfBoundsException(n.toString())
+ cursor.asInstanceOf[::[A]].tl = newElem
}
}
@@ -212,34 +210,31 @@ final class ListBuffer[A]
* @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
*/
def insertAll(n: Int, seq: Traversable[A]) {
- try {
- if (exported) copy()
- var elems = seq.toList.reverse
- len += elems.length
- if (n == 0) {
- while (!elems.isEmpty) {
- val newElem = new :: (elems.head, start)
- if (start.isEmpty) last0 = newElem
- start = newElem
- elems = elems.tail
- }
- } else {
- var cursor = start
- var i = 1
- while (i < n) {
- cursor = cursor.tail
- i += 1
- }
- while (!elems.isEmpty) {
- val newElem = new :: (elems.head, cursor.tail)
- if (cursor.tail.isEmpty) last0 = newElem
- cursor.asInstanceOf[::[A]].tl = newElem
- elems = elems.tail
- }
+ // We check the bounds early, so that we don't trigger copying.
+ if (n < 0 || n > len) throw new IndexOutOfBoundsException(n.toString)
+ if (exported) copy()
+ var elems = seq.toList.reverse
+ len += elems.length
+ if (n == 0) {
+ while (!elems.isEmpty) {
+ val newElem = new :: (elems.head, start)
+ if (start.isEmpty) last0 = newElem
+ start = newElem
+ elems = elems.tail
+ }
+ } else {
+ var cursor = start
+ var i = 1
+ while (i < n) {
+ cursor = cursor.tail
+ i += 1
+ }
+ while (!elems.isEmpty) {
+ val newElem = new :: (elems.head, cursor.tail)
+ if (cursor.tail.isEmpty) last0 = newElem
+ cursor.asInstanceOf[::[A]].tl = newElem
+ elems = elems.tail
}
- } catch {
- case ex: Exception =>
- throw new IndexOutOfBoundsException(n.toString())
}
}
@@ -249,7 +244,12 @@ final class ListBuffer[A]
* @param n the index which refers to the first element to remove.
* @param count the number of elements to remove.
*/
+ @annotation.migration("Invalid input values will be rejected in future releases.", "2.11")
override def remove(n: Int, count: Int) {
+ if (n >= len)
+ return
+ if (count < 0)
+ throw new IllegalArgumentException(s"removing negative number ($count) of elements")
if (exported) copy()
val n1 = n max 0
val count1 = count min (len - n1)
diff --git a/src/library/scala/collection/mutable/MultiMap.scala b/src/library/scala/collection/mutable/MultiMap.scala
index 31c8a50a84..4635bfbe64 100644
--- a/src/library/scala/collection/mutable/MultiMap.scala
+++ b/src/library/scala/collection/mutable/MultiMap.scala
@@ -15,8 +15,36 @@ package mutable
/** A trait for mutable maps with multiple values assigned to a key.
*
* This class is typically used as a mixin. It turns maps which map `A`
- * to `Set[B]` objects into multi maps which map `A` to
- * `B` objects.
+ * to `Set[B]` objects into multimaps that map `A` to `B` objects.
+ *
+ * @example {{{
+ * // first import all necessary types from package `collection.mutable`
+ * import collection.mutable.{ HashMap, MultiMap, Set }
+ *
+ * // to create a `MultiMap` the easiest way is to mixin it into a normal
+ * // `Map` instance
+ * val mm = new HashMap[Int, Set[String]] with MultiMap[Int, String]
+ *
+ * // to add key-value pairs to a multimap it is important to use
+ * // the method `addBinding` because standard methods like `+` will
+ * // overwrite the complete key-value pair instead of adding the
+ * // value to the existing key
+ * mm.addBinding(1, "a")
+ * mm.addBinding(2, "b")
+ * mm.addBinding(1, "c")
+ *
+ * // mm now contains `Map(2 -> Set(b), 1 -> Set(c, a))`
+ *
+ * // to check if the multimap contains a value there is method
+ * // `entryExists`, which allows to traverse the including set
+ * mm.entryExists(1, _ == "a") == true
+ * mm.entryExists(1, _ == "b") == false
+ * mm.entryExists(2, _ == "b") == true
+ *
+ * // to remove a previous added value there is the method `removeBinding`
+ * mm.removeBinding(1, "a")
+ * mm.entryExists(1, _ == "a") == false
+ * }}}
*
* @define coll multimap
* @define Coll `MultiMap`
@@ -57,7 +85,8 @@ trait MultiMap[A, B] extends Map[A, Set[B]] {
this
}
- /** Removes the binding of `value` to `key` if it exists.
+ /** Removes the binding of `value` to `key` if it exists, otherwise this
+ * operation doesn't have any effect.
*
* If this was the last value assigned to the specified key, the
* set assigned to that key will be removed as well.
diff --git a/src/library/scala/package.scala b/src/library/scala/package.scala
index 84f6f0be9c..d3f8df9110 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/sys/process/ProcessImpl.scala b/src/library/scala/sys/process/ProcessImpl.scala
index 2e494cc82f..c21c0daa5e 100644
--- a/src/library/scala/sys/process/ProcessImpl.scala
+++ b/src/library/scala/sys/process/ProcessImpl.scala
@@ -222,7 +222,10 @@ private[process] trait ProcessImpl {
p.exitValue()
}
override def destroy() = {
- try p.destroy()
+ try{
+ outputThreads foreach (_.stop())
+ p.destroy()
+ }
finally inputThread.interrupt()
}
}
diff --git a/src/manual/scala/man1/scaladoc.scala b/src/manual/scala/man1/scaladoc.scala
index a9facf1433..34c58b6b8e 100644
--- a/src/manual/scala/man1/scaladoc.scala
+++ b/src/manual/scala/man1/scaladoc.scala
@@ -75,7 +75,10 @@ object scaladoc extends Command {
"Define the overall version number of the documentation, typically the version of the library being documented."),
Definition(
CmdOption("doc-source-url", Argument("url")),
- "Define a URL to be concatenated with source locations for link to source files."))),
+ "Define a URL to be concatenated with source locations for link to source files."),
+ Definition(
+ CmdOption("doc-external-uris", Argument("external-doc")),
+ "Define comma-separated list of file://classpath_entry_path#doc_URL URIs for linking to external dependencies."))),
Section("Compiler Options",
DefinitionList(
diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala
index e24971a309..2a7b55cb5a 100644
--- a/src/reflect/scala/reflect/internal/Definitions.scala
+++ b/src/reflect/scala/reflect/internal/Definitions.scala
@@ -944,6 +944,7 @@ trait Definitions extends api.StandardDefinitions {
lazy val BeanPropertyAttr = requiredClass[scala.beans.BeanProperty]
lazy val BooleanBeanPropertyAttr = requiredClass[scala.beans.BooleanBeanProperty]
lazy val CloneableAttr = requiredClass[scala.annotation.cloneable]
+ lazy val CompileTimeOnlyAttr = getClassIfDefined("scala.reflect.macros.compileTimeOnly")
lazy val DeprecatedAttr = requiredClass[scala.deprecated]
lazy val DeprecatedNameAttr = requiredClass[scala.deprecatedName]
lazy val DeprecatedInheritanceAttr = requiredClass[scala.deprecatedInheritance]
diff --git a/src/reflect/scala/reflect/internal/Printers.scala b/src/reflect/scala/reflect/internal/Printers.scala
index e513ccb32c..80d247c0ea 100644
--- a/src/reflect/scala/reflect/internal/Printers.scala
+++ b/src/reflect/scala/reflect/internal/Printers.scala
@@ -561,8 +561,11 @@ trait Printers extends api.Printers { self: SymbolTable =>
if (isError) print(": error>")
} else if (hasSymbol) {
tree match {
- case _: Ident | _: Select | _: SelectFromTypeTree => print(tree.symbol)
- case _ => print(tree.symbol.name)
+ case refTree: RefTree =>
+ if (tree.symbol.name != refTree.name) print("[", tree.symbol, " aka ", refTree.name, "]")
+ else print(tree.symbol)
+ case _ =>
+ print(tree.symbol.name)
}
} else {
print(name)
diff --git a/src/reflect/scala/reflect/internal/StdAttachments.scala b/src/reflect/scala/reflect/internal/StdAttachments.scala
index 9fe443bf50..1df91a67b0 100644
--- a/src/reflect/scala/reflect/internal/StdAttachments.scala
+++ b/src/reflect/scala/reflect/internal/StdAttachments.scala
@@ -19,9 +19,26 @@ trait StdAttachments {
def setPos(newpos: Position): this.type = { pos = newpos; this }
}
+ /** When present, indicates that the host `Ident` has been created from a backquoted identifier.
+ */
case object BackquotedIdentifierAttachment
+ /** Stores the trees that give rise to a refined type to be used in reification.
+ * Unfortunately typed `CompoundTypeTree` is lacking essential info, and the reifier cannot use `CompoundTypeTree.tpe`.
+ * Therefore we need this hack (see `Reshape.toPreTyperTypeTree` for a detailed explanation).
+ */
case class CompoundTypeTreeOriginalAttachment(parents: List[Tree], stats: List[Tree])
+ /** Is added by the macro engine to the results of macro expansions.
+ * Stores the original expandee as it entered the `macroExpand` function.
+ */
case class MacroExpansionAttachment(original: Tree)
+
+ /** When present, suppresses macro expansion for the host.
+ * This is occasionally necessary, e.g. to prohibit eta-expansion of macros.
+ *
+ * Does not affect expandability of child nodes, there's context.withMacrosDisabled for that
+ * (but think thrice before using that API - see the discussion at https://github.com/scala/scala/pull/1639).
+ */
+ case object SuppressMacroExpansionAttachment
}
diff --git a/src/reflect/scala/reflect/internal/SymbolTable.scala b/src/reflect/scala/reflect/internal/SymbolTable.scala
index d077a975a8..02ac59a461 100644
--- a/src/reflect/scala/reflect/internal/SymbolTable.scala
+++ b/src/reflect/scala/reflect/internal/SymbolTable.scala
@@ -6,6 +6,7 @@
package scala.reflect
package internal
+import scala.annotation.elidable
import scala.collection.{ mutable, immutable }
import util._
@@ -107,6 +108,11 @@ abstract class SymbolTable extends macros.Universe
val global: SymbolTable.this.type = SymbolTable.this
} with util.TraceSymbolActivity
+ /** Check that the executing thread is the compiler thread. No-op here,
+ * overridden in interactive.Global. */
+ @elidable(elidable.WARNING)
+ def assertCorrectThread() {}
+
/** Are we compiling for Java SE? */
// def forJVM: Boolean
@@ -339,6 +345,12 @@ abstract class SymbolTable extends macros.Universe
/** Is this symbol table a part of a compiler universe?
*/
def isCompilerUniverse = false
+
+ /**
+ * Adds the `sm` String interpolator to a [[scala.StringContext]].
+ */
+ implicit val StringContextStripMarginOps: StringContext => StringContextStripMarginOps = util.StringContextStripMarginOps
+
}
object SymbolTableStats {
diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala
index 06bf54c1f8..a27afe9dfd 100644
--- a/src/reflect/scala/reflect/internal/Symbols.scala
+++ b/src/reflect/scala/reflect/internal/Symbols.scala
@@ -79,7 +79,7 @@ trait Symbols extends api.Symbols { self: SymbolTable =>
def isImplementationArtifact: Boolean = (this hasFlag BRIDGE) || (this hasFlag VBRIDGE) || (this hasFlag ARTIFACT)
def isJava: Boolean = isJavaDefined
def isVal: Boolean = isTerm && !isModule && !isMethod && !isMutable
- def isVar: Boolean = isTerm && !isModule && !isMethod && isMutable
+ def isVar: Boolean = isTerm && !isModule && !isMethod && !isLazy && isMutable
def newNestedSymbol(name: Name, pos: Position, newFlags: Long, isClass: Boolean): Symbol = name match {
case n: TermName => newTermSymbol(n, pos, newFlags)
@@ -743,6 +743,9 @@ trait Symbols extends api.Symbols { self: SymbolTable =>
def elisionLevel = getAnnotation(ElidableMethodClass) flatMap { _.intArg(0) }
def implicitNotFoundMsg = getAnnotation(ImplicitNotFoundClass) flatMap { _.stringArg(0) }
+ def isCompileTimeOnly = hasAnnotation(CompileTimeOnlyAttr)
+ def compileTimeOnlyMessage = getAnnotation(CompileTimeOnlyAttr) flatMap (_ stringArg 0)
+
/** Is this symbol an accessor method for outer? */
final def isOuterAccessor = {
hasFlag(STABLE | ARTIFACT) &&
@@ -1213,6 +1216,7 @@ trait Symbols extends api.Symbols { self: SymbolTable =>
}
val current = phase
try {
+ assertCorrectThread()
phase = phaseOf(infos.validFrom)
tp.complete(this)
} finally {
@@ -1283,6 +1287,7 @@ trait Symbols extends api.Symbols { self: SymbolTable =>
infos = infos.prev
if (validTo < curPeriod) {
+ assertCorrectThread()
// adapt any infos that come from previous runs
val current = phase
try {
diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala
index b8f5e73acb..6df4b75a88 100644
--- a/src/reflect/scala/reflect/internal/Trees.scala
+++ b/src/reflect/scala/reflect/internal/Trees.scala
@@ -391,6 +391,9 @@ trait Trees extends api.Trees { self: SymbolTable =>
case class TypeApply(fun: Tree, args: List[Tree])
extends GenericApply with TypeApplyApi {
+
+ assert(fun.isTerm, fun)
+
override def symbol: Symbol = fun.symbol
override def symbol_=(sym: Symbol) { fun.symbol = sym }
}
@@ -426,7 +429,11 @@ trait Trees extends api.Trees { self: SymbolTable =>
object This extends ThisExtractor
case class Select(qualifier: Tree, name: Name)
- extends RefTree with SelectApi
+ extends RefTree with SelectApi {
+
+ // !!! assert disabled due to test case pos/annotDepMethType.scala triggering it.
+ // assert(qualifier.isTerm, qualifier)
+ }
object Select extends SelectExtractor
case class Ident(name: Name) extends RefTree with IdentContextApi {
@@ -458,7 +465,10 @@ trait Trees extends api.Trees { self: SymbolTable =>
object SingletonTypeTree extends SingletonTypeTreeExtractor
case class SelectFromTypeTree(qualifier: Tree, name: TypeName)
- extends RefTree with TypTree with SelectFromTypeTreeApi
+ extends RefTree with TypTree with SelectFromTypeTreeApi {
+
+ assert(qualifier.isType, qualifier)
+ }
object SelectFromTypeTree extends SelectFromTypeTreeExtractor
case class CompoundTypeTree(templ: Template)
@@ -467,6 +477,9 @@ trait Trees extends api.Trees { self: SymbolTable =>
case class AppliedTypeTree(tpt: Tree, args: List[Tree])
extends TypTree with AppliedTypeTreeApi {
+
+ assert(tpt.isType, tpt)
+
override def symbol: Symbol = tpt.symbol
override def symbol_=(sym: Symbol) { tpt.symbol = sym }
}
@@ -1313,25 +1326,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 d5347705a6..0c4cda8313 100644
--- a/src/reflect/scala/reflect/internal/Types.scala
+++ b/src/reflect/scala/reflect/internal/Types.scala
@@ -146,6 +146,7 @@ trait Types extends api.Types { self: SymbolTable =>
/** Undo all changes to constraints to type variables upto `limit`. */
//OPT this method is public so we can do `manual inlining`
def undoTo(limit: UndoPairs) {
+ assertCorrectThread()
while ((log ne limit) && log.nonEmpty) {
val (tv, constr) = log.head
tv.constr = constr
@@ -324,6 +325,18 @@ trait Types extends api.Types { self: SymbolTable =>
}
}
+ /** Same as a call to narrow unless existentials are visible
+ * after widening the type. In that case, narrow from the widened
+ * type instead of the proxy. This gives buried existentials a
+ * chance to make peace with the other types. See SI-5330.
+ */
+ private def narrowForFindMember(tp: Type): Type = {
+ val w = tp.widen
+ // Only narrow on widened type when we have to -- narrow is expensive unless the target is a singleton type.
+ if ((tp ne w) && containsExistential(w)) w.narrow
+ else tp.narrow
+ }
+
/** The base class for all types */
abstract class Type extends TypeApiImpl with Annotatable[Type] {
/** Types for which asSeenFrom always is the identity, no matter what
@@ -1078,7 +1091,7 @@ trait Types extends api.Types { self: SymbolTable =>
(other ne sym) &&
((other.owner eq sym.owner) ||
(flags & PRIVATE) != 0 || {
- if (self eq null) self = this.narrow
+ if (self eq null) self = narrowForFindMember(this)
if (symtpe eq null) symtpe = self.memberType(sym)
!(self.memberType(other) matches symtpe)
})}) {
@@ -1160,7 +1173,7 @@ trait Types extends api.Types { self: SymbolTable =>
if ((member ne sym) &&
((member.owner eq sym.owner) ||
(flags & PRIVATE) != 0 || {
- if (self eq null) self = this.narrow
+ if (self eq null) self = narrowForFindMember(this)
if (membertpe eq null) membertpe = self.memberType(member)
!(membertpe matches self.memberType(sym))
})) {
@@ -1175,7 +1188,7 @@ trait Types extends api.Types { self: SymbolTable =>
(other ne sym) &&
((other.owner eq sym.owner) ||
(flags & PRIVATE) != 0 || {
- if (self eq null) self = this.narrow
+ if (self eq null) self = narrowForFindMember(this)
if (symtpe eq null) symtpe = self.memberType(sym)
!(self.memberType(other) matches symtpe)
})}) {
diff --git a/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala b/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala
new file mode 100644
index 0000000000..e7579229b2
--- /dev/null
+++ b/src/reflect/scala/reflect/internal/util/StripMarginInterpolator.scala
@@ -0,0 +1,40 @@
+package scala.reflect
+package internal
+package util
+
+trait StripMarginInterpolator {
+ def stringContext: StringContext
+
+ /**
+ * A safe combination of `[[scala.collection.immutable.StringLike#stripMargin]]
+ * and [[scala.StringContext#raw]].
+ *
+ * The margin of each line is defined by whitespace leading up to a '|' character.
+ * This margin is stripped '''before''' the arguments are interpolated into to string.
+ *
+ * String escape sequences are '''not''' processed; this interpolater is designed to
+ * be used with triple quoted Strings.
+ *
+ * {{{
+ * scala> val foo = "f|o|o"
+ * foo: String = f|o|o
+ * scala> sm"""|${foo}
+ * |"""
+ * res0: String =
+ * "f|o|o
+ * "
+ * }}}
+ */
+ final def sm(args: Any*): String = {
+ def isLineBreak(c: Char) = c == '\n' || c == '\f' // compatible with StringLike#isLineBreak
+ def stripTrailingPart(s: String) = {
+ val (pre, post) = s.span(c => !isLineBreak(c))
+ pre + post.stripMargin
+ }
+ val stripped: List[String] = stringContext.parts.toList match {
+ case head :: tail => head.stripMargin :: (tail map stripTrailingPart)
+ case Nil => Nil
+ }
+ new StringContext(stripped: _*).raw(args: _*)
+ }
+}
diff --git a/src/reflect/scala/reflect/internal/util/package.scala b/src/reflect/scala/reflect/internal/util/package.scala
new file mode 100644
index 0000000000..6d77235db6
--- /dev/null
+++ b/src/reflect/scala/reflect/internal/util/package.scala
@@ -0,0 +1,9 @@
+package scala.reflect
+package internal
+
+package object util {
+ /**
+ * Adds the `sm` String interpolator to a [[scala.StringContext]].
+ */
+ implicit class StringContextStripMarginOps(val stringContext: StringContext) extends StripMarginInterpolator
+}
diff --git a/src/reflect/scala/reflect/macros/compileTimeOnly.scala b/src/reflect/scala/reflect/macros/compileTimeOnly.scala
new file mode 100644
index 0000000000..5a3a352a53
--- /dev/null
+++ b/src/reflect/scala/reflect/macros/compileTimeOnly.scala
@@ -0,0 +1,16 @@
+package scala.reflect
+package macros
+
+import scala.annotation.meta._
+
+/**
+ * An annotation that designates a member should not be referred to after
+ * type checking (which includes macro expansion); it must only be used in
+ * the arguments of some other macro that will eliminate it from the AST.
+ *
+ * @param message the error message to print during compilation if a reference remains
+ * after type checking
+ * @since 2.10.1
+ */
+@getter @setter @beanGetter @beanSetter
+final class compileTimeOnly(message: String) extends scala.annotation.StaticAnnotation
diff --git a/src/reflect/scala/reflect/runtime/JavaMirrors.scala b/src/reflect/scala/reflect/runtime/JavaMirrors.scala
index 2d08cd887b..ab93d7033a 100644
--- a/src/reflect/scala/reflect/runtime/JavaMirrors.scala
+++ b/src/reflect/scala/reflect/runtime/JavaMirrors.scala
@@ -129,11 +129,10 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni
private def ErrorStaticModule(sym: Symbol) = throw new ScalaReflectionException(s"$sym is a static module, use reflectModule on a RuntimeMirror to obtain its ModuleMirror")
private def ErrorNotMember(sym: Symbol, owner: Symbol) = throw new ScalaReflectionException(s"expected a member of $owner, you provided ${sym.kindString} ${sym.fullName}")
private def ErrorNotField(sym: Symbol) = throw new ScalaReflectionException(s"expected a field or an accessor method symbol, you provided $sym")
- private def ErrorNonExistentField(sym: Symbol) = throw new ScalaReflectionException(s"""
- |Scala field ${sym.name} isn't represented as a Java field, neither it has a Java accessor method
- |note that private parameters of class constructors don't get mapped onto fields and/or accessors,
- |unless they are used outside of their declaring constructors.
- """.trim.stripMargin)
+ private def ErrorNonExistentField(sym: Symbol) = throw new ScalaReflectionException(
+ sm"""Scala field ${sym.name} isn't represented as a Java field, neither it has a Java accessor method
+ |note that private parameters of class constructors don't get mapped onto fields and/or accessors,
+ |unless they are used outside of their declaring constructors.""")
private def ErrorSetImmutableField(sym: Symbol) = throw new ScalaReflectionException(s"cannot set an immutable field ${sym.name}")
private def ErrorNotConstructor(sym: Symbol, owner: Symbol) = throw new ScalaReflectionException(s"expected a constructor of $owner, you provided $sym")
private def ErrorFree(member: Symbol, freeType: Symbol) = throw new ScalaReflectionException(s"cannot reflect ${member.kindString} ${member.name}, because it's a member of a weak type ${freeType.name}")
@@ -541,8 +540,8 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni
val result = anns find (_.annotationType == annotClass)
if (result.isEmpty && (anns exists (_.annotationType.getName == name)))
throw new ClassNotFoundException(
- s"""Mirror classloader mismatch: $jclazz (loaded by ${ReflectionUtils.show(jclazz.getClassLoader)})
- |is unrelated to the mirror's classloader: (${ReflectionUtils.show(classLoader)})""".stripMargin)
+ sm"""Mirror classloader mismatch: $jclazz (loaded by ${ReflectionUtils.show(jclazz.getClassLoader)})
+ |is unrelated to the mirror's classloader: (${ReflectionUtils.show(classLoader)})""")
result
}
def loadBytes[T: ClassTag](name: String): Option[T] =
@@ -955,8 +954,8 @@ private[reflect] trait JavaMirrors extends internal.SymbolTable with api.JavaUni
javaTypeToValueClass(jclazz) orElse lookupClass
assert (cls.isType,
- s"""${if (cls == NoSymbol) "not a type: symbol" else "no symbol could be"}
- | loaded from $jclazz in $owner with name $simpleName and classloader $classLoader""".stripMargin)
+ sm"""${if (cls == NoSymbol) "not a type: symbol" else "no symbol could be"}
+ | loaded from $jclazz in $owner with name $simpleName and classloader $classLoader""")
cls.asClass
}
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/neg/gadts1.check b/test/files/neg/gadts1.check
index 44d2b114d6..a5e3e0de10 100644
--- a/test/files/neg/gadts1.check
+++ b/test/files/neg/gadts1.check
@@ -3,9 +3,9 @@ gadts1.scala:15: error: type mismatch;
required: a
case NumTerm(n) => c.x = Double(1.0)
^
-gadts1.scala:20: error: class Cell of type Test.Cell does not take type parameters.
+gadts1.scala:20: error: Test.Cell[a] does not take parameters
case Cell[a](x: Int) => c.x = 5
- ^
+ ^
gadts1.scala:20: error: type mismatch;
found : Int(5)
required: a
diff --git a/test/files/neg/t5753.check b/test/files/neg/t5753.check
new file mode 100644
index 0000000000..76602de17d
--- /dev/null
+++ b/test/files/neg/t5753.check
@@ -0,0 +1,4 @@
+Test_2.scala:9: error: macro implementation not found: foo (the most common reason for that is that you cannot use macro implementations in the same compilation run that defines them)
+ println(foo(42))
+ ^
+one error found
diff --git a/test/files/neg/t5753.flags b/test/files/neg/t5753.flags
new file mode 100644
index 0000000000..cd66464f2f
--- /dev/null
+++ b/test/files/neg/t5753.flags
@@ -0,0 +1 @@
+-language:experimental.macros \ No newline at end of file
diff --git a/test/files/neg/t5753/Impls$class.class b/test/files/neg/t5753/Impls$class.class
new file mode 100644
index 0000000000..476329174e
--- /dev/null
+++ b/test/files/neg/t5753/Impls$class.class
Binary files differ
diff --git a/test/files/neg/t5753/Impls.class b/test/files/neg/t5753/Impls.class
new file mode 100644
index 0000000000..dfcf89ed44
--- /dev/null
+++ b/test/files/neg/t5753/Impls.class
Binary files differ
diff --git a/test/files/neg/t5753/Impls_Macros_1.scala b/test/files/neg/t5753/Impls_Macros_1.scala
new file mode 100644
index 0000000000..1d9c26458c
--- /dev/null
+++ b/test/files/neg/t5753/Impls_Macros_1.scala
@@ -0,0 +1,6 @@
+import scala.reflect.macros.{Context => Ctx}
+
+trait Impls {
+def impl(c: Ctx)(x: c.Expr[Any]) = x
+}
+
diff --git a/test/files/neg/t5753/Test_2.scala b/test/files/neg/t5753/Test_2.scala
new file mode 100644
index 0000000000..2369b18e76
--- /dev/null
+++ b/test/files/neg/t5753/Test_2.scala
@@ -0,0 +1,11 @@
+import scala.reflect.macros.{Context => Ctx}
+
+object Macros extends Impls {
+ def foo(x: Any) = macro impl
+}
+
+object Test extends App {
+ import Macros._
+ println(foo(42))
+}
+
diff --git a/test/files/neg/t6323a.check b/test/files/neg/t6323a.check
index 670247887c..a80c9a0a81 100644
--- a/test/files/neg/t6323a.check
+++ b/test/files/neg/t6323a.check
@@ -1,6 +1,6 @@
t6323a.scala:11: `package`.this.materializeTypeTag[Test](scala.reflect.runtime.`package`.universe) is not a valid implicit value for reflect.runtime.universe.TypeTag[Test] because:
failed to typecheck the materialized tag:
-cannot create a TypeTag referring to local class Test.Test
+cannot create a TypeTag referring to local class Test.Test: use WeakTypeTag instead
val value = u.typeOf[Test]
^
t6323a.scala:11: error: No TypeTag available for Test
diff --git a/test/files/neg/t6357.check b/test/files/neg/t6357.check
new file mode 100644
index 0000000000..a534d1439a
--- /dev/null
+++ b/test/files/neg/t6357.check
@@ -0,0 +1,4 @@
+t6357.scala:3: error: value class may not be a local class
+ final class Y(val j: Int) extends AnyVal
+ ^
+one error found
diff --git a/test/files/neg/t6357.scala b/test/files/neg/t6357.scala
new file mode 100644
index 0000000000..47f5629638
--- /dev/null
+++ b/test/files/neg/t6357.scala
@@ -0,0 +1,6 @@
+object K {
+ def q = {
+ final class Y(val j: Int) extends AnyVal
+ 3
+ }
+}
diff --git a/test/files/neg/t6539.check b/test/files/neg/t6539.check
new file mode 100644
index 0000000000..b647636338
--- /dev/null
+++ b/test/files/neg/t6539.check
@@ -0,0 +1,10 @@
+Test_2.scala:2: error: cto may only be used as an argument to m
+ M.cto // error
+ ^
+Test_2.scala:3: error: cto may only be used as an argument to m
+ M.m(M.cto, ()) // error
+ ^
+Test_2.scala:5: error: cto may only be used as an argument to m
+ M.cto // error
+ ^
+three errors found
diff --git a/test/files/neg/t6539/Macro_1.scala b/test/files/neg/t6539/Macro_1.scala
new file mode 100644
index 0000000000..ed52776d95
--- /dev/null
+++ b/test/files/neg/t6539/Macro_1.scala
@@ -0,0 +1,10 @@
+import language.experimental.macros
+import reflect.macros.Context
+
+object M {
+ def m(a: Any, b: Any): Any = macro mImpl
+ def mImpl(c: Context)(a: c.Expr[Any], b: c.Expr[Any]) = a
+
+ @reflect.macros.compileTimeOnly("cto may only be used as an argument to " + "m")
+ def cto = 0
+}
diff --git a/test/files/neg/t6539/Test_2.scala b/test/files/neg/t6539/Test_2.scala
new file mode 100644
index 0000000000..5a602879ec
--- /dev/null
+++ b/test/files/neg/t6539/Test_2.scala
@@ -0,0 +1,6 @@
+object Test {
+ M.cto // error
+ M.m(M.cto, ()) // error
+ M.m((), M.cto) // okay
+ M.cto // error
+}
diff --git a/test/files/neg/t6597.check b/test/files/neg/t6597.check
new file mode 100644
index 0000000000..1d52519d1d
--- /dev/null
+++ b/test/files/neg/t6597.check
@@ -0,0 +1,4 @@
+t6597.scala:3: error: illegal combination of modifiers: implicit and case for: class Quux
+ implicit case class Quux(value: Int) extends AnyVal with T
+ ^
+one error found
diff --git a/test/files/neg/t6597.scala b/test/files/neg/t6597.scala
new file mode 100644
index 0000000000..dde53bcc89
--- /dev/null
+++ b/test/files/neg/t6597.scala
@@ -0,0 +1,5 @@
+object Test {
+ trait T extends Any
+ implicit case class Quux(value: Int) extends AnyVal with T
+ object Quux
+}
diff --git a/test/files/neg/t6663.check b/test/files/neg/t6663.check
new file mode 100644
index 0000000000..aa4faa4a46
--- /dev/null
+++ b/test/files/neg/t6663.check
@@ -0,0 +1,6 @@
+t6663.scala:16: error: type mismatch;
+ found : String
+ required: Int
+ var v = new C(42).foo[String].get :Int
+ ^
+one error found
diff --git a/test/files/neg/t6663.scala b/test/files/neg/t6663.scala
new file mode 100644
index 0000000000..4a358dfbc5
--- /dev/null
+++ b/test/files/neg/t6663.scala
@@ -0,0 +1,19 @@
+import language.dynamics
+
+class C(v: Any) extends Dynamic {
+ def selectDynamic[T](n: String): Option[T] = Option(v.asInstanceOf[T])
+ def applyDynamic[T](n: String)(): Option[T] = Option(v.asInstanceOf[T])
+}
+
+object Test extends App {
+ // this should be converted to
+ // C(42).selectDynamic[String]("foo").get
+ // causing a compile error.
+
+ // but, before fixing SI-6663, became
+ // C(42).selectDynamic("foo").get, ignoring
+ // the [String] type parameter
+ var v = new C(42).foo[String].get :Int
+ println(v)
+}
+
diff --git a/test/files/neg/valueclasses-impl-restrictions.check b/test/files/neg/valueclasses-impl-restrictions.check
index 17d07ba960..63924493aa 100644
--- a/test/files/neg/valueclasses-impl-restrictions.check
+++ b/test/files/neg/valueclasses-impl-restrictions.check
@@ -2,20 +2,16 @@ valueclasses-impl-restrictions.scala:3: error: implementation restriction: neste
This restriction is planned to be removed in subsequent releases.
object X
^
-valueclasses-impl-restrictions.scala:4: error: implementation restriction: lazy val is not allowed in value class
-This restriction is planned to be removed in subsequent releases.
- lazy val y = 1
- ^
-valueclasses-impl-restrictions.scala:10: error: implementation restriction: nested trait is not allowed in value class
+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:16: error: implementation restriction: nested class is not allowed in value class
+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:22: error: implementation restriction: nested class is not allowed in value class
+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)
^
-5 errors found
+four errors found
diff --git a/test/files/neg/valueclasses-impl-restrictions.scala b/test/files/neg/valueclasses-impl-restrictions.scala
index 53396db958..137f3f854c 100644
--- a/test/files/neg/valueclasses-impl-restrictions.scala
+++ b/test/files/neg/valueclasses-impl-restrictions.scala
@@ -1,7 +1,6 @@
class M(val t: Int) extends AnyVal {
def lazyString = {
object X
- lazy val y = 1
() => X
}
}
diff --git a/test/files/pos/t5330.scala b/test/files/pos/t5330.scala
new file mode 100644
index 0000000000..813acd4b83
--- /dev/null
+++ b/test/files/pos/t5330.scala
@@ -0,0 +1,22 @@
+trait FM[A] {
+ def map(f: A => Any)
+}
+
+trait M[A] extends FM[A] {
+ def map(f: A => Any)
+}
+
+trait N[A] extends FM[A]
+
+object test {
+ def kaboom(xs: M[_]) = xs map (x => ()) // missing parameter type.
+
+ def okay1[A](xs: M[A]) = xs map (x => ())
+ def okay2(xs: FM[_]) = xs map (x => ())
+ def okay3(xs: N[_]) = xs map (x => ())
+}
+
+class CC2(xs: List[_]) {
+ def f(x1: Any, x2: Any) = null
+ def g = xs map (x => f(x, x))
+}
diff --git a/test/files/pos/t5330b.scala b/test/files/pos/t5330b.scala
new file mode 100644
index 0000000000..dbeb165cd8
--- /dev/null
+++ b/test/files/pos/t5330b.scala
@@ -0,0 +1,6 @@
+abstract trait Base {
+ def foo: this.type
+};
+class Derived[T] extends Base {
+ def foo: Nothing = sys.error("!!!")
+}
diff --git a/test/files/pos/t5330c.scala b/test/files/pos/t5330c.scala
new file mode 100644
index 0000000000..af31f3dfd1
--- /dev/null
+++ b/test/files/pos/t5330c.scala
@@ -0,0 +1,5 @@
+object t5330c {
+ val s: Set[_ >: Char] = Set('A')
+ s forall ("ABC" contains _)
+ s.forall( c => "ABC".toSeq.contains( c ))
+}
diff --git a/test/files/pos/t5726.scala b/test/files/pos/t5726.scala
new file mode 100644
index 0000000000..b28ebd8674
--- /dev/null
+++ b/test/files/pos/t5726.scala
@@ -0,0 +1,17 @@
+import scala.language.dynamics
+
+class DynamicTest extends Dynamic {
+ def selectDynamic(name: String) = s"value of $name"
+ def updateDynamic(name: String)(value: Any) {
+ println(s"You have just updated property '$name' with value: $value")
+ }
+}
+
+object MyApp extends App {
+ def testing() {
+ val test = new DynamicTest
+ test.firstName = "John"
+ }
+
+ testing()
+}
diff --git a/test/files/pos/t6014.scala b/test/files/pos/t6014.scala
new file mode 100644
index 0000000000..46e03bb552
--- /dev/null
+++ b/test/files/pos/t6014.scala
@@ -0,0 +1,13 @@
+object Test {
+ case class CC[T](key: T)
+ type Alias[T] = Seq[CC[T]]
+
+ def f(xs: Seq[CC[_]]) = xs map { case CC(x) => CC(x) } // ok
+ def g(xs: Alias[_]) = xs map { case CC(x) => CC(x) } // fails
+ // ./a.scala:11: error: missing parameter type for expanded function
+ // The argument types of an anonymous function must be fully known. (SLS 8.5)
+ // Expected type was: ?
+ // def g(xs: Alias[_]) = xs map { case CC(x) => CC(x) } // fails
+ // ^
+ // one error found
+} \ No newline at end of file
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/t6551.scala b/test/files/pos/t6551.scala
new file mode 100644
index 0000000000..8bb396a19f
--- /dev/null
+++ b/test/files/pos/t6551.scala
@@ -0,0 +1,13 @@
+import scala.language.dynamics
+
+object Test {
+ def main(args: Array[String]) {
+ class Lenser[T] extends Dynamic {
+ def selectDynamic(propName: String) = ???
+ }
+
+ def lens[T] = new Lenser[T]
+
+ val qq = lens[String]
+ }
+}
diff --git a/test/files/pos/t6722.scala b/test/files/pos/t6722.scala
new file mode 100644
index 0000000000..576746c915
--- /dev/null
+++ b/test/files/pos/t6722.scala
@@ -0,0 +1,11 @@
+import scala.language.dynamics
+
+class Dyn extends Dynamic {
+ def selectDynamic(s: String): Dyn = new Dyn
+ def get[T]: T = null.asInstanceOf[T]
+}
+
+object Foo {
+ val dyn = new Dyn
+ dyn.foo.bar.baz.get[String]
+}
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_aliases.check b/test/files/run/showraw_aliases.check
new file mode 100644
index 0000000000..aebd354031
--- /dev/null
+++ b/test/files/run/showraw_aliases.check
@@ -0,0 +1,2 @@
+Block(List(Import(Select(Select(Ident(scala), scala.reflect), scala.reflect.runtime), List(ImportSelector(newTermName("universe"), <offset>, newTermName("ru"), <offset>)))), Select(Select(Select(Select(Ident(scala), scala.reflect), scala.reflect.runtime), scala.reflect.runtime.package), [newTermName("universe") aka newTermName("ru")]))
+Block(List(Import(Select(Select(Ident(scala#<id>), scala.reflect#<id>), scala.reflect.runtime#<id>), List(ImportSelector(newTermName("universe"), <offset>, newTermName("ru"), <offset>)))), Select(Select(Select(Select(Ident(scala#<id>), scala.reflect#<id>), scala.reflect.runtime#<id>), scala.reflect.runtime.package#<id>), [newTermName("universe")#<id> aka newTermName("ru")]))
diff --git a/test/files/run/showraw_aliases.scala b/test/files/run/showraw_aliases.scala
new file mode 100644
index 0000000000..65b4fcb1cd
--- /dev/null
+++ b/test/files/run/showraw_aliases.scala
@@ -0,0 +1,17 @@
+import scala.reflect.runtime.universe._
+import scala.tools.reflect.ToolBox
+
+object Test extends App {
+ val tb = runtimeMirror(getClass.getClassLoader).mkToolBox()
+ val tree = tb.parse("""
+ import scala.reflect.runtime.{universe => ru}
+ ru
+ """)
+ val ttree = tb.typeCheck(tree)
+
+ def stabilizeIds(s: String) = """#\d+""".r.replaceAllIn(s, "#<id>")
+ def stabilizePositions(s: String) = """\d+""".r.replaceAllIn(s, "<offset>")
+ def stabilize(s: String) = stabilizePositions(stabilizeIds(s))
+ println(stabilize(showRaw(ttree)))
+ println(stabilize(showRaw(ttree, printIds = true)))
+} \ No newline at end of file
diff --git a/test/files/run/sm-interpolator.scala b/test/files/run/sm-interpolator.scala
new file mode 100644
index 0000000000..7f7b9f061a
--- /dev/null
+++ b/test/files/run/sm-interpolator.scala
@@ -0,0 +1,41 @@
+object Test extends App {
+ import scala.reflect.internal.util.StringContextStripMarginOps
+ def check(actual: Any, expected: Any) = if (actual != expected) sys.error(s"expected: [$expected], actual: [$actual])")
+
+ val bar = "|\n ||"
+
+ check(
+ sm"""|ab
+ |de
+ |${bar} | ${1}""",
+ "ab \nde\n|\n || | 1")
+
+ check(
+ sm"|",
+ "")
+
+ check(
+ sm"${0}",
+ "0")
+
+ check(
+ sm"${0}",
+ "0")
+
+ check(
+ sm"""${0}|${1}
+ |""",
+ "0|1\n")
+
+ check(
+ sm""" ||""",
+ "|")
+
+ check(
+ sm""" ${" "} ||""",
+ " ||")
+
+ check(
+ sm"\n",
+ raw"\n".stripMargin)
+}
diff --git a/test/files/run/t5733.check b/test/files/run/t5733.check
new file mode 100644
index 0000000000..e697046a94
--- /dev/null
+++ b/test/files/run/t5733.check
@@ -0,0 +1,2 @@
+Running ABTest asserts
+Done
diff --git a/test/files/run/t5733.scala b/test/files/run/t5733.scala
new file mode 100644
index 0000000000..360264e4ed
--- /dev/null
+++ b/test/files/run/t5733.scala
@@ -0,0 +1,53 @@
+import scala.language.dynamics
+
+object A extends Dynamic {
+ var a = "a"
+
+ def selectDynamic(method:String): String = a
+
+ def updateDynamic(method:String)(v:String) { a = v }
+}
+
+class B extends Dynamic {
+ var b = "b"
+
+ def selectDynamic(method:String): String = b
+
+ def updateDynamic(method:String)(v:String) { b = v }
+}
+
+object Test extends App {
+ assert( A.foo == "a" )
+ assert( A.bar == "a" )
+ A.aaa = "aaa"
+ assert( A.bar == "aaa" )
+
+ val b = new B
+ assert( b.foo == "b" )
+ assert( b.bar == "b" )
+ b.bbb = "bbb"
+ assert( b.bar == "bbb" )
+
+ {
+ println("Running ABTest asserts")
+ A.a = "a"
+ (new ABTest).test()
+ }
+
+ println("Done")
+}
+
+class ABTest {
+ def test() {
+ assert( A.foo == "a" )
+ assert( A.bar == "a" )
+ A.aaa = "aaa"
+ assert( A.bar == "aaa" )
+
+ val b = new B
+ assert( b.foo == "b" )
+ assert( b.bar == "b" )
+ b.bbb = "bbb"
+ assert( b.bar == "bbb" )
+ }
+}
diff --git a/test/files/run/t5753_1.check b/test/files/run/t5753_1.check
new file mode 100644
index 0000000000..f70d7bba4a
--- /dev/null
+++ b/test/files/run/t5753_1.check
@@ -0,0 +1 @@
+42 \ No newline at end of file
diff --git a/test/files/run/t5753_1.flags b/test/files/run/t5753_1.flags
new file mode 100644
index 0000000000..cd66464f2f
--- /dev/null
+++ b/test/files/run/t5753_1.flags
@@ -0,0 +1 @@
+-language:experimental.macros \ No newline at end of file
diff --git a/test/files/run/t5753_1/Impls_Macros_1.scala b/test/files/run/t5753_1/Impls_Macros_1.scala
new file mode 100644
index 0000000000..1664301f5f
--- /dev/null
+++ b/test/files/run/t5753_1/Impls_Macros_1.scala
@@ -0,0 +1,10 @@
+import scala.reflect.macros.Context
+import language.experimental.macros
+
+trait Impls {
+ def impl(c: Context)(x: c.Expr[Any]) = x
+}
+
+object Macros extends Impls {
+ def foo(x: Any) = macro impl
+} \ No newline at end of file
diff --git a/test/files/run/t5753_1/Test_2.scala b/test/files/run/t5753_1/Test_2.scala
new file mode 100644
index 0000000000..a2777638bc
--- /dev/null
+++ b/test/files/run/t5753_1/Test_2.scala
@@ -0,0 +1,4 @@
+object Test extends App {
+ import Macros._
+ println(foo(42))
+} \ No newline at end of file
diff --git a/test/files/run/t5753_2.check b/test/files/run/t5753_2.check
new file mode 100644
index 0000000000..f70d7bba4a
--- /dev/null
+++ b/test/files/run/t5753_2.check
@@ -0,0 +1 @@
+42 \ No newline at end of file
diff --git a/test/files/run/t5753_2.flags b/test/files/run/t5753_2.flags
new file mode 100644
index 0000000000..cd66464f2f
--- /dev/null
+++ b/test/files/run/t5753_2.flags
@@ -0,0 +1 @@
+-language:experimental.macros \ No newline at end of file
diff --git a/test/files/run/t5753_2/Impls_Macros_1.scala b/test/files/run/t5753_2/Impls_Macros_1.scala
new file mode 100644
index 0000000000..e23c0b938b
--- /dev/null
+++ b/test/files/run/t5753_2/Impls_Macros_1.scala
@@ -0,0 +1,10 @@
+import scala.reflect.macros.{Context => Ctx}
+
+trait Macro_T {
+ def foo[T](c: Ctx)(s: c.Expr[T]) = s
+}
+
+object Macros {
+ def foo[T](s: T) = macro Impls.foo[T]
+ object Impls extends Macro_T
+}
diff --git a/test/files/run/t5753_2/Test_2.scala b/test/files/run/t5753_2/Test_2.scala
new file mode 100644
index 0000000000..a2777638bc
--- /dev/null
+++ b/test/files/run/t5753_2/Test_2.scala
@@ -0,0 +1,4 @@
+object Test extends App {
+ import Macros._
+ println(foo(42))
+} \ No newline at end of file
diff --git a/test/files/run/t6023.check b/test/files/run/t6023.check
new file mode 100644
index 0000000000..ee93565234
--- /dev/null
+++ b/test/files/run/t6023.check
@@ -0,0 +1,12 @@
+{
+ abstract trait Foo extends AnyRef {
+ <stable> <accessor> def a: Int
+ };
+ ()
+}
+{
+ abstract trait Foo extends AnyRef {
+ <stable> <accessor> def a: Int
+ };
+ ()
+}
diff --git a/test/files/run/t6023.scala b/test/files/run/t6023.scala
new file mode 100644
index 0000000000..07af3685a5
--- /dev/null
+++ b/test/files/run/t6023.scala
@@ -0,0 +1,17 @@
+import scala.reflect.runtime.universe._
+import scala.reflect.runtime.{currentMirror => cm}
+import scala.tools.reflect.ToolBox
+
+object Test extends App {
+ // test 1: reify
+ val tree = reify{ trait Foo { val a: Int } }.tree
+ println(tree.toString)
+
+ // test 2: import and typecheck
+ val toolbox = cm.mkToolBox()
+ val ttree = toolbox.typeCheck(tree)
+ println(ttree.toString)
+
+ // test 3: import and compile
+ toolbox.eval(tree)
+}
diff --git a/test/files/run/t6150.scala b/test/files/run/t6150.scala
new file mode 100644
index 0000000000..bd8af5d460
--- /dev/null
+++ b/test/files/run/t6150.scala
@@ -0,0 +1,44 @@
+
+
+
+
+object Test {
+ import collection.{ immutable, mutable, generic }
+ def TheOneTrueCBF = collection.IndexedSeq.ReusableCBF
+
+ val cbf1 = implicitly[generic.CanBuildFrom[immutable.Vector[Int], Int, collection.IndexedSeq[Int]]]
+ val cbf2 = implicitly[generic.CanBuildFrom[immutable.IndexedSeq[Int], Int, collection.IndexedSeq[Int]]]
+ val cbf3 = implicitly[generic.CanBuildFrom[collection.IndexedSeq[Int], Int, collection.IndexedSeq[Int]]]
+
+ val cbf4 = implicitly[generic.CanBuildFrom[immutable.Vector[Int], Int, immutable.IndexedSeq[Int]]]
+ val cbf5 = implicitly[generic.CanBuildFrom[immutable.Vector[Int], Int, immutable.Vector[Int]]]
+ val cbf6 = implicitly[generic.CanBuildFrom[immutable.IndexedSeq[Int], Int, immutable.IndexedSeq[Int]]]
+
+ def check[C](v: C) = {
+ assert(v == Vector(1, 2, 3, 4))
+ assert(v.isInstanceOf[Vector[_]])
+ }
+ def checkRealMccoy(x: AnyRef) = {
+ assert(x eq TheOneTrueCBF, cbf1)
+ }
+
+ val v = immutable.Vector(1, 2, 3)
+ val iiv: immutable.IndexedSeq[Int] = immutable.Vector(1, 2, 3)
+ val iv: IndexedSeq[Int] = immutable.Vector(1, 2, 3)
+
+ def main(args: Array[String]): Unit = {
+ List(cbf1, cbf2, cbf3, cbf4, cbf5, cbf6) foreach checkRealMccoy
+ check(v.:+(4)(cbf1))
+ check(v.:+(4)(cbf2))
+ check(v.:+(4)(cbf3))
+
+ check(iiv.:+(4)(cbf2))
+ check(iiv.:+(4)(cbf3))
+
+ check(iv.:+(4)(cbf3))
+ }
+}
+
+
+
+
diff --git a/test/files/run/t6320.check b/test/files/run/t6320.check
new file mode 100644
index 0000000000..e56bacd223
--- /dev/null
+++ b/test/files/run/t6320.check
@@ -0,0 +1,17 @@
+Type in expressions to have them evaluated.
+Type :help for more information.
+
+scala>
+
+scala> import scala.language.dynamics
+import scala.language.dynamics
+
+scala> class Dyn(m: Map[String, Any]) extends Dynamic { def selectDynamic[T](s: String): T = m(s).asInstanceOf[T] }
+defined class Dyn
+
+scala> new Dyn(Map("foo" -> 10)).foo[Int]
+res0: Int = 10
+
+scala>
+
+scala>
diff --git a/test/files/run/t6320.scala b/test/files/run/t6320.scala
new file mode 100644
index 0000000000..26085a3d7d
--- /dev/null
+++ b/test/files/run/t6320.scala
@@ -0,0 +1,9 @@
+import scala.tools.partest.ReplTest
+
+object Test extends ReplTest {
+ def code = """
+import scala.language.dynamics
+class Dyn(m: Map[String, Any]) extends Dynamic { def selectDynamic[T](s: String): T = m(s).asInstanceOf[T] }
+new Dyn(Map("foo" -> 10)).foo[Int]
+ """
+}
diff --git a/test/files/run/t6488.check b/test/files/run/t6488.check
new file mode 100644
index 0000000000..35821117c8
--- /dev/null
+++ b/test/files/run/t6488.check
@@ -0,0 +1 @@
+Success
diff --git a/test/files/run/t6488.scala b/test/files/run/t6488.scala
new file mode 100644
index 0000000000..487614ecfd
--- /dev/null
+++ b/test/files/run/t6488.scala
@@ -0,0 +1,11 @@
+import sys.process._
+object Test {
+ // Program that prints "Success" if the command was successfully run then destroyed
+ // It will silently pass if the command "/bin/ls" does not exist
+ // It will fail due to the uncatchable exception in t6488 race condition
+ def main(args: Array[String]) {
+ try Process("/bin/ls").run(ProcessLogger { _ => () }).destroy
+ catch { case _ => () }
+ println("Success")
+ }
+}
diff --git a/test/files/run/t6632.check b/test/files/run/t6632.check
new file mode 100644
index 0000000000..1f084b1dac
--- /dev/null
+++ b/test/files/run/t6632.check
@@ -0,0 +1,3 @@
+java.lang.IndexOutOfBoundsException: -1
+java.lang.IndexOutOfBoundsException: -2
+java.lang.IndexOutOfBoundsException: -3
diff --git a/test/files/run/t6632.scala b/test/files/run/t6632.scala
new file mode 100644
index 0000000000..c1c8d4abe0
--- /dev/null
+++ b/test/files/run/t6632.scala
@@ -0,0 +1,29 @@
+object Test extends App {
+ import collection.mutable.ListBuffer
+
+ def newLB = ListBuffer('a, 'b, 'c, 'd, 'e)
+
+ val lb0 = newLB
+
+ try {
+ lb0.insert(-1, 'x)
+ } catch {
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+
+ val lb1 = newLB
+
+ try {
+ lb1.insertAll(-2, Array('x, 'y, 'z))
+ } catch {
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+
+ val lb2 = newLB
+
+ try {
+ lb2.update(-3, 'u)
+ } catch {
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+} \ No newline at end of file
diff --git a/test/files/run/t6633.check b/test/files/run/t6633.check
new file mode 100644
index 0000000000..1ff8cdbc44
--- /dev/null
+++ b/test/files/run/t6633.check
@@ -0,0 +1,3 @@
+java.lang.IndexOutOfBoundsException: 9
+replStringOf OK
+length OK
diff --git a/test/files/run/t6633.scala b/test/files/run/t6633.scala
new file mode 100644
index 0000000000..bd993c8d88
--- /dev/null
+++ b/test/files/run/t6633.scala
@@ -0,0 +1,33 @@
+object Test extends App {
+ import collection.mutable.ListBuffer
+
+ def newLB = ListBuffer('a, 'b, 'c, 'd, 'e)
+
+ val lb0 = newLB
+
+ try {
+ lb0.insert(9, 'x)
+ } catch {
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+
+ val lb1 = newLB
+
+ try {
+ lb1.insert(9, 'x)
+ } catch {
+ case ex: IndexOutOfBoundsException =>
+ }
+
+ val replStr = scala.runtime.ScalaRunTime.replStringOf(lb1, 100)
+ if (replStr == "ListBuffer('a, 'b, 'c, 'd, 'e)\n")
+ println("replStringOf OK")
+ else
+ println("replStringOf FAILED: " + replStr)
+
+ val len = lb1.length
+ if (len == 5)
+ println("length OK")
+ else
+ println("length FAILED: " + len)
+} \ No newline at end of file
diff --git a/test/files/run/t6634.check b/test/files/run/t6634.check
new file mode 100644
index 0000000000..f6cbb30c67
--- /dev/null
+++ b/test/files/run/t6634.check
@@ -0,0 +1,31 @@
+Trying lb0 ...
+Checking ...
+String OK.
+Length OK.
+
+Trying lb1 ...
+Checking ...
+String OK.
+Length OK.
+
+Trying lb2 ...
+Checking ...
+String OK.
+Length OK.
+
+Trying lb3 ...
+Checking ...
+String OK.
+Length OK.
+
+Trying lb4 ...
+Checking ...
+String OK.
+Length OK.
+
+Trying lb5 ...
+java.lang.IllegalArgumentException: removing negative number (-1) of elements
+Checking ...
+String OK.
+Length OK.
+
diff --git a/test/files/run/t6634.scala b/test/files/run/t6634.scala
new file mode 100644
index 0000000000..759e6d519d
--- /dev/null
+++ b/test/files/run/t6634.scala
@@ -0,0 +1,80 @@
+import collection.mutable.ListBuffer
+
+object Test extends App {
+ def newLB = ListBuffer('a, 'b, 'c, 'd, 'e)
+
+ val lb0 = newLB
+ println("Trying lb0 ...")
+ try {
+ lb0.remove(5, 0)
+ } catch {
+ // Not thrown in 2.10, will be thrown in 2.11
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+ checkNotCorrupted(lb0)
+
+ val lb1 = newLB
+ println("Trying lb1 ...")
+ try {
+ lb1.remove(6, 6)
+ } catch {
+ // Not thrown in 2.10, will be thrown in 2.11
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+ checkNotCorrupted(lb1)
+
+ val lb2 = newLB
+ println("Trying lb2 ...")
+ try {
+ lb2.remove(99, 6)
+ } catch {
+ // Not thrown in 2.10, will be thrown in 2.11
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+ checkNotCorrupted(lb2)
+
+ val lb3 = newLB
+ println("Trying lb3 ...")
+ try {
+ lb3.remove(1, 9)
+ } catch {
+ // Not thrown in 2.10, will be thrown in 2.11
+ case ex: IllegalArgumentException => println(ex)
+ }
+ checkNotCorrupted(lb3, "ListBuffer('a)", 1)
+
+ val lb4 = newLB
+ println("Trying lb4 ...")
+ try {
+ lb4.remove(-1, 1)
+ } catch {
+ // Not thrown in 2.10, will be thrown in 2.11
+ case ex: IndexOutOfBoundsException => println(ex)
+ }
+ checkNotCorrupted(lb4, "ListBuffer('b, 'c, 'd, 'e)", 4)
+
+ val lb5 = newLB
+ println("Trying lb5 ...")
+ try {
+ lb5.remove(1, -1)
+ } catch {
+ case ex: IllegalArgumentException => println(ex)
+ }
+ checkNotCorrupted(lb5)
+
+ // buffer should neither be changed nor corrupted after calling remove with invalid arguments
+ def checkNotCorrupted(
+ lb: ListBuffer[Symbol],
+ expectedString: String = "ListBuffer('a, 'b, 'c, 'd, 'e)",
+ expectedLength: Int = 5) = {
+ println("Checking ...")
+ val replStr = scala.runtime.ScalaRunTime.replStringOf(lb, 100)
+ if (replStr == expectedString + "\n") println("String OK.")
+ else println("!!! replStringOf FAILED: " + replStr)
+
+ val len = lb.length
+ if (len == expectedLength) println("Length OK.")
+ else println("!!! length FAILED: " + len)
+ println()
+ }
+} \ No newline at end of file
diff --git a/test/files/run/t6662.check b/test/files/run/t6662.check
new file mode 100644
index 0000000000..6a452c185a
--- /dev/null
+++ b/test/files/run/t6662.check
@@ -0,0 +1 @@
+()
diff --git a/test/files/run/t6662/Macro_1.scala b/test/files/run/t6662/Macro_1.scala
new file mode 100644
index 0000000000..f373eaaf94
--- /dev/null
+++ b/test/files/run/t6662/Macro_1.scala
@@ -0,0 +1,8 @@
+import language.experimental.macros
+import scala.reflect.macros.Context
+
+object Demo {
+ def id[T](a: T): T = macro idImpl[T]
+
+ def idImpl[T: c.WeakTypeTag](c: Context)(a: c.Expr[T]): c.Expr[T] = a
+}
diff --git a/test/files/run/t6662/Test_2.scala b/test/files/run/t6662/Test_2.scala
new file mode 100644
index 0000000000..03a80b655a
--- /dev/null
+++ b/test/files/run/t6662/Test_2.scala
@@ -0,0 +1,8 @@
+// Macro usage:
+
+object Test {
+ def main(args: Array[String]) {
+ val s = Demo id ()
+ println(s)
+ }
+}
diff --git a/test/files/run/t6663.check b/test/files/run/t6663.check
new file mode 100644
index 0000000000..d81cc0710e
--- /dev/null
+++ b/test/files/run/t6663.check
@@ -0,0 +1 @@
+42
diff --git a/test/files/run/t6663.scala b/test/files/run/t6663.scala
new file mode 100644
index 0000000000..6818d286d9
--- /dev/null
+++ b/test/files/run/t6663.scala
@@ -0,0 +1,17 @@
+import language.dynamics
+
+class C(v: Any) extends Dynamic {
+ def selectDynamic[T](n: String): Option[T] = Option(v.asInstanceOf[T])
+ def applyDynamic[T](n: String)(): Option[T] = Option(v.asInstanceOf[T])
+}
+
+object Test extends App {
+ // this should be converted to
+ // C(42).selectDynamic[Int]("foo").get
+ // but, before fixing SI-6663, became
+ // C(42).selectDynamic[Nothing]("foo").get
+ // leading to a ClassCastException
+ var v = new C(42).foo[Int].get
+ println(v)
+}
+
diff --git a/test/files/run/t6673.check b/test/files/run/t6673.check
new file mode 100644
index 0000000000..ef2aa551dc
--- /dev/null
+++ b/test/files/run/t6673.check
@@ -0,0 +1 @@
+List(x)
diff --git a/test/files/run/t6673.scala b/test/files/run/t6673.scala
new file mode 100644
index 0000000000..115bbdf234
--- /dev/null
+++ b/test/files/run/t6673.scala
@@ -0,0 +1,5 @@
+object Test extends App {
+ def foo(f: String => Array[String])(s: String) = f(s)
+ val test = foo(Array(_)) _
+ println(test("x").toList)
+} \ No newline at end of file
diff --git a/test/files/run/t6677.scala b/test/files/run/t6677.scala
new file mode 100644
index 0000000000..e6eaf6a498
--- /dev/null
+++ b/test/files/run/t6677.scala
@@ -0,0 +1,28 @@
+
+class Test {
+ val cm: reflect.runtime.universe.Mirror = reflect.runtime.currentMirror
+ def error {
+ new cm.universe.Traverser // java.lang.VerifyError: (class: Test, method: error signature: ()V) Incompatible object argument for function call
+
+ }
+
+ def okay1 {
+ val cm: reflect.runtime.universe.Mirror = reflect.runtime.currentMirror
+
+ new cm.universe.Traverser
+ }
+
+ def okay2 {
+ val cm: reflect.runtime.universe.Mirror = reflect.runtime.currentMirror
+ val u: reflect.runtime.universe.type = cm.universe
+ new u.Traverser
+ }
+}
+
+object Test {
+ def main(args: Array[String]) {
+ new Test().error
+ new Test().okay1
+ new Test().okay2
+ }
+}
diff --git a/test/files/run/t6677b.scala b/test/files/run/t6677b.scala
new file mode 100644
index 0000000000..e4fe5e3722
--- /dev/null
+++ b/test/files/run/t6677b.scala
@@ -0,0 +1,33 @@
+trait U {
+ trait U1 {
+ class X
+ }
+ type U11 <: U1
+ val u : U11 = null.asInstanceOf[U11]
+}
+trait A extends U
+
+trait B extends U {
+ def foo = ""
+ class U11 extends U1 { class X extends super.X { foo } } // refer to foo to add $outer pointer
+ override val u = new U11
+}
+class C {
+ val ab: A with B = new A with B // `B with A` works.
+
+ def foo {
+ // fails
+ new ab.u.X
+
+ // works:
+ val u = ab.u
+ new u.X
+ }
+}
+object Test {
+ def main(args: Array[String]) {
+ // java.lang.NoSuchMethodError: A.u()LB$U11;
+ // at C.foo(t6677b.scala:23)
+ new C().foo
+ }
+}
diff --git a/test/files/run/t6687.scala b/test/files/run/t6687.scala
new file mode 100644
index 0000000000..ee44e5f0d2
--- /dev/null
+++ b/test/files/run/t6687.scala
@@ -0,0 +1,10 @@
+import scala.reflect.runtime.universe._
+
+class A { lazy val x = 1 }
+
+object Test {
+ def main(args: Array[String]): Unit = {
+ val vars = typeOf[A].members.toList filter (x => x.isTerm && x.asTerm.isVar)
+ assert(vars.isEmpty, vars)
+ }
+}
diff --git a/test/files/run/t6695.scala b/test/files/run/t6695.scala
new file mode 100644
index 0000000000..b527238a51
--- /dev/null
+++ b/test/files/run/t6695.scala
@@ -0,0 +1,18 @@
+object Test extends App {
+ try {
+ Array("a", "b", "c") match {
+ case Array("a", "x", "c") => println("x")
+ case Array("a", "b", "x") => println("a");
+ case Array("a", "d", _*) => println("wrongly positive")
+ }
+ assert(false, "match succeeded")
+ } catch {
+ case _: MatchError => // okay
+ }
+
+ Array("a", "b", "c") match {
+ case Array("a", "x", "c") => println("x")
+ case Array("a", "b", "x") => println("a");
+ case Array("a", "b", _*) => // okay
+ }
+}
diff --git a/test/files/run/t6706.scala b/test/files/run/t6706.scala
new file mode 100644
index 0000000000..905494ca8d
--- /dev/null
+++ b/test/files/run/t6706.scala
@@ -0,0 +1,14 @@
+object Test {
+ var name = "foo" + 1
+ var s1 = Symbol(name)
+ s1 = null
+ System.gc
+ val s2 = Symbol("foo1")
+ name = null
+ System.gc
+ val s3 = Symbol("foo1")
+
+ def main(args: Array[String]): Unit = {
+ assert(s2 eq s3, ((s2, System.identityHashCode(s2), s3, System.identityHashCode(s3))))
+ }
+}
diff --git a/test/files/run/t6731.check b/test/files/run/t6731.check
new file mode 100644
index 0000000000..a5d59bd378
--- /dev/null
+++ b/test/files/run/t6731.check
@@ -0,0 +1,40 @@
+Mono$.bar()
+Mono$.bar
+Mono$.bar()
+Mono$.bar
+Mono$.bar
+Mono$.baz
+Mono$.bar(bippy=1, boppy=2)
+Mono$.baz
+Poly.bar[Nothing]
+Poly.bar[Int]
+Poly.bar[Nothing]()
+Poly.bar[Int]()
+Poly.bar[Int](1, 2, 3)
+Poly.bar[Nothing]
+Poly.bar[Int]
+Poly.bar[Nothing]()
+Poly.bar[Int]()
+Poly.bar[Int](1, 2, 3)
+Updating.bar
+Updating.bar = b
+Nest1$Nest2$Nest3$.bippy(1, 2, 3)
+Nest1$Nest2$Nest3$.bippy
+Named.bippy(a=1, b=2)
+Named.boppy(c=3, d=4)
+Named.apply()
+Named.apply()
+Named.apply(e=5, f=6)
+Named2.bippy(1)(q0, c)
+Named2.bippy(1)(q0, c)
+Named2.bippy(1)(b, q0)
+Named2.bippy(1)(q0, c)
+Named2.bippy(1)(c, b)
+Named2.bippy(1)(b, c)
+Named2.bippy(1)(q0, c)
+Named2.bippy(2)(b, c)
+Named2.bippy(1)(q0, c)
+Named2.bippy(5)(b, c)
+Named2.dingus(100)(b, dong)
+Named2.bippy(1)(q0, q1)
+Named2.hello(100)(!!, !!)
diff --git a/test/files/run/t6731.scala b/test/files/run/t6731.scala
new file mode 100644
index 0000000000..89d212e91e
--- /dev/null
+++ b/test/files/run/t6731.scala
@@ -0,0 +1,143 @@
+import scala.language.dynamics
+import scala.reflect.{ ClassTag, classTag }
+
+object Util {
+ def show[T](x: T): T = { println(x) ; x }
+ def mkArgs(xs: Any*) = xs map { case ((k, v)) => k + "=" + v ; case x => "" + x } mkString ("(", ", ", ")")
+}
+import Util._
+
+abstract class MonoDynamic extends Dynamic {
+ def selectDynamic(name: String): String = show(this + "." + name)
+ def applyDynamic(name: String)(args: Any*): String = show(this + "." + name + mkArgs(args: _*))
+ def applyDynamicNamed(name: String)(args: (String, Any)*): String = show(this + "." + name + mkArgs(args: _*))
+
+ override def toString = this.getClass.getName split '.' last
+}
+
+object Mono extends MonoDynamic {
+ def f(s: String): String = s
+
+ def f1 = this.bar()
+ def f2 = this.bar
+ def f3 = f(this.bar())
+ def f4 = f(this.bar)
+ def f5 = f(f(f(f(f(f(this.bar)))))) + f(f(f(f(f(f(this.baz))))))
+ def f6 = f(f(f(f(f(f(this.bar(bippy = 1, boppy = 2))))))) + f(f(f(f(f(f(this.baz))))))
+}
+
+object Poly extends Dynamic {
+ def selectDynamic[T: ClassTag](name: String): String = show(s"$this.$name[${classTag[T]}]")
+ def applyDynamic[T: ClassTag](name: String)(args: Any*): String = show(args.mkString(s"$this.$name[${classTag[T]}](", ", ", ")"))
+
+ def f(s: String): String = s
+
+ def f1 = this.bar
+ def f2 = this.bar[Int]
+ def f3 = this.bar()
+ def f4 = this.bar[Int]()
+ def f5 = this.bar[Int](1, 2, 3)
+
+ def f6 = f(f(this.bar))
+ def f7 = f(f(this.bar[Int]))
+ def f8 = f(f(this.bar()))
+ def f9 = f(f(this.bar[Int]()))
+ def f10 = f(f(this.bar[Int](1, 2, 3)))
+
+ override def toString = "Poly"
+}
+
+object Updating extends Dynamic {
+ def selectDynamic(name: String): String = show(s"$this.$name")
+ def updateDynamic(name: String)(value: Any): String = show(s"$this.$name = $value")
+
+ def f1 = this.bar
+ def f2 = this.bar = "b"
+
+ override def toString = "Updating"
+}
+
+object Nest1 extends Dynamic {
+ def applyDynamic(name: String)(args: Any*): Nest2.type = Nest2
+
+ object Nest2 extends Dynamic {
+ def applyDynamicNamed(name: String)(args: (String, Any)*): Nest3.type = Nest3
+
+ object Nest3 extends MonoDynamic {
+
+ }
+ }
+
+ def f1 = Nest1.bip().bop(foo = "bar").bippy(1, 2, 3)
+ def f2 = Nest1.bip("abc").bop(foo = 5).bippy
+}
+
+object Named extends Dynamic {
+ def applyDynamic(name: String)(args: Any*): Named.type = {
+ show(this + "." + name + mkArgs(args: _*))
+ this
+ }
+ def applyDynamicNamed(name: String)(args: (String, Any)*): Named.type = {
+ show(this + "." + name + mkArgs(args: _*))
+ this
+ }
+
+ def f1 = this.bippy(a = 1, b = 2).boppy(c = 3, d = 4)()()(e = 5, f = 6)
+ override def toString = "Named"
+}
+
+object Named2 extends Dynamic {
+ def applyDynamic(name: String)(a: Any)(b: Any = "b", c: Any = "c"): Named2.type = {
+ show(this + "." + name + mkArgs(a) + mkArgs(b, c))
+ this
+ }
+ def applyDynamicNamed(name: String)(a: (String, Any))(b: (String, Any), c: (String, Any)): Named2.type = {
+ show(this + "." + name + mkArgs(a) + mkArgs(b, c))
+ this
+ }
+
+ def f1 = this.bippy(1)(b = "q0")
+ def f2 = this.bippy(1)("q0")
+ def f3 = this.bippy(1)(c = "q0")
+ def f4 = this.bippy(1)("q0")
+ def f5 = this.bippy(1)(c = "b", b = "c")
+ def f6 = this.bippy(1)("b", "c")
+ def f7 = this.bippy(1)(b = "q0").bippy(2)()
+ def f8 = this.bippy(1)("q0").bippy(5)(c = "c").dingus(100)(c = "dong")
+ def f9 = this.bippy(1)(b = "q0", c = "q1").hello(100)("!!", "!!")
+
+ override def toString = "Named2"
+}
+
+
+object Test {
+ def main(args: Array[String]): Unit = {
+ {
+ import Mono._
+ f1 ; f2 ; f3 ; f4 ; f5
+ f6
+ }
+ {
+ import Poly._
+ f1 ; f2 ; f3 ; f4 ; f5
+ f6 ; f7 ; f8 ; f9 ; f10
+ }
+ {
+ import Updating._
+ f1 ; f2
+ }
+ {
+ import Nest1._
+ f1 ; f2
+ }
+ {
+ import Named._
+ f1
+ }
+ {
+ import Named2._
+ f1 ; f2 ; f3 ; f4 ; f5
+ f6 ; f7 ; f8 ; f9
+ }
+ }
+}
diff --git a/test/scaladoc/run/SI-191-deprecated.check b/test/scaladoc/run/SI-191-deprecated.check
new file mode 100755
index 0000000000..3925a0d464
--- /dev/null
+++ b/test/scaladoc/run/SI-191-deprecated.check
@@ -0,0 +1 @@
+Done. \ No newline at end of file
diff --git a/test/scaladoc/run/SI-191-deprecated.scala b/test/scaladoc/run/SI-191-deprecated.scala
new file mode 100755
index 0000000000..746aa9c598
--- /dev/null
+++ b/test/scaladoc/run/SI-191-deprecated.scala
@@ -0,0 +1,71 @@
+import scala.tools.nsc.doc.model._
+import scala.tools.nsc.doc.model.comment._
+import scala.tools.partest.ScaladocModelTest
+import java.net.{URI, URL}
+import java.io.File
+
+object Test extends ScaladocModelTest {
+
+ override def code =
+ """
+ /** See:
+ * - [[scala.collection.Map]] Simple linking
+ * - [[scala.collection.immutable.::]] Linking with symbolic name
+ * - [[scala.Int]].toLong Linking to a class
+ * - [[scala.Predef]] Linking to an object
+ * - [[scala.Int.toLong]] Linking to a method
+ * - [[scala]] Linking to a package
+ * - [[scala.AbstractMethodError]] Linking to a member in the package object
+ * - [[scala.Predef.String]] Linking to a member in an object
+ *
+ * Don't look at:
+ * - [[scala.NoLink]] Not linking :)
+ */
+ object Test {
+ def foo(param: Any) {}
+ def barr(l: scala.collection.immutable.List[Any]) {}
+ def bar(l: List[String]) {} // TODO: Should be able to link to type aliases
+ def baz(d: java.util.Date) {} // Should not be resolved
+ }
+ """
+
+ def scalaURL = "http://bog.us"
+
+ override def scaladocSettings = "-no-link-warnings -external-urls scala=" + scalaURL
+
+ def testModel(rootPackage: Package) {
+ import access._
+ val test = rootPackage._object("Test")
+
+ def check(memberDef: Def, expected: Int) {
+ val externals = memberDef.valueParams(0)(0).resultType.refEntity collect {
+ case (_, (LinkToExternal(name, url), _)) => assert(url.contains(scalaURL)); name
+ }
+ assert(externals.size == expected)
+ }
+
+ check(test._method("foo"), 1)
+ check(test._method("bar"), 0)
+ check(test._method("barr"), 2)
+ check(test._method("baz"), 0)
+
+ val expectedUrls = collection.mutable.Set[String](
+ "scala.collection.Map",
+ "scala.collection.immutable.::",
+ "scala.Int",
+ "scala.Predef$",
+ "scala.Int@toLong:Long",
+ "scala.package",
+ "scala.package@AbstractMethodError=AbstractMethodError",
+ "scala.Predef$@String=String"
+ ).map(scalaURL + "/index.html#" + _)
+
+ def isExpectedExternalLink(l: EntityLink) = l.link match {
+ case LinkToExternal(name, url) => assert(expectedUrls contains url, url); true
+ case _ => false
+ }
+
+ assert(countLinks(test.comment.get, isExpectedExternalLink) == 8,
+ countLinks(test.comment.get, isExpectedExternalLink) + " == 8")
+ }
+}
diff --git a/test/scaladoc/run/SI-191.check b/test/scaladoc/run/SI-191.check
new file mode 100755
index 0000000000..3925a0d464
--- /dev/null
+++ b/test/scaladoc/run/SI-191.check
@@ -0,0 +1 @@
+Done. \ No newline at end of file
diff --git a/test/scaladoc/run/SI-191.scala b/test/scaladoc/run/SI-191.scala
new file mode 100755
index 0000000000..0fb28145c3
--- /dev/null
+++ b/test/scaladoc/run/SI-191.scala
@@ -0,0 +1,76 @@
+import scala.tools.nsc.doc.model._
+import scala.tools.nsc.doc.model.comment._
+import scala.tools.partest.ScaladocModelTest
+import java.net.{URI, URL}
+import java.io.File
+
+object Test extends ScaladocModelTest {
+
+ override def code =
+ """
+ /** See:
+ * - [[scala.collection.Map]] Simple linking
+ * - [[scala.collection.immutable.::]] Linking with symbolic name
+ * - [[scala.Int]].toLong Linking to a class
+ * - [[scala.Predef]] Linking to an object
+ * - [[scala.Int.toLong]] Linking to a method
+ * - [[scala]] Linking to a package
+ * - [[scala.AbstractMethodError]] Linking to a member in the package object
+ * - [[scala.Predef.String]] Linking to a member in an object
+ *
+ * Don't look at:
+ * - [[scala.NoLink]] Not linking :)
+ */
+ object Test {
+ def foo(param: Any) {}
+ def barr(l: scala.collection.immutable.List[Any]) {}
+ def bar(l: List[String]) {} // TODO: Should be able to link to type aliases
+ def baz(d: java.util.Date) {} // Should not be resolved
+ }
+ """
+
+ def scalaURL = "http://bog.us"
+
+ override def scaladocSettings = {
+ val scalaLibUri = getClass.getClassLoader.getResource("scala/Function1.class").toURI.getSchemeSpecificPart.split("!")(0)
+ val scalaLib = new File(new URL(scalaLibUri).getPath).getPath
+ val extArg = new URI("file", scalaLib, scalaURL).toString
+ "-no-link-warnings -doc-external-uris " + extArg
+ }
+
+ def testModel(rootPackage: Package) {
+ import access._
+ val test = rootPackage._object("Test")
+
+ def check(memberDef: Def, expected: Int) {
+ val externals = memberDef.valueParams(0)(0).resultType.refEntity collect {
+ case (_, (LinkToExternal(name, url), _)) => assert(url.contains(scalaURL)); name
+ }
+ assert(externals.size == expected)
+ }
+
+ check(test._method("foo"), 1)
+ check(test._method("bar"), 0)
+ check(test._method("barr"), 2)
+ check(test._method("baz"), 0)
+
+ val expectedUrls = collection.mutable.Set[String](
+ "scala.collection.Map",
+ "scala.collection.immutable.::",
+ "scala.Int",
+ "scala.Predef$",
+ "scala.Int@toLong:Long",
+ "scala.package",
+ "scala.package@AbstractMethodError=AbstractMethodError",
+ "scala.Predef$@String=String"
+ ).map(scalaURL + "/index.html#" + _)
+
+ def isExpectedExternalLink(l: EntityLink) = l.link match {
+ case LinkToExternal(name, url) => assert(expectedUrls contains url, url); true
+ case _ => false
+ }
+
+ assert(countLinks(test.comment.get, isExpectedExternalLink) == 8,
+ countLinks(test.comment.get, isExpectedExternalLink) + " == 8")
+ }
+}