summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAntonio Cunei <antonio.cunei@epfl.ch>2011-05-02 10:18:52 +0000
committerAntonio Cunei <antonio.cunei@epfl.ch>2011-05-02 10:18:52 +0000
commitcb6a345a2f35f2f85832c9bf2f509c6f98a40d01 (patch)
treede8db551cbe7fd2d89c4885d670ac896f9d1c3dc
parent960edcd25172b6cc98b573379ef8d4cc960ddec2 (diff)
downloadscala-cb6a345a2f35f2f85832c9bf2f509c6f98a40d01.tar.gz
scala-cb6a345a2f35f2f85832c9bf2f509c6f98a40d01.tar.bz2
scala-cb6a345a2f35f2f85832c9bf2f509c6f98a40d01.zip
Merged revisions 24830-24831,24834-24862 via sv...
Merged revisions 24830-24831,24834-24862 via svnmerge from https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk ........ r24830 | extempore | 2011-04-26 21:00:24 +0200 (Tue, 26 Apr 2011) | 1 line Some solid progress on the pattern matcher, no review. ........ r24831 | odersky | 2011-04-27 12:26:39 +0200 (Wed, 27 Apr 2011) | 1 line More bridges in collections. Review by prokopec. ........ r24834 | extempore | 2011-04-27 20:35:47 +0200 (Wed, 27 Apr 2011) | 1 line Fixed inversion of fsc's exit code, closes #4519 no review. ........ r24835 | extempore | 2011-04-27 20:36:04 +0200 (Wed, 27 Apr 2011) | 2 lines Fixed a booch I made in io.Position's positioning. Closes #4498, no review. ........ r24836 | extempore | 2011-04-27 20:36:16 +0200 (Wed, 27 Apr 2011) | 1 line A little cleanup on a repl command, no review. ........ r24837 | extempore | 2011-04-27 20:36:32 +0200 (Wed, 27 Apr 2011) | 5 lines Trying to fix the pattern matcher took me into the lambda lifter, and I made some changes which seemed sensible to me. I'm going to be a stickler about eliminating mutable maps which hold mutable listbuffers. I could use some confirmation that I didn't somehow break the world: review by dragos. ........ r24838 | extempore | 2011-04-27 20:36:47 +0200 (Wed, 27 Apr 2011) | 4 lines Trying out a different strategy for restoring terminal settings so we don't have a list of hardcoded terminal types. Now it saves the terminal settings on script start and restores those on exit. Closes #4170, review by rytz. ........ r24839 | extempore | 2011-04-28 01:49:27 +0200 (Thu, 28 Apr 2011) | 1 line Cleaned up some hopelessly atrophied documentation, no review. ........ r24840 | extempore | 2011-04-28 03:10:22 +0200 (Thu, 28 Apr 2011) | 4 lines Upgraded -d so you can output classes directly to a jar. Very (very) loosely based on a patch from dmharrah. Like dmharrah before me, I see little if any change in compile times, which I find difficult to explain. Closes #27, review by dmharrah. ........ r24841 | extempore | 2011-04-28 17:12:42 +0200 (Thu, 28 Apr 2011) | 5 lines Improvements to the AST browser contributed by Yuvi Masory. Uses Nimbus LAF when available and improves readability by padding components. Adds menu items and key bindings for expanding and contracting nodes, closing the browser and continuing compilation, and closing the browser and aborting. No review. ........ r24842 | extempore | 2011-04-28 18:23:45 +0200 (Thu, 28 Apr 2011) | 15 lines Improved the error message for another of the most common situations I hear about in newbieland. It could be taken further. If compilation fails due to an unimplemented abstract method, and there is a concrete method of the same name and arity, it will do a pairwise analysis of the parameters and attempt to further explain where you went off the beam if it feels it can do so sensibly. Such as in the test case: % scalac S.scala S.scala:1: error: class S needs to be abstract, since method g in class J of type (y: Int,z: java.util.List)Int is not defined (Note that java.util.List does not match java.util.List[String]. To implement a raw type, use java.util.List[_]) class S extends J { ^ one error found No review. ........ r24843 | extempore | 2011-04-28 18:26:05 +0200 (Thu, 28 Apr 2011) | 11 lines I wrote a warning when nullary methods return Unit. I wimped out of including it in this patch because we had about 200 of them, and that's what is fixed in this patch. I will add the warning to some kind of "-Xlint" feature after 2.9. This is motivated at least partly by the resolution of #4506, which indicates the distinction between "def foo()" and "def foo" will continue to jab its pointy stick into our eyes, so I believe we have a minimal duty of at least following our own advice about what they mean and not making a semirandom choice as to whether a method has parens or not. Review by community. ........ r24844 | odersky | 2011-04-29 13:07:56 +0200 (Fri, 29 Apr 2011) | 1 line Fixes #4525. No review. ........ r24845 | plocinic | 2011-04-29 16:27:35 +0200 (Fri, 29 Apr 2011) | 1 line remove now redundant check (see #4426). review by extempore ........ r24846 | plocinic | 2011-04-29 16:27:40 +0200 (Fri, 29 Apr 2011) | 1 line Closes #4457. Review by odersky ........ r24847 | odersky | 2011-04-29 17:35:37 +0200 (Fri, 29 Apr 2011) | 1 line Ignore type errors raised in later phases that are due to mismatching existentials. Quick fix to address lift build failures. Review by dragos. ........ r24848 | odersky | 2011-04-29 18:02:53 +0200 (Fri, 29 Apr 2011) | 1 line Second version of trying to avoid the lift crasher bug. ........ r24849 | odersky | 2011-04-29 18:13:31 +0200 (Fri, 29 Apr 2011) | 1 line Issuing warnings with detailed info when we encounter the lift crasher case. ........ r24850 | michelou | 2011-04-29 21:41:12 +0200 (Fri, 29 Apr 2011) | 2 lines removed legacy library code (package scala.mobile) ........ r24851 | extempore | 2011-04-29 22:13:10 +0200 (Fri, 29 Apr 2011) | 4 lines Fixing the pattern matcher regression I introduced between rc1 and rc2. Not done with this situation but at least I managed to boil out the big problem and keep my five closed pattern matcher tickets to boot. Closes #4523, no review. ........ r24852 | extempore | 2011-04-30 00:40:03 +0200 (Sat, 30 Apr 2011) | 1 line Making further unapply regressions less likely, no review. ........ r24853 | extempore | 2011-04-30 22:00:39 +0200 (Sat, 30 Apr 2011) | 3 lines After having to update the code for someone else, ran damarau levenshtein on trunk again. Patchwise, I guess correcting spelling errors in comments is about as safe as it gets. No review. ........ r24854 | extempore | 2011-04-30 22:01:00 +0200 (Sat, 30 Apr 2011) | 1 line Don't crash the pickler with erroneous types. Review by odersky. ........ r24855 | extempore | 2011-04-30 22:01:25 +0200 (Sat, 30 Apr 2011) | 4 lines Completely to my surprise, found that fixing all those sequence issues revealed that the pattern matcher can catch a lot more inexhaustive cases than it has been catching. Fixed most of the inexhaustive matches in the compiler, which had become a bit warnier. No review. ........ r24856 | extempore | 2011-04-30 22:01:48 +0200 (Sat, 30 Apr 2011) | 2 lines A few minor cleanups involving logging messages, assertion messages, compiler warnings, and other innocuous matters. No review. ........ r24857 | extempore | 2011-05-01 07:10:09 +0200 (Sun, 01 May 2011) | 2 lines Don't issue a deprecation warning if the deprecated method is being called from a bridge method. No review. ........ r24858 | extempore | 2011-05-01 07:10:58 +0200 (Sun, 01 May 2011) | 4 lines Since I don't want to commit anything "interesting" until we ship 2.9, a few uninteresting cleanups involving how types are printed, getting some debugging code in shape to prepare for the long winter ahead, etc. No review. ........ r24859 | extempore | 2011-05-01 07:43:05 +0200 (Sun, 01 May 2011) | 2 lines Realized how noisy the @deprecated-takes-two-arguments message was and quieted it down. Oh, and documented the arguments. No review. ........ r24860 | extempore | 2011-05-01 20:15:49 +0200 (Sun, 01 May 2011) | 7 lines Reducing the sbt launcher footprint by eliminating val references which go through the scala package object, since they lead to otherwise unnecessary classes becoming required at startup. Mostly this means library files with constructors like "Iterator.empty" or "Stream.continually" receive a direct import of that companion. The one slightly less than cosmetic change was moving the strange xml value "$scope" back into Predef, because otherwise I have to touch the xml code generation. No review. ........ r24861 | extempore | 2011-05-01 21:58:44 +0200 (Sun, 01 May 2011) | 2 lines Added a @bridge'd $scope back to scala package object for binary compat. No review. ........ r24862 | extempore | 2011-05-02 05:28:58 +0200 (Mon, 02 May 2011) | 4 lines Figuring it couldn't hurt if more people had a command of some of our binary compatibility impacting code, I went over the ModuleDef elimination with my clarify stick and made the machinery more transparent, to me anyway. Review by plocinic. ........
-rw-r--r--docs/examples/mobile/sort.scala17
-rw-r--r--src/actors/scala/actors/Actor.scala4
-rw-r--r--src/actors/scala/actors/Combinators.scala2
-rw-r--r--src/actors/scala/actors/IScheduler.scala2
-rw-r--r--src/actors/scala/actors/remote/TcpService.scala4
-rw-r--r--src/attic/scala/tools/nsc/models/SemanticTokens.scala4
-rw-r--r--src/compiler/scala/tools/ant/FastScalac.scala2
-rw-r--r--src/compiler/scala/tools/ant/Same.scala2
-rw-r--r--src/compiler/scala/tools/ant/sabbus/Break.scala2
-rw-r--r--src/compiler/scala/tools/ant/sabbus/Make.scala2
-rw-r--r--src/compiler/scala/tools/ant/templates/tool-unix.tmpl40
-rw-r--r--src/compiler/scala/tools/nsc/CompileClient.scala9
-rw-r--r--src/compiler/scala/tools/nsc/Global.scala22
-rw-r--r--src/compiler/scala/tools/nsc/NoPhase.scala2
-rw-r--r--src/compiler/scala/tools/nsc/Phase.scala2
-rw-r--r--src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala126
-rw-r--r--src/compiler/scala/tools/nsc/ast/TreeGen.scala26
-rw-r--r--src/compiler/scala/tools/nsc/ast/TreePrinters.scala8
-rw-r--r--src/compiler/scala/tools/nsc/ast/Trees.scala13
-rw-r--r--src/compiler/scala/tools/nsc/ast/parser/Parsers.scala6
-rw-r--r--src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala11
-rw-r--r--src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala14
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/GenICode.scala20
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala8
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/ICodes.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/Members.scala10
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/Printers.scala6
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala2
-rw-r--r--src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala4
-rw-r--r--src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala92
-rw-r--r--src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala109
-rw-r--r--src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala8
-rw-r--r--src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala2
-rw-r--r--src/compiler/scala/tools/nsc/doc/doclet/Generator.scala4
-rw-r--r--src/compiler/scala/tools/nsc/doc/html/Doclet.scala2
-rw-r--r--src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala2
-rw-r--r--src/compiler/scala/tools/nsc/doc/model/Entity.scala4
-rw-r--r--src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala2
-rw-r--r--src/compiler/scala/tools/nsc/interactive/Global.scala2
-rw-r--r--src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala4
-rw-r--r--src/compiler/scala/tools/nsc/interpreter/ILoop.scala17
-rw-r--r--src/compiler/scala/tools/nsc/interpreter/Power.scala13
-rw-r--r--src/compiler/scala/tools/nsc/io/AbstractFile.scala4
-rw-r--r--src/compiler/scala/tools/nsc/io/Jar.scala2
-rw-r--r--src/compiler/scala/tools/nsc/io/Lexer.scala4
-rw-r--r--src/compiler/scala/tools/nsc/io/Pickler.scala2
-rw-r--r--src/compiler/scala/tools/nsc/io/PlainFile.scala4
-rw-r--r--src/compiler/scala/tools/nsc/io/VirtualDirectory.scala4
-rw-r--r--src/compiler/scala/tools/nsc/io/VirtualFile.scala4
-rw-r--r--src/compiler/scala/tools/nsc/io/ZipArchive.scala4
-rw-r--r--src/compiler/scala/tools/nsc/javac/JavaScanners.scala12
-rw-r--r--src/compiler/scala/tools/nsc/matching/MatchSupport.scala5
-rw-r--r--src/compiler/scala/tools/nsc/matching/Matrix.scala10
-rw-r--r--src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala4
-rw-r--r--src/compiler/scala/tools/nsc/matching/ParallelMatching.scala275
-rw-r--r--src/compiler/scala/tools/nsc/matching/PatternBindings.scala20
-rw-r--r--src/compiler/scala/tools/nsc/matching/Patterns.scala61
-rw-r--r--src/compiler/scala/tools/nsc/plugins/Plugins.scala8
-rw-r--r--src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala4
-rw-r--r--src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala2
-rw-r--r--src/compiler/scala/tools/nsc/reporters/StoreReporter.scala2
-rw-r--r--src/compiler/scala/tools/nsc/settings/MutableSettings.scala25
-rw-r--r--src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala4
-rw-r--r--src/compiler/scala/tools/nsc/symtab/Definitions.scala2
-rw-r--r--src/compiler/scala/tools/nsc/symtab/NameManglers.scala4
-rw-r--r--src/compiler/scala/tools/nsc/symtab/StdNames.scala1
-rw-r--r--src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala10
-rw-r--r--src/compiler/scala/tools/nsc/symtab/Symbols.scala150
-rw-r--r--src/compiler/scala/tools/nsc/symtab/TypeDebugging.scala10
-rw-r--r--src/compiler/scala/tools/nsc/symtab/Types.scala71
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala4
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala8
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala9
-rw-r--r--src/compiler/scala/tools/nsc/transform/AddInterfaces.scala8
-rw-r--r--src/compiler/scala/tools/nsc/transform/Erasure.scala4
-rw-r--r--src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala7
-rw-r--r--src/compiler/scala/tools/nsc/transform/LambdaLift.scala169
-rw-r--r--src/compiler/scala/tools/nsc/transform/OverridingPairs.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Analyzer.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Contexts.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Duplicators.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Implicits.scala61
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Infer.scala10
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Namers.scala12
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/RefChecks.scala321
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala2
-rw-r--r--src/compiler/scala/tools/nsc/typechecker/Typers.scala39
-rw-r--r--src/compiler/scala/tools/nsc/util/ClassPath.scala4
-rw-r--r--src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala2
-rw-r--r--src/compiler/scala/tools/util/Which.scala5
-rw-r--r--src/dbc/scala/dbc/Database.scala4
-rw-r--r--src/detach/library/scala/runtime/RemoteRef.scala2
-rw-r--r--src/detach/plugin/scala/tools/detach/Detach.scala10
-rw-r--r--src/library/scala/App.scala2
-rw-r--r--src/library/scala/Array.scala11
-rw-r--r--src/library/scala/Option.scala2
-rw-r--r--src/library/scala/Predef.scala5
-rw-r--r--src/library/scala/annotation/switch.scala43
-rw-r--r--src/library/scala/collection/IterableViewLike.scala1
-rw-r--r--src/library/scala/collection/Iterator.scala3
-rw-r--r--src/library/scala/collection/JavaConversions.scala2
-rwxr-xr-xsrc/library/scala/collection/JavaConverters.scala2
-rw-r--r--src/library/scala/collection/SeqLike.scala7
-rw-r--r--src/library/scala/collection/SeqViewLike.scala5
-rw-r--r--src/library/scala/collection/TraversableProxy.scala2
-rw-r--r--src/library/scala/collection/immutable/List.scala16
-rw-r--r--src/library/scala/collection/immutable/ListMap.scala5
-rw-r--r--src/library/scala/collection/immutable/ListSet.scala4
-rw-r--r--src/library/scala/collection/immutable/MapLike.scala3
-rw-r--r--src/library/scala/collection/immutable/Range.scala10
-rw-r--r--src/library/scala/collection/immutable/SortedMap.scala3
-rw-r--r--src/library/scala/collection/immutable/TreeMap.scala5
-rw-r--r--src/library/scala/collection/immutable/TrieIterator.scala4
-rw-r--r--src/library/scala/collection/immutable/Vector.scala2
-rw-r--r--src/library/scala/collection/mutable/ArrayStack.scala2
-rw-r--r--src/library/scala/collection/mutable/BufferLike.scala2
-rw-r--r--src/library/scala/collection/mutable/FlatHashTable.scala4
-rw-r--r--src/library/scala/collection/mutable/HashTable.scala4
-rw-r--r--src/library/scala/collection/mutable/MapLike.scala6
-rw-r--r--src/library/scala/collection/mutable/ObservableBuffer.scala6
-rw-r--r--src/library/scala/collection/mutable/ObservableMap.scala2
-rw-r--r--src/library/scala/collection/mutable/ObservableSet.scala2
-rw-r--r--src/library/scala/collection/mutable/OpenHashMap.scala4
-rw-r--r--src/library/scala/collection/mutable/PriorityQueue.scala2
-rw-r--r--src/library/scala/collection/mutable/RevertibleHistory.scala2
-rw-r--r--src/library/scala/collection/mutable/SetLike.scala8
-rw-r--r--src/library/scala/collection/mutable/UnrolledBuffer.scala1
-rw-r--r--src/library/scala/collection/package.scala2
-rw-r--r--src/library/scala/collection/parallel/ParIterableLike.scala8
-rw-r--r--src/library/scala/collection/parallel/ParIterableView.scala24
-rw-r--r--src/library/scala/collection/parallel/ParSeqLike.scala44
-rw-r--r--src/library/scala/collection/parallel/ParSeqView.scala30
-rw-r--r--src/library/scala/collection/parallel/ParSeqViewLike.scala31
-rw-r--r--src/library/scala/collection/parallel/Splitter.scala8
-rw-r--r--src/library/scala/collection/parallel/Tasks.scala32
-rw-r--r--src/library/scala/collection/parallel/immutable/ParHashMap.scala2
-rw-r--r--src/library/scala/collection/parallel/immutable/ParRange.scala13
-rw-r--r--src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala2
-rw-r--r--src/library/scala/compat/Platform.scala2
-rw-r--r--src/library/scala/concurrent/Lock.scala4
-rw-r--r--src/library/scala/concurrent/pilib.scala4
-rw-r--r--src/library/scala/deprecated.scala9
-rw-r--r--src/library/scala/io/BufferedSource.scala1
-rw-r--r--src/library/scala/io/Position.scala2
-rw-r--r--src/library/scala/math/Ordered.scala4
-rw-r--r--src/library/scala/mobile/Code.scala234
-rw-r--r--src/library/scala/mobile/Location.scala72
-rw-r--r--src/library/scala/package.scala10
-rw-r--r--src/library/scala/reflect/ScalaBeanInfo.scala2
-rw-r--r--src/library/scala/runtime/RichBoolean.scala4
-rw-r--r--src/library/scala/sys/SystemProperties.scala2
-rw-r--r--src/library/scala/sys/process/BasicIO.scala1
-rw-r--r--src/library/scala/sys/process/Process.scala4
-rw-r--r--src/library/scala/sys/process/ProcessImpl.scala2
-rw-r--r--src/library/scala/testing/Benchmark.scala4
-rw-r--r--src/library/scala/util/MurmurHash.scala1
-rw-r--r--src/library/scala/util/Random.scala9
-rw-r--r--src/library/scala/util/Sorting.scala1
-rw-r--r--src/library/scala/util/control/Breaks.scala2
-rw-r--r--src/library/scala/util/parsing/ast/Binders.scala4
-rw-r--r--src/library/scala/xml/MetaData.scala2
-rw-r--r--src/library/scala/xml/Null.scala1
-rw-r--r--src/library/scala/xml/dtd/ContentModelParser.scala2
-rw-r--r--src/library/scala/xml/dtd/Scanner.scala4
-rw-r--r--src/library/scala/xml/factory/LoggedNodeFactory.scala2
-rw-r--r--src/library/scala/xml/parsing/FactoryAdapter.scala19
-rw-r--r--src/library/scala/xml/parsing/MarkupParserCommon.scala6
-rw-r--r--src/library/scala/xml/persistent/CachedFileStorage.scala14
-rwxr-xr-xsrc/library/scala/xml/pull/XMLEventReader.scala10
-rw-r--r--src/partest/scala/tools/partest/nest/ConsoleRunner.scala2
-rw-r--r--src/partest/scala/tools/partest/nest/Worker.scala2
-rw-r--r--src/partest/scala/tools/partest/package.scala2
-rw-r--r--src/scalacheck/org/scalacheck/Prop.scala2
-rw-r--r--src/scalacheck/org/scalacheck/Properties.scala2
-rw-r--r--src/scalap/scala/tools/scalap/CodeWriter.scala2
-rw-r--r--src/scalap/scala/tools/scalap/JavaWriter.scala4
-rw-r--r--src/scalap/scala/tools/scalap/MetaParser.scala2
-rw-r--r--src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala2
-rw-r--r--src/swing/scala/swing/BufferWrapper.scala5
-rw-r--r--src/swing/scala/swing/Component.scala2
-rw-r--r--src/swing/scala/swing/Container.scala2
-rw-r--r--src/swing/scala/swing/MainFrame.scala2
-rw-r--r--src/swing/scala/swing/Publisher.scala2
-rw-r--r--src/swing/scala/swing/TextField.scala4
-rw-r--r--src/swing/scala/swing/UIElement.scala6
-rw-r--r--test/files/buildmanager/t2649/t2649.check4
-rw-r--r--test/files/buildmanager/t2790/t2790.check4
-rw-r--r--test/files/buildmanager/t3054/foo/Foo.scala2
-rw-r--r--test/files/buildmanager/t4215/A.scala2
-rw-r--r--test/files/continuations-neg/lazy.check4
-rw-r--r--test/files/continuations-neg/lazy.scala4
-rw-r--r--test/files/neg/abstract-class-2.check5
-rw-r--r--test/files/neg/abstract-class-2.scala14
-rw-r--r--test/files/neg/abstract-class-error.check5
-rw-r--r--test/files/neg/abstract-class-error/J.java4
-rw-r--r--test/files/neg/abstract-class-error/S.scala4
-rw-r--r--test/files/neg/accesses.check16
-rw-r--r--test/files/neg/accesses.scala32
-rw-r--r--test/files/neg/bug1960.check2
-rw-r--r--test/files/neg/bug1960.scala2
-rw-r--r--test/files/neg/bug4533.check4
-rw-r--r--test/files/neg/bug4533.scala8
-rw-r--r--test/files/neg/bug630.scala4
-rw-r--r--test/files/neg/exhausting.check6
-rw-r--r--test/files/neg/names-defaults-neg.check16
-rw-r--r--test/files/neg/patmatexhaust.check25
-rw-r--r--test/files/neg/patmatexhaust.flags1
-rw-r--r--test/files/neg/patmatexhaust.scala10
-rw-r--r--test/files/neg/t2910.check2
-rw-r--r--test/files/neg/t2910.scala4
-rw-r--r--test/files/neg/t3115.check4
-rw-r--r--test/files/neg/t3774.check2
-rw-r--r--test/files/neg/t4457_1.check7
-rw-r--r--test/files/neg/t4457_1.scala33
-rw-r--r--test/files/neg/t4457_2.check13
-rw-r--r--test/files/neg/t4457_2.scala33
-rw-r--r--test/files/neg/tailrec.scala2
-rw-r--r--test/files/neg/tcpoly_infer_ticket1162.check2
-rw-r--r--test/files/neg/varargs.check6
-rw-r--r--test/files/pos/t4457_1.scala26
-rw-r--r--test/files/res/bug722/Parser.scala2
-rw-r--r--test/files/res/bug722/ScanBased.scala4
-rw-r--r--test/files/res/bug785/ScalaNewTyper.scala2
-rw-r--r--test/files/run/io-position.checkbin0 -> 126 bytes
-rw-r--r--test/files/run/io-position.scala13
-rw-r--r--test/files/run/patmat-exprs.check1
-rw-r--r--test/files/run/patmat-exprs.scala579
-rw-r--r--test/files/run/t1500.check2
232 files changed, 2228 insertions, 1584 deletions
diff --git a/docs/examples/mobile/sort.scala b/docs/examples/mobile/sort.scala
deleted file mode 100644
index b0bfe43a54..0000000000
--- a/docs/examples/mobile/sort.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-package examples.mobile
-
-import java.net._
-import scala.mobile._
-
-
-object sort extends Application {
- val url = new URL("http://scala.epfl.ch/classes/examples.jar")
-
- val location = new Location(url)
- val obj = location create "examples.sort"
- val ar = Array(6, 2, 8, 5, 1)
- obj[Array[Int], Unit]("println")(ar)
- obj[Array[Int], Unit]("sort")(ar)
- obj[Array[Int], Unit]("println")(ar)
- Console.println
-}
diff --git a/src/actors/scala/actors/Actor.scala b/src/actors/scala/actors/Actor.scala
index 059ab3abf7..25cfbf7865 100644
--- a/src/actors/scala/actors/Actor.scala
+++ b/src/actors/scala/actors/Actor.scala
@@ -95,7 +95,7 @@ object Actor extends Combinators {
* This permits to re-use the current thread as an actor
* even if its <code>ActorProxy</code> has died for some reason.
*/
- def resetProxy {
+ def resetProxy() {
val a = tl.get
if ((null ne a) && a.isInstanceOf[ActorProxy])
tl.set(new ActorProxy(Thread.currentThread, parentScheduler))
@@ -110,7 +110,7 @@ object Actor extends Combinators {
* a thread pool). Permanent references in thread-local storage
* are a potential memory leak.
*/
- def clearSelf {
+ def clearSelf() {
tl.set(null)
}
diff --git a/src/actors/scala/actors/Combinators.scala b/src/actors/scala/actors/Combinators.scala
index 9d63af61f9..5276c7843e 100644
--- a/src/actors/scala/actors/Combinators.scala
+++ b/src/actors/scala/actors/Combinators.scala
@@ -41,6 +41,6 @@ private[actors] trait Combinators {
* of the next loop iteration when invoked inside the body of `loop`
* or `loopWhile`.
*/
- def continue: Unit = throw new KillActorControl
+ def continue(): Unit = throw new KillActorControl
}
diff --git a/src/actors/scala/actors/IScheduler.scala b/src/actors/scala/actors/IScheduler.scala
index 865ead58a0..2bb90a5fa7 100644
--- a/src/actors/scala/actors/IScheduler.scala
+++ b/src/actors/scala/actors/IScheduler.scala
@@ -77,6 +77,6 @@ trait IScheduler {
def onLockup(millis: Int)(handler: () => Unit) {}
@deprecated("this member is going to be removed in a future release", "2.7.7")
- def printActorDump {}
+ def printActorDump() {}
}
diff --git a/src/actors/scala/actors/remote/TcpService.scala b/src/actors/scala/actors/remote/TcpService.scala
index b310478457..d156443fcb 100644
--- a/src/actors/scala/actors/remote/TcpService.scala
+++ b/src/actors/scala/actors/remote/TcpService.scala
@@ -222,7 +222,7 @@ private[actors] class TcpServiceWorker(parent: TcpService, so: Socket) extends T
parent.serializer.writeObject(dataout, parent.node)
}
- def readNode {
+ def readNode() {
val node = parent.serializer.readObject(datain)
node match {
case n: Node =>
@@ -240,7 +240,7 @@ private[actors] class TcpServiceWorker(parent: TcpService, so: Socket) extends T
var running = true
- def halt = synchronized {
+ def halt() = synchronized {
so.close()
running = false
}
diff --git a/src/attic/scala/tools/nsc/models/SemanticTokens.scala b/src/attic/scala/tools/nsc/models/SemanticTokens.scala
index edbc13ccdc..6c2fe79d77 100644
--- a/src/attic/scala/tools/nsc/models/SemanticTokens.scala
+++ b/src/attic/scala/tools/nsc/models/SemanticTokens.scala
@@ -648,11 +648,11 @@ class SemanticTokens(val compiler: Global) {
var token: Token = end
var offset: Int = 0
- def next: Unit = if (token == end) end else {
+ def next(): Unit = if (token == end) end else {
offset = offset + token.length
token = token.next
}
- def prev: Unit = if (token.prev == begin) token else {
+ def prev(): Unit = if (token.prev == begin) token else {
offset = offset - token.prev.length
token = token.prev
}
diff --git a/src/compiler/scala/tools/ant/FastScalac.scala b/src/compiler/scala/tools/ant/FastScalac.scala
index 403d9cc117..a2a7496824 100644
--- a/src/compiler/scala/tools/ant/FastScalac.scala
+++ b/src/compiler/scala/tools/ant/FastScalac.scala
@@ -103,7 +103,7 @@ class FastScalac extends Scalac {
val args = (cmdOptions ::: (sourceFiles map (_.toString))).toArray
try {
- if (scala.tools.nsc.CompileClient.process(args) != 0 && failonerror)
+ if (scala.tools.nsc.CompileClient.process(args) && failonerror)
buildError("Compile failed; see the compiler error output for details.")
}
catch {
diff --git a/src/compiler/scala/tools/ant/Same.scala b/src/compiler/scala/tools/ant/Same.scala
index 988bb4c315..52bc440756 100644
--- a/src/compiler/scala/tools/ant/Same.scala
+++ b/src/compiler/scala/tools/ant/Same.scala
@@ -89,7 +89,7 @@ class Same extends ScalaMatchingTask {
private var allEqualNow = true
/** Tests if all mandatory attributes are set and valid. */
- private def validateAttributes = {
+ private def validateAttributes() = {
if (origin.isEmpty) sys.error("Mandatory attribute 'dir' is not set.")
if (destination.isEmpty) sys.error("Mandatory attribute 'todir' is not set.")
}
diff --git a/src/compiler/scala/tools/ant/sabbus/Break.scala b/src/compiler/scala/tools/ant/sabbus/Break.scala
index 3c5000a30b..91dab5b0ee 100644
--- a/src/compiler/scala/tools/ant/sabbus/Break.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Break.scala
@@ -19,7 +19,7 @@ class Break extends Task {
private var id: Option[String] = None
- override def execute {
+ override def execute() {
if (id.isEmpty) sys.error("Attribute 'id' is not set")
Compilers.break(id.get)
}
diff --git a/src/compiler/scala/tools/ant/sabbus/Make.scala b/src/compiler/scala/tools/ant/sabbus/Make.scala
index bf6b39d401..75cd0105ac 100644
--- a/src/compiler/scala/tools/ant/sabbus/Make.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Make.scala
@@ -13,7 +13,7 @@ import java.io.File
import org.apache.tools.ant.Task
class Make extends Task with TaskArgs {
- override def execute {
+ override def execute() {
if (id.isEmpty) sys.error("Mandatory attribute 'id' is not set.")
if (compilerPath.isEmpty) sys.error("Mandatory attribute 'compilerpath' is not set.")
val settings = new Settings
diff --git a/src/compiler/scala/tools/ant/templates/tool-unix.tmpl b/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
index 1976535333..a3dc58263b 100644
--- a/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
+++ b/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
@@ -9,29 +9,39 @@
##############################################################################
# Not sure what the right default is here: trying nonzero.
-SCALA_EXIT_STATUS=127
-REENABLE_ECHO=true
-
-function reenableEcho() {
- REENABLE_ECHO=false
- # reenable echo
- case "$TERM" in
- rxvt* | xterm* | screen*)
- stty icanon echo
- ;;
- esac
+scala_exit_status=127
+saved_stty=""
+
+# restore stty settings (echo in particular)
+function restoreSttySettings() {
+ if [[ -n $SCALA_RUNNER_DEBUG ]]; then
+ echo "restoring stty: $saved_stty"
+ fi
+
+ stty $saved_stty
+ saved_stty=""
}
function onExit() {
- if $REENABLE_ECHO; then
- reenableEcho
- exit $SCALA_EXIT_STATUS
+ if [[ "$saved_stty" != "" ]]; then
+ restoreSttySettings
+ exit $scala_exit_status
fi
}
# to reenable echo if we are interrupted before completing.
trap onExit INT
+# save terminal settings
+saved_stty=$(stty -g 2>/dev/null)
+# clear on error so we don't later try to restore them
+if [[ ! $? ]]; then
+ saved_stty=""
+fi
+if [[ -n $SCALA_RUNNER_DEBUG ]]; then
+ echo "saved stty: $saved_stty"
+fi
+
cygwin=false;
case "`uname`" in
CYGWIN*) cygwin=true ;;
@@ -152,5 +162,5 @@ fi
# record the exit status lest it be overwritten:
# then reenable echo and propagate the code.
-SCALA_EXIT_STATUS=$?
+scala_exit_status=$?
onExit
diff --git a/src/compiler/scala/tools/nsc/CompileClient.scala b/src/compiler/scala/tools/nsc/CompileClient.scala
index fd4f777890..dc65bf780e 100644
--- a/src/compiler/scala/tools/nsc/CompileClient.scala
+++ b/src/compiler/scala/tools/nsc/CompileClient.scala
@@ -19,7 +19,7 @@ class StandardCompileClient extends HasCompileSocket with CompileOutputCommon {
val versionMsg = "Fast " + Properties.versionMsg
var verbose = false
- def process(args: Array[String]): Int = {
+ def process(args: Array[String]): Boolean = {
// Trying to get out in front of the log messages in case we're
// going from verbose to not verbose.
verbose = (args contains "-verbose")
@@ -34,7 +34,7 @@ class StandardCompileClient extends HasCompileSocket with CompileOutputCommon {
if (settings.version.value) {
Console println versionMsg
- return 0
+ return true
}
info(versionMsg)
@@ -46,7 +46,7 @@ class StandardCompileClient extends HasCompileSocket with CompileOutputCommon {
if (settings.server.value == "") compileSocket.getOrCreateSocket(vmArgs mkString " ", !shutdown)
else Some(compileSocket.getSocket(settings.server.value))
- val success = socket match {
+ socket match {
case Some(sock) => compileOnServer(sock, fscArgs)
case _ =>
echo(
@@ -55,13 +55,12 @@ class StandardCompileClient extends HasCompileSocket with CompileOutputCommon {
)
shutdown
}
- if (success) 1 else 0
}
}
object CompileClient extends StandardCompileClient {
def main(args: Array[String]): Unit = sys exit {
- try process(args)
+ try { if (process(args)) 0 else 1 }
catch { case _: Exception => 1 }
}
}
diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala
index 2e2f9c1ad7..6af7fe991f 100644
--- a/src/compiler/scala/tools/nsc/Global.scala
+++ b/src/compiler/scala/tools/nsc/Global.scala
@@ -289,7 +289,7 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
abstract class GlobalPhase(prev: Phase) extends Phase(prev) {
phaseWithId(id) = this
- def run {
+ def run() {
echoPhaseSummary(this)
currentRun.units foreach applyPhase
}
@@ -738,7 +738,7 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
/** take note that phase is completed
* (for progress reporting)
*/
- def advancePhase {
+ def advancePhase() {
unitc = 0
phasec += 1
refreshProgress
@@ -746,18 +746,18 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
/** take note that a phase on a unit is completed
* (for progress reporting)
*/
- def advanceUnit {
+ def advanceUnit() {
unitc += 1
refreshProgress
}
- def cancel { reporter.cancelled = true }
+ def cancel() { reporter.cancelled = true }
- private var phasec: Int = 0 // phases completed
- private var unitc: Int = 0 // units completed this phase
- private def currentProgress = (phasec * size) + unitc
- private def totalProgress = (phaseDescriptors.size - 1) * size // -1: drops terminal phase
- private def refreshProgress = if (size > 0) progress(currentProgress, totalProgress)
+ private var phasec: Int = 0 // phases completed
+ private var unitc: Int = 0 // units completed this phase
+ private def currentProgress = (phasec * size) + unitc
+ private def totalProgress = (phaseDescriptors.size - 1) * size // -1: drops terminal phase
+ private def refreshProgress() = if (size > 0) progress(currentProgress, totalProgress)
// ----- finding phases --------------------------------------------
@@ -881,7 +881,7 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
atPhase(phase.next) {
trackers foreach { t =>
t.snapshot()
- inform(t.show())
+ inform(t.show("Heading from " + phase.prev.name + " to " + phase.name))
}
}
}
@@ -1226,6 +1226,6 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
def forScaladoc = onlyPresentation
def createJavadoc = false
- @deprecated("Use forInteractive or forScaladoc, depending on what you're after")
+ @deprecated("Use forInteractive or forScaladoc, depending on what you're after", "2.9.0")
def onlyPresentation = false
}
diff --git a/src/compiler/scala/tools/nsc/NoPhase.scala b/src/compiler/scala/tools/nsc/NoPhase.scala
index 92e5fceaa5..a74d14acf7 100644
--- a/src/compiler/scala/tools/nsc/NoPhase.scala
+++ b/src/compiler/scala/tools/nsc/NoPhase.scala
@@ -7,5 +7,5 @@ package scala.tools.nsc
object NoPhase extends Phase(null) {
def name = "<no phase>"
- def run { throw new Error("NoPhase.run") }
+ def run() { throw new Error("NoPhase.run") }
}
diff --git a/src/compiler/scala/tools/nsc/Phase.scala b/src/compiler/scala/tools/nsc/Phase.scala
index 95b0d82ee8..f79b7c4367 100644
--- a/src/compiler/scala/tools/nsc/Phase.scala
+++ b/src/compiler/scala/tools/nsc/Phase.scala
@@ -39,7 +39,7 @@ abstract class Phase(val prev: Phase) {
def flatClasses: Boolean = false
def refChecked: Boolean = false
def keepsTypeParams = true
- def run: Unit
+ def run(): Unit
override def toString() = name
override def hashCode = id.## + name.##
diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
index 8fd0017b81..613928856d 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
@@ -31,6 +31,9 @@ abstract class TreeBrowsers {
import global._
import nme.EMPTY
+ val borderSize = 10
+
+
def create(): SwingBrowser = new SwingBrowser();
/** Pseudo tree class, so that all JTree nodes are treated uniformly */
@@ -93,37 +96,38 @@ abstract class TreeBrowsers {
listeners = l :: listeners
/** Return the index'th child of parent */
- def getChild(parent: Any, index: Int): AnyRef =
+ def getChild(parent: AnyRef, index: Int): AnyRef =
packChildren(parent)(index)
/** Return the number of children this 'parent' has */
- def getChildCount(parent: Any): Int =
+ def getChildCount(parent: AnyRef): Int =
packChildren(parent).length
/** Return the index of the given child */
- def getIndexOfChild(parent: Any, child: Any): Int =
+ def getIndexOfChild(parent: AnyRef, child: AnyRef): Int =
packChildren(parent) indexOf child
/** Return the root node */
def getRoot(): AnyRef = program
/** Test whether the given node is a leaf */
- def isLeaf(node: Any): Boolean = packChildren(node).isEmpty
+ def isLeaf(node: AnyRef): Boolean = packChildren(node).isEmpty
def removeTreeModelListener(l: TreeModelListener): Unit =
listeners = listeners filterNot (_ == l)
/** we ignore this message for now */
- def valueForPathChanged(path: TreePath, newValue: Any) = ()
+ def valueForPathChanged(path: TreePath, newValue: AnyRef) = ()
/**
* Return a list of children for the given node.
*/
- def packChildren(t: Any): List[AnyRef] =
- TreeInfo.children(t.asInstanceOf[Tree])
+ def packChildren(t: AnyRef): List[AnyRef] = TreeInfo.children(t.asInstanceOf[Tree])
}
+
+
/**
* A window that can host the Tree widget and provide methods for
* displaying information
@@ -132,16 +136,45 @@ abstract class TreeBrowsers {
* @version 1.0
*/
class BrowserFrame(phaseName: String = "unknown") {
- val frame = new JFrame("Scala AST [" + phaseName + "]")
+ try {
+ UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel")
+ }
+ catch {
+ case _ => UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName())
+ }
+
+ val frame = new JFrame("Scala AST after " + phaseName + " phase")
+ frame.setJMenuBar(new ASTMenuBar())
val topLeftPane = new JPanel(new BorderLayout())
val topRightPane = new JPanel(new BorderLayout())
val bottomPane = new JPanel(new BorderLayout())
var splitPane: JSplitPane = _
- var treeModel: TreeModel = _
-
+ var treeModel: ASTTreeModel = _
+ var jTree: JTree = _
val textArea: JTextArea = new JTextArea(30, 120)
+ textArea.setBorder(BorderFactory.createEmptyBorder(borderSize, borderSize, borderSize, borderSize))
+
val infoPanel = new TextInfoPanel()
+
+ private def setExpansionState(root: JTree, expand: Boolean): Unit = {
+ def _setExpansionState(root: JTree, path: TreePath): Unit = {
+ val last = path.getLastPathComponent
+ for (i <- 0 until root.getModel.getChildCount(last)) {
+ val child = root.getModel.getChild(last, i)
+ val childPath = path pathByAddingChild child
+ _setExpansionState(root, childPath)
+ }
+ if (expand) {jTree expandPath path}
+ else {jTree collapsePath path}
+ }
+ _setExpansionState(root, new TreePath(root.getModel.getRoot))
+ }
+
+ def expandAll(subtree: JTree) = setExpansionState(subtree, true)
+ def collapseAll(subtree: JTree) = setExpansionState(subtree, false)
+
+
/** Create a frame that displays the AST.
*
* @param lock The lock is used in order to stop the compilation thread
@@ -160,7 +193,7 @@ abstract class TreeBrowsers {
override def windowClosed(e: WindowEvent): Unit = lock.release
});
- val tree = new JTree(treeModel) {
+ jTree = new JTree(treeModel) {
/** Return the string for a tree node. */
override def convertValueToText(value: Any, sel: Boolean,
exp: Boolean, leaf: Boolean,
@@ -173,7 +206,7 @@ abstract class TreeBrowsers {
}
}
- tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
+ jTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
def valueChanged(e: javax.swing.event.TreeSelectionEvent): Unit = {
textArea.setText(e.getPath().getLastPathComponent().toString())
infoPanel.update(e.getPath().getLastPathComponent())
@@ -183,9 +216,10 @@ abstract class TreeBrowsers {
val topSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, topLeftPane, topRightPane)
topSplitPane.setResizeWeight(0.5)
- topLeftPane.add(new JScrollPane(tree), BorderLayout.CENTER)
+ jTree.setBorder(
+ BorderFactory.createEmptyBorder(borderSize, borderSize, borderSize, borderSize))
+ topLeftPane.add(new JScrollPane(jTree), BorderLayout.CENTER)
topRightPane.add(new JScrollPane(infoPanel), BorderLayout.CENTER)
-
bottomPane.add(new JScrollPane(textArea), BorderLayout.CENTER)
textArea.setFont(new Font("monospaced", Font.PLAIN, 14))
textArea.setEditable(false)
@@ -196,7 +230,67 @@ abstract class TreeBrowsers {
frame.setVisible(true)
}
- def setTreeModel(tm: TreeModel): Unit = treeModel = tm
+ class ASTMenuBar extends JMenuBar {
+ val menuKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
+ val shiftKey = InputEvent.SHIFT_MASK
+ val jmFile = new JMenu("File")
+ // val jmiSaveImage = new JMenuItem(
+ // new AbstractAction("Save Tree Image") {
+ // putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, menuKey, false))
+ // override def actionPerformed(e: ActionEvent) {
+ // //TODO
+ // }
+ // }
+ // )
+
+ // jmFile add jmiSaveImage
+
+ def closeWindow() = frame.getToolkit().getSystemEventQueue().postEvent(
+ new WindowEvent(frame, WindowEvent.WINDOW_CLOSING))
+
+ val jmiCancel = new JMenuItem (
+ new AbstractAction("Cancel Compilation") {
+ putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Q, menuKey + shiftKey, false))
+ override def actionPerformed(e: ActionEvent) {
+ closeWindow()
+ global.currentRun.cancel
+ }
+ }
+ )
+ jmFile add jmiCancel
+
+ val jmiExit = new JMenuItem (
+ new AbstractAction("Exit") {
+ putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Q, menuKey, false))
+ override def actionPerformed(e: ActionEvent) = closeWindow()
+ }
+ )
+ jmFile add jmiExit
+ add(jmFile)
+
+ val jmView = new JMenu("View")
+ val jmiExpand = new JMenuItem(
+ new AbstractAction("Expand All Nodes") {
+ putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, menuKey, false))
+ override def actionPerformed(e: ActionEvent) {
+ expandAll(jTree)
+ }
+ }
+ )
+ jmView add jmiExpand
+ val jmiCollapse = new JMenuItem(
+ new AbstractAction("Collapse All Nodes") {
+ putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_L, menuKey, false))
+ override def actionPerformed(e: ActionEvent) {
+ collapseAll(jTree)
+ }
+ }
+ )
+ jmView add jmiCollapse
+ add(jmView)
+ }
+
+ def setTreeModel(tm: ASTTreeModel): Unit = treeModel = tm
}
/**
@@ -204,6 +298,8 @@ abstract class TreeBrowsers {
*/
class TextInfoPanel extends JTextArea(20, 50) {
+ setBorder(BorderFactory.createEmptyBorder(borderSize, borderSize, borderSize, borderSize))
+ setEditable(false)
setFont(new Font("monospaced", Font.PLAIN, 12))
def update(v: AnyRef): Unit = {
diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala
index d232bee46d..b655507658 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala
@@ -111,6 +111,11 @@ abstract class TreeGen {
if (sym.owner.isClass) mkAttributedRef(sym.owner.thisType, sym)
else mkAttributedIdent(sym)
+ /** Builds an untyped reference to given symbol. */
+ def mkUnattributedRef(sym: Symbol): Tree =
+ if (sym.owner.isClass) Select(This(sym.owner), sym)
+ else Ident(sym)
+
/** Replaces tree type with a stable type if possible */
def stabilize(tree: Tree): Tree = {
for(tp <- stableTypeFor(tree)) tree.tpe = tp
@@ -255,7 +260,7 @@ abstract class TreeGen {
def mkSoftRef(expr: Tree): Tree = New(TypeTree(SoftReferenceClass.tpe), List(List(expr)))
def mkCached(cvar: Symbol, expr: Tree): Tree = {
- val cvarRef = if (cvar.owner.isClass) Select(This(cvar.owner), cvar) else Ident(cvar)
+ val cvarRef = mkUnattributedRef(cvar)
Block(
List(
If(Apply(Select(cvarRef, nme.eq), List(Literal(Constant(null)))),
@@ -265,17 +270,24 @@ abstract class TreeGen {
)
}
+ // Builds a tree of the form "{ lhs = rhs ; lhs }"
+ def mkAssignAndReturn(lhs: Symbol, rhs: Tree): Tree = {
+ val lhsRef = mkAttributedRef(lhs)
+ Block(Assign(lhsRef, rhs) :: Nil, lhsRef)
+ }
+
def mkModuleVarDef(accessor: Symbol) = {
- val mval = accessor.owner.newVariable(accessor.pos.focus, nme.moduleVarName(accessor.name))
- .setInfo(accessor.tpe.finalResultType)
- .setFlag(LAZY)
- .setFlag(MODULEVAR)
- mval.setLazyAccessor(accessor)
+ val mval = (
+ accessor.owner.newVariable(accessor.pos.focus, nme.moduleVarName(accessor.name))
+ setInfo accessor.tpe.finalResultType
+ setFlag (LAZY | MODULEVAR)
+ setLazyAccessor accessor
+ )
if (mval.owner.isClass) {
mval setFlag (PRIVATE | LOCAL | SYNTHETIC)
mval.owner.info.decls.enter(mval)
}
- ValDef(mval, EmptyTree)
+ ValDef(mval)
}
// def m: T = { if (m$ eq null) m$ = new m$class(...) m$ }
diff --git a/src/compiler/scala/tools/nsc/ast/TreePrinters.scala b/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
index b8c3e12ee6..96f4355590 100644
--- a/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
@@ -41,8 +41,8 @@ trait TreePrinters { trees: SymbolTable =>
def flush() = out.flush()
- def indent = indentMargin += indentStep
- def undent = indentMargin -= indentStep
+ def indent() = indentMargin += indentStep
+ def undent() = indentMargin -= indentStep
protected def doPrintPositions = settings.Xprintpos.value
def printPosition(tree: Tree) = if (doPrintPositions) print(tree.pos.show)
@@ -546,7 +546,7 @@ trait TreePrinters { trees: SymbolTable =>
}
val List(thenStmts, elseStmts) = List(thenp, elsep) map allStatements
- print("if ("); print(cond); print(")")
+ print("if ("); print(cond); print(") ")
thenStmts match {
case List(x: If) => ifIndented(x)
@@ -555,7 +555,7 @@ trait TreePrinters { trees: SymbolTable =>
}
if (elseStmts.nonEmpty) {
- print("else")
+ print(" else")
indent ; println()
elseStmts match {
case List(x) => printRaw(x)
diff --git a/src/compiler/scala/tools/nsc/ast/Trees.scala b/src/compiler/scala/tools/nsc/ast/Trees.scala
index 8bb7b77154..56a7ee6ec8 100644
--- a/src/compiler/scala/tools/nsc/ast/Trees.scala
+++ b/src/compiler/scala/tools/nsc/ast/Trees.scala
@@ -85,6 +85,12 @@ trait Trees extends reflect.generic.Trees { self: SymbolTable =>
ft.result
}
+ def changeOwner(pairs: (Symbol, Symbol)*): Tree = {
+ pairs.foldLeft(tree) { case (t, (oldOwner, newOwner)) =>
+ new ChangeOwnerTraverser(oldOwner, newOwner) apply t
+ }
+ }
+
/** Is there part of this tree which satisfies predicate `p'? */
def exists(p: Tree => Boolean): Boolean = !find(p).isEmpty
@@ -1034,13 +1040,6 @@ trait Trees extends reflect.generic.Trees { self: SymbolTable =>
}
}
- final class TreeList {
- private var trees = List[Tree]()
- def append(t: Tree): TreeList = { trees = t :: trees; this }
- def append(ts: List[Tree]): TreeList = { trees = ts reverse_::: trees; this }
- def toList: List[Tree] = trees.reverse
- }
-
object posAssigner extends Traverser {
var pos: Position = _
override def traverse(t: Tree) {
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
index 38392e5dd6..84959d04ac 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
@@ -2188,12 +2188,12 @@ self =>
}
/** Def ::= val PatDef
- * | var VarDef
+ * | var PatDef
* | def FunDef
* | type [nl] TypeDef
* | TmplDef
- * Dcl ::= val ValDcl
- * | var ValDcl
+ * Dcl ::= val PatDcl
+ * | var PatDcl
* | def FunDcl
* | type [nl] TypeDcl
*/
diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
index d1214d8fe4..810d3e7497 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
@@ -67,8 +67,8 @@ abstract class TreeBuilder {
}
/** Traverse pattern and collect all variable names with their types in buffer
- * The variables keep their positions; whereas the pattern is converted to be synthetic
- * for all nodes that contain a variable position.
+ * The variables keep their positions; whereas the pattern is converted to be
+ * synthetic for all nodes that contain a variable position.
*/
class GetVarTraverser extends Traverser {
val buf = new ListBuffer[(Name, Tree, Position)]
@@ -149,7 +149,8 @@ abstract class TreeBuilder {
case _ => t
}
- def makeAnnotated(t: Tree, annot: Tree): Tree = atPos(annot.pos union t.pos)(Annotated(annot, t))
+ def makeAnnotated(t: Tree, annot: Tree): Tree =
+ atPos(annot.pos union t.pos)(Annotated(annot, t))
def makeSelfDef(name: TermName, tpt: Tree): ValDef =
ValDef(Modifiers(PRIVATE), name, tpt, EmptyTree)
@@ -261,7 +262,7 @@ abstract class TreeBuilder {
/** Create tree for for-comprehension generator <val pat0 <- rhs0> */
def makeGenerator(pos: Position, pat: Tree, valeq: Boolean, rhs: Tree): Enumerator = {
- val pat1 = patvarTransformer.transform(pat);
+ val pat1 = patvarTransformer.transform(pat)
val rhs1 =
if (valeq) rhs
else matchVarPattern(pat1) match {
@@ -582,7 +583,7 @@ abstract class TreeBuilder {
}
var cnt = 0
val restDefs = for ((vname, tpt, pos) <- vars) yield atPos(pos) {
- cnt = cnt + 1
+ cnt += 1
ValDef(mods, vname.toTermName, tpt, Select(Ident(tmp), newTermName("_" + cnt)))
}
firstDef :: restDefs
diff --git a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
index bfd5b175a7..0948e072b4 100644
--- a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
+++ b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
@@ -203,7 +203,7 @@ abstract class ScalaPrimitives {
private val primitives: mutable.Map[Symbol, Int] = new mutable.HashMap()
/** Initialize the primitive map */
- def init {
+ def init() {
primitives.clear()
// scala.Any
addPrimitive(Any_==, EQ)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
index 3d08e8734d..70bbd85330 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
@@ -206,7 +206,7 @@ trait BasicBlocks {
/** Remove the last instruction of this basic block. It is
* fast for an open block, but slower when the block is closed.
*/
- def removeLastInstruction {
+ def removeLastInstruction() {
if (closed)
removeInstructionsAt(size)
else {
@@ -301,7 +301,7 @@ trait BasicBlocks {
}
/** Close the block */
- def close {
+ def close() {
assert(!closed || ignore)
assert(instructionList.nonEmpty, "Empty block.")
closed = true
@@ -310,7 +310,7 @@ trait BasicBlocks {
instrs = instructionList.toArray
}
- def open {
+ def open() {
assert(closed)
closed = false
ignore = false
@@ -318,7 +318,7 @@ trait BasicBlocks {
instructionList = instructionList.reverse // prepare for appending to the head
}
- def clear {
+ def clear() {
instructionList = Nil
instrs = null
preds = null
@@ -330,11 +330,11 @@ trait BasicBlocks {
* added to this basic block. It makes the generation of THROW
* and RETURNs easier.
*/
- def enterIgnoreMode = {
+ def enterIgnoreMode() = {
ignore = true
}
- def exitIgnoreMode {
+ def exitIgnoreMode() {
assert(ignore, "Exit ignore mode when not in ignore mode.")
ignore = false
}
@@ -351,7 +351,7 @@ trait BasicBlocks {
def exceptionSuccessorsForBlock(block: BasicBlock): List[BasicBlock] =
method.exh collect { case x if x covers block => x.startBlock }
- /** Cached value of successors. Must be recomputed whenver a block in the current method is changed. */
+ /** Cached value of successors. Must be recomputed whenever a block in the current method is changed. */
private var succs: List[BasicBlock] = Nil
private def updateSuccs() {
resetFlag(DIRTYSUCCS)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
index 540c5f50dd..dd85541780 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
@@ -48,7 +48,7 @@ abstract class GenICode extends SubComponent {
var unit: CompilationUnit = _
- override def run {
+ override def run() {
scalaPrimitives.init
classes.clear
super.run
@@ -1142,10 +1142,14 @@ abstract class GenICode extends SubComponent {
log("Dropped an " + from);
case _ =>
- if (settings.debug.value)
- assert(from != UNIT, "Can't convert from UNIT to " + to + " at: " + pos)
- assert(!from.isReferenceType && !to.isReferenceType, "type error: can't convert from " + from + " to " + to +" in unit "+this.unit)
- ctx.bb.emit(CALL_PRIMITIVE(Conversion(from, to)), pos);
+ if (settings.debug.value) {
+ assert(from != UNIT,
+ "Can't convert from UNIT to " + to + " at: " + pos)
+ }
+ assert(!from.isReferenceType && !to.isReferenceType,
+ "type error: can't convert from " + from + " to " + to +" in unit " + unit.source + " at " + pos)
+
+ ctx.bb.emit(CALL_PRIMITIVE(Conversion(from, to)), pos)
}
} else if (from == NothingReference) {
ctx.bb.emit(THROW(ThrowableClass))
@@ -1485,7 +1489,7 @@ abstract class GenICode extends SubComponent {
log("Entering genCond with tree: " + tree);
// the default emission
- def default = {
+ def default() = {
val ctx1 = genLoad(tree, ctx, BOOL)
ctx1.bb.closeWith(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL) setPos tree.pos)
}
@@ -1994,11 +1998,11 @@ abstract class GenICode extends SubComponent {
new Context(this) setBasicBlock block
}
- def enterScope = {
+ def enterScope() {
scope = new Scope(scope)
}
- def exitScope = {
+ def exitScope() {
if (bb.nonEmpty) {
scope.locals foreach { lv => bb.emit(SCOPE_EXIT(lv)) }
}
diff --git a/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala b/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala
index b3e5001192..3d3097e497 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/ICodeCheckers.scala
@@ -86,7 +86,7 @@ abstract class ICodeCheckers {
checkerDebug(msg)
}
- def checkICodes: Unit = {
+ def checkICodes(): Unit = {
if (settings.verbose.value)
println("[[consistency check at the beginning of phase " + globalPhase.name + "]]")
classes.values foreach check
@@ -321,9 +321,9 @@ abstract class ICodeCheckers {
}
}
- def popStack = { checkStack(1) ; popStackN(1) match { case List(x) => x } }
- def popStack2 = { checkStack(2) ; popStackN(2) match { case List(x, y) => (x, y) } }
- def popStack3 = { checkStack(3) ; popStackN(3) match { case List(x, y, z) => (x, y, z) } }
+ def popStack = { checkStack(1) ; (popStackN(1): @unchecked) match { case List(x) => x } }
+ def popStack2 = { checkStack(2) ; (popStackN(2): @unchecked) match { case List(x, y) => (x, y) } }
+ def popStack3 = { checkStack(3) ; (popStackN(3): @unchecked) match { case List(x, y, z) => (x, y, z) } }
/** Called by faux instruction LOAD_EXCEPTION to wipe out the stack. */
def clearStack() = {
diff --git a/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala b/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
index c1f9481a0e..9c7c9e5010 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
@@ -61,7 +61,7 @@ abstract class ICodes extends AnyRef
/** Print all classes and basic blocks. Used for debugging. */
- def dump {
+ def dump() {
if (alreadyDumping) return
else alreadyDumping = true
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Members.scala b/src/compiler/scala/tools/nsc/backend/icode/Members.scala
index 69258c9ecb..630f109bb6 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Members.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Members.scala
@@ -198,7 +198,7 @@ trait Members { self: ICodes =>
override def toString() = symbol.fullName
import opcodes._
- def checkLocals: Unit = {
+ def checkLocals(): Unit = {
def localsSet = code.blocks.flatten collect {
case LOAD_LOCAL(l) => l
case STORE_LOCAL(l) => l
@@ -218,7 +218,7 @@ trait Members { self: ICodes =>
*
* This method should be most effective after heavy inlining.
*/
- def normalize: Unit = if (this.code ne null) {
+ def normalize(): Unit = if (this.code ne null) {
val nextBlock: mutable.Map[BasicBlock, BasicBlock] = mutable.HashMap.empty
for (b <- code.blocks.toList
if b.successors.length == 1;
@@ -251,7 +251,7 @@ trait Members { self: ICodes =>
checkValid(this)
}
- def dump {
+ def dump() {
val printer = new TextPrinter(new PrintWriter(Console.out, true),
new DumpLinearizer)
printer.printMethod(this)
@@ -262,10 +262,10 @@ trait Members { self: ICodes =>
class Local(val sym: Symbol, val kind: TypeKind, val arg: Boolean) {
var index: Int = -1
- /** Starting PC for this local's visbility range. */
+ /** Starting PC for this local's visibility range. */
var start: Int = _
- /** Ending PC for this local's visbility range. */
+ /** Ending PC for this local's visibility range. */
var end: Int = _
/** PC-based ranges for this local variable's visibility */
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Printers.scala b/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
index e9c288cdfa..958a708111 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
@@ -26,8 +26,8 @@ trait Printers { self: ICodes =>
def setWriter(w: PrintWriter) { out = w }
- def indent { margin += TAB }
- def undent { margin -= TAB }
+ def indent() { margin += TAB }
+ def undent() { margin -= TAB }
def print(s: String) { out.print(s) }
def print(o: Any) { print(o.toString()) }
@@ -37,7 +37,7 @@ trait Printers { self: ICodes =>
println
}
- def println {
+ def println() {
out.println()
var i = 0
while (i < margin) {
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
index ee3b579145..e1e9360e43 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
@@ -212,7 +212,7 @@ abstract class CopyPropagation {
}
}
- override def run {
+ override def run() {
forwardAnalysis(blockTransfer)
if (settings.debug.value) {
linearizer.linearize(method).foreach(b => if (b != method.code.startBlock)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
index 8c4aca19cf..60cb679782 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
@@ -43,7 +43,7 @@ trait DataFlowAnalysis[L <: SemiLattice] {
f
}
- def run: Unit
+ def run(): Unit
/** Implements forward dataflow analysis: the transfer function is
* applied when inputs to a Program point change, to obtain the new
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
index c8d9005ff4..7d96c72d2b 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
@@ -74,7 +74,7 @@ abstract class Liveness {
Pair(genSet, killSet)
}
- override def run {
+ override def run() {
backwardAnalysis(blockTransfer)
if (settings.debug.value) {
linearizer.linearize(method).foreach(b => if (b != method.code.startBlock)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
index 8e1d0e58a7..31a2dbfbec 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
@@ -142,7 +142,7 @@ abstract class ReachingDefinitions {
(drops, stackOut)
}
- override def run {
+ override def run() {
forwardAnalysis(blockTransfer)
if (settings.debug.value) {
linearizer.linearize(method).foreach(b => if (b != method.code.startBlock)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
index 11ed9557fd..0826a7676f 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
@@ -627,11 +627,11 @@ abstract class TypeFlowAnalysis {
private var lastStart = 0L
- def reset {
+ def reset() {
millis = 0L
}
- def start {
+ def start() {
lastStart = System.currentTimeMillis
}
diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala
new file mode 100644
index 0000000000..2f0d86c993
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/jvm/BytecodeWriters.scala
@@ -0,0 +1,92 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2011 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package backend.jvm
+
+import ch.epfl.lamp.fjbg._
+import java.io.{ DataOutputStream, OutputStream }
+import scala.tools.nsc.io.{ AbstractFile, Path }
+import scala.tools.nsc.util.ScalaClassLoader
+import scala.tools.util.Javap
+import java.util.jar.{ JarEntry, JarOutputStream }
+
+/** For the last mile: turning generated bytecode in memory into
+ * something you can use. Has implementations for writing to class
+ * files, jars, and disassembled/javap output.
+ */
+trait BytecodeWriters {
+ val global: Global
+ import global._
+
+ private def outputDirectory(sym: Symbol): AbstractFile = (
+ settings.outputDirs.outputDirFor {
+ atPhase(currentRun.flattenPhase.prev)(sym.sourceFile)
+ }
+ )
+ private def getFile(base: AbstractFile, cls: JClass, suffix: String): AbstractFile = {
+ var dir = base
+ val pathParts = cls.getName().split("[./]").toList
+ for (part <- pathParts.init) {
+ dir = dir.subdirectoryNamed(part)
+ }
+ dir.fileNamed(pathParts.last + suffix)
+ }
+ private def getFile(sym: Symbol, cls: JClass, suffix: String): AbstractFile =
+ getFile(outputDirectory(sym), cls, suffix)
+
+ trait BytecodeWriter {
+ def writeClass(label: String, jclass: JClass, sym: Symbol): Unit
+ def close(): Unit = ()
+ }
+
+ class DirectToJarfileWriter(val jarFile: AbstractFile) extends BytecodeWriter {
+ private val out = new JarOutputStream(jarFile.bufferedOutput)
+ def writeClass(label: String, jclass: JClass, sym: Symbol) {
+ val path = jclass.getName + ".class"
+ out putNextEntry new JarEntry(path)
+ val dataStream = new DataOutputStream(out)
+ try jclass writeTo dataStream
+ finally dataStream.flush()
+ informProgress("added " + label + path + " to jar")
+ }
+ override def close() = out.close()
+ }
+
+ trait JavapBytecodeWriter extends BytecodeWriter {
+ val baseDir = Path(settings.Ygenjavap.value)
+
+ def emitJavap(bytes: Array[Byte], javapFile: io.File) {
+ val pw = javapFile.printWriter()
+ val javap = new Javap(ScalaClassLoader.getSystemLoader(), pw) {
+ override def findBytes(path: String): Array[Byte] = bytes
+ }
+
+ try javap(Seq("-verbose", "dummy")) foreach (_.show())
+ finally pw.close()
+ }
+ abstract override def writeClass(label: String, jclass: JClass, sym: Symbol) {
+ super.writeClass(label, jclass, sym)
+
+ val bytes = getFile(sym, jclass, ".class").toByteArray
+ val segments = jclass.getName().split("[./]")
+ val javapFile = segments.foldLeft(baseDir)(_ / _) changeExtension "javap" toFile
+
+ javapFile.parent.createDirectory()
+ emitJavap(bytes, javapFile)
+ }
+ }
+
+ trait ClassBytecodeWriter extends BytecodeWriter {
+ def writeClass(label: String, jclass: JClass, sym: Symbol) {
+ val outfile = getFile(sym, jclass, ".class")
+ val outstream = new DataOutputStream(outfile.bufferedOutput)
+
+ try jclass writeTo outstream
+ finally outstream.close()
+ informProgress("wrote '" + label + "' to " + outfile)
+ }
+ }
+}
diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
index ac0cb97d45..76e0162593 100644
--- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
+++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
@@ -7,20 +7,19 @@
package scala.tools.nsc
package backend.jvm
-import java.io.DataOutputStream
+import java.io.{ DataOutputStream, OutputStream }
import java.nio.ByteBuffer
import scala.collection.{ mutable, immutable }
-import mutable.{ ListBuffer, LinkedHashSet }
import scala.reflect.generic.{ PickleFormat, PickleBuffer }
import scala.tools.reflect.SigParser
import scala.tools.nsc.io.{ AbstractFile, Path }
import scala.tools.nsc.util.ScalaClassLoader
import scala.tools.nsc.symtab._
import scala.tools.nsc.symtab.classfile.ClassfileConstants._
-
import ch.epfl.lamp.fjbg._
import JAccessFlags._
import JObjectType.{ JAVA_LANG_STRING, JAVA_LANG_OBJECT }
+import java.util.jar.{ JarEntry, JarOutputStream }
/** This class ...
*
@@ -28,7 +27,7 @@ import JObjectType.{ JAVA_LANG_STRING, JAVA_LANG_OBJECT }
* @version 1.0
*
*/
-abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
+abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with BytecodeWriters {
import global._
import icodes._
import icodes.opcodes._
@@ -45,27 +44,48 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
/** Create a new phase */
override def newPhase(p: Phase): Phase = new JvmPhase(p)
+ private def outputDirectory(sym: Symbol): AbstractFile = (
+ settings.outputDirs.outputDirFor {
+ atPhase(currentRun.flattenPhase.prev)(sym.sourceFile)
+ }
+ )
+ private def getFile(base: AbstractFile, cls: JClass, suffix: String): AbstractFile = {
+ var dir = base
+ val pathParts = cls.getName().split("[./]").toList
+ for (part <- pathParts.init) {
+ dir = dir.subdirectoryNamed(part)
+ }
+ dir.fileNamed(pathParts.last + suffix)
+ }
+ private def getFile(sym: Symbol, cls: JClass, suffix: String): AbstractFile =
+ getFile(outputDirectory(sym), cls, suffix)
+
/** JVM code generation phase
*/
class JvmPhase(prev: Phase) extends ICodePhase(prev) {
def name = phaseName
override def erasedTypes = true
+ def apply(cls: IClass) = sys.error("no implementation")
- override def run {
+ override def run() {
// we reinstantiate the bytecode generator at each run, to allow the GC
// to collect everything
- val codeGenerator = new BytecodeGenerator
if (settings.debug.value) inform("[running phase " + name + " on icode]")
if (settings.Xdce.value)
for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym))
icodes.classes -= sym
- classes.values foreach codeGenerator.genClass
- classes.clear
- }
-
- def apply(cls: IClass) {
- error("no implementation")
+ val bytecodeWriter = settings.outputDirs.getSingleOutput match {
+ case Some(f) if f hasExtension "jar" =>
+ new DirectToJarfileWriter(f)
+ case _ =>
+ if (settings.Ygenjavap.isDefault) new ClassBytecodeWriter { }
+ else new ClassBytecodeWriter with JavapBytecodeWriter { }
+ }
+ val codeGenerator = new BytecodeGenerator(bytecodeWriter)
+ classes.values foreach (codeGenerator genClass _)
+ bytecodeWriter.close()
+ classes.clear()
}
}
@@ -81,8 +101,10 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
* Java bytecode generator.
*
*/
- class BytecodeGenerator extends BytecodeUtil {
+ class BytecodeGenerator(bytecodeWriter: BytecodeWriter) extends BytecodeUtil {
+ def this() = this(new ClassBytecodeWriter { })
def debugLevel = settings.debuginfo.indexOfChoice
+ import bytecodeWriter.writeClass
val MIN_SWITCH_DENSITY = 0.7
val INNER_CLASSES_FLAGS =
@@ -139,18 +161,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
super.javaName(sym)
}
- protected def emitJavap(bytes: Array[Byte], javapFile: io.File) {
- import scala.tools.util.Javap
- val pw = javapFile.printWriter()
- try {
- val javap = new Javap(ScalaClassLoader.getSystemLoader(), pw) {
- override def findBytes(path: String): Array[Byte] = bytes
- }
- javap(Seq("-verbose", "dummy")) foreach (_.show())
- }
- finally pw.close()
- }
-
/** Write a class to disk, adding the Scala signature (pickled type
* information) and inner classes.
*
@@ -159,19 +169,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
*/
def emitClass(jclass: JClass, sym: Symbol) {
addInnerClasses(jclass)
- val outfile = getFile(sym, jclass, ".class")
- val outstream = new DataOutputStream(outfile.bufferedOutput)
- jclass writeTo outstream
- outstream.close()
- informProgress("wrote " + outfile)
-
- if (!settings.Ygenjavap.isDefault) {
- val segments = jclass.getName().split("[./]")
- val javapFile = segments.foldLeft(Path(settings.Ygenjavap.value))(_ / _) changeExtension "javap" toFile
-
- javapFile.parent.createDirectory()
- emitJavap(outfile.toByteArray, javapFile)
- }
+ writeClass("" + sym.name, jclass, sym)
}
/** Returns the ScalaSignature annotation if it must be added to this class,
@@ -219,7 +217,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
var isRemoteClass: Boolean = false
var isParcelableClass = false
- private val innerClassBuffer = new ListBuffer[Symbol]
+ private val innerClassBuffer = new mutable.ListBuffer[Symbol]
def genClass(c: IClass) {
clasz = c
@@ -301,6 +299,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
val ssa = scalaSignatureAddingMarker(jclass, c.symbol)
addGenericSignature(jclass, c.symbol, c.symbol.owner)
addAnnotations(jclass, c.symbol.annotations ++ ssa)
+
addEnclosingMethodAttribute(jclass, c.symbol)
emitClass(jclass, c.symbol)
@@ -407,11 +406,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
jcode.emitRETURN()
// write the bean information class file.
- val outfile = getFile(c.symbol, beanInfoClass, ".class")
- val outstream = new DataOutputStream(outfile.bufferedOutput)
- beanInfoClass writeTo outstream
- outstream.close()
- informProgress("wrote BeanInfo " + outfile)
+ writeClass("BeanInfo ", beanInfoClass, c.symbol)
}
/** Add the given 'throws' attributes to jmethod */
@@ -757,7 +752,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
if (!jmethod.isAbstract() && !method.native) {
val jcode = jmethod.getCode().asInstanceOf[JExtendedCode]
- // add a fake local for debugging purpuses
+ // add a fake local for debugging purposes
if (emitVars && isClosureApply(method.symbol)) {
val outerField = clasz.symbol.info.decl(nme.OUTER_LOCAL)
if (outerField != NoSymbol) {
@@ -833,7 +828,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
}
}
- def addModuleInstanceField {
+ def addModuleInstanceField() {
jclass.addNewField(PublicStaticFinal,
nme.MODULE_INSTANCE_FIELD.toString,
jclass.getType())
@@ -981,6 +976,9 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
*/
def addForwarders(jclass: JClass, moduleClass: Symbol) {
assert(moduleClass.isModuleClass)
+ if (settings.debug.value)
+ log("Dumping mirror class for object: " + moduleClass)
+
val className = jclass.getName
val linkedClass = moduleClass.companionClass
val linkedModule = linkedClass.companionSymbol
@@ -1031,7 +1029,9 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
* instead be made to add the forwarder methods to the companion class.
*/
def dumpMirrorClass(clasz: Symbol, sourceFile: String) {
- val mirrorName = javaName(clasz).init // drops "$"
+ import JAccessFlags._
+ val moduleName = javaName(clasz) // + "$"
+ val mirrorName = moduleName.substring(0, moduleName.length() - 1)
val mirrorClass = fjbgContext.JClass(ACC_SUPER | ACC_PUBLIC | ACC_FINAL,
mirrorName,
JAVA_LANG_OBJECT.getName,
@@ -1077,7 +1077,7 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
}
/** Generate exception handlers for the current method. */
- def genExceptionHandlers {
+ def genExceptionHandlers() {
/** Return a list of pairs of intervals where the handler is active.
* The intervals in the list have to be inclusive in the beginning and
@@ -1803,19 +1803,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid {
(sym.isJavaDefined && sym.isNonBottomSubClass(ClassfileAnnotationClass))
}
- /** Return an abstract file for the given class symbol, with the desired suffix.
- * Create all necessary subdirectories on the way.
- */
- def getFile(sym: Symbol, cls: JClass, suffix: String): AbstractFile = {
- val sourceFile = atPhase(currentRun.flattenPhase.prev)(sym.sourceFile)
- var dir: AbstractFile = settings.outputDirs.outputDirFor(sourceFile)
- val pathParts = cls.getName().split("[./]").toList
- for (part <- pathParts.init) {
- dir = dir.subdirectoryNamed(part)
- }
- dir.fileNamed(pathParts.last + suffix)
- }
-
/** Merge adjacent ranges. */
private def mergeEntries(ranges: List[(Int, Int)]): List[(Int, Int)] =
(ranges.foldLeft(Nil: List[(Int, Int)]) { (collapsed: List[(Int, Int)], p: (Int, Int)) => (collapsed, p) match {
diff --git a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
index d593a13d8b..1968ca56aa 100644
--- a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
+++ b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
@@ -36,7 +36,7 @@ abstract class GenMSIL extends SubComponent {
override def erasedTypes = true
- override def run {
+ override def run() {
if (settings.debug.value) inform("[running phase " + name + " on icode]")
val codeGenerator = new BytecodeGenerator
@@ -784,7 +784,7 @@ abstract class GenMSIL extends SubComponent {
/** There might be open handlers, but no more blocks. happens when try/catch end
* with `throw` or `return`
- * def foo { try { .. throw } catch { _ => .. throw } }
+ * def foo() { try { .. throw } catch { _ => .. throw } }
*
* In this case we need some code after the catch block for the auto-generated
* `leave` instruction. So we're adding a (dead) `throw new Exception`.
@@ -1091,7 +1091,7 @@ abstract class GenMSIL extends SubComponent {
// we're generating a constructor (method: IMethod is a constructor), and we're
// calling another constructor of the same class.
- // @LUC TODO: this can probably break, namely when having: class A { def this { new A() } }
+ // @LUC TODO: this can probably break, namely when having: class A { def this() { new A() } }
// instead, we should instruct the CALL_METHOD with additional information, know whether it's
// an instance creation constructor call or not.
mcode.Emit(OpCodes.Call, constructorInfo)
@@ -1114,7 +1114,7 @@ abstract class GenMSIL extends SubComponent {
var doEmit = true
getTypeOpt(msym.owner) match {
case Some(typ) if (typ.IsEnum) => {
- def negBool = {
+ def negBool() = {
mcode.Emit(OpCodes.Ldc_I4_0)
mcode.Emit(OpCodes.Ceq)
}
diff --git a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
index e1774523a5..d176ef43e3 100644
--- a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
+++ b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
@@ -131,7 +131,7 @@ abstract class DeadCodeElimination extends SubComponent {
/** Mark useful instructions. Instructions in the worklist are each inspected and their
* dependencies are marked useful too, and added to the worklist.
*/
- def mark {
+ def mark() {
// log("Starting with worklist: " + worklist)
while (!worklist.isEmpty) {
val (bb, idx) = worklist.iterator.next
diff --git a/src/compiler/scala/tools/nsc/doc/doclet/Generator.scala b/src/compiler/scala/tools/nsc/doc/doclet/Generator.scala
index 2caf67ee78..735b79c336 100644
--- a/src/compiler/scala/tools/nsc/doc/doclet/Generator.scala
+++ b/src/compiler/scala/tools/nsc/doc/doclet/Generator.scala
@@ -19,12 +19,12 @@ abstract class Generator {
mutable.Set.empty[()=>Boolean]
/** Outputs documentation (as a side effect). */
- def generate: Unit = {
+ def generate(): Unit = {
assert(checks forall { check => check() })
generateImpl
}
/** Outputs documentation (as a side effect). This method is called only if all `checks` are true. */
- protected def generateImpl: Unit
+ protected def generateImpl(): Unit
}
diff --git a/src/compiler/scala/tools/nsc/doc/html/Doclet.scala b/src/compiler/scala/tools/nsc/doc/html/Doclet.scala
index a16fc920c6..035a6e3dfa 100644
--- a/src/compiler/scala/tools/nsc/doc/html/Doclet.scala
+++ b/src/compiler/scala/tools/nsc/doc/html/Doclet.scala
@@ -6,7 +6,7 @@ import doclet._
/** * The default doclet used by the scaladoc command line tool when no user-provided doclet is provided. */
class Doclet extends Generator with Universer with Indexer {
- def generateImpl {
+ def generateImpl() {
new html.HtmlFactory(universe, index).generate
}
diff --git a/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala b/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala
index 8d260c2889..7e1be90d3d 100644
--- a/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala
+++ b/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala
@@ -24,7 +24,7 @@ class HtmlFactory(val universe: doc.Universe, index: doc.Index) {
/** Generates the Scaladoc site for a model into the site root. A scaladoc site is a set of HTML and related files
* that document a model extracted from a compiler run.
* @param model The model to generate in the form of a sequence of packages. */
- def generate : Unit = {
+ def generate() {
def copyResource(subPath: String) {
val bytes = new Streamable.Bytes {
diff --git a/src/compiler/scala/tools/nsc/doc/model/Entity.scala b/src/compiler/scala/tools/nsc/doc/model/Entity.scala
index 86de011e68..a09194c2dd 100644
--- a/src/compiler/scala/tools/nsc/doc/model/Entity.scala
+++ b/src/compiler/scala/tools/nsc/doc/model/Entity.scala
@@ -161,7 +161,7 @@ trait MemberEntity extends Entity {
/** Whether this member is implicit. */
def isImplicit: Boolean
- /** Whether this member is abtract. */
+ /** Whether this member is abstract. */
def isAbstract: Boolean
}
@@ -260,7 +260,7 @@ trait Class extends Trait with HigherKinded {
def constructors: List[Constructor]
/** The value parameters of this case class, or an empty list if this class is not a case class. As case class value
- * paramters cannot be curried, the outer list has exactly one element. */
+ * parameters cannot be curried, the outer list has exactly one element. */
def valueParams: List[List[ValueParam]]
}
diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
index 405da29a57..db616e9657 100644
--- a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
+++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
@@ -449,7 +449,7 @@ class ModelFactory(val global: Global, val settings: doc.Settings) { thisFactory
else if (bSym.isMethod && !bSym.hasAccessorFlag && !bSym.isConstructor && !bSym.isModule) {
val cSym = { // This unsightly hack closes issue #4086.
if (bSym == definitions.Object_synchronized) {
- val cSymInfo = bSym.info match {
+ val cSymInfo = (bSym.info: @unchecked) match {
case PolyType(ts, MethodType(List(bp), mt)) =>
val cp = bp.cloneSymbol.setInfo(appliedType(definitions.ByNameParamClass.typeConstructor, List(bp.info)))
PolyType(ts, MethodType(List(cp), mt))
diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala
index d8f43fd209..da97e10584 100644
--- a/src/compiler/scala/tools/nsc/interactive/Global.scala
+++ b/src/compiler/scala/tools/nsc/interactive/Global.scala
@@ -144,7 +144,7 @@ class Global(settings: Settings, reporter: Reporter, projectName: String = "")
unitOfFile.getOrElse(source.file, { println("precondition violated: "+source+" is not loaded"); new Exception().printStackTrace(); new RichCompilationUnit(source) })
/** Work through toBeRemoved list to remove any units.
- * Then return optionlly unit associated with given source.
+ * Then return optionally unit associated with given source.
*/
protected[interactive] def getUnit(s: SourceFile): Option[RichCompilationUnit] = {
toBeRemoved.synchronized {
diff --git a/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala b/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala
index 38ad73686a..f78365a7a8 100644
--- a/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala
+++ b/src/compiler/scala/tools/nsc/interactive/tests/InteractiveTest.scala
@@ -94,7 +94,7 @@ abstract class InteractiveTest {
adjustPaths(settings.bootclasspath, settings.classpath, settings.javabootclasspath, settings.sourcepath)
}
- protected def printClassPath {
+ protected def printClassPath() {
println("\toutDir: %s".format(outDir.path))
println("\tbaseDir: %s".format(baseDir.path))
println("\targsString: %s".format(argsString))
@@ -229,7 +229,7 @@ abstract class InteractiveTest {
reload.get
}
- def runTest: Unit = {
+ def runTest(): Unit = {
if (runRandomTests) randomTests(20, sourceFiles)
completionTests()
typeAtTests()
diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala
index fbb3457f4d..74a23d119d 100644
--- a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala
@@ -268,6 +268,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: PrintWriter)
cmd("phase", "<phase>", "set the implicit phase for power commands", phaseCommand),
cmd("wrap", "<method>", "name of method to wrap around each repl line", wrapCommand) withLongHelp ("""
|:wrap
+ |:wrap clear
|:wrap <method>
|
|Installs a wrapper around each line entered into the repl.
@@ -281,7 +282,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: PrintWriter)
|}
|:wrap timed
|
- |If given no argument, :wrap removes any wrapper present.
+ |If given no argument, :wrap names the wrapper installed.
+ |An argument of clear will remove the wrapper if any is active.
|Note that wrappers do not compose (a new one replaces the old
|one) and also that the :phase command uses the same machinery,
|so setting :wrap will clear any :phase setting.
@@ -436,8 +438,15 @@ class ILoop(in0: Option[BufferedReader], protected val out: PrintWriter)
words(line) match {
case Nil =>
- intp setExecutionWrapper ""
- "Cleared wrapper."
+ intp.executionWrapper match {
+ case "" => "No execution wrapper is set."
+ case s => "Current execution wrapper: " + s
+ }
+ case "clear" :: Nil =>
+ intp.executionWrapper match {
+ case "" => "No execution wrapper is set."
+ case s => intp.clearExecutionWrapper() ; "Cleared execution wrapper."
+ }
case wrapper :: Nil =>
intp.typeOfExpression(wrapper) match {
case Some(PolyType(List(targ), MethodType(List(arg), restpe))) =>
@@ -673,7 +682,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: PrintWriter)
}
def transcript(start: String) = {
- // Printing this message doesn't work very well becaues it's buried in the
+ // Printing this message doesn't work very well because it's buried in the
// transcript they just pasted. Todo: a short timer goes off when
// lines stop coming which tells them to hit ctrl-D.
//
diff --git a/src/compiler/scala/tools/nsc/interpreter/Power.scala b/src/compiler/scala/tools/nsc/interpreter/Power.scala
index c2f72e9f37..5a0830841d 100644
--- a/src/compiler/scala/tools/nsc/interpreter/Power.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/Power.scala
@@ -106,11 +106,12 @@ abstract class Power[G <: Global](
val modClass = pkgSymbol.moduleClass
/** Looking for dwindling returns */
- def droppedEnough() = unseenHistory.size >= 4 && (
- unseenHistory.takeRight(4).sliding(2) map (_.toList) forall {
- case List(a, b) => a > b
+ def droppedEnough() = unseenHistory.size >= 4 && {
+ unseenHistory takeRight 4 sliding 2 forall { it =>
+ val List(a, b) = it.toList
+ a > b
}
- )
+ }
def isRecur(sym: Symbol) = true
def isIgnore(sym: Symbol) = sym.isAnonOrRefinementClass || (sym.name.toString contains "$mc")
@@ -134,7 +135,7 @@ abstract class Power[G <: Global](
def init = customInit getOrElse """
|import scala.tools.nsc._
|import scala.collection.JavaConverters._
- |import global._
+ |import global.{ error => _, _ }
|import power.Implicits._
""".stripMargin
@@ -280,7 +281,7 @@ abstract class Power[G <: Global](
class PrintingConvenience[T: Prettifier](value: T) {
val pretty = implicitly[Prettifier[T]]
- def > { >(_ => true) }
+ def >() { >(_ => true) }
def >(s: String): Unit = >(_ contains s)
def >(r: Regex): Unit = >(_ matches r.pattern.toString)
def >(p: String => Boolean): Unit = pretty.grep(value, p)
diff --git a/src/compiler/scala/tools/nsc/io/AbstractFile.scala b/src/compiler/scala/tools/nsc/io/AbstractFile.scala
index 54f74beb2c..12a632fca6 100644
--- a/src/compiler/scala/tools/nsc/io/AbstractFile.scala
+++ b/src/compiler/scala/tools/nsc/io/AbstractFile.scala
@@ -114,10 +114,10 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
def isClassContainer = isDirectory || (sfile exists (Path isJarOrZip _))
/** Create a file on disk, if one does not exist already. */
- def create: Unit
+ def create(): Unit
/** Delete the underlying file or directory (recursively). */
- def delete: Unit
+ def delete(): Unit
/** Is this abstract file a directory? */
def isDirectory: Boolean
diff --git a/src/compiler/scala/tools/nsc/io/Jar.scala b/src/compiler/scala/tools/nsc/io/Jar.scala
index bd7dbde5ec..e8eab682fc 100644
--- a/src/compiler/scala/tools/nsc/io/Jar.scala
+++ b/src/compiler/scala/tools/nsc/io/Jar.scala
@@ -82,7 +82,7 @@ class JarWriter(file: File, val manifest: Manifest = new Manifest()) {
}
private def transfer(in: InputStream, out: OutputStream) = {
val buf = new Array[Byte](10240)
- def loop: Unit = in.read(buf, 0, buf.length) match {
+ def loop(): Unit = in.read(buf, 0, buf.length) match {
case -1 => in.close()
case n => out.write(buf, 0, n) ; loop
}
diff --git a/src/compiler/scala/tools/nsc/io/Lexer.scala b/src/compiler/scala/tools/nsc/io/Lexer.scala
index 262aac7809..8f103f9b98 100644
--- a/src/compiler/scala/tools/nsc/io/Lexer.scala
+++ b/src/compiler/scala/tools/nsc/io/Lexer.scala
@@ -30,10 +30,10 @@ object Lexer {
/** A subclass of token representing integer literals */
case class IntLit(override val str: String) extends Token(str)
- /** A subclass of token representaing floating point literals */
+ /** A subclass of token representing floating point literals */
case class FloatLit(override val str: String) extends Token(str)
- /** A subclass of token represenating string literals */
+ /** A subclass of token representing string literals */
case class StringLit(override val str: String) extends Token(str) {
override def toString = quoted(str)
}
diff --git a/src/compiler/scala/tools/nsc/io/Pickler.scala b/src/compiler/scala/tools/nsc/io/Pickler.scala
index 78c1369b64..fe9aa3b9c0 100644
--- a/src/compiler/scala/tools/nsc/io/Pickler.scala
+++ b/src/compiler/scala/tools/nsc/io/Pickler.scala
@@ -5,7 +5,7 @@ import Lexer._
import java.io.Writer
/** An abstract class for writing and reading Scala objects to and
- * from a legible representation. The presesentation follows the folloing grammar:
+ * from a legible representation. The presesentation follows the following grammar:
* {{{
* Pickled = `true' | `false' | `null' | NumericLit | StringLit |
* Labelled | Pickled `,' Pickled
diff --git a/src/compiler/scala/tools/nsc/io/PlainFile.scala b/src/compiler/scala/tools/nsc/io/PlainFile.scala
index 9e7b6d6655..ce4bca490f 100644
--- a/src/compiler/scala/tools/nsc/io/PlainFile.scala
+++ b/src/compiler/scala/tools/nsc/io/PlainFile.scala
@@ -76,10 +76,10 @@ class PlainFile(val givenPath: Path) extends AbstractFile {
}
/** Does this abstract file denote an existing file? */
- def create: Unit = if (!exists) givenPath.createFile()
+ def create(): Unit = if (!exists) givenPath.createFile()
/** Delete the underlying file or directory (recursively). */
- def delete: Unit =
+ def delete(): Unit =
if (givenPath.isFile) givenPath.delete()
else if (givenPath.isDirectory) givenPath.toDirectory.deleteRecursively()
diff --git a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
index 66ff9e6011..0bcb2de43f 100644
--- a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
+++ b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
@@ -31,10 +31,10 @@ extends AbstractFile {
override def output = sys.error("directories cannot be written")
/** Does this abstract file denote an existing file? */
- def create { unsupported }
+ def create() { unsupported }
/** Delete the underlying file or directory (recursively). */
- def delete { unsupported }
+ def delete() { unsupported }
/** Returns an abstract file with the given name. It does not
* check that it exists.
diff --git a/src/compiler/scala/tools/nsc/io/VirtualFile.scala b/src/compiler/scala/tools/nsc/io/VirtualFile.scala
index d7176364c0..4a8aa1a69d 100644
--- a/src/compiler/scala/tools/nsc/io/VirtualFile.scala
+++ b/src/compiler/scala/tools/nsc/io/VirtualFile.scala
@@ -78,10 +78,10 @@ class VirtualFile(val name: String, _path: String) extends AbstractFile
}
/** Does this abstract file denote an existing file? */
- def create { unsupported }
+ def create() { unsupported }
/** Delete the underlying file or directory (recursively). */
- def delete { unsupported }
+ def delete() { unsupported }
/**
* Returns the abstract file in this abstract directory with the
diff --git a/src/compiler/scala/tools/nsc/io/ZipArchive.scala b/src/compiler/scala/tools/nsc/io/ZipArchive.scala
index cba92d813f..22121cc714 100644
--- a/src/compiler/scala/tools/nsc/io/ZipArchive.scala
+++ b/src/compiler/scala/tools/nsc/io/ZipArchive.scala
@@ -285,8 +285,8 @@ final class URLZipArchive(url: URL) extends AbstractFile with ZipContainer {
/** Methods we don't support but have to implement because of the design */
def file: JFile = null
- def create: Unit = unsupported
- def delete: Unit = unsupported
+ def create(): Unit = unsupported
+ def delete(): Unit = unsupported
def output = unsupported
def container = unsupported
diff --git a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
index c600f6364b..ed5ebb1a01 100644
--- a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
+++ b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
@@ -63,7 +63,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
var errpos: ScanPosition
var lastPos: ScanPosition
def skipToken: ScanPosition
- def nextToken: Unit
+ def nextToken(): Unit
def next: AbstractJavaTokenData
def intVal(negated: Boolean): Long
def floatVal(negated: Boolean): Double
@@ -282,7 +282,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
p - 1
}
- def nextToken {
+ def nextToken() {
if (next.token == EMPTY) {
fetchToken()
}
@@ -648,7 +648,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
// Identifiers ---------------------------------------------------------------
- private def getIdentRest {
+ private def getIdentRest() {
while (true) {
(in.ch: @switch) match {
case 'A' | 'B' | 'C' | 'D' | 'E' |
@@ -734,7 +734,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
/** read fractional part and exponent of floating point number
* if one is present.
*/
- protected def getFraction {
+ protected def getFraction() {
token = DOUBLELIT
while ('0' <= in.ch && in.ch <= '9') {
putChar(in.ch)
@@ -823,7 +823,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
}
/** read a number into name and set base
*/
- protected def getNumber {
+ protected def getNumber() {
while (digit2int(in.ch, if (base < 10) 10 else base) >= 0) {
putChar(in.ch)
in.next
@@ -905,7 +905,7 @@ trait JavaScanners extends ast.parser.ScannersCommon {
/** INIT: read lookahead character and token.
*/
- def init {
+ def init() {
in.next
nextToken
}
diff --git a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala
index ca2e252d35..c5673fced7 100644
--- a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala
+++ b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala
@@ -31,10 +31,7 @@ trait MatchSupport extends ast.TreeDSL { self: ParallelMatching =>
import definitions._
implicit def enrichType(x: Type): RichType = new RichType(x)
- // A subtype test which creates fresh existentials for type
- // parameters on the right hand side.
- private[matching] def matches(arg1: Type, arg2: Type) =
- decodedEqualsType(arg1) matchesPattern decodedEqualsType(arg2)
+ val subrangeTypes = Set(ByteClass, ShortClass, CharClass, IntClass)
class RichType(undecodedTpe: Type) {
def tpe = decodedEqualsType(undecodedTpe)
diff --git a/src/compiler/scala/tools/nsc/matching/Matrix.scala b/src/compiler/scala/tools/nsc/matching/Matrix.scala
index 8dc960894c..6b691826a9 100644
--- a/src/compiler/scala/tools/nsc/matching/Matrix.scala
+++ b/src/compiler/scala/tools/nsc/matching/Matrix.scala
@@ -128,6 +128,10 @@ trait Matrix extends MatrixAdditions {
}
def recordSyntheticSym(sym: Symbol): Symbol = {
_syntheticSyms += sym
+ if (_syntheticSyms.size > 25000) {
+ cunit.error(owner.pos, "Sanity check failed: over 25000 symbols created for pattern match.")
+ abort("This is a bug in the pattern matcher.")
+ }
sym
}
@@ -236,6 +240,12 @@ trait Matrix extends MatrixAdditions {
tracing("create")(new PatternVar(lhs, rhs, checked))
}
+ def createLazy(tpe: Type, f: Symbol => Tree, checked: Boolean) = {
+ val lhs = newVar(owner.pos, tpe, Flags.LAZY :: flags(checked))
+ val rhs = f(lhs)
+
+ tracing("createLazy")(new PatternVar(lhs, rhs, checked))
+ }
private def newVar(
pos: Position,
diff --git a/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala b/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala
index e59d8c7858..c5c57938ca 100644
--- a/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala
+++ b/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala
@@ -136,7 +136,7 @@ trait MatrixAdditions extends ast.TreeDSL {
/** Exhaustiveness checking requires looking for sealed classes
* and if found, making sure all children are covered by a pattern.
*/
- class ExhaustivenessChecker(rep: Rep) {
+ class ExhaustivenessChecker(rep: Rep, matchPos: Position) {
val Rep(tvars, rows) = rep
import Flags.{ MUTABLE, ABSTRACT, SEALED }
@@ -201,7 +201,7 @@ trait MatrixAdditions extends ast.TreeDSL {
def check = {
def errMsg = (inexhaustives map mkMissingStr).mkString
if (inexhaustives.nonEmpty)
- cunit.warning(tvars.head.lhs.pos, "match is not exhaustive!\n" + errMsg)
+ cunit.warning(matchPos, "match is not exhaustive!\n" + errMsg)
rep
}
diff --git a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
index f41c37080a..e198656eb5 100644
--- a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
+++ b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
@@ -50,14 +50,10 @@ trait ParallelMatching extends ast.TreeDSL
shortCuts(key) = theLabel
-key
}
+ def createLabelDef(prefix: String, params: List[Symbol] = Nil, tpe: Type = matchResultType) = {
+ val labelSym = owner.newLabel(owner.pos, cunit.freshTermName(prefix)) setInfo MethodType(params, tpe)
- /** first time bx is requested, a LabelDef is returned. next time, a jump.
- * the function takes care of binding
- */
- final def requestBody(bx: Int, subst: Bindings): Tree = {
- // shortcut
- if (bx < 0) Apply(ID(shortCuts(-bx)), Nil)
- else targets(bx) labelBody subst
+ (body: Tree) => LabelDef(labelSym, params, body setType tpe)
}
/** This is the recursively focal point for translating the current
@@ -74,7 +70,11 @@ trait ParallelMatching extends ast.TreeDSL
val newRows = rows1 flatMap (_ expandAlternatives classifyPat)
if (rows1.length != newRows.length) make(roots1, newRows) // recursive call if any change
- else Rep(roots1, newRows).checkExhaustive
+ else {
+ val rep = Rep(roots1, newRows)
+ new ExhaustivenessChecker(rep, roots.head.sym.pos).check
+ rep
+ }
}
override def toString() = "MatchMatrix(%s) { %s }".format(matchResultType, indentAll(targets))
@@ -108,7 +108,7 @@ trait ParallelMatching extends ast.TreeDSL
// tests
def isDefined = sym ne NoSymbol
- def isSubrangeType = Set(ByteClass, ShortClass, CharClass, IntClass) contains tpe.typeSymbol
+ def isSubrangeType = subrangeTypes(tpe.typeSymbol)
def isCaseClass = tpe.typeSymbol.isCase
// sequences
@@ -171,8 +171,7 @@ trait ParallelMatching extends ast.TreeDSL
def size = ps.length
def headType = head.necessaryType
- def isCaseHead = head.isCaseClass
- private val dummyCount = if (isCaseHead) headType.typeSymbol.caseFieldAccessors.length else 0
+ private val dummyCount = if (head.isCaseClass) headType.typeSymbol.caseFieldAccessors.length else 0
def dummies = emptyPatterns(dummyCount)
def apply(i: Int): Pattern = ps(i)
@@ -205,12 +204,6 @@ trait ParallelMatching extends ast.TreeDSL
override def toString() = "%s match {%s}".format(scrut, indentAll(ps))
} // PatternMatch
- /** picks which rewrite rule to apply
- * @precondition: column does not contain alternatives
- */
- def MixtureRule(scrut: Scrutinee, column: List[Pattern], rest: Rep): RuleApplication =
- PatternMatch(scrut, column) mkRule rest
-
/***** Rule Applications *****/
sealed abstract class RuleApplication {
@@ -250,14 +243,21 @@ trait ParallelMatching extends ast.TreeDSL
def pmatch: PatternMatch = impossible
def rest: Rep = guardedRest
- lazy val cond = if (guard.isEmpty) TRUE else guard
- lazy val success = requestBody(bx, subst)
- lazy val failure = guardedRest.toTree
- lazy val pvgroup = PatternVarGroup.fromBindings(subst.get())
+ private lazy val (valDefs, successTree) = targets(bx) applyBindings subst.toMap
+ lazy val cond = guard
+ lazy val success = successTree
+ lazy val failure = guardedRest.toTree
final def tree(): Tree =
- if (guard.isEmpty) success
- else squeezedBlock(pvgroup.valDefs, codegen)
+ if (bx < 0) REF(shortCuts(-bx))
+ else squeezedBlock(
+ valDefs,
+ if (cond.isEmpty) success else codegen
+ )
+
+ override def toString = "(case %d) {\n Bindings: %s\n\n if (%s) { %s }\n else { %s }\n}".format(
+ bx, subst, guard, success, guardedRest
+ )
}
class MixLiteralInts(val pmatch: PatternSwitch, val rest: Rep) extends RuleApplication {
@@ -287,8 +287,8 @@ trait ParallelMatching extends ast.TreeDSL
// bound vars and rows for default pattern (only one row, but a list is easier to use later)
lazy val (defaultVars, defaultRows) = defaultPattern match {
- case None => (Nil, Nil)
- case Some(Pattern(_, vs)) => (vs, List(rebindAll(rest rows literals.size, vs, scrut.sym)))
+ case None => (Nil, Nil)
+ case Some(p) => (p.boundVariables, List(rebindAll(rest rows literals.size, p.boundVariables, scrut.sym)))
}
// literalMap is a map from each literal to a list of row indices.
@@ -330,46 +330,41 @@ trait ParallelMatching extends ast.TreeDSL
/** mixture rule for unapply pattern
*/
class MixUnapply(val pmatch: PatternMatch, val rest: Rep) extends RuleApplication {
- val uapattern = head match { case x: UnapplyPattern => x ; case _ => abort("XXX") }
- val ua @ UnApply(app, args) = head.tree
-
- // Note: trailingArgs is not necessarily Nil, because unapply can take implicit parameters.
- val Apply(fxn, _ :: trailingArgs) = app
- private def reapply = Apply(fxn, scrut.id :: trailingArgs)
+ val Pattern(UnApply(unMethod, unArgs)) = head
+ val Apply(unTarget, _ :: trailing) = unMethod
+
+ object SameUnapplyCall {
+ def isSame(t: Tree) = isEquivalentTree(unTarget, t)
+ def unapply(x: Pattern) = /*tracing("SameUnapplyCall (%s vs. %s)".format(unTarget, x))*/(x match {
+ case Pattern(UnApply(Apply(fn, _), args)) if isSame(fn) => Some(args)
+ case _ => None
+ })
+ }
+ object SameUnapplyPattern {
+ def isSame(t: Tree) = isEquivalentTree(unMethod, t)
+ def apply(x: Pattern) = unapply(x).isDefined
+ def unapply(x: Pattern) = /*tracing("SameUnapplyPattern (%s vs. %s)".format(unMethod, x))*/(x match {
+ case Pattern(UnApply(t, _)) if isSame(t) => Some(unArgs)
+ case _ => None
+ })
+ }
private lazy val zipped = pmatch pzip rest.rows
lazy val unapplyResult: PatternVar =
- scrut.createVar(app.tpe, lhs => reapply setType lhs.tpe)
-
- // XXX in transition.
- object sameUnapplyCall {
- private def sameFunction(fn1: Tree) = fxn.symbol == fn1.symbol && (fxn equalsStructure fn1)
-
- def unapply(p: Pattern) = condOpt(p) {
- case Pattern(UnApply(Apply(fn1, _), args), _) if sameFunction(fn1) =>
- tracing("sameUnapply")(args)
- }
- }
- object SameUnapply {
- def unapply(p: Pattern) = p match {
- case x: UnapplyPattern if uapattern isSameUnapply x => Some(args)
- case _ => None
- }
- }
- def isSameUnapply(p: Pattern) = SameUnapply.unapply(p).isDefined
+ scrut.createVar(unMethod.tpe, Apply(unTarget, scrut.id :: trailing) setType _.tpe)
lazy val cond: Tree =
if (unapplyResult.tpe.isBoolean) ID(unapplyResult.valsym)
else unapplyResult.valsym IS_DEFINED
lazy val failure =
- mkFail(zipped.tail filterNot (x => isSameUnapply(x._1)) map { case (pat, r) => r insert pat })
+ mkFail(zipped.tail filterNot (x => SameUnapplyPattern(x._1)) map { case (pat, r) => r insert pat })
private def doSuccess: (List[PatternVar], List[PatternVar], List[Row]) = {
// pattern variable for the unapply result of Some(x).get
lazy val pv = scrut.createVar(
- app.tpe typeArgs 0,
+ unMethod.tpe typeArgs 0,
_ => fn(ID(unapplyResult.lhs), nme.get)
)
def tuple = pv.lhs
@@ -384,15 +379,15 @@ trait ParallelMatching extends ast.TreeDSL
// the filter prevents infinite unapply recursion
def mkNewRows(sameFilter: (List[Tree]) => List[Tree]) = {
- val dum = if (args.length <= 1) args.length else tpes.size
+ val dum = if (unArgs.length <= 1) unArgs.length else tpes.size
for ((pat, r) <- zipped) yield pat match {
- case sameUnapplyCall(xs) => r.insert2(toPats(sameFilter(xs)) ::: List(NoPattern), pat.boundVariables, scrut.sym)
- case _ => r insert (emptyPatterns(dum) ::: List(pat))
+ case SameUnapplyCall(xs) => r.insert2(toPats(sameFilter(xs)) :+ NoPattern, pat.boundVariables, scrut.sym)
+ case _ => r insert (emptyPatterns(dum) :+ pat)
}
}
// 0 is Boolean, 1 is Option[T], 2+ is Option[(T1,T2,...)]
- args.length match {
+ unArgs.length match {
case 0 => (Nil, Nil, mkNewRows((xs) => Nil))
case 1 => (List(pv), List(pv), mkNewRows(xs => List(xs.head)))
case _ => (pv :: tuplePVs, tuplePVs, mkNewRows(identity))
@@ -420,9 +415,6 @@ trait ParallelMatching extends ast.TreeDSL
private def pivotLen = pivot.nonStarLength
private def seqDummies = emptyPatterns(pivot.elems.length + 1)
- // one pattern var per sequence element up to elemCount, and one more for the rest of the sequence
- lazy val pvs = scrut createSequenceVars pivotLen
-
// Should the given pattern join the expanded pivot in the success matrix? If so,
// this partial function will be defined for the pattern, and the result of the apply
// is the expanded sequence of new patterns.
@@ -500,35 +492,31 @@ trait ParallelMatching extends ast.TreeDSL
nullSafe(compareFn, FALSE)(scrut.id)
// condition(head.tpe, scrut.id, head.boundVariables.nonEmpty)
}
- lazy val success = squeezedBlock(pvs map (_.valDef), remake(successRows, pvs, hasStar).toTree)
+ lazy val success = {
+ // one pattern var per sequence element up to elemCount, and one more for the rest of the sequence
+ lazy val pvs = scrut createSequenceVars pivotLen
+
+ squeezedBlock(pvs map (_.valDef), remake(successRows, pvs, hasStar).toTree)
+ }
lazy val failure = remake(failRows).toTree
final def tree(): Tree = codegen
}
- // @todo: equals test for same constant
class MixEquals(val pmatch: PatternMatch, val rest: Rep) extends RuleApplication {
- private lazy val labelBody =
- remake((rest.rows.tail, pmatch.tail).zipped map (_ insert _)).toTree
-
private lazy val rhs =
decodedEqualsType(head.tpe) match {
case SingleType(pre, sym) => REF(pre, sym)
case PseudoType(o) => o
}
+ private lazy val labelDef =
+ createLabelDef("fail%")(remake((rest.rows.tail, pmatch.tail).zipped map (_ insert _)).toTree)
- lazy val label =
- owner.newLabel(scrut.pos, cunit.freshTermName("failCont%")) setInfo MethodType(Nil, labelBody.tpe)
-
- lazy val cond =
- handleOuter(rhs MEMBER_== scrut.id )
-
- lazy val success = remake(List(
- rest.rows.head.insert2(List(NoPattern), head.boundVariables, scrut.sym),
- Row(emptyPatterns(1 + rest.tvars.size), NoBinding, EmptyTree, createShortCut(label))
- )).toTree
-
- lazy val failure = LabelDef(label, Nil, labelBody)
+ lazy val cond = handleOuter(rhs MEMBER_== scrut.id)
+ lazy val successOne = rest.rows.head.insert2(List(NoPattern), head.boundVariables, scrut.sym)
+ lazy val successTwo = Row(emptyPatterns(1 + rest.tvars.size), NoBinding, EmptyTree, createShortCut(labelDef.symbol))
+ lazy val success = remake(List(successOne, successTwo)).toTree
+ lazy val failure = labelDef
final def tree() = codegen
override def toString() = "MixEquals(%s == %s)".format(scrut, head)
@@ -566,16 +554,16 @@ trait ParallelMatching extends ast.TreeDSL
def subs() = passl(ifEquiv(NoPattern), pattern subpatterns pmatch)
val (oneY, oneN) = pattern match {
- case Pattern(LIT(null), _) if !(p =:= s) => (None, passr) // (1)
- case x if isObjectTest => (passl(), None) // (2)
- case Pattern(Typed(pp, _), _) if sMatchesP => (typed(pp), None) // (4)
+ case Pattern(LIT(null)) if !(p =:= s) => (None, passr) // (1)
+ case x if isObjectTest => (passl(), None) // (2)
+ case Pattern(Typed(pp, _)) if sMatchesP => (typed(pp), None) // (4)
// The next line used to be this which "fixed" 1697 but introduced
// numerous regressions including #3136.
- // case Pattern(_: UnApply, _) => (passl(), passr)
- case Pattern(_: UnApply, _) => (None, passr)
- case x if !x.isDefault && sMatchesP => (subs(), None)
- case x if x.isDefault || pMatchesS => (passl(), passr)
- case _ => (None, passr)
+ // case Pattern(_: UnApply, _) => (passl(), passr)
+ case Pattern(_: UnApply) => (None, passr)
+ case x if !x.isDefault && sMatchesP => (subs(), None)
+ case x if x.isDefault || pMatchesS => (passl(), passr)
+ case _ => (None, passr)
}
oneY map (_ys +=)
oneN map (_ns +=)
@@ -656,34 +644,82 @@ trait ParallelMatching extends ast.TreeDSL
"Row(%d)(%s%s)".format(bx, pp(pats), bs)
}
}
+ abstract class State {
+ def bx: Int // index into the list of rows
+ def params: List[Symbol] // bound names to be supplied as arguments to labeldef
+ def body: Tree // body to execute upon match
+ def label: Option[LabelDef] // label definition for this state
+
+ // Called with a bindings map when a match is achieved.
+ // Returns a list of variable declarations based on the labeldef parameters
+ // and the given substitution, and the body to execute.
+ protected def applyBindingsImpl(subst: Map[Symbol, Symbol]): (List[ValDef], Tree)
+
+ final def applyBindings(subst: Map[Symbol, Symbol]): (List[ValDef], Tree) = {
+ _referenceCount += 1
+ applyBindingsImpl(subst)
+ }
+
+ private var _referenceCount = 0
+ def referenceCount = _referenceCount
+ def unreached = referenceCount == 0
+ def shouldInline(sym: Symbol) = referenceCount == 1 && label.exists(_.symbol == sym)
+
+ protected def maybeCast(lhs: Symbol, rhs: Symbol)(tree: Tree) = {
+ if (rhs.tpe <:< lhs.tpe) tree
+ else tree AS lhs.tpe
+ }
+
+ protected def newValDefinition(lhs: Symbol, rhs: Symbol) =
+ VAL(lhs) === maybeCast(lhs, rhs)(Ident(rhs))
+
+ protected def newValReference(lhs: Symbol, rhs: Symbol) =
+ maybeCast(lhs, rhs)(Ident(rhs))
+
+ protected def mapSubst[T](subst: Map[Symbol, Symbol])(f: (Symbol, Symbol) => T): List[T] =
+ params flatMap { lhs =>
+ subst get lhs map (rhs => f(lhs, rhs)) orElse {
+ // This should not happen; the code should be structured so it is
+ // impossible, but that still lies ahead.
+ cunit.warning(lhs.pos, "No binding")
+ None
+ }
+ }
+
+ protected def valDefsFor(subst: Map[Symbol, Symbol]) =
+ mapSubst(subst)(typer typedValDef newValDefinition(_, _))
+
+ protected def identsFor(subst: Map[Symbol, Symbol]) =
+ mapSubst(subst)(typer typed newValReference(_, _))
- case class FinalState(bx: Int, body: Tree, params: List[Symbol]) {
- private var referenceCount = 0
// typer is not able to digest a body of type Nothing being assigned result type Unit
- private def caseResultType = if (body.tpe.isNothing) body.tpe else matchResultType
- private lazy val label: LabelDef = body match {
- case Literal(_) => null
- case _ =>
- val symbol = owner.newLabel(body.pos, "body%" + bx) setInfo MethodType(params, caseResultType)
- // typer typedLabelDef
- LabelDef(symbol, params, body setType caseResultType)
- }
-
- def unreached = referenceCount == 0
- def shouldInline(sym: Symbol) = referenceCount == 1 && label != null && label.symbol == sym
-
- def labelBody(subst: Bindings): Tree = {
- referenceCount += 1
- val pvgroup = PatternVarGroup.fromBindings(subst.get(), params)
-
- if (referenceCount > 1 && label != null)
- ID(label.symbol) APPLY (pvgroup map (_.rhs))
- else squeezedBlock(pvgroup.valDefs,
- if (label != null) label
- else body.duplicate setType caseResultType
- )
+ protected def caseResultType =
+ if (body.tpe.isNothing) body.tpe else matchResultType
+ }
+
+ case class LiteralState(bx: Int, params: List[Symbol], body: Tree) extends State {
+ def label = None
+
+ protected def applyBindingsImpl(subst: Map[Symbol, Symbol]) =
+ (valDefsFor(subst), body.duplicate setType caseResultType)
+ }
+
+ case class FinalState(bx: Int, params: List[Symbol], body: Tree) extends State {
+ traceCategory("Final State", "(%s) => %s", paramsString, body)
+ def label = Some(labelDef)
+
+ private lazy val labelDef = createLabelDef("body%" + bx, params, caseResultType)(body)
+
+ protected def applyBindingsImpl(subst: Map[Symbol, Symbol]) = {
+ val tree =
+ if (referenceCount > 1) ID(labelDef.symbol) APPLY identsFor(subst)
+ else labelDef
+
+ (valDefsFor(subst), tree)
}
- override def toString() = pp("Final%d%s".format(bx, pp(params)) -> body)
+
+ private def paramsString = params map (s => s.name + ": " + s.tpe) mkString ", "
+ override def toString() = pp("(%s) => %s".format(pp(params), body))
}
case class Rep(val tvars: PatternVarGroup, val rows: List[Row]) {
@@ -691,9 +727,6 @@ trait ParallelMatching extends ast.TreeDSL
lazy val guardedRest = if (guard.isEmpty) Rep(Nil, Nil) else make(tvars, rows.tail)
lazy val (defaults, others) = pats span (_.isDefault)
- /** Sealed classes. */
- def checkExhaustive = new ExhaustivenessChecker(this).check
-
/** Cut out the column containing the non-default pattern. */
class Cut(index: Int) {
/** The first two separate out the 'i'th pattern in each row from the remainder. */
@@ -706,7 +739,10 @@ trait ParallelMatching extends ast.TreeDSL
private val (_ncol, _nrep) =
(others.head :: _column.tail, make(_tvars, _rows))
- def mix = MixtureRule(new Scrutinee(specialVar(_pv.sym, _pv.checked)), _ncol, _nrep)
+ def mix() = {
+ val newScrut = new Scrutinee(specialVar(_pv.sym, _pv.checked))
+ PatternMatch(newScrut, _ncol) mkRule _nrep
+ }
}
/** Converts this to a tree - recursively acquires subreps. */
@@ -719,9 +755,8 @@ trait ParallelMatching extends ast.TreeDSL
VariableRule(binding, guard, guardedRest, index)
}
-
- /** The MixtureRule. */
- def mixture() = new Cut(defaults.size) mix
+ /** The MixtureRule: picks a rewrite rule to apply. */
+ private def mixture() = new Cut(defaults.size) mix()
/** Applying the rule will result in one of:
*
@@ -742,14 +777,18 @@ trait ParallelMatching extends ast.TreeDSL
/** Expands the patterns recursively. */
final def expand(roots: List[PatternVar], cases: List[CaseDef]) = tracing("expand") {
- for ((CaseDef(pat, guard, body), index) <- cases.zipWithIndex) yield {
+ for ((CaseDef(pat, guard, body), bx) <- cases.zipWithIndex) yield {
val subtrees = pat match {
case x if roots.length <= 1 => List(x)
case Apply(_, args) => args
case WILD() => emptyTrees(roots.length)
}
- val row = Row(toPats(subtrees), NoBinding, guard, index)
- val state = FinalState(index, body, Pattern(pat).deepBoundVariables)
+ val params = pat filter (_.isInstanceOf[Bind]) map (_.symbol) distinct
+ val row = Row(toPats(subtrees), NoBinding, guard, bx)
+ val state = body match {
+ case x: Literal => LiteralState(bx, params, body)
+ case _ => FinalState(bx, params, body)
+ }
row -> state
}
diff --git a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala
index 88983a792f..8bba8b559c 100644
--- a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala
+++ b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala
@@ -20,9 +20,16 @@ trait PatternBindings extends ast.TreeDSL
import Debug._
/** EqualsPattern **/
- def isEquals(tpe: Type) = cond(tpe) { case TypeRef(_, EqualsPatternClass, _) => true }
- def mkEqualsRef(tpe: Type) = typeRef(NoPrefix, EqualsPatternClass, List(tpe))
- def decodedEqualsType(tpe: Type) = condOpt(tpe) { case TypeRef(_, EqualsPatternClass, List(arg)) => arg } getOrElse (tpe)
+ def isEquals(tpe: Type) = cond(tpe) { case TypeRef(_, EqualsPatternClass, _) => true }
+ def mkEqualsRef(tpe: Type) = typeRef(NoPrefix, EqualsPatternClass, List(tpe))
+ def decodedEqualsType(tpe: Type) = condOpt(tpe) { case TypeRef(_, EqualsPatternClass, List(arg)) => arg } getOrElse (tpe)
+
+ // A subtype test which creates fresh existentials for type
+ // parameters on the right hand side.
+ def matches(arg1: Type, arg2: Type) = decodedEqualsType(arg1) matchesPattern decodedEqualsType(arg2)
+
+ // For spotting duplicate unapplies
+ def isEquivalentTree(t1: Tree, t2: Tree) = (t1.symbol == t2.symbol) && (t1 equalsStructure t2)
// used as argument to `EqualsPatternClass'
case class PseudoType(o: Tree) extends SimpleTypeProxy {
@@ -121,7 +128,7 @@ trait PatternBindings extends ast.TreeDSL
}
case class Binding(pvar: Symbol, tvar: Symbol) {
- override def toString() = pp(pvar -> tvar)
+ override def toString() = pvar.name + " -> " + tvar.name
}
class Bindings(private val vlist: List[Binding]) {
@@ -129,6 +136,7 @@ trait PatternBindings extends ast.TreeDSL
// traceCategory("Bindings", this.toString)
def get() = vlist
+ def toMap = vlist map (x => (x.pvar, x.tvar)) toMap
def add(vs: Iterable[Symbol], tvar: Symbol): Bindings = {
val newBindings = vs.toList map (v => Binding(v, tvar))
@@ -136,8 +144,8 @@ trait PatternBindings extends ast.TreeDSL
}
override def toString() =
- if (vlist.isEmpty) "No Bindings"
- else "%d Bindings(%s)".format(vlist.size, pp(vlist))
+ if (vlist.isEmpty) "<none>"
+ else vlist.mkString(", ")
}
val NoBinding: Bindings = new Bindings(Nil)
diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala
index e1f8204960..3ea1b1cdb2 100644
--- a/src/compiler/scala/tools/nsc/matching/Patterns.scala
+++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala
@@ -68,13 +68,14 @@ trait Patterns extends ast.TreeDSL {
// 8.1.2
case class TypedPattern(tree: Typed) extends Pattern {
private val Typed(expr, tpt) = tree
+ private lazy val exprPat = Pattern(expr)
override def subpatternsForVars: List[Pattern] = List(Pattern(expr))
override def simplify(pv: PatternVar) = Pattern(expr) match {
case ExtractorPattern(ua) if pv.sym.tpe <:< tpt.tpe => this rebindTo expr
case _ => this
}
- override def description = "Typ(%s: %s)".format(Pattern(expr), tpt)
+ override def description = "%s: %s".format(exprPat.boundNameString, tpt)
}
// 8.1.3
@@ -143,7 +144,7 @@ trait Patterns extends ast.TreeDSL {
// 8.1.5
case class ConstructorPattern(tree: Apply) extends ApplyPattern with NamePattern {
- require(fn.isType && this.isCaseClass)
+ require(fn.isType && this.isCaseClass, "tree: " + tree + " fn: " + fn)
def name = tpe.typeSymbol.name
def cleanName = tpe.typeSymbol.decodedName
def hasPrefix = tpe.prefix.prefixString != ""
@@ -173,22 +174,18 @@ trait Patterns extends ast.TreeDSL {
// 8.1.7 / 8.1.8 (unapply and unapplySeq calls)
case class ExtractorPattern(tree: UnApply) extends UnapplyPattern {
- override def simplify(pv: PatternVar) =
- if (pv.tpe <:< arg.tpe) this
- else this rebindTo uaTyped
-
- override def description = "Unapply(%s => %s)".format(necessaryType, resTypesString)
- }
-
- case class SequenceExtractorPattern(tree: UnApply, elems: List[Tree]) extends UnapplyPattern with SequenceLikePattern {
override def simplify(pv: PatternVar) = {
- pv.sym setFlag NO_EXHAUSTIVE
+ if (pv.sym hasFlag NO_EXHAUSTIVE) ()
+ else {
+ TRACE("Setting NO_EXHAUSTIVE on " + pv.sym + " due to extractor " + tree)
+ pv.sym setFlag NO_EXHAUSTIVE
+ }
if (pv.tpe <:< arg.tpe) this
else this rebindTo uaTyped
}
- override def description = "UnapplySeq(%s => %s)".format(necessaryType, resTypesString)
+ override def description = "Unapply(%s => %s)".format(necessaryType, resTypesString)
}
// Special List handling. It was like that when I got here.
@@ -196,22 +193,28 @@ trait Patterns extends ast.TreeDSL {
private val cons = ConsClass.primaryConstructor.tpe.resultType
private val consRef = typeRef(cons.prefix, ConsClass, List(tpt.tpe))
private val listRef = typeRef(cons.prefix, ListClass, List(tpt.tpe))
+ private val seqRef = typeRef(cons.prefix, SeqClass, List(tpt.tpe))
+ private def thisSeqRef = {
+ val tc = (tree.tpe baseType SeqClass).typeConstructor
+ if (tc.typeParams.size == 1) appliedType(tc, List(tpt.tpe))
+ else seqRef
+ }
// Fold a list into a well-typed x :: y :: etc :: tree.
- private def listFolder(x: Tree, xs: Tree) = unbind(x) match {
- case _: Star => Pattern(x) rebindTo WILD(x.tpe) boundTree
+ private def listFolder(x: Pattern, xs: Pattern): Pattern = x match {
+ case Pattern(Star(_)) => x rebindTo WILD(x.tpe)
case _ =>
val dummyMethod = new TermSymbol(NoSymbol, NoPosition, "matching$dummy")
val consType = MethodType(dummyMethod newSyntheticValueParams List(tpt.tpe, listRef), consRef)
- Apply(TypeTree(consType), List(x, xs)) setType consRef
+ Pattern(Apply(TypeTree(consType), List(x.boundTree, xs.boundTree)) setType consRef)
}
+ private def foldedPatterns = elems.foldRight(NilPattern)((x, y) => listFolder(Pattern(x), y))
override def necessaryType = if (nonStarPatterns.nonEmpty) consRef else listRef
- override def simplify(pv: PatternVar) = {
- pv.sym setFlag NO_EXHAUSTIVE
+ override def simplify(pv: PatternVar) = {
if (pv.tpe <:< necessaryType)
- this rebindTo elems.foldRight(gen.mkNil)(listFolder)
+ foldedPatterns
else
this rebindTo (Typed(tree, TypeTree(necessaryType)) setType necessaryType)
}
@@ -298,9 +301,10 @@ trait Patterns extends ast.TreeDSL {
case _ => tracing("Pattern")(p)
}
}
- def unapply(other: Any): Option[(Tree, List[Symbol])] = other match {
+ // matching on Pattern(...) always skips the bindings.
+ def unapply(other: Any): Option[Tree] = other match {
case x: Tree => unapply(Pattern(x))
- case x: Pattern => Some((x.tree, x.boundVariables))
+ case x: Pattern => Some(x.tree)
case _ => None
}
}
@@ -318,9 +322,8 @@ trait Patterns extends ast.TreeDSL {
}
def apply(x: UnApply): Pattern = x match {
- case UnapplySeq(container, tpt, elems) =>
- if (container == ListModule) ListExtractorPattern(x, tpt, elems)
- else SequenceExtractorPattern(x, elems)
+ case UnapplySeq(ListModule, tpt, elems) =>
+ ListExtractorPattern(x, tpt, elems)
case _ =>
ExtractorPattern(x)
}
@@ -403,13 +406,6 @@ trait Patterns extends ast.TreeDSL {
case Nil => "Boolean"
case xs => xs.mkString(", ")
}
-
- private def isSameFunction(f1: Tree, f2: Tree) =
- (f1.symbol == f2.symbol) && (f1 equalsStructure f2)
-
- // XXX args
- def isSameUnapply(other: UnapplyPattern) =
- isSameFunction(unfn, other.unfn)
}
sealed trait ApplyPattern extends Pattern {
@@ -459,6 +455,11 @@ trait Patterns extends ast.TreeDSL {
tree setType tpe
this
}
+ def boundName: Option[Name] = boundTree match {
+ case Bind(name, _) => Some(name)
+ case _ => None
+ }
+ def boundNameString = "" + (boundName getOrElse "_")
def equalsCheck =
tracing("equalsCheck")(
diff --git a/src/compiler/scala/tools/nsc/plugins/Plugins.scala b/src/compiler/scala/tools/nsc/plugins/Plugins.scala
index 64e38fee9a..36227c1052 100644
--- a/src/compiler/scala/tools/nsc/plugins/Plugins.scala
+++ b/src/compiler/scala/tools/nsc/plugins/Plugins.scala
@@ -105,12 +105,8 @@ trait Plugins {
* Extract all phases supplied by plugins and add them to the phasesSet.
* @see phasesSet
*/
- protected def computePluginPhases(): Unit = {
- // For reasons not yet apparent to me, plugins started appearing
- // as null when I added phaseTimings to global.
- if (plugins != null)
- phasesSet ++= (plugins flatMap (_.components))
- }
+ protected def computePluginPhases(): Unit =
+ phasesSet ++= (plugins flatMap (_.components))
/** Summary of the options for all loaded plugins */
def pluginOptionsHelp: String =
diff --git a/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala b/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
index 2ffaa1c80a..7d2c0fe424 100644
--- a/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
@@ -16,7 +16,7 @@ import scala.tools.nsc.util.Position
abstract class AbstractReporter extends Reporter {
private val positions = new HashMap[Position, Severity]
- override def reset {
+ override def reset() {
super.reset
positions.clear
}
@@ -27,7 +27,7 @@ abstract class AbstractReporter extends Reporter {
private def isPromptSet = settings.prompt.value
def display(pos: Position, msg: String, severity: Severity): Unit
- def displayPrompt: Unit
+ def displayPrompt(): Unit
protected def info0(pos: Position, msg: String, _severity: Severity, force: Boolean) {
val severity =
diff --git a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
index 93e6f77dbd..75c25afa5b 100644
--- a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
@@ -94,7 +94,7 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr
print(pos, msg, severity)
}
- def displayPrompt: Unit = try {
+ def displayPrompt(): Unit = try {
var continue = true
while (continue) {
writer.print("r)esume, a)bort: ")
diff --git a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
index bc08478490..9f0e55c422 100644
--- a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
@@ -27,7 +27,7 @@ class StoreReporter extends Reporter {
}
}
- override def reset {
+ override def reset() {
super.reset
infos.clear
}
diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala
index 477c2a528e..87398e4117 100644
--- a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala
+++ b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala
@@ -8,7 +8,7 @@ package scala.tools
package nsc
package settings
-import io.{ AbstractFile, VirtualDirectory }
+import io.{ AbstractFile, Path, PlainFile, VirtualDirectory }
import scala.tools.util.StringOps
import scala.collection.mutable.ListBuffer
import scala.io.Source
@@ -239,20 +239,25 @@ class MutableSettings(val errorFn: String => Unit) extends AbsSettings with Scal
checkDir(AbstractFile.getDirectory(outDir), outDir))
/** Check that dir is exists and is a directory. */
- private def checkDir(dir: AbstractFile, name: String): AbstractFile = {
- if ((dir eq null) || !dir.isDirectory)
+ private def checkDir(dir: AbstractFile, name: String, allowJar: Boolean = false): AbstractFile = (
+ if (dir != null && dir.isDirectory)
+ dir
+ else if (allowJar && dir == null && Path.isJarOrZip(name, false))
+ new PlainFile(Path(name))
+ else
throw new FatalError(name + " does not exist or is not a directory")
- dir
- }
+ )
/** Set the single output directory. From now on, all files will
* be dumped in there, regardless of previous calls to 'add'.
*/
def setSingleOutput(outDir: String) {
val dst = AbstractFile.getDirectory(outDir)
- setSingleOutput(checkDir(dst, outDir))
+ setSingleOutput(checkDir(dst, outDir, true))
}
+ def getSingleOutput: Option[AbstractFile] = singleOutDir
+
/** Set the single output directory. From now on, all files will
* be dumped in there, regardless of previous calls to 'add'.
*/
@@ -310,7 +315,7 @@ class MutableSettings(val errorFn: String => Unit) extends AbsSettings with Scal
singleOutDir match {
case Some(d) =>
d match {
- case _: VirtualDirectory => Nil
+ case _: VirtualDirectory | _: io.ZipArchive => Nil
case _ => List(d.lookupPathUnchecked(srcPath, false))
}
case None =>
@@ -377,7 +382,7 @@ class MutableSettings(val errorFn: String => Unit) extends AbsSettings with Scal
// Helper to validate an input
private def isInputValid(k: Int): Boolean = (min <= k) && (k <= max)
- // Helper to generate a textual explaination of valid inputs
+ // Helper to generate a textual explanation of valid inputs
private def getValidText: String = (min, max) match {
case (IntMin, IntMax) => "can be any integer"
case (IntMin, x) => "must be less than or equal to "+x
@@ -395,7 +400,7 @@ class MutableSettings(val errorFn: String => Unit) extends AbsSettings with Scal
}
}
- def errorMsg = errorFn("invalid setting for -"+name+" "+getValidText)
+ def errorMsg() = errorFn("invalid setting for -"+name+" "+getValidText)
def tryToSet(args: List[String]) =
if (args.isEmpty) errorAndValue("missing argument", None)
@@ -485,7 +490,7 @@ class MutableSettings(val errorFn: String => Unit) extends AbsSettings with Scal
class OutputSetting private[nsc](
private[nsc] val outputDirs: OutputDirs,
default: String)
- extends StringSetting("-d", "directory", "Specify where to place generated class files", default) {
+ extends StringSetting("-d", "directory|jar", "destination for generated classfiles.", default) {
value = default
override def value_=(str: String) {
super.value_=(str)
diff --git a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala
index cc960e55dd..c5b477c7bd 100644
--- a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala
+++ b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala
@@ -36,10 +36,10 @@ trait StandardScalaSettings {
val help = BooleanSetting ("-help", "Print a synopsis of standard options")
val make = ChoiceSetting ("-make", "policy", "Recompilation detection policy", List("all", "changed", "immediate", "transitive", "transitivenocp"), "all")
. withDeprecationMessage ("this option is unmaintained. Use sbt or an IDE for selective recompilation.")
- val nowarn = BooleanSetting ("-nowarn", "Generate no warnings")
+ val nowarn = BooleanSetting ("-nowarn", "Generate no warnings.")
val optimise: BooleanSetting // depends on post hook which mutates other settings
val print = BooleanSetting ("-print", "Print program with Scala-specific features removed.")
- val target = ChoiceSetting ("-target", "target", "Specify for which target object files should be built", List("jvm-1.5", "msil"), "jvm-1.5")
+ val target = ChoiceSetting ("-target", "target", "Target platform for object files.", List("jvm-1.5", "msil"), "jvm-1.5")
val unchecked = BooleanSetting ("-unchecked", "Enable detailed unchecked (erasure) warnings.")
val uniqid = BooleanSetting ("-uniqid", "Uniquely tag all identifiers in debugging output.")
val usejavacp = BooleanSetting ("-usejavacp", "Utilize the java.class.path in classpath resolution.")
diff --git a/src/compiler/scala/tools/nsc/symtab/Definitions.scala b/src/compiler/scala/tools/nsc/symtab/Definitions.scala
index 9f666e008f..005a3c87ed 100644
--- a/src/compiler/scala/tools/nsc/symtab/Definitions.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Definitions.scala
@@ -798,7 +798,7 @@ trait Definitions extends reflect.generic.StandardDefinitions {
sym
}
- def init {
+ def init() {
if (isInitialized) return
EmptyPackageClass setInfo ClassInfoType(Nil, new Scope, EmptyPackageClass)
diff --git a/src/compiler/scala/tools/nsc/symtab/NameManglers.scala b/src/compiler/scala/tools/nsc/symtab/NameManglers.scala
index ce372b6e50..c40e1765ce 100644
--- a/src/compiler/scala/tools/nsc/symtab/NameManglers.scala
+++ b/src/compiler/scala/tools/nsc/symtab/NameManglers.scala
@@ -66,6 +66,7 @@ trait NameManglers {
self: nme.type =>
val IMPL_CLASS_SUFFIX = "$class"
+ val SINGLETON_SUFFIX = ".type"
val LOCALDUMMY_PREFIX = "<local " // owner of local blocks
val PROTECTED_PREFIX = "protected$"
val PROTECTED_SET_PREFIX = PROTECTED_PREFIX + "set"
@@ -84,6 +85,7 @@ trait NameManglers {
def isProtectedAccessorName(name: Name) = name startsWith PROTECTED_PREFIX
def isSetterName(name: Name) = name endsWith SETTER_SUFFIX
def isTraitSetterName(name: Name) = isSetterName(name) && (name containsName TRAIT_SETTER_SEPARATOR_STRING)
+ def isSingletonName(name: Name) = name endsWith SINGLETON_SUFFIX
def isOpAssignmentName(name: Name) = name match {
case raw.NE | raw.LE | raw.GE | EMPTY => false
@@ -152,6 +154,8 @@ trait NameManglers {
else name
}
+ def dropSingletonName(name: Name): TypeName = name stripEnd SINGLETON_SUFFIX toTypeName
+ def singletonName(name: Name): TypeName = name append SINGLETON_SUFFIX toTypeName
def implClassName(name: Name): TypeName = name append IMPL_CLASS_SUFFIX toTypeName
def interfaceName(implname: Name): TypeName = implname stripEnd IMPL_CLASS_SUFFIX toTypeName
def localDummyName(clazz: Symbol): TermName = newTermName(LOCALDUMMY_PREFIX + clazz.name + ">")
diff --git a/src/compiler/scala/tools/nsc/symtab/StdNames.scala b/src/compiler/scala/tools/nsc/symtab/StdNames.scala
index f60bd17b32..4a7f52f2b5 100644
--- a/src/compiler/scala/tools/nsc/symtab/StdNames.scala
+++ b/src/compiler/scala/tools/nsc/symtab/StdNames.scala
@@ -191,7 +191,6 @@ trait StdNames extends reflect.generic.StdNames with NameManglers {
val copy: NameType = "copy"
val delayedInit: NameType = "delayedInit"
val delayedInitArg: NameType = "delayedInit$body"
- val dottype: NameType = ".type"
val drop: NameType = "drop"
val elem: NameType = "elem"
val eq: NameType = "eq"
diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala b/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala
index 870787a9ea..1f32355bf7 100644
--- a/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala
+++ b/src/compiler/scala/tools/nsc/symtab/SymbolTrackers.scala
@@ -131,7 +131,11 @@ trait SymbolTrackers {
else " (" + Flags.flagsToString(masked) + ")"
}
def symString(sym: Symbol) = (
- sym + changedOwnerString + flagSummaryString
+ if (settings.debug.value && sym.hasRawInfo && sym.rawInfo.isComplete) {
+ val s = sym.defString take 240
+ if (s.length == 240) s + "..." else s
+ }
+ else sym + changedOwnerString + flagSummaryString
)
def flatten = children.foldLeft(Set(root))(_ ++ _.flatten)
@@ -173,7 +177,7 @@ trait SymbolTrackers {
prevFlags = current map (s => (s, (s.flags & flagsMask))) toMap;
history = change :: history
}
- def show(): String = {
+ def show(label: String): String = {
val hierarchy = Node(current)
val Change(added, removed, symMap, owners, flags) = history.head
def detailString(sym: Symbol) = {
@@ -194,7 +198,7 @@ trait SymbolTrackers {
"" + hierarchy + (
if (removed.isEmpty) ""
- else "\n\n!!! %s symbols vanished:\n".format(removed.size) + removedString
+ else "\n\n!!! " + label + ", " + removed.size + " symbols vanished:\n" + removedString
)
}
}
diff --git a/src/compiler/scala/tools/nsc/symtab/Symbols.scala b/src/compiler/scala/tools/nsc/symtab/Symbols.scala
index c29edaa75d..524b5a047d 100644
--- a/src/compiler/scala/tools/nsc/symtab/Symbols.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Symbols.scala
@@ -339,8 +339,9 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
final def isCapturedVariable = isVariable && hasFlag(CAPTURED)
final def isGetter = isTerm && hasAccessorFlag && !nme.isSetterName(name)
+ // todo: make independent of name, as this can be forged.
final def isSetter = isTerm && hasAccessorFlag && nme.isSetterName(name)
- //todo: make independent of name, as this can be forged.
+ def isSetterParameter = isValueParameter && owner.isSetter
final def hasGetter = isTerm && nme.isLocalName(name)
@@ -385,6 +386,10 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
*/
final def skipPackageObject: Symbol = if (isPackageObjectClass) owner else this
+ /** If this is a constructor, its owner: otherwise this.
+ */
+ final def skipConstructor: Symbol = if (isConstructor) owner else this
+
/** Conditions where we omit the prefix when printing a symbol, to avoid
* unpleasantries like Predef.String, $iw.$iw.Foo and <empty>.Bippy.
*/
@@ -408,6 +413,7 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
def isStrictFP = hasAnnotation(ScalaStrictFPAttr) || (enclClass hasAnnotation ScalaStrictFPAttr)
def isSerializable = info.baseClasses.exists(p => p == SerializableClass || p == JavaSerializableClass) || hasAnnotation(SerializableAttr) // last part can be removed, @serializable annotation is deprecated
def isDeprecated = hasAnnotation(DeprecatedAttr)
+ def hasBridgeAnnotation = hasAnnotation(BridgeClass)
def deprecationMessage = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 0)
def deprecationVersion = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 1)
// !!! when annotation arguments are not literal strings, but any sort of
@@ -661,7 +667,7 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
final def setFlag(mask: Long): this.type = { rawflags = rawflags | mask; this }
final def resetFlag(mask: Long): this.type = { rawflags = rawflags & ~mask; this }
final def getFlag(mask: Long): Long = flags & mask
- final def resetFlags { rawflags = rawflags & TopLevelCreationFlags }
+ final def resetFlags() { rawflags = rawflags & TopLevelCreationFlags }
/** The class or term up to which this symbol is accessible,
* or RootClass if it is public.
@@ -1171,6 +1177,9 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
/** For a lazy value, its lazy accessor. NoSymbol for all others */
def lazyAccessor: Symbol = NoSymbol
+ /** If this is a lazy value, the lazy accessor; otherwise this symbol. */
+ def lazyAccessorOrSelf: Symbol = if (isLazy) lazyAccessor else this
+
/** For an outer accessor: The class from which the outer originates.
* For all other symbols: NoSymbol
*/
@@ -1223,6 +1232,35 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
}
}
+ /** The method or class which logically encloses the current symbol.
+ * If the symbol is defined in the initialization part of a template
+ * this is the template's primary constructor, otherwise it is
+ * the physically enclosing method or class.
+ *
+ * Example 1:
+ *
+ * def f() { val x = { def g() = ...; g() } }
+ *
+ * In this case the owner chain of `g' is `x', followed by `f' and
+ * `g.logicallyEnclosingMember == f`.
+ *
+ * Example 2:
+ *
+ * class C {
+ * def <init> = { ... }
+ * val x = { def g() = ...; g() } }
+ * }
+ *
+ * In this case the owner chain of `g' is `x', followed by `C' but
+ * g.logicallyEnclosingMember is the primary constructor symbol `<init>'
+ * (or, for traits: `$init') of `C'.
+ *
+ */
+ def logicallyEnclosingMember: Symbol =
+ if (isLocalDummy) enclClass.primaryConstructor
+ else if (isMethod || isClass) this
+ else owner.logicallyEnclosingMember
+
/** The top-level class containing this symbol */
def toplevelClass: Symbol =
if (owner.isPackageClass) {
@@ -1527,7 +1565,7 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
// ToString -------------------------------------------------------------------
/** A tag which (in the ideal case) uniquely identifies class symbols */
- final def tag: Int = fullName.hashCode()
+ final def tag = fullName.##
/** The simple name of this Symbol */
final def simpleName: Name = name
@@ -1537,7 +1575,7 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
* (the initial Name) before falling back on id, which varies depending
* on exactly when a symbol is loaded.
*/
- final def sealedSortName: String = initName.toString + "#" + id
+ final def sealedSortName = initName + "#" + id
/** String representation of symbol's definition key word */
final def keyString: String =
@@ -1552,12 +1590,21 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
else if (isTerm && (!isParameter || isParamAccessor)) "val"
else ""
- /** String representation of symbol's kind */
- final def kindString: String =
- if (isPackageClass)
- if (settings.debug.value) "package class" else "package"
- else if (isModuleClass)
- if (settings.debug.value) "singleton class" else "object"
+ /** Accurate string representation of symbols' kind, suitable for developers. */
+ final def accurateKindString: String =
+ if (isPackage) "package"
+ else if (isPackageClass) "package class"
+ else if (isPackageObject) "package object"
+ else if (isPackageObjectClass) "package object class"
+ else if (isRefinementClass) "refinement class"
+ else if (isModule) "module"
+ else if (isModuleClass) "module class"
+ else sanitizedKindString
+
+ /** String representation of symbol's kind, suitable for the masses. */
+ private def sanitizedKindString: String =
+ if (isPackage || isPackageClass) "package"
+ else if (isModule || isModuleClass) "object"
else if (isAnonymousClass) "anonymous class"
else if (isRefinementClass) ""
else if (isTrait) "trait"
@@ -1565,44 +1612,64 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
else if (isType) "type"
else if (isTerm && isLazy) "lazy value"
else if (isVariable) "variable"
- else if (isPackage) "package"
- else if (isModule) "object"
else if (isClassConstructor) "constructor"
else if (isSourceMethod) "method"
else if (isTerm) "value"
else ""
+ final def kindString: String =
+ if (settings.debug.value) accurateKindString
+ else sanitizedKindString
+
+ /** If the name of the symbol's owner should be used when you care about
+ * seeing an interesting name: in such cases this symbol is e.g. a method
+ * parameter with a synthetic name, a constructor named "this", an object
+ * "package", etc. The kind string, if non-empty, will be phrased relative
+ * to the name of the owner.
+ */
+ def hasMeaninglessName = (
+ isSetterParameter // x$1
+ || isClassConstructor // this
+ || isPackageObject // package
+ || isPackageObjectClass // package$
+ || isRefinementClass // <refinement>
+ )
+
/** String representation of symbol's simple name.
* If !settings.debug translates expansions of operators back to operator symbol.
* E.g. $eq => =.
- * If settings.uniquId adds id.
+ * If settings.uniqid, adds id.
*/
- def nameString: String = decodedName + idString
+ def nameString = decodedName + idString
/** If settings.uniqid is set, the symbol's id, else "" */
- final def idString: String =
- if (settings.uniqid.value) "#"+id // +" in "+owner.name+"#"+owner.id // DEBUG
- else ""
+ final def idString = if (settings.uniqid.value) "#"+id else ""
- /** String representation, including symbol's kind
- * e.g., "class Foo", "method Bar".
+ /** String representation, including symbol's kind e.g., "class Foo", "method Bar".
+ * If hasMeaninglessName is true, uses the owner's name to disambiguate identity.
*/
- override def toString(): String =
- if (isValueParameter && owner.isSetter)
- "parameter of setter "+owner.nameString
- else if (isPackageObject || isPackageObjectClass)
- "package object "+owner.nameString
- else
- compose(List(kindString,
- if (isClassConstructor) owner.simpleName.decode+idString else nameString))
+ override def toString = compose(
+ kindString,
+ if (hasMeaninglessName) owner.nameString else nameString
+ )
- /** String representation of location. */
- def locationString: String = {
+ /** String representation of location.
+ */
+ def ownsString = {
val owns = owner.skipPackageObject
- if (!owns.isClass || (owns.printWithoutPrefix && owns != ScalaPackageClass)) ""
- else " in " + owns
+ if (owns.isClass && !owns.printWithoutPrefix && !isScalaPackageClass) "" + owns
+ else ""
}
+ /** String representation of location, plus a preposition. Doesn't do much,
+ * for backward compatibility reasons.
+ */
+ def locationString = ownsString match {
+ case "" => ""
+ case s => " in " + s
+ }
+ def fullLocationString = toString + locationString
+
/** String representation of symbol's definition following its name */
final def infoString(tp: Type): String = {
def typeParamsString: String = tp match {
@@ -1661,23 +1728,24 @@ trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
def defaultFlagString = hasFlagsToString(defaultFlagMask)
/** String representation of symbol's definition */
- def defString: String = {
- compose(List(defaultFlagString, keyString, varianceString + nameString +
- (if (hasRawInfo) infoString(rawInfo) else "<_>")))
- }
+ def defString = compose(
+ defaultFlagString,
+ keyString,
+ varianceString + nameString + (
+ if (hasRawInfo) infoString(rawInfo) else "<_>"
+ )
+ )
/** Concatenate strings separated by spaces */
- private def compose(ss: List[String]): String =
- ss.filter("" !=).mkString("", " ", "")
+ private def compose(ss: String*) = ss filter (_ != "") mkString " "
- def isSingletonExistential: Boolean =
- (name endsWith nme.dottype) && (info.bounds.hi.typeSymbol isSubClass SingletonClass)
+ def isSingletonExistential =
+ nme.isSingletonName(name) && (info.bounds.hi.typeSymbol isSubClass SingletonClass)
/** String representation of existentially bound variable */
def existentialToString =
if (isSingletonExistential && !settings.debug.value)
- "val "+name.subName(0, name.length - nme.dottype.length)+": "+
- dropSingletonType(info.bounds.hi)
+ "val " + nme.dropSingletonName(name) + ": " + dropSingletonType(info.bounds.hi)
else defString
}
diff --git a/src/compiler/scala/tools/nsc/symtab/TypeDebugging.scala b/src/compiler/scala/tools/nsc/symtab/TypeDebugging.scala
index 5ed7344bd8..62e812704b 100644
--- a/src/compiler/scala/tools/nsc/symtab/TypeDebugging.scala
+++ b/src/compiler/scala/tools/nsc/symtab/TypeDebugging.scala
@@ -14,6 +14,7 @@ trait TypeDebugging {
// @M toString that is safe during debugging (does not normalize, ...)
object TypeDebugStrings {
object str {
+ def parentheses(xs: List[_]): String = xs.mkString("(", ", ", ")")
def brackets(xs: List[_]): String = if (xs.isEmpty) "" else xs.mkString("[", ", ", "]")
def tparams(tparams: List[Type]): String = brackets(tparams map debug)
def parents(ps: List[Type]): String = (ps map debug).mkString(" with ")
@@ -47,7 +48,7 @@ trait TypeDebugging {
println("toLongString = " + toLongString)
}
- def debug(tp: Type): String = tp match {
+ private def debug(tp: Type): String = tp match {
case TypeRef(pre, sym, args) => debug(pre) + "." + sym.nameString + str.tparams(args)
case ThisType(sym) => sym.nameString + ".this"
case SingleType(pre, sym) => debug(pre) +"."+ sym.nameString +".type"
@@ -59,8 +60,13 @@ trait TypeDebugging {
case ExistentialType(tparams, qtpe) => "forSome "+ str.brackets(tparams) + " " + debug(qtpe)
case _ => tp.toString
}
+ def debugString(tp: Type) = debug(tp)
}
+ private def TDS = TypeDebugStrings
- def debugString(tp: Type) = TypeDebugStrings.debug(tp)
+ def paramString(tp: Type) = TDS.str parentheses (tp.params map (_.defString))
+ def typeParamsString(tp: Type) = TDS.str brackets (tp.typeParams map (_.defString))
+ def typeArgsString(tp: Type) = TDS.str brackets (tp.typeArgs map (_.safeToString))
+ def debugString(tp: Type) = TDS debugString tp
}
diff --git a/src/compiler/scala/tools/nsc/symtab/Types.scala b/src/compiler/scala/tools/nsc/symtab/Types.scala
index 3e41df45f8..61e1d118c5 100644
--- a/src/compiler/scala/tools/nsc/symtab/Types.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Types.scala
@@ -1372,7 +1372,7 @@ trait Types extends reflect.generic.Types { self: SymbolTable =>
// parents forall (p => p.isNullable && !p.typeSymbol.isAbstractType);
override def safeToString: String =
- parents.mkString("", " with ", "") +
+ parents.mkString(" with ") +
(if (settings.debug.value || parents.isEmpty || (decls.elems ne null))
decls.mkString("{", "; ", "}") else "")
}
@@ -1910,8 +1910,6 @@ A type's typeSymbol should never be inspected directly.
pre.prefixString + sym.nameString
var str = monopart + (if (args.isEmpty) "" else args.mkString("[", ",", "]"))
- //if (sym.nameString startsWith "moduleType")
- // str += ("_in_"+sym.ownerChain)
if (sym.isPackageClass)
packagePrefix + str
else if (sym.isModuleClass)
@@ -1930,19 +1928,19 @@ A type's typeSymbol should never be inspected directly.
else str
}
- override def prefixString =
+ override def prefixString = "" + (
if (settings.debug.value)
super.prefixString
else if (sym.printWithoutPrefix)
""
else if (sym.isPackageClass)
sym.fullName + "."
- else if (isStable && (sym.name endsWith ".type"))
- sym.name.toString dropRight 4
+ else if (isStable && nme.isSingletonName(sym.name))
+ nme.dropSingletonName(sym.name) + "."
else
super.prefixString
-
- override def kind = "TypeRef"
+ )
+ override def kind = "TypeRef"
}
object TypeRef extends TypeRefExtractor {
@@ -2006,8 +2004,7 @@ A type's typeSymbol should never be inspected directly.
override def finalResultType: Type = resultType.finalResultType
- override def safeToString: String =
- params.map(_.defString).mkString("(", ",", ")") + resultType
+ override def safeToString = paramString(this) + resultType
override def cloneInfo(owner: Symbol) = {
val vparams = cloneSymbols(params, owner)
@@ -2099,8 +2096,7 @@ A type's typeSymbol should never be inspected directly.
override def isHigherKinded = !typeParams.isEmpty
- override def safeToString: String =
- (typeParams map (_.defString) mkString ("[", ",", "]"))+ resultType
+ override def safeToString = typeParamsString(this) + resultType
override def cloneInfo(owner: Symbol) = {
val tparams = cloneSymbols(typeParams, owner)
@@ -2263,7 +2259,7 @@ A type's typeSymbol should never be inspected directly.
tv.suspended = true
suspended += tv
}
- def resumeAll: Unit = {
+ def resumeAll(): Unit = {
for(tv <- suspended) {
tv.suspended = false
}
@@ -2451,32 +2447,31 @@ A type's typeSymbol should never be inspected directly.
}
}
- override val isHigherKinded = typeArgs.isEmpty && !params.isEmpty
+ override val isHigherKinded = typeArgs.isEmpty && params.nonEmpty
override def normalize: Type =
- if (constr.instValid) constr.inst
- else if (isHigherKinded) { // get here when checking higher-order subtyping of the typevar by itself (TODO: check whether this ever happens?)
- typeFun(params, applyArgs(params map (_.typeConstructor)))
- } else {
- super.normalize
- }
+ if (constr.instValid) constr.inst
+ // get here when checking higher-order subtyping of the typevar by itself
+ // TODO: check whether this ever happens?
+ else if (isHigherKinded) typeFun(params, applyArgs(params map (_.typeConstructor)))
+ else super.normalize
override def typeSymbol = origin.typeSymbol
- override def safeToString: String = {
- def varString = "?"+(if (settings.explaintypes.value) level else "")+
- origin+
- (if(typeArgs.isEmpty) "" else (typeArgs map (_.safeToString)).mkString("[ ", ", ", " ]")) // +"#"+tid //DEBUG
- if (constr.inst eq null) "<null " + origin + ">"
- // else if (settings.debug.value) varString+"(@"+constr.## +")"+constr.toString
- else if (constr.inst eq NoType) varString
- else constr.inst.toString
- }
override def isStable = origin.isStable
override def isVolatile = origin.isVolatile
+
+ private def levelString = if (settings.explaintypes.value) level else ""
+ override def safeToString = constr.inst match {
+ case null => "<null " + origin + ">"
+ case NoType => "?" + levelString + origin + typeArgsString(this)
+ case x => "" + x
+ }
override def kind = "TypeVar"
def cloneInternal = {
- assert(!suspended) // cloning a suspended type variable when it's suspended will cause the clone to never be resumed with the current implementation
+ // cloning a suspended type variable when it's suspended will cause the clone
+ // to never be resumed with the current implementation
+ assert(!suspended)
TypeVar(origin, constr cloneInternal, typeArgs, params) // @M TODO: clone args/params?
}
}
@@ -2523,14 +2518,12 @@ A type's typeSymbol should never be inspected directly.
override def withSelfsym(sym: Symbol) =
AnnotatedType(annotations, underlying, sym)
- /** Drop the annotations on the bounds, unless but the low and high bounds are
- * exactly tp. */
- override def bounds: TypeBounds = {
- val oftp = underlying.bounds
- oftp match {
- case TypeBounds(lo, hi) if ((lo eq this) && (hi eq this)) => TypeBounds(this,this)
- case _ => oftp
- }
+ /** Drop the annotations on the bounds, unless but the low and high
+ * bounds are exactly tp.
+ */
+ override def bounds: TypeBounds = underlying.bounds match {
+ case TypeBounds(_: this.type, _: this.type) => TypeBounds(this, this)
+ case oftp => oftp
}
// ** Replace formal type parameter symbols with actual type arguments. * /
@@ -3788,7 +3781,7 @@ A type's typeSymbol should never be inspected directly.
*/
object commonOwnerMap extends TypeMap {
var result: Symbol = _
- def init = { result = NoSymbol }
+ def init() = { result = NoSymbol }
def apply(tp: Type): Type = {
assert(tp ne null)
tp.normalize match {
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
index a1ff7d99ef..db2a06e255 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
@@ -108,7 +108,7 @@ abstract class ClassfileParser {
protected def statics: Symbol = staticModule.moduleClass
- private def parseHeader {
+ private def parseHeader() {
val magic = in.nextInt
if (magic != JAVA_MAGIC)
throw new IOException("class file '" + in.file + "' "
@@ -1095,7 +1095,7 @@ abstract class ClassfileParser {
/** Enter own inner classes in the right scope. It needs the scopes to be set up,
* and implicitly current class' superclasses.
*/
- private def enterOwnInnerClasses {
+ private def enterOwnInnerClasses() {
def className(name: Name): Name = {
name.subName(name.lastPos('.') + 1, name.length)
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
index bd03fa3f8d..8ae305cc25 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
@@ -226,7 +226,7 @@ abstract class ICodeReader extends ClassfileParser {
val codeLength = in.nextInt
val code = new LinearCode
- def parseInstruction {
+ def parseInstruction() {
import opcodes._
import code._
var size = 1 // instruction size
@@ -739,7 +739,7 @@ abstract class ICodeReader extends ClassfileParser {
method.code
}
- def resolveDups {
+ def resolveDups() {
import opcodes._
val tfa = new analysis.MethodTFA() {
@@ -922,7 +922,7 @@ abstract class ICodeReader extends ClassfileParser {
}
/** Recover def-use chains for NEW and initializers. */
- def resolveNEWs {
+ def resolveNEWs() {
import opcodes._
val rdef = new reachingDefinitions.ReachingDefinitionsAnalysis
@@ -957,7 +957,7 @@ abstract class ICodeReader extends ClassfileParser {
def getLocal(idx: Int, kind: TypeKind): Local = {
assert(idx < maxLocals, "Index too large for local variable.");
- def checkValidIndex {
+ def checkValidIndex() {
locals.get(idx - 1) match {
case Some(others) if others exists (_._2.isWideType) =>
global.globalError("Illegal index: " + idx + " points in the middle of another local")
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
index 0940598bd2..862e37ec2b 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
@@ -56,6 +56,15 @@ abstract class Pickler extends SubComponent {
case _ =>
}
}
+ // If there are any erroneous types in the tree, then we will crash
+ // when we pickle it: so let's report an erorr instead. We know next
+ // to nothing about what happened, but our supposition is a lot better
+ // than "bad type: <error>" in terms of explanatory power.
+ for (t <- unit.body ; if t.isErroneous) {
+ unit.error(t.pos, "erroneous or inaccessible type")
+ return
+ }
+
pickle(unit.body)
}
}
diff --git a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
index 7e523d292c..78541db82a 100644
--- a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
+++ b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
@@ -48,8 +48,8 @@ abstract class AddInterfaces extends InfoTransform {
private val implMethodMap = new mutable.HashMap[Symbol, Symbol]
override def newPhase(prev: scala.tools.nsc.Phase): StdPhase = {
- implClassMap.clear
- implMethodMap.clear
+ implClassMap.clear()
+ implMethodMap.clear()
super.newPhase(prev)
}
@@ -60,8 +60,8 @@ abstract class AddInterfaces extends InfoTransform {
{ sym.info; // to set lateMETHOD flag if necessary
sym.isMethod &&
!sym.isLabel &&
- !(sym hasFlag PRIVATE) &&
- (!(sym hasFlag BRIDGE) || (sym hasAnnotation BridgeClass)) && // count @_$bridge$_ annotated classes as interface members
+ !sym.isPrivate &&
+ (!(sym hasFlag BRIDGE) || sym.hasBridgeAnnotation) && // count @_$bridge$_ annotated classes as interface members
!sym.isConstructor &&
!sym.isImplOnly
}
diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala
index 36552894e5..007ab36e5e 100644
--- a/src/compiler/scala/tools/nsc/transform/Erasure.scala
+++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala
@@ -458,7 +458,7 @@ abstract class Erasure extends AddInterfaces
else if (sym.name == nme.apply)
tp
else if (sym.name == nme.update)
- tp match {
+ (tp: @unchecked) match {
case MethodType(List(index, tvar), restpe) =>
MethodType(List(index.cloneSymbol.setInfo(erasure(index.tpe)), tvar),
erasedTypeRef(UnitClass))
@@ -987,7 +987,7 @@ abstract class Erasure extends AddInterfaces
case Apply(fn, args) =>
if (fn.symbol == Any_asInstanceOf)
- fn match {
+ (fn: @unchecked) match {
case TypeApply(Select(qual, _), List(targ)) =>
if (qual.tpe <:< targ.tpe) {
atPos(tree.pos) { Typed(qual, TypeTree(targ.tpe)) }
diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
index 5f9c2b544a..79f13cc6d3 100644
--- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
+++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
@@ -25,6 +25,7 @@ abstract class ExplicitOuter extends InfoTransform
import global._
import definitions._
import CODE._
+ import Debug.TRACE
/** The following flags may be set by this phase: */
override def phaseNewFlags: Long = notPRIVATE | notPROTECTED | lateFINAL
@@ -70,7 +71,9 @@ abstract class ExplicitOuter extends InfoTransform
class RemoveBindingsTransformer(toRemove: Set[Symbol]) extends Transformer {
override def transform(tree: Tree) = tree match {
- case Bind(_, body) if toRemove(tree.symbol) => super.transform(body)
+ case Bind(_, body) if toRemove(tree.symbol) =>
+ TRACE("Dropping unused binding: " + tree.symbol)
+ super.transform(body)
case _ => super.transform(tree)
}
}
@@ -532,7 +535,7 @@ abstract class ExplicitOuter extends InfoTransform
class Phase(prev: scala.tools.nsc.Phase) extends super.Phase(prev) {
override val checkable = false
- override def run {
+ override def run() {
super.run
Pattern.clear() // clear the cache
}
diff --git a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
index 98b6110f7f..9cfd497c76 100644
--- a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
+++ b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
@@ -54,7 +54,7 @@ abstract class LambdaLift extends InfoTransform {
private var changedFreeVars: Boolean = _
/** Buffers for lifted out classes and methods */
- private val liftedDefs = new LinkedHashMap[Symbol, ListBuffer[Tree]]
+ private val liftedDefs = new LinkedHashMap[Symbol, List[Tree]]
private type SymSet = TreeSet[Symbol]
@@ -63,51 +63,15 @@ abstract class LambdaLift extends InfoTransform {
private def symSet(f: LinkedHashMap[Symbol, SymSet], sym: Symbol): SymSet =
f.getOrElseUpdate(sym, newSymSet)
- private def outer(sym: Symbol): Symbol =
- if (sym.isConstructor) sym.owner.owner else sym.owner
-
private def isSameOwnerEnclosure(sym: Symbol) =
- enclMethOrClass(sym.owner) == enclMethOrClass(currentOwner)
+ sym.owner.logicallyEnclosingMember == currentOwner.logicallyEnclosingMember
- /** The method or class which logically encloses the current symbol.
- * If the symbol is defined in the initialization part of a template
- * this is the template's primary constructor, otherwise it is
- * the physically enclosing method or class.
- *
- * Example 1:
- *
- * def f() { val x = { def g() = ...; g() } }
- *
- * In this case the owner chain of `g' is `x', followed by `f' and
- * enclMethOrClass(`g') == `f'.
- *
- * Example 2:
- *
- * class C {
- * def <init> = { ... }
- * val x = { def g() = ...; g() } }
- * }
- *
- * In this case the owner chain of `g' is `x', followed by `C' but
- * enclMethOrClass(`g') is the primary constructor symbol `<init>'
- * (or, for traits: `$init') of `C'.
- *
- */
- private def enclMethOrClass(sym: Symbol): Symbol = {
- def localToConstr(sym: Symbol) =
- if (sym.isLocalDummy) sym.owner.primaryConstructor else sym;
- var encl = localToConstr(sym)
- while (!encl.isMethod && !encl.isClass)
- encl = localToConstr(outer(encl))
- encl
- }
-
- /** Mark symbol `sym' as being free in `owner', unless `sym'
- * is defined in `owner' or there is a class between `owner's owner
+ /** Mark symbol `sym' as being free in `enclosure', unless `sym'
+ * is defined in `enclosure' or there is a class between `enclosure's owner
* and the owner of `sym'.
- * Return `true' if there is no class between `owner' and
+ * Return `true' if there is no class between `enclosure' and
* the owner of sym.
- * pre: sym.isLocal, (owner.isMethod || owner.isClass)
+ * pre: sym.isLocal, (enclosure.isMethod || enclosure.isClass)
*
* The idea of `markFree' is illustrated with an example:
*
@@ -132,13 +96,13 @@ abstract class LambdaLift extends InfoTransform {
* }
* }
*/
- private def markFree(sym: Symbol, owner: Symbol): Boolean = {
+ private def markFree(sym: Symbol, enclosure: Symbol): Boolean = {
if (settings.debug.value)
- log("mark " + sym + " of " + sym.owner + " free in " + owner)
- if (owner == enclMethOrClass(sym.owner)) true
- else if (owner.isPackageClass || !markFree(sym, enclMethOrClass(outer(owner)))) false
+ log("mark free: " + sym + " of " + sym.owner + " marked free in " + enclosure)
+ if (enclosure == sym.owner.logicallyEnclosingMember) true
+ else if (enclosure.isPackageClass || !markFree(sym, enclosure.skipConstructor.owner.logicallyEnclosingMember)) false
else {
- val ss = symSet(free, owner)
+ val ss = symSet(free, enclosure)
if (!ss(sym)) {
ss addEntry sym
renamable addEntry sym
@@ -152,7 +116,7 @@ abstract class LambdaLift extends InfoTransform {
sym.owner.setInfo(sym.owner.info.cloneInfo(sym.owner))
}
changedFreeVars = true
- if (settings.debug.value) log("" + sym + " is free in " + owner);
+ if (settings.debug.value) log("" + sym + " is free in " + enclosure);
if ((sym.isVariable || (sym.isValue && sym.isLazy)) && !sym.hasFlag(CAPTURED)) {
sym setFlag CAPTURED
val symClass = sym.tpe.typeSymbol
@@ -166,30 +130,15 @@ abstract class LambdaLift extends InfoTransform {
}
}
}
- !owner.isClass
+ !enclosure.isClass
}
}
private def markCalled(sym: Symbol, owner: Symbol) {
if (settings.debug.value)
- log("mark " + sym + " of " + sym.owner + " called by " + owner);
+ log("mark called: " + sym + " of " + sym.owner + " is called by " + owner)
symSet(called, owner) addEntry sym
}
-/*
- if (owner == enclMethOrClass(sym.owner)) true
- else if (owner.isPackageClass || !markCalled(sym, enclMethOrClass(outer(owner)))) false
- else {
- val ss = symSet(called, owner);
- if (!(ss contains sym)) {
- ss addEntry sym;
- if (settings.debug.value) log("" + sym + " is called by " + owner);
- }
- !owner.isClass
- }
- }
-*/
- def freeVars(sym: Symbol): Iterator[Symbol] =
- free get sym map (_.iterator) getOrElse Iterator.empty
/** The traverse function */
private val freeVarTraverser = new Traverser {
@@ -198,7 +147,7 @@ abstract class LambdaLift extends InfoTransform {
val sym = tree.symbol;
tree match {
case ClassDef(_, _, _, _) =>
- liftedDefs(tree.symbol) = new ListBuffer
+ liftedDefs(tree.symbol) = Nil
if (sym.isLocal) renamable addEntry sym
case DefDef(_, _, _, _, _, _) =>
if (sym.isLocal) {
@@ -211,16 +160,14 @@ abstract class LambdaLift extends InfoTransform {
if (sym == NoSymbol) {
assert(name == nme.WILDCARD)
} else if (sym.isLocal) {
- val owner = enclMethOrClass(currentOwner)
+ val owner = currentOwner.logicallyEnclosingMember
if (sym.isTerm && !sym.isMethod) markFree(sym, owner)
else if (sym.isMethod) markCalled(sym, owner)
//symSet(called, owner) addEntry sym
}
case Select(_, _) =>
- if (sym.isConstructor && sym.owner.isLocal) {
- val owner = enclMethOrClass(currentOwner);
- markCalled(sym, owner) //symSet(called, owner) addEntry sym
- }
+ if (sym.isConstructor && sym.owner.isLocal)
+ markCalled(sym, currentOwner.logicallyEnclosingMember)
case _ =>
}
super.traverse(tree)
@@ -237,18 +184,17 @@ abstract class LambdaLift extends InfoTransform {
* value/variable/let that are free in some function or class, and to
* all class/function symbols that are owned by some function.
*/
- private def computeFreeVars {
+ private def computeFreeVars() {
freeVarTraverser.traverse(unit.body)
do {
changedFreeVars = false
- for (caller <- called.keys;
- callee <- called(caller);
- fv <- freeVars(callee))
+ for (caller <- called.keys ; callee <- called(caller) ; fvs <- free get callee ; fv <- fvs)
markFree(fv, caller)
} while (changedFreeVars)
for (sym <- renamable) {
+ val originalName = sym.name
val base = sym.name + "$" + (
if (sym.isAnonymousFunction && sym.owner.isMethod)
sym.owner.name + "$"
@@ -258,43 +204,41 @@ abstract class LambdaLift extends InfoTransform {
if (sym.name.isTypeName) unit.freshTypeName(base)
else unit.freshTermName(base)
- if (settings.debug.value) log("renamed: " + sym.name)
+ if (settings.debug.value)
+ log("renaming in %s: %s => %s".format(sym.owner.fullLocationString, originalName, sym.name))
}
atPhase(phase.next) {
- for (owner <- free.keys) {
+ for ((owner, freeValues) <- free.toList) {
if (settings.debug.value)
- log("free(" + owner + owner.locationString + ") = " + free(owner).toList)
- proxies(owner) =
- for (fv <- free(owner).toList) yield {
- val proxy = owner.newValue(owner.pos, fv.name)
- .setFlag(if (owner.isClass) PARAMACCESSOR | PRIVATE | LOCAL else PARAM)
- .setFlag(SYNTHETIC)
- .setInfo(fv.info);
- if (owner.isClass) owner.info.decls enter proxy;
- proxy
- }
+ log("free var proxy: %s, %s".format(owner.fullLocationString, freeValues.toList.mkString(", ")))
+
+ proxies(owner) =
+ for (fv <- freeValues.toList) yield {
+ val proxy = owner.newValue(owner.pos, fv.name)
+ .setFlag(if (owner.isClass) PARAMACCESSOR | PRIVATE | LOCAL else PARAM)
+ .setFlag(SYNTHETIC)
+ .setInfo(fv.info);
+ if (owner.isClass) owner.info.decls enter proxy;
+ proxy
+ }
}
}
}
private def proxy(sym: Symbol) = {
- def searchIn(owner: Symbol): Symbol = {
+ def searchIn(searchee: Symbol): Symbol = {
if (settings.debug.value)
- log("searching for " + sym + "(" + sym.owner + ") in " + owner +
- " " + enclMethOrClass(owner));//debug
- proxies.get(enclMethOrClass(owner)) match {
- case Some(ps) =>
- ps filter (p => p.name == sym.name) match {
- case List(p) => p
- case List() => searchIn(outer(owner))
- }
- case None => searchIn(outer(owner))
- }
+ log("searching for " + sym + "(" + sym.owner + ") in " + searchee + " " + searchee.logicallyEnclosingMember)
+
+ val ps = (proxies get searchee.logicallyEnclosingMember).toList.flatten filter (_.name == sym.name)
+ if (ps.isEmpty) searchIn(searchee.skipConstructor.owner)
+ else ps.head
}
if (settings.debug.value)
- log("proxy " + sym + " in " + sym.owner + " from " + currentOwner.ownerChain +
- " " + enclMethOrClass(sym.owner));//debug
+ log("proxy " + sym + " in " + sym.owner + " from " + currentOwner.ownerChain.mkString(" -> ") +
+ " " + sym.owner.logicallyEnclosingMember)
+
if (isSameOwnerEnclosure(sym)) sym
else searchIn(currentOwner)
}
@@ -317,20 +261,21 @@ abstract class LambdaLift extends InfoTransform {
}
private def addFreeArgs(pos: Position, sym: Symbol, args: List[Tree]) = {
- def freeArg(fv: Symbol) = atPos(pos)(proxyRef(fv))
- val fvs = freeVars(sym).toList
- if (fvs.isEmpty) args else args ::: (fvs map freeArg)
+ free get sym match {
+ case Some(fvs) => args ++ (fvs.toList map (fv => atPos(pos)(proxyRef(fv))))
+ case _ => args
+ }
}
private def addFreeParams(tree: Tree, sym: Symbol): Tree = proxies.get(sym) match {
case Some(ps) =>
- val freeParams = ps map (p => ValDef(p) setPos tree.pos setType NoType);
+ val freeParams = ps map (p => ValDef(p) setPos tree.pos setType NoType)
tree match {
- case DefDef(mods, name, tparams, List(vparams), tpt, rhs) =>
+ case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
val addParams = cloneSymbols(ps).map(_.setFlag(PARAM))
sym.updateInfo(
lifted(MethodType(sym.info.params ::: addParams, sym.info.resultType)))
- treeCopy.DefDef(tree, mods, name, tparams, List(vparams ::: freeParams), tpt, rhs)
+ treeCopy.DefDef(tree, mods, name, tparams, List(vparamss.head ++ freeParams), tpt, rhs)
case ClassDef(mods, name, tparams, impl @ Template(parents, self, body)) =>
// Disabled attempt to to add getters to freeParams
// this does not work yet. Problem is that local symbols need local names
@@ -384,14 +329,15 @@ abstract class LambdaLift extends InfoTransform {
*/
private def liftDef(tree: Tree): Tree = {
val sym = tree.symbol
+ val oldOwner = sym.owner
if (sym.owner.isAuxiliaryConstructor && sym.isMethod) // # bug 1909
sym setFlag STATIC
sym.owner = sym.owner.enclClass
if (sym.isClass) sym.owner = sym.owner.toInterface
if (sym.isMethod) sym setFlag LIFTED
- liftedDefs(sym.owner) += tree
+ liftedDefs(sym.owner) ::= tree
sym.owner.info.decls enterUnique sym
- if (settings.debug.value) log("lifted: " + sym + sym.locationString)
+ if (settings.debug.value) log("lifted: " + sym + " from " + oldOwner + " to " + sym.owner)
EmptyTree
}
@@ -468,7 +414,10 @@ abstract class LambdaLift extends InfoTransform {
override def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {
def addLifted(stat: Tree): Tree = stat match {
case ClassDef(mods, name, tparams, impl @ Template(parents, self, body)) =>
- val lifted = /*fixTraitGetters*/(liftedDefs(stat.symbol).toList map addLifted)
+ val lifted = liftedDefs get stat.symbol match {
+ case Some(xs) => xs reverseMap addLifted
+ case _ => log("unexpectedly no lifted defs for " + stat.symbol) ; Nil
+ }
val result = treeCopy.ClassDef(
stat, mods, name, tparams, treeCopy.Template(impl, parents, self, body ::: lifted))
liftedDefs -= stat.symbol
@@ -484,7 +433,7 @@ abstract class LambdaLift extends InfoTransform {
override def transformUnit(unit: CompilationUnit) {
computeFreeVars
atPhase(phase.next)(super.transformUnit(unit))
- assert(liftedDefs.isEmpty, liftedDefs.keys.toList)
+ assert(liftedDefs.isEmpty, liftedDefs.keys mkString ", ")
}
} // class LambdaLifter
diff --git a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
index 8e977b32e5..1710e8e4c3 100644
--- a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
+++ b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
@@ -174,7 +174,7 @@ abstract class OverridingPairs {
def hasNext: Boolean = curEntry ne null
@tailrec
- final def next {
+ final def next() {
if (curEntry ne null) {
overriding = curEntry.sym
if (nextEntry ne null) {
diff --git a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
index e8c8def012..1635a9a534 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
@@ -80,7 +80,7 @@ trait Analyzer extends AnyRef
// Lacking a better fix, we clear it here (before the phase is created, meaning for each
// compiler run). This is good enough for the resident compiler, which was the most affected.
undoLog.clear()
- override def run {
+ override def run() {
val start = startTimer(typerNanos)
global.echoPhaseSummary(this)
currentRun.units foreach applyPhase
diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
index 7567cf6483..96d81d63a8 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
@@ -495,7 +495,7 @@ trait Contexts { self: Analyzer =>
private var implicitsCache: List[List[ImplicitInfo]] = null
private var implicitsRunId = NoRunId
- def resetCache : Unit = {
+ def resetCache() {
implicitsRunId = NoRunId
implicitsCache = null
if (outer != null && outer != this) outer.resetCache
diff --git a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala
index 286310cad0..4a966f1fca 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala
@@ -39,7 +39,7 @@ abstract class Duplicators extends Analyzer {
override def newTyper(context: Context): Typer =
new BodyDuplicator(context)
- private def resetClassOwners {
+ private def resetClassOwners() {
oldClassOwner = null
newClassOwner = null
}
diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
index a05aefe1fa..53b4f0dac6 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
@@ -68,7 +68,7 @@ trait Implicits {
private final val sizeLimit = 50000
private type Infos = List[ImplicitInfo]
private type Infoss = List[List[ImplicitInfo]]
- private type InfoMap = LinkedHashMap[Symbol, List[ImplicitInfo]]
+ private type InfoMap = LinkedHashMap[Symbol, List[ImplicitInfo]] // A map from class symbols to their associated implicits
private val implicitsCache = new LinkedHashMap[Type, Infoss]
private val infoMapCache = new LinkedHashMap[Symbol, InfoMap]
private val improvesCache = new HashMap[(ImplicitInfo, ImplicitInfo), Boolean]
@@ -752,7 +752,9 @@ trait Implicits {
if (implicitInfoss.forall(_.isEmpty)) SearchFailure
else new ImplicitComputation(implicitInfoss, if (isLocal) util.HashSet[Name](128) else null) findBest()
- /** The parts of a type is the smallest set of types that contains
+ /** Produce an implicict info map, i.e. a map from the class symbols C of all parts of this type to
+ * the implicit infos in the companion objects of these class symbols C.
+ * The parts of a type is the smallest set of types that contains
* - the type itself
* - the parts of its immediate components (prefix and argument)
* - the parts of its base types
@@ -763,10 +765,11 @@ trait Implicits {
* which are members of these companion objects.
*/
private def companionImplicitMap(tp: Type): InfoMap = {
- val infoMap = new InfoMap
- val seen = mutable.HashSet[Type]() // cycle detection
- def getClassParts(tp: Type, infoMap: InfoMap, seen: mutable.Set[Type]) = tp match {
+ /** Populate implicit info map by traversing all parts of type `tp`.
+ * Parameters as for `getParts`.
+ */
+ def getClassParts(tp: Type)(implicit infoMap: InfoMap, seen: mutable.Set[Type], pending: Set[Symbol]) = tp match {
case TypeRef(pre, sym, args) =>
infoMap get sym match {
case Some(infos1) =>
@@ -789,17 +792,22 @@ trait Implicits {
val bts = tp.baseTypeSeq
var i = 1
while (i < bts.length) {
- getParts(bts(i), infoMap, seen)
+ getParts(bts(i))
i += 1
}
- getParts(pre, infoMap, seen)
+ getParts(pre)
}
}
- /** Enter all parts of `tp` into `parts` set.
- * This method is performance critical: about 2-4% of all type checking is spent here
+ /** Populate implicit info map by traversing all parts of type `tp`.
+ * This method is performance critical.
+ * @param tp The type for which we want to traverse parts
+ * @param infoMap The infoMap in which implicit infos corresponding to parts are stored
+ * @param seen The types that were already visited previously when collecting parts for the given infoMap
+ * @param pending The set of static symbols for which we are currently trying to collect their parts
+ * in order to cache them in infoMapCache
*/
- def getParts(tp: Type, infoMap: InfoMap, seen: mutable.Set[Type]) {
+ def getParts(tp: Type)(implicit infoMap: InfoMap, seen: mutable.Set[Type], pending: Set[Symbol]) {
if (seen(tp))
return
seen += tp
@@ -809,46 +817,45 @@ trait Implicits {
if (!((sym.name == tpnme.REFINE_CLASS_NAME) ||
(sym.name startsWith tpnme.ANON_CLASS_NAME) ||
(sym.name == tpnme.ROOT))) {
- if (sym.isStatic)
+ if (sym.isStatic && !(pending contains sym))
infoMap ++= {
infoMapCache get sym match {
case Some(imap) => imap
case None =>
- infoMapCache(sym) = LinkedHashMap.empty // to break cycles
val result = new InfoMap
- getClassParts(sym.tpe, result, new mutable.HashSet[Type]())
+ getClassParts(sym.tpe)(result, new mutable.HashSet(), pending + sym)
infoMapCache(sym) = result
result
}
}
else
- getClassParts(tp, infoMap, seen)
- args foreach (getParts(_, infoMap, seen))
+ getClassParts(tp)
+ args foreach (getParts(_))
}
} else if (sym.isAliasType) {
- getParts(tp.normalize, infoMap, seen)
+ getParts(tp.normalize)
} else if (sym.isAbstractType) {
- getParts(tp.bounds.hi, infoMap, seen)
+ getParts(tp.bounds.hi)
}
case ThisType(_) =>
- getParts(tp.widen, infoMap, seen)
+ getParts(tp.widen)
case _: SingletonType =>
- getParts(tp.widen, infoMap, seen)
+ getParts(tp.widen)
case RefinedType(ps, _) =>
- for (p <- ps) getParts(p, infoMap, seen)
+ for (p <- ps) getParts(p)
case AnnotatedType(_, t, _) =>
- getParts(t, infoMap, seen)
+ getParts(t)
case ExistentialType(_, t) =>
- getParts(t, infoMap, seen)
+ getParts(t)
case PolyType(_, t) =>
- getParts(t, infoMap, seen)
+ getParts(t)
case _ =>
}
}
- getParts(tp, infoMap, seen)
- if (settings.verbose.value)
- println("companion implicits of "+tp+" = "+infoMap) // DEBUG
+ val infoMap = new InfoMap
+ getParts(tp)(infoMap, new mutable.HashSet(), Set())
+ if (traceImplicits) println("companion implicits of "+tp+" = "+infoMap)
infoMap
}
@@ -1110,7 +1117,7 @@ trait Implicits {
object ImplicitNotFoundMsg {
def unapply(sym: Symbol): Option[(Message)] = sym.implicitNotFoundMsg map (m => (new Message(sym, m)))
- // check the message's syntax: should be a string literal that may contain occurences of the string "${X}",
+ // check the message's syntax: should be a string literal that may contain occurrences of the string "${X}",
// where `X` refers to a type parameter of `sym`
def check(sym: Symbol): Option[String] =
sym.getAnnotation(ImplicitNotFoundClass).flatMap(_.stringArg(0) match {
diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
index fd27f178ef..6c27bcace6 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
@@ -1066,7 +1066,7 @@ trait Infer {
}
errorMessages.toList
}
- /** Substitite free type variables `undetparams' of polymorphic argument
+ /** Substitute free type variables `undetparams' of polymorphic argument
* expression `tree', given two prototypes `strictPt', and `lenientPt'.
* `strictPt' is the first attempt prototype where type parameters
* are left unchanged. `lenientPt' is the fall-back prototype where type
@@ -1113,7 +1113,7 @@ trait Infer {
}
}
- /** Substitite free type variables `undetparams' of polymorphic argument
+ /** Substitute free type variables `undetparams' of polymorphic argument
* expression <code>tree</code> to `targs', Error if `targs' is null
*
* @param tree ...
@@ -1195,7 +1195,7 @@ trait Infer {
tp
}
- /** Substitite free type variables <code>undetparams</code> of type constructor
+ /** Substitute free type variables <code>undetparams</code> of type constructor
* <code>tree</code> in pattern, given prototype <code>pt</code>.
*
* @param tree ...
@@ -1568,7 +1568,9 @@ trait Infer {
(alts map pre.memberType) +", argtpes = "+ argtpes +", pt = "+ pt)
var allApplicable = alts filter (alt =>
- isApplicable(undetparams, followApply(pre.memberType(alt)), argtpes, pt))
+ // TODO: this will need to be re-written once we substitute throwing exceptions
+ // with generating error trees. We wrap this applicability in try/catch because of #4457.
+ try {isApplicable(undetparams, followApply(pre.memberType(alt)), argtpes, pt)} catch {case _: TypeError => false})
//log("applicable: "+ (allApplicable map pre.memberType))
diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala
index f1f8257fff..8f20f2a120 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala
@@ -347,7 +347,7 @@ trait Namers { self: Analyzer =>
def enterSym(tree: Tree): Context = {
def finishWith(tparams: List[TypeDef]) { enterSymFinishWith(tree, tparams) }
- def finish = finishWith(Nil)
+ def finish() = finishWith(Nil)
def sym = tree.symbol
if (sym != NoSymbol) {
if (forInteractive && sym != null && sym.owner.isTerm) {
@@ -1239,8 +1239,14 @@ trait Namers { self: Analyzer =>
case ImportSelector(from, _, to, _) :: rest =>
if (from != nme.WILDCARD && base != ErrorType) {
isValidSelector(from) {
- if (currentRun.compileSourceFor(expr, from))
- return typeSig(tree)
+ if (currentRun.compileSourceFor(expr, from)) {
+ // XXX This used to be "return typeSig(tree)" but since this method
+ // returns Unit, that is deceptive at best. Just in case it is side-effecting
+ // somehow, I left the call in before the return; if you know it is
+ // not side effecting, please delete the call.
+ typeSig(tree)
+ return
+ }
def notMember = context.error(tree.pos, from.decode + " is not a member of " + expr)
// for Java code importing Scala objects
diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
index 3eb5107870..c08c55f4e4 100644
--- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
@@ -507,6 +507,48 @@ abstract class RefChecks extends InfoTransform {
else analyzer.varNotice(member)
)
}
+ else if (underlying.isMethod) {
+ // If there is a concrete method whose name matches the unimplemented
+ // abstract method, and a cursory examination of the difference reveals
+ // something obvious to us, let's make it more obvious to them.
+ val abstractParams = underlying.tpe.paramTypes
+ val matchingName = clazz.tpe.nonPrivateMembersAdmitting(VBRIDGE)
+ val matchingArity = matchingName filter { m =>
+ !m.isDeferred &&
+ (m.name == underlying.name) &&
+ (m.tpe.paramTypes.size == underlying.tpe.paramTypes.size) &&
+ (m.tpe.typeParams.size == underlying.tpe.typeParams.size)
+ }
+
+ matchingArity match {
+ // So far so good: only one candidate method
+ case concrete :: Nil =>
+ val mismatches = abstractParams zip concrete.tpe.paramTypes filterNot { case (x, y) => x =:= y }
+ mismatches match {
+ // Only one mismatched parameter: say something useful.
+ case (pa, pc) :: Nil =>
+ val addendum =
+ if (pa.typeSymbol == pc.typeSymbol) {
+ // TODO: what is the optimal way to test for a raw type at this point?
+ // Compilation has already failed so we shouldn't have to worry overmuch
+ // about forcing types.
+ if (underlying.isJavaDefined && pa.typeArgs.isEmpty && pa.typeSymbol.typeParams.nonEmpty)
+ ". To implement a raw type, use %s[_]".format(pa)
+ else if (pa.prefix =:= pc.prefix)
+ ": their type parameters differ"
+ else
+ ": their prefixes (i.e. enclosing instances) differ"
+ }
+ else ""
+
+ undefined("\n(Note that %s does not match %s%s)".format(pa, pc, addendum))
+ case xs =>
+ undefined("")
+ }
+ case _ =>
+ undefined("")
+ }
+ }
else undefined("")
}
@@ -825,9 +867,6 @@ abstract class RefChecks extends InfoTransform {
currentLevel = currentLevel.outer
}
- private def normalizeSymToRef(sym: Symbol): Symbol =
- if(sym isLazy) sym.lazyAccessor else sym
-
private def enterSyms(stats: List[Tree]) {
var index = -1
for (stat <- stats) {
@@ -835,7 +874,7 @@ abstract class RefChecks extends InfoTransform {
stat match {
case ClassDef(_, _, _, _) | DefDef(_, _, _, _, _, _) | ModuleDef(_, _, _) | ValDef(_, _, _, _) =>
//assert(stat.symbol != NoSymbol, stat);//debug
- val sym = normalizeSymToRef(stat.symbol)
+ val sym = stat.symbol.lazyAccessorOrSelf
if (sym.isLocal) {
currentLevel.scope.enter(sym)
symIndex(sym) = index;
@@ -981,11 +1020,75 @@ abstract class RefChecks extends InfoTransform {
override def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {
pushLevel()
- enterSyms(stats)
- var index = -1
- val stats1 = stats flatMap { stat => index += 1; transformStat(stat, index) }
- popLevel()
- stats1
+ try {
+ enterSyms(stats)
+ var index = -1
+ stats flatMap { stat => index += 1; transformStat(stat, index) }
+ }
+ finally popLevel()
+ }
+
+ /** Eliminate ModuleDefs.
+ * - A top level object is replaced with their module class.
+ * - An inner object is transformed into a module var, created on first access.
+ *
+ * In both cases, this transformation returns the list of replacement trees:
+ * - Top level: the module class accessor definition
+ * - Inner: a class definition, declaration of module var, and module var accessor
+ */
+ private def eliminateModuleDefs(tree: Tree): List[Tree] = {
+ val ModuleDef(mods, name, impl) = tree
+ val sym = tree.symbol
+
+ // transformedInfo check is necessary here because the object info may already
+ // have been transformed, and we do not want to have duplicate lazy accessors
+ // (through duplicate nested object -> lazy val transformation.)
+ val transformedInfo = sym.isLazy
+ val classSym = if (transformedInfo) sym.lazyAccessor else sym.moduleClass
+ val cdef = ClassDef(mods | MODULE, name.toTypeName, Nil, impl) setSymbol classSym setType NoType
+
+ def findOrCreateModuleVar() = localTyper.typedPos(tree.pos) {
+ lazy val createModuleVar = gen.mkModuleVarDef(sym)
+ if (!transformedInfo) createModuleVar
+ else sym.owner.info.decl(nme.moduleVarName(sym.name.toTermName)) match {
+ // In case we are dealing with local symbol then we already have
+ // to correct error with forward reference
+ case NoSymbol => createModuleVar
+ case vsym => ValDef(vsym)
+ }
+ }
+ def createStaticModuleAccessor() = atPhase(phase.next) {
+ val method = (
+ sym.owner.newMethod(sym.pos, sym.name.toTermName)
+ setFlag (sym.flags | STABLE) resetFlag MODULE setInfo NullaryMethodType(sym.moduleClass.tpe)
+ )
+ sym.owner.info.decls enter method
+ localTyper.typedPos(tree.pos)(gen.mkModuleAccessDef(method, sym))
+ }
+ def createInnerModuleAccessor(vdef: Tree) = List(
+ vdef,
+ localTyper.typedPos(tree.pos) {
+ val vsym = vdef.symbol
+ atPhase(phase.next) {
+ val rhs = gen.newModule(sym, vsym.tpe)
+ // side effecting symbol flags
+ if (!transformedInfo) {
+ sym resetFlag (MODULE | FINAL | CASE)
+ sym setFlag (LAZY | ACCESSOR | SYNTHETIC)
+ sym setInfo NullaryMethodType(sym.tpe)
+ sym setFlag (lateMETHOD | STABLE)
+ }
+ val body = if (sym.owner.isTrait) rhs else gen.mkAssignAndReturn(vsym, rhs)
+ DefDef(sym, body.changeOwner(vsym -> sym))
+ }
+ }
+ )
+ transformTrees(cdef :: {
+ if (sym.isStatic)
+ if (sym.allOverriddenSymbols.isEmpty) Nil
+ else List(createStaticModuleAccessor())
+ else createInnerModuleAccessor(findOrCreateModuleVar)
+ })
}
/** Implements lazy value accessors:
@@ -994,127 +1097,47 @@ abstract class RefChecks extends InfoTransform {
* - 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.
*/
- def transformStat(tree: Tree, index: Int): List[Tree] = {
- def checkForwardReference(sym: Symbol) =
- if (sym.isLocal && index <= currentLevel.maxindex) {
- if (settings.debug.value) Console.println(currentLevel.refsym)
- unit.error(currentLevel.refpos, "forward reference extends over definition of " + sym)
- }
- tree match {
- case ModuleDef(mods, name, impl) =>
- val sym = tree.symbol
- def mkClassDef(transformedInfo: Boolean) = {
- ClassDef(mods | MODULE, name.toTypeName, Nil, impl)
- .setPos(tree.pos)
- .setSymbol(if (transformedInfo) sym.lazyAccessor else sym.moduleClass)
- .setType(NoType)
- }
- if (sym.isStatic) {
- val cdef = mkClassDef(false)
-
- if (!sym.allOverriddenSymbols.isEmpty) {
- val factory = sym.owner.newMethod(sym.pos, sym.name.toTermName)
- .setFlag(sym.flags | STABLE).resetFlag(MODULE)
- .setInfo(NullaryMethodType(sym.moduleClass.tpe))
- sym.owner.info.decls.enter(factory)
- val ddef =
- atPhase(phase.next) {
- localTyper.typed {
- gen.mkModuleAccessDef(factory, sym)
- }
- }
- transformTrees(List(cdef, ddef))
- } else {
- List(transform(cdef))
- }
- } else {
- def lazyNestedObjectTrees(transformedInfo: Boolean) = {
- // transformedInfo flag is necessary here because it is possible
- // that the object info was already run through the transformInfo.
- // Since we do not want to have duplicate lazy accessors
- // (through duplicate nested object -> lazy val transformation) we have this check here.
- val cdef = mkClassDef(transformedInfo)
- val vdef = localTyper.typedPos(tree.pos){
- if (!transformedInfo)
- gen.mkModuleVarDef(sym)
- else {
- val vsym0 = sym.owner.info.decl(nme.moduleVarName(sym.name.toTermName))
- // In case we are dealing with local symbol then we already have correct error with forward reference
- ValDef(if (vsym0 == NoSymbol) gen.mkModuleVarDef(sym).symbol else vsym0, EmptyTree)
- }
- }
- val vsym = vdef.symbol
-
- val ddef = atPhase(phase.next) {
- localTyper.typed {
- val rhs = gen.newModule(sym, vsym.tpe)
- if (!transformedInfo) {
- sym.resetFlag(MODULE | FINAL | CASE)
- sym.setFlag(LAZY | ACCESSOR | SYNTHETIC)
-
- sym.setInfo(NullaryMethodType(sym.tpe))
- sym setFlag (lateMETHOD | STABLE)
- }
+ 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)))
+ log("Made lazy def: " + lazyDef)
- val ownerTransformer = new ChangeOwnerTraverser(vsym, sym)
- val lazyDef = atPos(tree.pos)(
- DefDef(sym, ownerTransformer(
- if (sym.owner.isTrait) rhs
- else Block(List(
- Assign(gen.mkAttributedRef(vsym), rhs)),
- gen.mkAttributedRef(vsym)))
- ))
- lazyDef
- }
- }
- transformTrees(List(cdef, vdef, ddef))
- }
- lazyNestedObjectTrees(sym.hasFlag(LAZY))
- }
+ if (hasUnitType) List(typed(lazyDef))
+ else List(
+ typed(ValDef(vsym)),
+ atPhase(phase.next)(typed(lazyDef))
+ )
+ }
- case ValDef(_, _, _, _) =>
- val tree1 = transform(tree); // important to do before forward reference check
-
- if (tree.symbol.hasFlag(LAZY)) {
- assert(tree.symbol.isTerm, tree.symbol)
- val ValDef(_, _, _, rhs) = tree1
- val vsym = tree.symbol
- val hasUnitType = (tree.symbol.tpe.typeSymbol == UnitClass)
- val lazyDefSym = vsym.lazyAccessor
- assert(lazyDefSym != NoSymbol, vsym)
- val ownerTransformer = new ChangeOwnerTraverser(vsym, lazyDefSym)
- val lazyDef = atPos(tree.pos)(
- DefDef(lazyDefSym, ownerTransformer(
- if (tree.symbol.owner.isTrait // for traits, this is further transformed in mixins
- || hasUnitType) rhs
- else Block(List(
- Assign(gen.mkAttributedRef(vsym), rhs)),
- gen.mkAttributedRef(vsym)))))
- log("Made lazy def: " + lazyDef)
- if (hasUnitType)
- typed(lazyDef) :: Nil
- else
- typed(ValDef(vsym, EmptyTree)) :: atPhase(phase.next) { typed(lazyDef) } :: Nil
- } else {
- checkForwardReference(normalizeSymToRef(tree.symbol))
- List(tree1)
+ def transformStat(tree: Tree, index: Int): List[Tree] = tree match {
+ 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)
+ else {
+ val lazySym = tree.symbol.lazyAccessorOrSelf
+ if (lazySym.isLocal && index <= currentLevel.maxindex) {
+ if (settings.debug.value)
+ Console.println(currentLevel.refsym)
+ unit.error(currentLevel.refpos, "forward reference extends over definition of " + lazySym)
}
-
- case Import(_, _) =>
- List()
-
- case _ =>
- List(transform(tree))
- }
+ List(tree1)
+ }
+ case Import(_, _) => Nil
+ case _ => List(transform(tree))
}
- /******** Begin transform inner function section ********/
-
- /** The private functions between here and 'transform' are conceptually
- * inner functions to that method, but have been moved outside of it to
- * ease the burden on the optimizer.
- */
-
/* Check whether argument types conform to bounds of type parameters */
private def checkBounds(pre: Type, owner: Symbol, tparams: List[Symbol], argtps: List[Type], pos: Position): Unit =
try typer.infer.checkBounds(pos, pre, owner, tparams, argtps, "")
@@ -1128,34 +1151,30 @@ abstract class RefChecks extends InfoTransform {
()
}
}
- private def isIrrefutable(pat: Tree, seltpe: Type): Boolean = {
- val result = pat match {
- case Apply(_, args) =>
- val clazz = pat.tpe.typeSymbol;
- clazz == seltpe.typeSymbol &&
- clazz.isCaseClass &&
- (args corresponds clazz.primaryConstructor.tpe.asSeenFrom(seltpe, clazz).paramTypes)(isIrrefutable) // @PP: corresponds
- case Typed(pat, tpt) =>
- seltpe <:< tpt.tpe
- case Ident(tpnme.WILDCARD) =>
- true
- case Bind(_, pat) =>
- isIrrefutable(pat, seltpe)
- case _ =>
- false
- }
- //Console.println("is irefutable? " + pat + ":" + pat.tpe + " against " + seltpe + ": " + result);//DEBUG
- result
+ private def isIrrefutable(pat: Tree, seltpe: Type): Boolean = pat match {
+ case Apply(_, args) =>
+ val clazz = pat.tpe.typeSymbol
+ clazz == seltpe.typeSymbol &&
+ clazz.isCaseClass &&
+ (args corresponds clazz.primaryConstructor.tpe.asSeenFrom(seltpe, clazz).paramTypes)(isIrrefutable)
+ case Typed(pat, tpt) =>
+ seltpe <:< tpt.tpe
+ case Ident(tpnme.WILDCARD) =>
+ true
+ case Bind(_, pat) =>
+ isIrrefutable(pat, seltpe)
+ case _ =>
+ false
}
- /** If symbol is deprecated and is not contained in a deprecated definition,
- * issue a deprecated warning
+
+ /** If symbol is deprecated, and the point of reference is not enclosed
+ * in either a deprecated member or a scala bridge method, issue a warning.
*/
private def checkDeprecated(sym: Symbol, pos: Position) {
- if (sym.isDeprecated && !currentOwner.ownerChain.exists(_.isDeprecated)) {
- val dmsg = sym.deprecationMessage
- val msg = sym.toString + sym.locationString +" is deprecated"+
- (if (dmsg.isDefined) ": "+ dmsg.get else "")
- unit.deprecationWarning(pos, msg)
+ if (sym.isDeprecated && !currentOwner.ownerChain.exists(x => x.isDeprecated || x.hasBridgeAnnotation)) {
+ val dmsg = sym.deprecationMessage map (": " + _) getOrElse ""
+
+ unit.deprecationWarning(pos, sym.fullLocationString + " is deprecated" + dmsg)
}
}
/** Similar to deprecation: check if the symbol is marked with @migration
@@ -1163,7 +1182,7 @@ abstract class RefChecks extends InfoTransform {
*/
private def checkMigration(sym: Symbol, pos: Position) = {
for (msg <- sym.migrationMessage)
- unit.warning(pos, "%s%s has changed semantics:\n%s".format(sym, sym.locationString, msg))
+ unit.warning(pos, sym.fullLocationString + " has changed semantics:\n" + msg)
}
/** Check that a deprecated val or def does not override a
diff --git a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
index 271999da9a..75483f777c 100644
--- a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
@@ -122,7 +122,7 @@ abstract class TreeCheckers extends Analyzer {
def assertFn(cond: Boolean, msg: => Any) =
if (!cond) errorFn(msg)
- def checkTrees {
+ def checkTrees() {
if (settings.verbose.value)
Console.println("[consistency check at the beginning of phase " + phase + "]")
diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
index add3bca6f2..8e49626df6 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
@@ -925,7 +925,32 @@ trait Typers extends Modes {
log("error tree = "+tree)
if (settings.explaintypes.value) explainTypes(tree.tpe, pt)
}
- typeErrorTree(tree, tree.tpe, pt)
+ try {
+ typeErrorTree(tree, tree.tpe, pt)
+ } catch {
+ case ex: TypeError =>
+ if (phase.id > currentRun.typerPhase.id &&
+ pt.existentialSkolems.nonEmpty) {
+ // Ignore type errors raised in later phases that are due to mismatching types with existential skolems
+ // We have lift crashing in 2.9 with an adapt failure in the pattern matcher.
+ // Here's my hypothsis why this happens. The pattern matcher defines a variable of type
+ //
+ // val x: T = expr
+ //
+ // where T is the type of expr, but T contains existential skolems ts.
+ // In that case, this value definition does not typecheck.
+ // The value definition
+ //
+ // val x: T forSome { ts } = expr
+ //
+ // would typechek. Or one can simply leave out the type of the `val':
+ //
+ // val x = expr
+ context.unit.warning(tree.pos, "recovering from existential Skolem type error in tree \n"+tree+"\nwith type "+tree.tpe+"\n expected type = "+pt+"\n context = "+context.tree)
+ adapt(tree, mode, pt.subst(pt.existentialSkolems, pt.existentialSkolems map (_ => WildcardType)))
+ } else
+ throw ex
+ }
}
}
}
@@ -2715,7 +2740,7 @@ trait Typers extends Modes {
fun1clazz,
List(selfsym.info, annClass.tpe))
- typed(func, mode, funcType) match {
+ (typed(func, mode, funcType): @unchecked) match {
case t @ Function(List(arg), rhs) =>
val subs =
new TreeSymSubstituter(List(arg.symbol),List(selfsym))
@@ -2744,12 +2769,7 @@ trait Typers extends Modes {
}
if (annType.typeSymbol == DeprecatedAttr && argss.flatten.size < 2)
- unit.deprecationWarning(ann.pos, """
- |The `deprecated` annotation now takes two String parameters: the first is
- |an explanation and/or recommended alternative, which will be printed to the
- |console and also appear in the scaladoc. The second is the first released
- |version in which the member was deprecated.""".trim.stripMargin
- )
+ unit.deprecationWarning(ann.pos, "@deprecated now takes two arguments; see the scaladoc.")
if ((typedAnn.tpe == null) || typedAnn.tpe.isErroneous) annotationError
else annInfo(typedAnn)
@@ -3178,8 +3198,7 @@ trait Typers extends Modes {
context.tree match {
case ValDef(mods, _, _, Apply(Select(`tree`, _), _)) if !mods.isMutable && sym != null && sym != NoSymbol =>
val sym1 = if (sym.owner.isClass && sym.getter(sym.owner) != NoSymbol) sym.getter(sym.owner)
- else if (sym.isLazyAccessor) sym.lazyAccessor
- else sym
+ else sym.lazyAccessorOrSelf
val pre = if (sym1.owner.isClass) sym1.owner.thisType else NoPrefix
intersectionType(List(tp, singleType(pre, sym1)))
case _ => tp
diff --git a/src/compiler/scala/tools/nsc/util/ClassPath.scala b/src/compiler/scala/tools/nsc/util/ClassPath.scala
index 962062eb2d..40c3316e09 100644
--- a/src/compiler/scala/tools/nsc/util/ClassPath.scala
+++ b/src/compiler/scala/tools/nsc/util/ClassPath.scala
@@ -414,11 +414,11 @@ extends ClassPath[T] {
})
}
- def show {
+ def show() {
println("ClassPath %s has %d entries and results in:\n".format(name, entries.size))
asClasspathString split ':' foreach (x => println(" " + x))
}
- def showDuplicates =
+ def showDuplicates() =
ClassPath findDuplicates this foreach {
case (name, xs) => println(xs.mkString(name + ":\n ", "\n ", "\n"))
}
diff --git a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala
index 5051ea6759..f27d25d1b0 100644
--- a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala
+++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala
@@ -110,7 +110,7 @@ class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int,
ch
}
- def rewind {
+ def rewind() {
if (oldBp == -1) throw new IllegalArgumentException
bp = oldBp
ch = oldCh
diff --git a/src/compiler/scala/tools/util/Which.scala b/src/compiler/scala/tools/util/Which.scala
index cf52455259..1cafe156b5 100644
--- a/src/compiler/scala/tools/util/Which.scala
+++ b/src/compiler/scala/tools/util/Which.scala
@@ -11,8 +11,7 @@ import scala.tools.nsc._
/** A tool for identifying which classfile is being used.
* under the given conditions.
*/
-object Which
-{
+object Which {
def main(args: Array[String]): Unit = {
val settings = new Settings()
val names = settings.processArguments(args.toList, true)._2
@@ -22,7 +21,7 @@ object Which
import cp._
for (name <- names) {
- def fail = println("Could not find: %s".format(name))
+ def fail() = println("Could not find: %s".format(name))
(cp findClass name) match {
case Some(classRep) => classRep.binary match {
case Some(f) => println("%s is %s".format(name, f))
diff --git a/src/dbc/scala/dbc/Database.scala b/src/dbc/scala/dbc/Database.scala
index 2895f2cb29..60e16367e8 100644
--- a/src/dbc/scala/dbc/Database.scala
+++ b/src/dbc/scala/dbc/Database.scala
@@ -87,7 +87,7 @@ import java.sql._
/** ..
*/
- def close {
+ def close() {
closing = true
for (conn <- availableConnections) conn.close()
}
@@ -134,7 +134,7 @@ import java.sql._
new scala.dbc.result.Status[Unit] {
val statement = statusStatement;
if (debug) Console.println("## " + statement.sqlString);
- def result = ();
+ def result = ()
private val connection = getConnection;
val jdbcStatement: java.sql.Statement = connection.createStatement();
jdbcStatement.execute(statement.sqlString);
diff --git a/src/detach/library/scala/runtime/RemoteRef.scala b/src/detach/library/scala/runtime/RemoteRef.scala
index 9b692fb415..d8444e5220 100644
--- a/src/detach/library/scala/runtime/RemoteRef.scala
+++ b/src/detach/library/scala/runtime/RemoteRef.scala
@@ -169,7 +169,7 @@ object RemoteRef { /*extends Thread {
private def warning(msg: String) { Debug.warning("[RemoteRef] "+msg) }
private def error(msg: String) { Debug.error("[RemoteRef] "+msg) }
- private def printDebugInfos {
+ private def printDebugInfos() {
def property(name: String): String =
name+"="+(
try { System.getProperty(name, "") }
diff --git a/src/detach/plugin/scala/tools/detach/Detach.scala b/src/detach/plugin/scala/tools/detach/Detach.scala
index 3ce8ef2fff..56433cd33e 100644
--- a/src/detach/plugin/scala/tools/detach/Detach.scala
+++ b/src/detach/plugin/scala/tools/detach/Detach.scala
@@ -756,7 +756,7 @@ abstract class Detach extends PluginComponent
proxy
}
- def addAccessors {
+ def addAccessors() {
def mkGetter(sym: Symbol, name: String): Symbol = {
val getter = if (sym.isMethod) {
val meth = sym.cloneSymbol(proxyIntf)
@@ -1131,8 +1131,8 @@ abstract class Detach extends PluginComponent
if (newDefs.isEmpty) stats1 else stats1 ::: newDefs
}
- private def genProxies {
- def printDebugInfo {
+ private def genProxies() {
+ def printDebugInfo() {
println("\ncompilation unit : "+unit)
for ((sym, _) <- detachedClosure) {
println("closure to detach: "+sym+" (owner: "+sym.owner+")")
@@ -1155,7 +1155,7 @@ abstract class Detach extends PluginComponent
println("\t"+sym+" -> "+xs.mkString(", ")+" ["+xs.length+"]")
}
}
- def printDebugInfo2 {
+ def printDebugInfo2() {
println("\nproxy classes :")
for (sym <- proxies.keysIterator)
println("\t"+sym+"("+sym.tpe+") -> "+proxies(sym))
@@ -1179,7 +1179,7 @@ abstract class Detach extends PluginComponent
* closures;</li>
* <li>it then adds proxies for free objects;</li>
* <li>finally, if transforms detached closures (both definition and
- * instantation).</li>
+ * instantiation).</li>
* </ol>
*/
override def transformUnit(unit: CompilationUnit) {
diff --git a/src/library/scala/App.scala b/src/library/scala/App.scala
index 59c6fccec3..826278ade0 100644
--- a/src/library/scala/App.scala
+++ b/src/library/scala/App.scala
@@ -51,7 +51,7 @@ trait App extends DelayedInit {
/** The main method.
* This stores all argument so that they can be retrieved with `args`
- * and the executes all initialization code segements in the order they were
+ * and the executes all initialization code segments in the order they were
* passed to `delayedInit`
* @param args the arguments passed to the main method
*/
diff --git a/src/library/scala/Array.scala b/src/library/scala/Array.scala
index 66ce9320bd..5ff5778800 100644
--- a/src/library/scala/Array.scala
+++ b/src/library/scala/Array.scala
@@ -6,15 +6,14 @@
** |/ **
\* */
-
-
package scala
import scala.collection.generic._
-import scala.collection.mutable.{ArrayBuilder, ArraySeq}
+import scala.collection.{ mutable, immutable }
+import mutable.{ ArrayBuilder, ArraySeq }
import compat.Platform.arraycopy
import scala.reflect.ClassManifest
-import scala.runtime.ScalaRunTime.{array_apply, array_update}
+import scala.runtime.ScalaRunTime.{ array_apply, array_update }
/** Contains a fallback builder for arrays when the element type
* does not have a class manifest. In that case a generic array is built.
@@ -26,7 +25,7 @@ class FallbackArrayBuilding {
* does not have a class manifest. Note that fallbackBuilder factory
* needs an implicit parameter (otherwise it would not be dominated in implicit search
* by Array.canBuildFrom). We make sure that that implicit search is always
- * successfull.
+ * successful.
*/
implicit def fallbackCanBuildFrom[T](implicit m: DummyImplicit): CanBuildFrom[Array[_], T, ArraySeq[T]] =
new CanBuildFrom[Array[_], T, ArraySeq[T]] {
@@ -372,7 +371,7 @@ object Array extends FallbackArrayBuilding {
def range(start: Int, end: Int, step: Int): Array[Int] = {
if (step == 0) throw new IllegalArgumentException("zero step")
val b = newBuilder[Int]
- b.sizeHint(Range.count(start, end, step, false))
+ b.sizeHint(immutable.Range.count(start, end, step, false))
var i = start
while (if (step < 0) end < i else i < end) {
diff --git a/src/library/scala/Option.scala b/src/library/scala/Option.scala
index c2b1764fdb..bab3a1c759 100644
--- a/src/library/scala/Option.scala
+++ b/src/library/scala/Option.scala
@@ -222,7 +222,7 @@ sealed abstract class Option[+A] extends Product with Serializable {
* if it is nonempty, or an empty iterator if the option is empty.
*/
def iterator: Iterator[A] =
- if (isEmpty) Iterator.empty else Iterator.single(this.get)
+ if (isEmpty) collection.Iterator.empty else collection.Iterator.single(this.get)
/** Returns a singleton list containing the $option's value
* if it is nonempty, or the empty list if the $option is empty.
diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala
index e03eab45a2..68fdee8411 100644
--- a/src/library/scala/Predef.scala
+++ b/src/library/scala/Predef.scala
@@ -57,6 +57,9 @@ object Predef extends LowPriorityImplicits {
def implicitly[T](implicit e: T) = e // for summoning implicit values from the nether world
@inline def locally[T](x: T): T = x // to communicate intent and avoid unmoored statements
+ // Apparently needed for the xml library
+ val $scope = scala.xml.TopScope
+
// Deprecated
@deprecated("Use sys.error(message) instead", "2.9.0")
@@ -312,7 +315,7 @@ object Predef extends LowPriorityImplicits {
implicit def stringCanBuildFrom: CanBuildFrom[String, Char, String] =
new CanBuildFrom[String, Char, String] {
def apply(from: String) = apply()
- def apply() = StringBuilder.newBuilder
+ def apply() = mutable.StringBuilder.newBuilder
}
implicit def seqToCharSequence(xs: collection.IndexedSeq[Char]): CharSequence = new CharSequence {
diff --git a/src/library/scala/annotation/switch.scala b/src/library/scala/annotation/switch.scala
index e4cb8c55a2..3734686b27 100644
--- a/src/library/scala/annotation/switch.scala
+++ b/src/library/scala/annotation/switch.scala
@@ -7,32 +7,23 @@
\* */
package scala.annotation
-/** <p>
- * An annotation to be applied to a match expression. If present,
- * the compiler will verify that the match has been compiled to a
- * <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc14.html"
- * target="_top"><code>tableswitch</code></a> or
- * <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc8.html#lookupswitch"
- * target="_top"><code>lookupswitch</code></a>, and issue an error if it
- * instead compiles into a series of conditional expressions.<br/>
- * Example:
- * </p>
- * <pre>
- * <b>def</b> fetchToken() {
- * (ch: @switch) <b>match</b> {
- * <b>case</b> ' ' | '\t' | CR | LF | FF <b>=&gt;</b>
- * nextChar()
- * fetchToken()
- * <b>case</b> 'A' &#47;*..'Z'*&#47; | '$' | '_' | 'a' &#47;*..'z'*&#47; <b>=&gt;</b>
- * putChar(ch)
- * nextChar()
- * getIdentRest()
- * <b>case</b> ',' <b>=&gt;</b>
- * nextChar(); token = COMMA
- * // more cases
- * }
- * }</pre>
+/** An annotation to be applied to a match expression. If present,
+ * the compiler will verify that the match has been compiled to a
+ * [[http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc14.html tableswitch]]
+ * or [[http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc8.html#lookupswitch lookupswitch]]
+ * and issue an error if it instead compiles into a series of conditional expressions.
+ * Example usage:
+{{{
+ val Constant = 'Q'
+ def tokenMe(ch: Char) = (ch: @switch) match {
+ case ' ' | '\t' | '\n' => 1
+ case 'A' | 'Z' | '$' => 2
+ case '5' | Constant => 3 // a non-literal may prevent switch generation: this would not compile
+ case _ => 4
+ }
+}}}
*
- * @since 2.8
+ * @author Paul Phillips
+ * @since 2.8
*/
final class switch extends annotation.StaticAnnotation
diff --git a/src/library/scala/collection/IterableViewLike.scala b/src/library/scala/collection/IterableViewLike.scala
index e0f1ada2b8..70f4519204 100644
--- a/src/library/scala/collection/IterableViewLike.scala
+++ b/src/library/scala/collection/IterableViewLike.scala
@@ -10,6 +10,7 @@ package scala.collection
import generic._
import TraversableView.NoBuilder
+import immutable.Stream
/** A template trait for non-strict views of iterable collections.
* $iterableViewInfo
diff --git a/src/library/scala/collection/Iterator.scala b/src/library/scala/collection/Iterator.scala
index 39c1d5b07f..f7f8e7a971 100644
--- a/src/library/scala/collection/Iterator.scala
+++ b/src/library/scala/collection/Iterator.scala
@@ -6,12 +6,11 @@
** |/ **
\* */
-
-
package scala.collection
import mutable.ArrayBuffer
import annotation.{ tailrec, migration }
+import immutable.Stream
/** The `Iterator` object provides various functions for
* creating specialized iterators.
diff --git a/src/library/scala/collection/JavaConversions.scala b/src/library/scala/collection/JavaConversions.scala
index fdb77a48c1..8b98f10875 100644
--- a/src/library/scala/collection/JavaConversions.scala
+++ b/src/library/scala/collection/JavaConversions.scala
@@ -504,7 +504,7 @@ object JavaConversions {
* Scala ConcurrentMap will be returned.
*
* @param m The ConcurrentMap to be converted.
- * @return A Scala mutable ConcurrrentMap view of the argument.
+ * @return A Scala mutable ConcurrentMap view of the argument.
*/
implicit def asScalaConcurrentMap[A, B](m: juc.ConcurrentMap[A, B]): mutable.ConcurrentMap[A, B] = m match {
case cmw: ConcurrentMapWrapper[a, b] => cmw.underlying
diff --git a/src/library/scala/collection/JavaConverters.scala b/src/library/scala/collection/JavaConverters.scala
index 4bb61b960a..0b55f54810 100755
--- a/src/library/scala/collection/JavaConverters.scala
+++ b/src/library/scala/collection/JavaConverters.scala
@@ -454,7 +454,7 @@ object JavaConverters {
* Scala <code>ConcurrentMap</code> will be returned.
*
* @param m The <code>ConcurrentMap</code> to be converted.
- * @return An object with an `asScala` method that returns a Scala mutable <code>ConcurrrentMap</code> view of the argument.
+ * @return An object with an `asScala` method that returns a Scala mutable <code>ConcurrentMap</code> view of the argument.
*/
implicit def asScalaConcurrentMapConverter[A, B](m: juc.ConcurrentMap[A, B]): AsScala[mutable.ConcurrentMap[A, B]] =
new AsScala(asScalaConcurrentMap(m))
diff --git a/src/library/scala/collection/SeqLike.scala b/src/library/scala/collection/SeqLike.scala
index 0411a2987e..37caf82027 100644
--- a/src/library/scala/collection/SeqLike.scala
+++ b/src/library/scala/collection/SeqLike.scala
@@ -6,15 +6,14 @@
** |/ **
\* */
-
-
package scala.collection
-import mutable.{ListBuffer, HashMap, ArraySeq}
-import immutable.{List, Range}
+import mutable.{ ListBuffer, ArraySeq }
+import immutable.{ List, Range }
import generic._
import parallel.ParSeq
import annotation.bridge
+import scala.math.Ordering
/** A template trait for sequences of type `Seq[A]`
* $seqInfo
diff --git a/src/library/scala/collection/SeqViewLike.scala b/src/library/scala/collection/SeqViewLike.scala
index 77dc15e695..37c66802ef 100644
--- a/src/library/scala/collection/SeqViewLike.scala
+++ b/src/library/scala/collection/SeqViewLike.scala
@@ -13,6 +13,7 @@ package scala.collection
import generic._
import Seq.fill
import TraversableView.NoBuilder
+import annotation.bridge
/** A template trait for non-strict views of sequences.
* $seqViewInfo
@@ -129,9 +130,13 @@ trait SeqViewLike[+A,
override def diff[B >: A](that: GenSeq[B]): This =
newForced(thisSeq diff that).asInstanceOf[This]
+ @bridge def diff[B >: A](that: Seq[B]): This = diff(that: GenSeq[B])
+
override def intersect[B >: A](that: GenSeq[B]): This =
newForced(thisSeq intersect that).asInstanceOf[This]
+ @bridge def intersect[B >: A](that: Seq[B]): This = intersect(that: GenSeq[B])
+
override def sorted[B >: A](implicit ord: Ordering[B]): This =
newForced(thisSeq sorted ord).asInstanceOf[This]
diff --git a/src/library/scala/collection/TraversableProxy.scala b/src/library/scala/collection/TraversableProxy.scala
index e965523ab2..215cf086d9 100644
--- a/src/library/scala/collection/TraversableProxy.scala
+++ b/src/library/scala/collection/TraversableProxy.scala
@@ -10,7 +10,7 @@
package scala.collection
-// Methods could be printed by cat TraverableLike.scala | egrep '^ (override )?def'
+// Methods could be printed by cat TraversableLike.scala | egrep '^ (override )?def'
/** This trait implements a proxy for traversable objects. It forwards
diff --git a/src/library/scala/collection/immutable/List.scala b/src/library/scala/collection/immutable/List.scala
index d8c8268a2e..ea0bc7523c 100644
--- a/src/library/scala/collection/immutable/List.scala
+++ b/src/library/scala/collection/immutable/List.scala
@@ -292,22 +292,6 @@ sealed abstract class List[+A] extends LinearSeq[A]
@deprecated("use `distinct' instead", "2.8.0")
def removeDuplicates: List[A] = distinct
- /** <p>
- * Sort the list according to the comparison function
- * `lt(e1: a, e2: a) =&gt; Boolean`,
- * which should be true iff `e1` precedes
- * `e2` in the desired ordering.
- * !!! todo: move sorting to IterableLike
- * </p>
- *
- * @param lt the comparison function
- * @return a list sorted according to the comparison function
- * `lt(e1: a, e2: a) =&gt; Boolean`.
- * @example <pre>
- * List("Steve", "Tom", "John", "Bob")
- * .sort((e1, e2) => (e1 compareTo e2) &lt; 0) =
- * List("Bob", "John", "Steve", "Tom")</pre>
- */
@deprecated("use `sortWith' instead", "2.8.0")
def sort(lt : (A,A) => Boolean): List[A] = {
/** Merge two already-sorted lists */
diff --git a/src/library/scala/collection/immutable/ListMap.scala b/src/library/scala/collection/immutable/ListMap.scala
index a0f20c6e96..edee4a9922 100644
--- a/src/library/scala/collection/immutable/ListMap.scala
+++ b/src/library/scala/collection/immutable/ListMap.scala
@@ -12,7 +12,7 @@ package scala.collection
package immutable
import generic._
-import annotation.tailrec
+import annotation.{tailrec, bridge}
/** $factoryInfo
* @since 1
@@ -100,6 +100,9 @@ class ListMap[A, +B] extends Map[A, B] with MapLike[A, B, ListMap[A, B]] with Se
override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): ListMap[A, B1] =
((repr: ListMap[A, B1]) /: xs.seq) (_ + _)
+ @bridge def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): ListMap[A, B1] =
+ ++(xs: GenTraversableOnce[(A, B1)])
+
/** This creates a new mapping without the given <code>key</code>.
* If the map does not contain a mapping for the given key, the
* method returns the same map.
diff --git a/src/library/scala/collection/immutable/ListSet.scala b/src/library/scala/collection/immutable/ListSet.scala
index 057b68d280..a298c629be 100644
--- a/src/library/scala/collection/immutable/ListSet.scala
+++ b/src/library/scala/collection/immutable/ListSet.scala
@@ -12,7 +12,7 @@ package scala.collection
package immutable
import generic._
-import annotation.tailrec
+import annotation.{tailrec, bridge}
import mutable.{ ListBuffer, Builder }
/** $factoryInfo
@@ -103,6 +103,8 @@ class ListSet[A] extends Set[A]
if (xs.isEmpty) this
else new ListSet.ListSetBuilder(this) ++= xs.seq result
+ @bridge def ++(xs: TraversableOnce[A]): ListSet[A] = ++(xs: GenTraversableOnce[A]): ListSet[A]
+
private[ListSet] def unchecked_+(e: A): ListSet[A] = new Node(e)
private[ListSet] def unchecked_outer: ListSet[A] =
throw new NoSuchElementException("Empty ListSet has no outer pointer")
diff --git a/src/library/scala/collection/immutable/MapLike.scala b/src/library/scala/collection/immutable/MapLike.scala
index d22adc03bc..fb2826b4df 100644
--- a/src/library/scala/collection/immutable/MapLike.scala
+++ b/src/library/scala/collection/immutable/MapLike.scala
@@ -11,6 +11,7 @@ package immutable
import generic._
import parallel.immutable.ParMap
+import annotation.bridge
/**
* A generic template for immutable maps from keys of type `A`
@@ -85,6 +86,8 @@ trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): immutable.Map[A, B1] =
((repr: immutable.Map[A, B1]) /: xs.seq) (_ + _)
+ @bridge def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): immutable.Map[A, B1] = ++(xs: GenTraversableOnce[(A, B1)])
+
/** Filters this map by retaining only keys satisfying a predicate.
* @param p the predicate used to test keys
* @return an immutable map consisting only of those key value pairs of this map where the key satisfies
diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala
index 2b1e4bff13..ef0f08bcfb 100644
--- a/src/library/scala/collection/immutable/Range.scala
+++ b/src/library/scala/collection/immutable/Range.scala
@@ -287,7 +287,7 @@ object Range {
// imprecision or surprises might result from anything, although this may
// not yet be fully implemented.
object BigDecimal {
- implicit val bigDecAsIntegral = scala.Numeric.BigDecimalAsIfIntegral
+ implicit val bigDecAsIntegral = scala.math.Numeric.BigDecimalAsIfIntegral
def apply(start: BigDecimal, end: BigDecimal, step: BigDecimal) =
NumericRange(start, end, step)
@@ -302,9 +302,9 @@ object Range {
// is necessary to keep 0.3d at 0.3 as opposed to
// 0.299999999999999988897769753748434595763683319091796875 or so.
object Double {
- implicit val bigDecAsIntegral = scala.Numeric.BigDecimalAsIfIntegral
- implicit val doubleAsIntegral = scala.Numeric.DoubleAsIfIntegral
- def toBD(x: Double): BigDecimal = scala.BigDecimal valueOf x
+ implicit val bigDecAsIntegral = scala.math.Numeric.BigDecimalAsIfIntegral
+ implicit val doubleAsIntegral = scala.math.Numeric.DoubleAsIfIntegral
+ def toBD(x: Double): BigDecimal = scala.math.BigDecimal valueOf x
def apply(start: Double, end: Double, step: Double) =
BigDecimal(toBD(start), toBD(end), toBD(step)) mapRange (_.doubleValue)
@@ -328,7 +328,7 @@ object Range {
def inclusive(start: Int, end: Int, step: Int) = NumericRange.inclusive(start, end, step)
}
- @deprecated("use Range instead")
+ @deprecated("use Range instead", "2.9.0")
trait ByOne extends Range {
@bridge override def foreach[@specialized(Unit) U](f: Int => U) =
super.foreach(f)
diff --git a/src/library/scala/collection/immutable/SortedMap.scala b/src/library/scala/collection/immutable/SortedMap.scala
index 64fa06bf2e..f7e05fef69 100644
--- a/src/library/scala/collection/immutable/SortedMap.scala
+++ b/src/library/scala/collection/immutable/SortedMap.scala
@@ -14,6 +14,7 @@ package immutable
import generic._
import mutable.Builder
import annotation.unchecked.uncheckedVariance
+import annotation.bridge
/** A map whose keys are sorted.
*
@@ -63,6 +64,8 @@ trait SortedMap[A, +B] extends Map[A, B]
*/
override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): SortedMap[A, B1] =
((repr: SortedMap[A, B1]) /: xs.seq) (_ + _)
+
+ @bridge def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): SortedMap[A, B1] = ++(xs: GenTraversableOnce[(A, B1)])
}
/** $factoryInfo
diff --git a/src/library/scala/collection/immutable/TreeMap.scala b/src/library/scala/collection/immutable/TreeMap.scala
index 7552e1983c..a46583c541 100644
--- a/src/library/scala/collection/immutable/TreeMap.scala
+++ b/src/library/scala/collection/immutable/TreeMap.scala
@@ -13,6 +13,7 @@ package immutable
import generic._
import mutable.Builder
+import annotation.bridge
/** $factoryInfo
* @define Coll immutable.TreeMap
@@ -110,9 +111,11 @@ class TreeMap[A, +B](override val size: Int, t: RedBlack[A]#Tree[B])(implicit va
*
* @param xs the traversable object.
*/
- override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): TreeMap[A, B1] =
+ override def ++[B1 >: B] (xs: GenTraversableOnce[(A, B1)]): TreeMap[A, B1] =
((repr: TreeMap[A, B1]) /: xs.seq) (_ + _)
+ @bridge def ++[B1 >: B] (xs: TraversableOnce[(A, B1)]): TreeMap[A, B1] = ++(xs: GenTraversableOnce[(A, B1)])
+
/** A new TreeMap with the entry added is returned,
* assuming that key is <em>not</em> in the TreeMap.
*
diff --git a/src/library/scala/collection/immutable/TrieIterator.scala b/src/library/scala/collection/immutable/TrieIterator.scala
index 088b280b8a..c2cd0b2efd 100644
--- a/src/library/scala/collection/immutable/TrieIterator.scala
+++ b/src/library/scala/collection/immutable/TrieIterator.scala
@@ -37,8 +37,8 @@ private[collection] abstract class TrieIterator[+T](elems: Array[Iterable[T]]) e
private[this] var subIter = initSubIter
private[this] def getElems(x: Iterable[T]): Array[Iterable[T]] = (x match {
- case x: HashTrieMap[a, b] => x.elems
- case x: HashTrieSet[T] => x.elems
+ case x: HashTrieMap[_, _] => x.elems
+ case x: HashTrieSet[_] => x.elems
}).asInstanceOf[Array[Iterable[T]]]
private[this] def collisionToArray(x: Iterable[T]): Array[Iterable[T]] = (x match {
diff --git a/src/library/scala/collection/immutable/Vector.scala b/src/library/scala/collection/immutable/Vector.scala
index 7a4a9bb18a..ab44585902 100644
--- a/src/library/scala/collection/immutable/Vector.scala
+++ b/src/library/scala/collection/immutable/Vector.scala
@@ -704,7 +704,7 @@ final class VectorBuilder[A]() extends Builder[A,Vector[A]] with VectorPointer[A
s
}
- def clear: Unit = {
+ def clear(): Unit = {
display0 = new Array[AnyRef](32)
depth = 1
blockIndex = 0
diff --git a/src/library/scala/collection/mutable/ArrayStack.scala b/src/library/scala/collection/mutable/ArrayStack.scala
index 2323830b7b..012105d7c4 100644
--- a/src/library/scala/collection/mutable/ArrayStack.scala
+++ b/src/library/scala/collection/mutable/ArrayStack.scala
@@ -143,7 +143,7 @@ extends Seq[T]
def dup() = push(top)
/** Empties the stack. */
- def clear {
+ def clear() {
index = 0
table = new Array(1)
}
diff --git a/src/library/scala/collection/mutable/BufferLike.scala b/src/library/scala/collection/mutable/BufferLike.scala
index c48dd5d621..9cab3bd656 100644
--- a/src/library/scala/collection/mutable/BufferLike.scala
+++ b/src/library/scala/collection/mutable/BufferLike.scala
@@ -312,4 +312,6 @@ trait BufferLike[A, +This <: BufferLike[A, This] with Buffer[A]]
"Use --= instead if you intend to remove by side effect from an existing collection.\n"
)
override def --(xs: GenTraversableOnce[A]): This = clone() --= xs.seq
+
+ @bridge def --(xs: TraversableOnce[A]): This = --(xs: GenTraversableOnce[A])
}
diff --git a/src/library/scala/collection/mutable/FlatHashTable.scala b/src/library/scala/collection/mutable/FlatHashTable.scala
index d78c466f69..f2e42f2ca1 100644
--- a/src/library/scala/collection/mutable/FlatHashTable.scala
+++ b/src/library/scala/collection/mutable/FlatHashTable.scala
@@ -241,7 +241,7 @@ trait FlatHashTable[A] extends FlatHashTable.HashUtils[A] {
}
// discards the previous sizemap and populates the new one
- protected def sizeMapInitAndRebuild {
+ protected def sizeMapInitAndRebuild() {
// first allocate
sizeMapInit(table.length)
@@ -263,7 +263,7 @@ trait FlatHashTable[A] extends FlatHashTable.HashUtils[A] {
}
}
- private[collection] def printSizeMap {
+ private[collection] def printSizeMap() {
println(sizemap.toList)
}
diff --git a/src/library/scala/collection/mutable/HashTable.scala b/src/library/scala/collection/mutable/HashTable.scala
index dea1ec7d44..0f6fde0260 100644
--- a/src/library/scala/collection/mutable/HashTable.scala
+++ b/src/library/scala/collection/mutable/HashTable.scala
@@ -265,7 +265,7 @@ trait HashTable[A, Entry >: Null <: HashEntry[A, Entry]] extends HashTable.HashU
}
// discards the previous sizemap and populates the new one
- protected def sizeMapInitAndRebuild {
+ protected def sizeMapInitAndRebuild() {
sizeMapInit(table.length)
// go through the buckets, count elements
@@ -291,7 +291,7 @@ trait HashTable[A, Entry >: Null <: HashEntry[A, Entry]] extends HashTable.HashU
}
}
- private[collection] def printSizeMap {
+ private[collection] def printSizeMap() {
println(sizemap.toList)
}
diff --git a/src/library/scala/collection/mutable/MapLike.scala b/src/library/scala/collection/mutable/MapLike.scala
index e737bf5509..92c6e8c162 100644
--- a/src/library/scala/collection/mutable/MapLike.scala
+++ b/src/library/scala/collection/mutable/MapLike.scala
@@ -11,7 +11,7 @@ package scala.collection
package mutable
import generic._
-import annotation.migration
+import annotation.{migration, bridge}
import parallel.mutable.ParMap
/** A template trait for mutable maps.
@@ -128,6 +128,8 @@ trait MapLike[A, B, +This <: MapLike[A, B, This] with Map[A, B]]
override def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): Map[A, B1] =
clone().asInstanceOf[Map[A, B1]] ++= xs.seq
+ @bridge def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): Map[A, B1] = ++(xs: GenTraversableOnce[(A, B1)])
+
/** Removes a key from this map, returning the value associated previously
* with that key as an option.
* @param key the key to be removed
@@ -247,4 +249,6 @@ trait MapLike[A, B, +This <: MapLike[A, B, This] with Map[A, B]]
"side effect to an existing map and return that map itself, use --=."
)
override def --(xs: GenTraversableOnce[A]): This = clone() --= xs.seq
+
+ @bridge def --(xs: TraversableOnce[A]): This = --(xs: GenTraversableOnce[A])
}
diff --git a/src/library/scala/collection/mutable/ObservableBuffer.scala b/src/library/scala/collection/mutable/ObservableBuffer.scala
index aa9bd7ac95..c38bf5fbf3 100644
--- a/src/library/scala/collection/mutable/ObservableBuffer.scala
+++ b/src/library/scala/collection/mutable/ObservableBuffer.scala
@@ -46,7 +46,7 @@ trait ObservableBuffer[A] extends Buffer[A] with Publisher[Message[A] with Undoa
val oldelement = apply(n)
super.update(n, newelement)
publish(new Update(Index(n), newelement) with Undoable {
- def undo { update(n, oldelement) }
+ def undo() { update(n, oldelement) }
})
}
@@ -54,7 +54,7 @@ trait ObservableBuffer[A] extends Buffer[A] with Publisher[Message[A] with Undoa
val oldelement = apply(n)
super.remove(n)
publish(new Remove(Index(n), oldelement) with Undoable {
- def undo { insert(n, oldelement) }
+ def undo() { insert(n, oldelement) }
})
oldelement
}
@@ -62,7 +62,7 @@ trait ObservableBuffer[A] extends Buffer[A] with Publisher[Message[A] with Undoa
abstract override def clear(): Unit = {
super.clear
publish(new Reset with Undoable {
- def undo { throw new UnsupportedOperationException("cannot undo") }
+ def undo() { throw new UnsupportedOperationException("cannot undo") }
})
}
}
diff --git a/src/library/scala/collection/mutable/ObservableMap.scala b/src/library/scala/collection/mutable/ObservableMap.scala
index 00087f8f61..ceb23d25c3 100644
--- a/src/library/scala/collection/mutable/ObservableMap.scala
+++ b/src/library/scala/collection/mutable/ObservableMap.scala
@@ -62,7 +62,7 @@ trait ObservableMap[A, B] extends Map[A, B] with Publisher[Message[(A, B)] with
abstract override def clear(): Unit = {
super.clear
publish(new Reset with Undoable {
- def undo: Unit = throw new UnsupportedOperationException("cannot undo")
+ def undo(): Unit = throw new UnsupportedOperationException("cannot undo")
})
}
}
diff --git a/src/library/scala/collection/mutable/ObservableSet.scala b/src/library/scala/collection/mutable/ObservableSet.scala
index 6bb1e45cec..1b375802a5 100644
--- a/src/library/scala/collection/mutable/ObservableSet.scala
+++ b/src/library/scala/collection/mutable/ObservableSet.scala
@@ -46,7 +46,7 @@ trait ObservableSet[A] extends Set[A] with Publisher[Message[A] with Undoable]
abstract override def clear(): Unit = {
super.clear
publish(new Reset with Undoable {
- def undo: Unit = throw new UnsupportedOperationException("cannot undo")
+ def undo(): Unit = throw new UnsupportedOperationException("cannot undo")
})
}
}
diff --git a/src/library/scala/collection/mutable/OpenHashMap.scala b/src/library/scala/collection/mutable/OpenHashMap.scala
index f558f68159..72e729f370 100644
--- a/src/library/scala/collection/mutable/OpenHashMap.scala
+++ b/src/library/scala/collection/mutable/OpenHashMap.scala
@@ -80,7 +80,7 @@ extends Map[Key, Value]
h ^ (h >>> 7) ^ (h >>> 4);
}
- private[this] def growTable = {
+ private[this] def growTable() = {
val oldSize = mask + 1;
val newSize = 4 * oldSize;
val oldTable = table;
@@ -179,7 +179,7 @@ extends Map[Key, Value]
var index = 0;
val initialModCount = modCount;
- private[this] def advance {
+ private[this] def advance() {
if (initialModCount != modCount) sys.error("Concurrent modification");
while((index <= mask) && (table(index) == null || table(index).value == None)) index+=1;
}
diff --git a/src/library/scala/collection/mutable/PriorityQueue.scala b/src/library/scala/collection/mutable/PriorityQueue.scala
index 2c03f329a7..31113797dd 100644
--- a/src/library/scala/collection/mutable/PriorityQueue.scala
+++ b/src/library/scala/collection/mutable/PriorityQueue.scala
@@ -253,7 +253,7 @@ class PriorityQueue[A](implicit val ord: Ordering[A])
*/
override def clone(): PriorityQueue[A] = new PriorityQueue[A] ++= this.iterator
- // def printstate {
+ // def printstate() {
// println("-----------------------")
// println("Size: " + resarr.p_size0)
// println("Internal array: " + resarr.p_array.toList)
diff --git a/src/library/scala/collection/mutable/RevertibleHistory.scala b/src/library/scala/collection/mutable/RevertibleHistory.scala
index 2c51f70b8b..922824ddf0 100644
--- a/src/library/scala/collection/mutable/RevertibleHistory.scala
+++ b/src/library/scala/collection/mutable/RevertibleHistory.scala
@@ -28,7 +28,7 @@ class RevertibleHistory[Evt <: Undoable, Pub] extends History[Evt, Pub] with Und
/** Rollback the full history.
*/
- def undo: Unit = {
+ def undo(): Unit = {
val old = log.toList.reverse
clear
old.foreach { case (sub, event) => event.undo }
diff --git a/src/library/scala/collection/mutable/SetLike.scala b/src/library/scala/collection/mutable/SetLike.scala
index 855ba74f8c..c3bc106153 100644
--- a/src/library/scala/collection/mutable/SetLike.scala
+++ b/src/library/scala/collection/mutable/SetLike.scala
@@ -13,7 +13,7 @@ package mutable
import generic._
import script._
-import scala.annotation.migration
+import annotation.{migration, bridge}
import parallel.mutable.ParSet
/** A template trait for mutable sets of type `mutable.Set[A]`.
@@ -173,7 +173,7 @@ trait SetLike[A, +This <: SetLike[A, This] with Set[A]]
* $addDuplicates
*
* @param xs the traversable object.
- * @return a new set cconsisting of elements of this set and those in `xs`.
+ * @return a new set consisting of elements of this set and those in `xs`.
*/
@migration(2, 8,
"As of 2.8, this operation creates a new set. To add the elements as a\n"+
@@ -181,6 +181,8 @@ trait SetLike[A, +This <: SetLike[A, This] with Set[A]]
)
override def ++(xs: GenTraversableOnce[A]): This = clone() ++= xs.seq
+ @bridge def ++(xs: TraversableOnce[A]): This = ++(xs: GenTraversableOnce[A])
+
/** Creates a new set consisting of all the elements of this set except `elem`.
*
* @param elem the element to remove.
@@ -221,6 +223,8 @@ trait SetLike[A, +This <: SetLike[A, This] with Set[A]]
)
override def --(xs: GenTraversableOnce[A]): This = clone() --= xs.seq
+ @bridge def --(xs: TraversableOnce[A]): This = --(xs: GenTraversableOnce[A])
+
/** Send a message to this scriptable object.
*
* @param cmd the message to send.
diff --git a/src/library/scala/collection/mutable/UnrolledBuffer.scala b/src/library/scala/collection/mutable/UnrolledBuffer.scala
index 0933aeaf69..9e0b313c4b 100644
--- a/src/library/scala/collection/mutable/UnrolledBuffer.scala
+++ b/src/library/scala/collection/mutable/UnrolledBuffer.scala
@@ -1,5 +1,6 @@
package scala.collection.mutable
+import collection.Iterator
import collection.generic._
import annotation.tailrec
diff --git a/src/library/scala/collection/package.scala b/src/library/scala/collection/package.scala
index f951f22057..f0a0c40bcd 100644
--- a/src/library/scala/collection/package.scala
+++ b/src/library/scala/collection/package.scala
@@ -5,7 +5,7 @@ package scala
*
* == Guide ==
*
- * A detailed guide for the collections library is avaialble
+ * A detailed guide for the collections library is available
* at [[http://www.scala-lang.org/docu/files/collections-api]].
*
* == Using Collections ==
diff --git a/src/library/scala/collection/parallel/ParIterableLike.scala b/src/library/scala/collection/parallel/ParIterableLike.scala
index b32ea108f4..7c176eeee4 100644
--- a/src/library/scala/collection/parallel/ParIterableLike.scala
+++ b/src/library/scala/collection/parallel/ParIterableLike.scala
@@ -842,11 +842,11 @@ self: ParIterableLike[T, Repr, Sequential] =>
extends NonDivisibleTask[R, Composite[FR, SR, R, First, Second]] {
def combineResults(fr: FR, sr: SR): R
@volatile var result: R = null.asInstanceOf[R]
- private[parallel] override def signalAbort {
+ private[parallel] override def signalAbort() {
ft.signalAbort
st.signalAbort
}
- protected def mergeSubtasks {
+ protected def mergeSubtasks() {
ft mergeThrowables st
if (throwable eq null) result = combineResults(ft.result, st.result)
}
@@ -883,7 +883,7 @@ self: ParIterableLike[T, Repr, Sequential] =>
def leaf(prevr: Option[R1]) = {
result = map(executeAndWaitResult(inner))
}
- private[parallel] override def signalAbort {
+ private[parallel] override def signalAbort() {
inner.signalAbort
}
override def requiresStrictSplitters = inner.requiresStrictSplitters
@@ -1395,7 +1395,7 @@ self: ParIterableLike[T, Repr, Sequential] =>
}
import collection.DebugUtils._
- private[parallel] def printDebugBuffer = println(buildString {
+ private[parallel] def printDebugBuffer() = println(buildString {
append =>
for (s <- debugBuffer) {
append(s)
diff --git a/src/library/scala/collection/parallel/ParIterableView.scala b/src/library/scala/collection/parallel/ParIterableView.scala
index 50f0e4f869..2b4f24126b 100644
--- a/src/library/scala/collection/parallel/ParIterableView.scala
+++ b/src/library/scala/collection/parallel/ParIterableView.scala
@@ -6,20 +6,11 @@
** |/ **
\* */
-
package scala.collection.parallel
-
-
-
-import scala.collection.Parallel
-import scala.collection.IterableView
-import scala.collection.GenIterableView
+import scala.collection.{ Parallel, IterableView, GenIterableView, Iterator }
import scala.collection.generic.CanCombineFrom
-
-
-
/** A template view of a non-strict view of a parallel iterable collection.
*
* @tparam T the type of elements
@@ -33,8 +24,6 @@ extends ParIterableViewLike[T, Coll, CollSeq, ParIterableView[T, Coll, CollSeq],
with GenIterableView[T, Coll]
-
-
object ParIterableView {
abstract class NoCombiner[T] extends Combiner[T, Nothing] {
// self: EnvironmentPassingCombiner[T, Nothing] =>
@@ -55,14 +44,3 @@ object ParIterableView {
def apply() = new NoCombiner[T] {} // was: with EnvironmentPassingCombiner[T, Nothing]
}
}
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/library/scala/collection/parallel/ParSeqLike.scala b/src/library/scala/collection/parallel/ParSeqLike.scala
index c9e6b45bd6..1d4d8a13ad 100644
--- a/src/library/scala/collection/parallel/ParSeqLike.scala
+++ b/src/library/scala/collection/parallel/ParSeqLike.scala
@@ -8,12 +8,7 @@
package scala.collection.parallel
-
-import scala.collection.Parallel
-import scala.collection.SeqLike
-import scala.collection.GenSeqLike
-import scala.collection.GenSeq
-import scala.collection.GenIterable
+import scala.collection.{ Parallel, SeqLike, GenSeqLike, GenSeq, GenIterable, Iterator }
import scala.collection.generic.DefaultSignalling
import scala.collection.generic.AtomicIndexFlag
import scala.collection.generic.CanBuildFrom
@@ -500,41 +495,4 @@ self =>
override def merge(that: Corresponds[S]) = result = result && that.result
override def requiresStrictSplitters = true
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/library/scala/collection/parallel/ParSeqView.scala b/src/library/scala/collection/parallel/ParSeqView.scala
index 8461390839..a08b9a4acb 100644
--- a/src/library/scala/collection/parallel/ParSeqView.scala
+++ b/src/library/scala/collection/parallel/ParSeqView.scala
@@ -9,18 +9,9 @@
package scala.collection.parallel
-
-
-
-import scala.collection.TraversableView
-import scala.collection.SeqView
-import scala.collection.Parallel
+import scala.collection.{ TraversableView, SeqView, Parallel, Iterator }
import scala.collection.generic.CanCombineFrom
-
-
-
-
/** A template view of a non-strict view of a parallel sequence.
*
* @tparam T the type of elements in this parallel sequence
@@ -33,7 +24,6 @@ trait ParSeqView[+T, +Coll <: Parallel, +CollSeq]
extends ParSeqViewLike[T, Coll, CollSeq, ParSeqView[T, Coll, CollSeq], SeqView[T, CollSeq]]
-
object ParSeqView {
abstract class NoCombiner[T] extends Combiner[T, Nothing] {
// self: EnvironmentPassingCombiner[T, Nothing] =>
@@ -54,21 +44,3 @@ object ParSeqView {
def apply() = new NoCombiner[T] {} // was: with EnvironmentPassingCombiner[T, Nothing]
}
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/library/scala/collection/parallel/ParSeqViewLike.scala b/src/library/scala/collection/parallel/ParSeqViewLike.scala
index b7ad227f11..0da6f413d9 100644
--- a/src/library/scala/collection/parallel/ParSeqViewLike.scala
+++ b/src/library/scala/collection/parallel/ParSeqViewLike.scala
@@ -8,17 +8,13 @@
package scala.collection.parallel
-import scala.collection.Parallel
-import scala.collection.{ SeqView, SeqViewLike }
-import scala.collection.{ GenSeqView, GenSeqViewLike }
-import scala.collection.GenSeq
-import scala.collection.GenIterable
-import scala.collection.GenTraversable
-import scala.collection.GenTraversableOnce
+import scala.collection.{ Parallel, SeqView, SeqViewLike, GenSeqView, GenSeqViewLike, GenSeq }
+import scala.collection.{ GenIterable, GenTraversable, GenTraversableOnce, Iterator }
import scala.collection.generic.{ CanBuildFrom, SliceInterval }
import scala.collection.generic.CanCombineFrom
import scala.collection.parallel.immutable.ParRange
+
/** A template view of a non-strict view of parallel sequence.
*
* @tparam T the type of the elements in this view
@@ -183,25 +179,4 @@ self =>
protected[this] def newSubtask(p: SuperParIterator) = new Force(cbf, down(p))
override def merge(that: Force[U, That]) = result = result combine that.result
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/library/scala/collection/parallel/Splitter.scala b/src/library/scala/collection/parallel/Splitter.scala
index 568a7c8e0d..ee10ea77c7 100644
--- a/src/library/scala/collection/parallel/Splitter.scala
+++ b/src/library/scala/collection/parallel/Splitter.scala
@@ -8,9 +8,7 @@
package scala.collection.parallel
-
-import scala.collection.Seq
-
+import scala.collection.{ Seq, Iterator }
/** A splitter (or a split iterator) can be split into more splitters that traverse over
* disjoint subsets of elements.
@@ -49,10 +47,8 @@ trait Splitter[+T] extends Iterator[T] {
* The rationale behind this is best given by the following example:
* try splitting an iterator over a linear hash table.
*/
-
}
-
object Splitter {
def empty[T]: Splitter[T] = new Splitter[T] {
def hasNext = false
@@ -60,5 +56,3 @@ object Splitter {
def split = Seq(this)
}
}
-
-
diff --git a/src/library/scala/collection/parallel/Tasks.scala b/src/library/scala/collection/parallel/Tasks.scala
index 497e0c638a..873291fb2d 100644
--- a/src/library/scala/collection/parallel/Tasks.scala
+++ b/src/library/scala/collection/parallel/Tasks.scala
@@ -57,7 +57,7 @@ trait Tasks {
// exception handling mechanism
@volatile var throwable: Throwable = null
- def forwardThrowable = if (throwable != null) throw throwable
+ def forwardThrowable() = if (throwable != null) throw throwable
// tries to do the leaf computation, storing the possible exception
private[parallel] def tryLeaf(lastres: Option[R]) {
@@ -101,7 +101,7 @@ trait Tasks {
}
// override in concrete task implementations to signal abort to other tasks
- private[parallel] def signalAbort {}
+ private[parallel] def signalAbort() {}
}
trait TaskImpl[R, +Tp] {
@@ -110,11 +110,11 @@ trait Tasks {
def split: Seq[TaskImpl[R, Tp]]
/** Code that gets called after the task gets started - it may spawn other tasks instead of calling `leaf`. */
- def compute
+ def compute()
/** Start task. */
- def start
+ def start()
/** Wait for task to finish. */
- def sync
+ def sync()
/** Try to cancel the task.
* @return `true` if cancellation is successful.
*/
@@ -126,7 +126,7 @@ trait Tasks {
*
* This method may be overridden.
*/
- def release {}
+ def release() {}
}
protected def newTaskImpl[R, Tp](b: Task[R, Tp]): TaskImpl[R, Tp]
@@ -161,9 +161,9 @@ trait AdaptiveWorkStealingTasks extends Tasks {
def split: Seq[TaskImpl[R, Tp]]
- def compute = if (body.shouldSplitFurther) internal else body.tryLeaf(None)
+ def compute() = if (body.shouldSplitFurther) internal else body.tryLeaf(None)
- def internal = {
+ def internal() = {
var last = spawnSubtasks()
last.body.tryLeaf(None)
@@ -231,7 +231,7 @@ trait ThreadPoolTasks extends Tasks {
@volatile var owned = false
@volatile var completed = false
- def start = synchronized {
+ def start() = synchronized {
// debuglog("Starting " + body)
// utb: future = executor.submit(this)
executor.synchronized {
@@ -239,7 +239,7 @@ trait ThreadPoolTasks extends Tasks {
executor.submit(this)
}
}
- def sync = synchronized {
+ def sync() = synchronized {
// debuglog("Syncing on " + body)
// utb: future.get()
executor.synchronized {
@@ -293,11 +293,11 @@ trait ThreadPoolTasks extends Tasks {
def queue = executor.getQueue.asInstanceOf[LinkedBlockingQueue[Runnable]]
@volatile var totaltasks = 0
- private def incrTasks = synchronized {
+ private def incrTasks() = synchronized {
totaltasks += 1
}
- private def decrTasks = synchronized {
+ private def decrTasks() = synchronized {
totaltasks -= 1
}
@@ -361,12 +361,12 @@ trait FutureThreadPoolTasks extends Tasks {
trait TaskImpl[R, +Tp] extends Runnable with super.TaskImpl[R, Tp] {
@volatile var future: Future[_] = null
- def start = {
+ def start() = {
executor.synchronized {
future = executor.submit(this)
}
}
- def sync = future.get
+ def sync() = future.get
def tryCancel = false
def run = {
compute
@@ -435,8 +435,8 @@ trait HavingForkJoinPool {
trait ForkJoinTasks extends Tasks with HavingForkJoinPool {
trait TaskImpl[R, +Tp] extends RecursiveAction with super.TaskImpl[R, Tp] {
- def start = fork
- def sync = join
+ def start() = fork
+ def sync() = join
def tryCancel = tryUnfork
}
diff --git a/src/library/scala/collection/parallel/immutable/ParHashMap.scala b/src/library/scala/collection/parallel/immutable/ParHashMap.scala
index b9b7cbd69d..85084a945f 100644
--- a/src/library/scala/collection/parallel/immutable/ParHashMap.scala
+++ b/src/library/scala/collection/parallel/immutable/ParHashMap.scala
@@ -115,7 +115,7 @@ self =>
override def toString = "HashTrieIterator(" + sz + ")"
}
- private[parallel] def printDebugInfo {
+ private[parallel] def printDebugInfo() {
println("Parallel hash trie")
println("Top level inner trie type: " + trie.getClass)
trie match {
diff --git a/src/library/scala/collection/parallel/immutable/ParRange.scala b/src/library/scala/collection/parallel/immutable/ParRange.scala
index 198274f4e2..2a10458457 100644
--- a/src/library/scala/collection/parallel/immutable/ParRange.scala
+++ b/src/library/scala/collection/parallel/immutable/ParRange.scala
@@ -6,17 +6,13 @@
** |/ **
\* */
-
package scala.collection.parallel.immutable
-
-
import scala.collection.immutable.Range
import scala.collection.parallel.Combiner
import scala.collection.generic.CanCombineFrom
import scala.collection.parallel.IterableSplitter
-
-
+import scala.collection.Iterator
/** Parallel ranges.
*
@@ -111,18 +107,11 @@ self =>
cb
}
}
-
}
-
object ParRange {
def apply(start: Int, end: Int, step: Int, inclusive: Boolean) = new ParRange(
if (inclusive) new Range.Inclusive(start, end, step)
else new Range(start, end, step)
)
}
-
-
-
-
-
diff --git a/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala b/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala
index a4dc9b4a14..dc583fb4e7 100644
--- a/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala
+++ b/src/library/scala/collection/parallel/mutable/UnrolledParArrayCombiner.scala
@@ -56,7 +56,7 @@ extends Combiner[T, ParArray[T]] {
new ParArray(arrayseq)
}
- def clear {
+ def clear() {
buff.clear
}
diff --git a/src/library/scala/compat/Platform.scala b/src/library/scala/compat/Platform.scala
index b1c6c69145..8ee356e95f 100644
--- a/src/library/scala/compat/Platform.scala
+++ b/src/library/scala/compat/Platform.scala
@@ -67,7 +67,7 @@ object Platform {
def currentTime: Long = System.currentTimeMillis()
@inline
- def collectGarbage: Unit = System.gc()
+ def collectGarbage(): Unit = System.gc()
/** The name of the default character set encoding as a string */
@inline
diff --git a/src/library/scala/concurrent/Lock.scala b/src/library/scala/concurrent/Lock.scala
index 5494ff8c68..08c9f6cd63 100644
--- a/src/library/scala/concurrent/Lock.scala
+++ b/src/library/scala/concurrent/Lock.scala
@@ -18,12 +18,12 @@ package scala.concurrent
class Lock {
var available = true
- def acquire = synchronized {
+ def acquire() = synchronized {
while (!available) wait()
available = false
}
- def release = synchronized {
+ def release() = synchronized {
available = true
notify()
}
diff --git a/src/library/scala/concurrent/pilib.scala b/src/library/scala/concurrent/pilib.scala
index cad8aecf86..7a3758b9c6 100644
--- a/src/library/scala/concurrent/pilib.scala
+++ b/src/library/scala/concurrent/pilib.scala
@@ -43,13 +43,13 @@ object pilib {
abstract class Spawn {
def <(p: => Unit): Spawn
def |(p: => Unit): Spawn
- def > : Unit
+ def > (): Unit
}
val spawn = new Spawn {
//object spawn extends Spawn { // BUG !
def <(p: => Unit): Spawn = { scala.concurrent.ops.spawn(p); this }
def |(p: => Unit): Spawn = { scala.concurrent.ops.spawn(p); this }
- def > : Unit = ()
+ def > (): Unit = ()
}
/////////////////////////// GUARDED PROCESSES //////////////////////////
diff --git a/src/library/scala/deprecated.scala b/src/library/scala/deprecated.scala
index f64e34a5ac..53f5c456c2 100644
--- a/src/library/scala/deprecated.scala
+++ b/src/library/scala/deprecated.scala
@@ -10,11 +10,12 @@ package scala
import annotation.target._
-/**
- * An annotation that designates the definition to which it is applied as deprecated.
- * Access to the member then generates a deprecated warning.
+/** An annotation that designates that a definition is deprecated.
+ * Access to the member then generates a deprecated warning.
*
- * @since 2.3
+ * @param message the message to print during compilation if the definition is accessed
+ * @param since a string identifying the first version in which the definition was deprecated
+ * @since 2.3
*/
@getter @setter @beanGetter @beanSetter
class deprecated(message: String = "", since: String = "") extends annotation.StaticAnnotation
diff --git a/src/library/scala/io/BufferedSource.scala b/src/library/scala/io/BufferedSource.scala
index 5df52d45e3..fafb57da55 100644
--- a/src/library/scala/io/BufferedSource.scala
+++ b/src/library/scala/io/BufferedSource.scala
@@ -10,6 +10,7 @@ package scala.io
import java.io.{ InputStream, BufferedReader, InputStreamReader }
import Source.DefaultBufSize
+import scala.collection.Iterator
/** This object provides convenience methods to create an iterable
* representation of a source file.
diff --git a/src/library/scala/io/Position.scala b/src/library/scala/io/Position.scala
index 5b6accfea3..917d61ec25 100644
--- a/src/library/scala/io/Position.scala
+++ b/src/library/scala/io/Position.scala
@@ -51,7 +51,7 @@ abstract class Position {
if (line >= LINE_MASK)
LINE_MASK << COLUMN_BITS
else
- (line << COLUMN_BITS) | math.min(LINE_MASK, line)
+ (line << COLUMN_BITS) | math.min(COLUMN_MASK, column)
}
/** Returns the line number of the encoded position. */
diff --git a/src/library/scala/math/Ordered.scala b/src/library/scala/math/Ordered.scala
index 5a07451f4a..64cbd5e8f2 100644
--- a/src/library/scala/math/Ordered.scala
+++ b/src/library/scala/math/Ordered.scala
@@ -20,14 +20,14 @@ package scala.math
* there is no reasonable way to provide a default implementation
* of equality for instances of Ordered[A]. Therefore, if you need
* to be able to use equality on an instance of Ordered[A] you must
- * provide it yourself either when inheiriting or instantiating.
+ * provide it yourself either when inheriting or instantiating.
*
* It is important that the hashCode method for an instance of
* Ordered[A] be consistent with the compare method. However,
* it is not possible to provide a sensible default implementation.
* Therefore, if you need to be able compute the hash of an
* instance of Ordered[A] you must provide it yourself either when
- * inheiriting or instantiating.
+ * inheriting or instantiating.
*
* @author Martin Odersky
* @version 1.1, 2006-07-24
diff --git a/src/library/scala/mobile/Code.scala b/src/library/scala/mobile/Code.scala
deleted file mode 100644
index b25a36a04f..0000000000
--- a/src/library/scala/mobile/Code.scala
+++ /dev/null
@@ -1,234 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2002-2011, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-
-
-package scala.mobile
-
-
-import java.lang.reflect.{Constructor, Method, Modifier}
-import java.lang.NoSuchMethodException
-
-/** The class <code>Code</code> provides <code>apply</code> methods
- * with different arities (actually up to 9 parameters) to invoke
- * a function simply by specifying its name and argument types.<p/>
- *
- * Example:<pre>
- * <b>val</b> url = <b>new</b> URL("http://scala-lang.org/classes/examples.jar");
- * <b>val</b> obj = <b>new</b> Location(url) create "examples.sort";
- * <b>val</b> ar = Array(6, 2, 8, 5, 1);
- * obj[Array[Int], Unit]("println")(ar);
- * obj[Array[Int], Unit]("sort")(ar);
- * obj[Array[Int], Unit]("println")(ar);</pre>
- *
- * @see <a href="Location.html">Location</a>
- *
- * @author Stephane Micheloud
- * @version 1.0, 04/05/2004
- */
-class Code(clazz: java.lang.Class[_]) {
-
- private type JObject = java.lang.Object
-
- private var instance: JObject = _
-
- ///////////////////////////// apply methods ///////////////////////////////
-
- type AnyClass = Class[T] forSome { type T }
-
- def apply[R](funName: String) =
- () => {
- val args = Array[JObject]()
- val types = Array[AnyClass]()
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, R](funName: String) =
- (_0: A0) => {
- val p = boxValue(_0)
- val args = Array(p._1)
- val types = Array[AnyClass](p._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, R](funName: String) =
- (_0: A0, _1: A1) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val args = Array(p0._1, p1._1)
- val types = Array[AnyClass](p0._2, p1._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, R](funName: String) =
- (_0: A0, _1: A1, _2: A2) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val args = Array(p0._1, p1._1, p2._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val args = Array(p0._1, p1._1, p2._1, p3._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, A4, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val p4 = boxValue(_4)
- val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, A4, A5, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val p4 = boxValue(_4)
- val p5 = boxValue(_5)
- val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, A4, A5, A6, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val p4 = boxValue(_4)
- val p5 = boxValue(_5)
- val p6 = boxValue(_6)
- val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, A4, A5, A6, A7, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val p4 = boxValue(_4)
- val p5 = boxValue(_5)
- val p6 = boxValue(_6)
- val p7 = boxValue(_7)
- val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- def apply[A0, A1, A2, A3, A4, A5, A6, A7, A8, R](funName: String) =
- (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7, _8: A8) => {
- val p0 = boxValue(_0)
- val p1 = boxValue(_1)
- val p2 = boxValue(_2)
- val p3 = boxValue(_3)
- val p4 = boxValue(_4)
- val p5 = boxValue(_5)
- val p6 = boxValue(_6)
- val p7 = boxValue(_7)
- val p8 = boxValue(_8)
- val args = Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1, p8._1)
- val types = Array[AnyClass](p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2, p8._2)
- applyFun(funName, args, types).asInstanceOf[R]
- }
-
- ////////////////////// private functions ///////////////////////
-
- private def boxValue(value: Any) = value match {
- case x: Byte => (java.lang.Byte.valueOf(x), java.lang.Byte.TYPE)
- case x: Boolean => (java.lang.Boolean.valueOf(x), java.lang.Boolean.TYPE)
- case x: Char => (java.lang.Character.valueOf(x), java.lang.Character.TYPE)
- case x: Short => (java.lang.Short.valueOf(x), java.lang.Short.TYPE)
- case x: Int => (java.lang.Integer.valueOf(x), java.lang.Integer.TYPE)
- case x: Long => (java.lang.Long.valueOf(x), java.lang.Long.TYPE)
- case x: Float => (java.lang.Float.valueOf(x), java.lang.Float.TYPE)
- case x: Double => (java.lang.Double.valueOf(x), java.lang.Double.TYPE)
- case _ =>
- val x = value.asInstanceOf[JObject]
- (x, x.getClass())
- }
-
- private def isConstructorName(methName: String) = {
- var className = clazz.getName()
- val classInx = className.lastIndexOf(".")
- val methInx = methName.lastIndexOf(".")
- if (classInx > 0 && methInx < 0)
- className = className.substring(classInx + 1, className.length())
- methName.equals(className)
- }
-
- private def applyFun(methName: String, args: Array[JObject],
- argTypes: Array[Class[T] forSome { type T }]): JObject = {
- try {
- val method = clazz.getMethod(methName, argTypes : _*)
- var obj: JObject = null
- if (! Modifier.isStatic(method.getModifiers())) {
- if (instance eq null) {
- instance = try {
- clazz.newInstance().asInstanceOf[AnyRef]
- } catch { case _ =>
- val cs = clazz.getConstructors()
-//Console.println("cs.length=" + cs.length);
- if (cs.length > 0) {
- cs(0).newInstance("").asInstanceOf[AnyRef]
- } else {
- sys.error("class " + clazz.getName() + " has no public constructor")
- }
- }
- }
- obj = instance
- }
- val result = method.invoke(obj, args : _*)
- if (result eq null) ().asInstanceOf[JObject] else result
- }
- catch {
- case me: NoSuchMethodException =>
- if (isConstructorName(methName)) {
- try {
- val cstr = clazz.getConstructor(argTypes : _*)
- instance = cstr.newInstance(args : _*).asInstanceOf[AnyRef]
- instance
- }
- catch {
- case e: Exception =>
- Console.println(e.getMessage())
- e.printStackTrace()
- }
- }
- else {
- Console.println(me.getMessage())
- me.printStackTrace()
- }
- null
- case e: Exception =>
- Console.println(e.getMessage())
- e.printStackTrace()
- null
- }
- }
-
-}
diff --git a/src/library/scala/mobile/Location.scala b/src/library/scala/mobile/Location.scala
deleted file mode 100644
index 159bf11141..0000000000
--- a/src/library/scala/mobile/Location.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2002-2011, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package scala.mobile
-
-import java.net._
-import scala.collection.mutable
-
-/** The class <code>Location</code> provides a <code>create</code>
- * method to instantiate objects from a network location by
- * specifying the URL address of the jar/class file.<p/>
- *
- * An update of the jar/class file should not break your code as far
- * as the used class names and method signatures are the same.<p/>
- *
- * Example:<pre>
- * <b>val</b> url = <b>new</b> URL("http://scala-lang.org/classes/examples.jar");
- * <b>val</b> obj = <b>new</b> Location(url) create "examples.sort";</pre>
- *
- * @see <a href="Code.html">Code</a>
- *
- * @author Stephane Micheloud
- * @version 1.0, 04/05/2004
- */
-class Location(url: URL) {
- /** A cache containing all class loaders of this location.
- */
- private val lcache = new mutable.HashMap[URL, ClassLoader]
-
- /** The class loader associated with this location.
- */
- private val loader =
- if (url eq null) ClassLoader.getSystemClassLoader()
- else lcache.getOrElseUpdate(url, new URLClassLoader(Array(url)))
-
- /** A cache containing all classes of this location.
- */
- private val ccache = new mutable.HashMap[String, java.lang.Class[_]]
-
- /** Return the code description for the string <code>className</code>
- * at this location.
- *
- * @param classname the name of the class
- * @return the code description corresponding to `className`.
- */
- def create(className: String) = new Code(
- ccache.getOrElseUpdate(className, {
- // source 'class A { ... }' becomes in bytecode: interface A.class + class A$class.class
- // source 'object A { ... }' becomes in bytecode: interface A.class + class A$.class
- val append = if (loader.loadClass(className).isInterface) "$class" else "$"
- loader loadClass (className + append)
- })
- )
-}
-
-/** The object <code>Location</code> can be used to instantiate
- * objects on the same Java VM. It is just provided to illustrate
- * the special case where resources are available locally.<p/>
- *
- * Example:<pre>
- * <b>val</b> obj = Location.create("xcode.Math");
- * <b>val</b> x = obj[Int, Int]("square")(5);</pre>
- *
- * @author Stephane Micheloud
- * @version 1.0, 04/05/2004
- */
-object Location extends Location(null)
diff --git a/src/library/scala/package.scala b/src/library/scala/package.scala
index 0e966acd6b..264fd18406 100644
--- a/src/library/scala/package.scala
+++ b/src/library/scala/package.scala
@@ -6,7 +6,7 @@
** |/ **
\* */
-
+import annotation.bridge
/**
* Core Scala types. They are always available without an explicit import.
@@ -72,12 +72,14 @@ package object scala {
val Range = scala.collection.immutable.Range
// Migrated from Predef
-
- val $scope = scala.xml.TopScope
-
@deprecated("Use Thread.currentThread instead", "2.9.0")
def currentThread = java.lang.Thread.currentThread()
+ // Moved back into Predef to avoid unnecessary indirection by
+ // way of the scala package object within the standard library,
+ // but bridged for compatibility.
+ @bridge def $scope = scala.xml.TopScope
+
// Numeric types which were moved into scala.math.*
type BigDecimal = scala.math.BigDecimal
diff --git a/src/library/scala/reflect/ScalaBeanInfo.scala b/src/library/scala/reflect/ScalaBeanInfo.scala
index 6b026907f4..bcb76c38bc 100644
--- a/src/library/scala/reflect/ScalaBeanInfo.scala
+++ b/src/library/scala/reflect/ScalaBeanInfo.scala
@@ -34,7 +34,7 @@ abstract class ScalaBeanInfo(clazz: java.lang.Class[_],
// override def getAdditionalBeanInfo() = Array(Introspector getBeanInfo clazz.getSuperclass)
- private def init {
+ private def init() {
var i = 0;
while (i < props.length) {
pd(i/3) = new PropertyDescriptor(props(i), clazz, props(i+1), props(i+2))
diff --git a/src/library/scala/runtime/RichBoolean.scala b/src/library/scala/runtime/RichBoolean.scala
index 5be4e07f2f..d44868708d 100644
--- a/src/library/scala/runtime/RichBoolean.scala
+++ b/src/library/scala/runtime/RichBoolean.scala
@@ -6,10 +6,8 @@
** |/ **
\* */
-
-
package scala.runtime
final class RichBoolean(val self: Boolean) extends OrderedProxy[Boolean] {
- protected val ord = Ordering[Boolean]
+ protected val ord = math.Ordering[Boolean]
}
diff --git a/src/library/scala/sys/SystemProperties.scala b/src/library/scala/sys/SystemProperties.scala
index 296db9e469..25fd6e53a8 100644
--- a/src/library/scala/sys/SystemProperties.scala
+++ b/src/library/scala/sys/SystemProperties.scala
@@ -8,7 +8,7 @@
package scala.sys
-import scala.collection.mutable
+import scala.collection.{ mutable, Iterator }
import scala.collection.JavaConverters._
import java.security.AccessControlException
diff --git a/src/library/scala/sys/process/BasicIO.scala b/src/library/scala/sys/process/BasicIO.scala
index 88e66afc91..6adce06f36 100644
--- a/src/library/scala/sys/process/BasicIO.scala
+++ b/src/library/scala/sys/process/BasicIO.scala
@@ -12,6 +12,7 @@ package process
import processInternal._
import java.io.{ BufferedReader, InputStreamReader, FilterInputStream, FilterOutputStream }
import java.util.concurrent.LinkedBlockingQueue
+import scala.collection.immutable.Stream
object BasicIO {
final val BufferSize = 8192
diff --git a/src/library/scala/sys/process/Process.scala b/src/library/scala/sys/process/Process.scala
index 983fc8309c..01fbaf19e3 100644
--- a/src/library/scala/sys/process/Process.scala
+++ b/src/library/scala/sys/process/Process.scala
@@ -38,7 +38,7 @@ trait ProcessCreation {
def apply(command: Seq[String], cwd: File, extraEnv: (String, String)*): ProcessBuilder =
apply(command, Some(cwd), extraEnv: _*)
- /** create ProcessBuilder with working dir optionaly set to File and extra environment variables */
+ /** create ProcessBuilder with working dir optionally set to File and extra environment variables */
def apply(command: String, cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = {
apply(command.split("""\s+"""), cwd, extraEnv : _*)
// not smart to use this on windows, because CommandParser uses \ to escape ".
@@ -48,7 +48,7 @@ trait ProcessCreation {
}*/
}
- /** create ProcessBuilder with working dir optionaly set to File and extra environment variables */
+ /** create ProcessBuilder with working dir optionally set to File and extra environment variables */
def apply(command: Seq[String], cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = {
val jpb = new JProcessBuilder(command.toArray: _*)
cwd foreach (jpb directory _)
diff --git a/src/library/scala/sys/process/ProcessImpl.scala b/src/library/scala/sys/process/ProcessImpl.scala
index 857c1af15e..b7549eeb06 100644
--- a/src/library/scala/sys/process/ProcessImpl.scala
+++ b/src/library/scala/sys/process/ProcessImpl.scala
@@ -28,7 +28,7 @@ private[process] trait ProcessImpl {
private[process] object Future {
def apply[T](f: => T): () => T = {
val result = new SyncVar[Either[Throwable, T]]
- def run: Unit =
+ def run(): Unit =
try result set Right(f)
catch { case e: Exception => result set Left(e) }
diff --git a/src/library/scala/testing/Benchmark.scala b/src/library/scala/testing/Benchmark.scala
index 34f769be11..c6ab992306 100644
--- a/src/library/scala/testing/Benchmark.scala
+++ b/src/library/scala/testing/Benchmark.scala
@@ -75,7 +75,7 @@ trait Benchmark {
* should not be measured. This method is run before each call to the
* benchmark payload, 'run'.
*/
- def setUp {
+ def setUp() {
}
/** Perform cleanup operations after each 'run'. For micro benchmarks,
@@ -84,7 +84,7 @@ trait Benchmark {
* write the results to a file. The execution time of this method is not
* measured.
*/
- def tearDown {
+ def tearDown() {
}
/** a string that is written at the beginning of the output line
diff --git a/src/library/scala/util/MurmurHash.scala b/src/library/scala/util/MurmurHash.scala
index f1f6e08254..71db2536be 100644
--- a/src/library/scala/util/MurmurHash.scala
+++ b/src/library/scala/util/MurmurHash.scala
@@ -20,6 +20,7 @@ package scala.util
*/
import java.lang.Integer.{ rotateLeft => rotl }
+import scala.collection.Iterator
/** A class designed to generate well-distributed non-cryptographic
* hashes. It is designed to be passed to a collection's foreach method,
diff --git a/src/library/scala/util/Random.scala b/src/library/scala/util/Random.scala
index f3d1397075..cfd6154874 100644
--- a/src/library/scala/util/Random.scala
+++ b/src/library/scala/util/Random.scala
@@ -6,20 +6,17 @@
** |/ **
\* */
-
-
package scala.util
-import collection.immutable.List
+import collection.mutable.ArrayBuffer
+import collection.generic.CanBuildFrom
+import scala.collection.immutable.{ List, Stream }
/**
* @author Stephane Micheloud
*
*/
class Random(val self: java.util.Random) {
- import collection.mutable.ArrayBuffer
- import collection.generic.CanBuildFrom
-
/** Creates a new random number generator using a single long seed. */
def this(seed: Long) = this(new java.util.Random(seed))
diff --git a/src/library/scala/util/Sorting.scala b/src/library/scala/util/Sorting.scala
index e687335b65..f286670f25 100644
--- a/src/library/scala/util/Sorting.scala
+++ b/src/library/scala/util/Sorting.scala
@@ -9,6 +9,7 @@
package scala.util
import scala.reflect.ClassManifest
+import scala.math.Ordering
/** The Sorting object provides functions that can sort various kinds of
* objects. You can provide a comparison function, or you can request a sort
diff --git a/src/library/scala/util/control/Breaks.scala b/src/library/scala/util/control/Breaks.scala
index 139fcc0bd6..c436df9f8f 100644
--- a/src/library/scala/util/control/Breaks.scala
+++ b/src/library/scala/util/control/Breaks.scala
@@ -57,7 +57,7 @@ class Breaks {
* @note this might be different than the statically closest enclosing
* block!
*/
- def break { throw breakException }
+ def break() { throw breakException }
}
/** An object that can be used for the break control abstraction.
diff --git a/src/library/scala/util/parsing/ast/Binders.scala b/src/library/scala/util/parsing/ast/Binders.scala
index 494cb04166..a4f457e1bf 100644
--- a/src/library/scala/util/parsing/ast/Binders.scala
+++ b/src/library/scala/util/parsing/ast/Binders.scala
@@ -172,8 +172,8 @@ trait Binders extends AbstractSyntax with Mappable {
* the binding in the returned scope also does, and thus the check that all variables are bound is deferred until this scope is left **/
def nested: Scope[binderType] = this // TODO
- def onEnter {}
- def onLeft {}
+ def onEnter() {}
+ def onLeft() {}
}
diff --git a/src/library/scala/xml/MetaData.scala b/src/library/scala/xml/MetaData.scala
index 2e55a9d67e..e3e025cf59 100644
--- a/src/library/scala/xml/MetaData.scala
+++ b/src/library/scala/xml/MetaData.scala
@@ -11,7 +11,7 @@ package scala.xml
import Utility.sbToString
import annotation.tailrec
-
+import scala.collection.Iterator
/**
* Copyright 2008 Google Inc. All Rights Reserved.
diff --git a/src/library/scala/xml/Null.scala b/src/library/scala/xml/Null.scala
index 7769ddf0df..0b527c91bd 100644
--- a/src/library/scala/xml/Null.scala
+++ b/src/library/scala/xml/Null.scala
@@ -11,6 +11,7 @@
package scala.xml
import Utility.{ isNameStart }
+import scala.collection.Iterator
/** Essentially, every method in here is a dummy, returning Zero[T].
* It provides a backstop for the unusual collection defined by MetaData,
diff --git a/src/library/scala/xml/dtd/ContentModelParser.scala b/src/library/scala/xml/dtd/ContentModelParser.scala
index 90255e966a..2d87bc0764 100644
--- a/src/library/scala/xml/dtd/ContentModelParser.scala
+++ b/src/library/scala/xml/dtd/ContentModelParser.scala
@@ -73,7 +73,7 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning #
sys.error("unexpected token:" + token2string(token) );
}
// sopt ::= S?
- def sOpt = if( token == S ) nextToken;
+ def sOpt() = if( token == S ) nextToken;
// (' S? mixed ::= '#PCDATA' S? ')'
// | '#PCDATA' (S? '|' S? atom)* S? ')*'
diff --git a/src/library/scala/xml/dtd/Scanner.scala b/src/library/scala/xml/dtd/Scanner.scala
index 20c0204e51..82a8d1af2f 100644
--- a/src/library/scala/xml/dtd/Scanner.scala
+++ b/src/library/scala/xml/dtd/Scanner.scala
@@ -33,7 +33,7 @@ class Scanner extends Tokens with parsing.TokenTests {
}
/** scans the next token */
- final def nextToken {
+ final def nextToken() {
if (token != END) token = readToken
}
@@ -41,7 +41,7 @@ class Scanner extends Tokens with parsing.TokenTests {
final def isIdentChar = ( ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z'));
- final def next = if (it.hasNext) c = it.next else c = ENDCH
+ final def next() = if (it.hasNext) c = it.next else c = ENDCH
final def acc(d: Char) {
if (c == d) next else sys.error("expected '"+d+"' found '"+c+"' !");
diff --git a/src/library/scala/xml/factory/LoggedNodeFactory.scala b/src/library/scala/xml/factory/LoggedNodeFactory.scala
index 6a777f4605..c15a9ebe7b 100644
--- a/src/library/scala/xml/factory/LoggedNodeFactory.scala
+++ b/src/library/scala/xml/factory/LoggedNodeFactory.scala
@@ -37,7 +37,7 @@ trait LoggedNodeFactory[A <: Node] extends NodeFactory[A] with scala.util.loggin
final val NONE = 0
final val CACHE = 1
final val FULL = 2
- /** 0 = no loggging, 1 = cache hits, 2 = detail */
+ /** 0 = no logging, 1 = cache hits, 2 = detail */
val logCompressLevel = 1
// methods of NodeFactory
diff --git a/src/library/scala/xml/parsing/FactoryAdapter.scala b/src/library/scala/xml/parsing/FactoryAdapter.scala
index f2dc191063..67e06ff5ca 100644
--- a/src/library/scala/xml/parsing/FactoryAdapter.scala
+++ b/src/library/scala/xml/parsing/FactoryAdapter.scala
@@ -6,20 +6,16 @@
** |/ **
\* */
-
-
package scala.xml
package parsing
import java.io.{ InputStream, Reader, File, FileDescriptor, FileInputStream }
-import collection.mutable.Stack
-
+import scala.collection.{ mutable, Iterator }
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler
// can be mixed into FactoryAdapter if desired
-trait ConsoleErrorHandler extends DefaultHandler
-{
+trait ConsoleErrorHandler extends DefaultHandler {
// ignore warning, crimson warns even for entity resolution!
override def warning(ex: SAXParseException): Unit = { }
override def error(ex: SAXParseException): Unit = printError("Error", ex)
@@ -38,15 +34,14 @@ trait ConsoleErrorHandler extends DefaultHandler
* namespace bindings, without relying on namespace handling of the
* underlying SAX parser.
*/
-abstract class FactoryAdapter extends DefaultHandler with factory.XMLLoader[Node]
-{
+abstract class FactoryAdapter extends DefaultHandler with factory.XMLLoader[Node] {
var rootElem: Node = null
val buffer = new StringBuilder()
- val attribStack = new Stack[MetaData]
- val hStack = new Stack[Node] // [ element ] contains siblings
- val tagStack = new Stack[String]
- var scopeStack = new Stack[NamespaceBinding]
+ val attribStack = new mutable.Stack[MetaData]
+ val hStack = new mutable.Stack[Node] // [ element ] contains siblings
+ val tagStack = new mutable.Stack[String]
+ var scopeStack = new mutable.Stack[NamespaceBinding]
var curTag : String = null
var capture: Boolean = false
diff --git a/src/library/scala/xml/parsing/MarkupParserCommon.scala b/src/library/scala/xml/parsing/MarkupParserCommon.scala
index d2174c2879..d9729e14e1 100644
--- a/src/library/scala/xml/parsing/MarkupParserCommon.scala
+++ b/src/library/scala/xml/parsing/MarkupParserCommon.scala
@@ -201,13 +201,13 @@ private[scala] trait MarkupParserCommon extends TokenTests {
def xToken(that: Seq[Char]) { that foreach xToken }
/** scan [S] '=' [S]*/
- def xEQ = { xSpaceOpt; xToken('='); xSpaceOpt }
+ def xEQ() = { xSpaceOpt; xToken('='); xSpaceOpt }
/** skip optional space S? */
- def xSpaceOpt = while (isSpace(ch) && !eof) nextch
+ def xSpaceOpt() = while (isSpace(ch) && !eof) nextch
/** scan [3] S ::= (#x20 | #x9 | #xD | #xA)+ */
- def xSpace =
+ def xSpace() =
if (isSpace(ch)) { nextch; xSpaceOpt }
else xHandleError(ch, "whitespace expected")
diff --git a/src/library/scala/xml/persistent/CachedFileStorage.scala b/src/library/scala/xml/persistent/CachedFileStorage.scala
index 7f5b6b6310..bcdd1a3f2d 100644
--- a/src/library/scala/xml/persistent/CachedFileStorage.scala
+++ b/src/library/scala/xml/persistent/CachedFileStorage.scala
@@ -10,9 +10,12 @@
package scala.xml
package persistent
-import java.io.{File, FileOutputStream}
+import java.io.{ File, FileOutputStream }
import java.nio.ByteBuffer
import java.nio.channels.Channels
+import java.lang.Thread
+import scala.util.logging.Logged
+import scala.collection.Iterator
/** <p>
* Mutable storage of immutable xml trees. Everything is kept in memory,
@@ -24,8 +27,7 @@ import java.nio.channels.Channels
*
* @author Burak Emir
*/
-abstract class CachedFileStorage(private val file1: File)
-extends java.lang.Thread with scala.util.logging.Logged {
+abstract class CachedFileStorage(private val file1: File) extends Thread with Logged {
private val file2 = new File(file1.getParent, file1.getName+"$")
@@ -33,7 +35,7 @@ extends java.lang.Thread with scala.util.logging.Logged {
*/
private var theFile: File = null
- private def switch = { theFile = if (theFile == file1) file2 else file1; }
+ private def switch() = { theFile = if (theFile == file1) file2 else file1; }
/** this storage modified since last modification check */
protected var dirty = false
@@ -82,7 +84,7 @@ extends java.lang.Thread with scala.util.logging.Logged {
}
/** saves the XML to file */
- private def save = if (this.dirty) {
+ private def save() = if (this.dirty) {
log("[save]\ndeleting "+theFile);
theFile.delete();
log("creating new "+theFile);
@@ -115,7 +117,7 @@ extends java.lang.Thread with scala.util.logging.Logged {
}
/** forces writing of contents to the file, even if there has not been any update. */
- def flush = {
+ def flush() = {
this.dirty = true;
save
}
diff --git a/src/library/scala/xml/pull/XMLEventReader.scala b/src/library/scala/xml/pull/XMLEventReader.scala
index 3902967626..51a2fda6aa 100755
--- a/src/library/scala/xml/pull/XMLEventReader.scala
+++ b/src/library/scala/xml/pull/XMLEventReader.scala
@@ -6,14 +6,13 @@
** |/ **
\* */
-
package scala.xml
package pull
+import scala.io.Source
+import java.lang.Thread
import java.util.concurrent.LinkedBlockingQueue
import java.nio.channels.ClosedChannelException
-
-import scala.io.Source
import scala.xml.parsing.{ ExternalSources, MarkupHandler, MarkupParser }
/**
@@ -49,7 +48,7 @@ class XMLEventReader(src: Source) extends ProducerConsumerIterator[XMLEvent] {
// fails for whatever reason the iterator correctness is not impacted,
// only performance (because it will finish the entire XML document,
// or at least as much as it can fit in the queue.)
- def stop = {
+ def stop() = {
produce(POISON)
parserThread.interrupt()
}
@@ -104,8 +103,7 @@ class XMLEventReader(src: Source) extends ProducerConsumerIterator[XMLEvent] {
// the next call hasNext is guaranteed not to block.
//
// This is not thread-safe for multiple consumers!
-trait ProducerConsumerIterator[T >: Null] extends Iterator[T]
-{
+trait ProducerConsumerIterator[T >: Null] extends Iterator[T] {
// abstract - iterator-specific distinguished object for marking eos
val EndOfStream: T
diff --git a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
index e2afc5644f..3957192f70 100644
--- a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
+++ b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
@@ -52,7 +52,7 @@ class ConsoleRunner extends DirectRunner {
def denotesTestSet(arg: String) = testSetArgs contains arg
- private def printVersion { NestUI outline (versionMsg + "\n") }
+ private def printVersion() { NestUI outline (versionMsg + "\n") }
private val unaryArgs = List(
"--pack", "--all", "--verbose", "--show-diff", "--show-log",
diff --git a/src/partest/scala/tools/partest/nest/Worker.scala b/src/partest/scala/tools/partest/nest/Worker.scala
index 301fe5e32b..bfa6427d21 100644
--- a/src/partest/scala/tools/partest/nest/Worker.scala
+++ b/src/partest/scala/tools/partest/nest/Worker.scala
@@ -57,7 +57,7 @@ class ScalaCheckFileManager(val origmanager: FileManager) extends FileManager {
}
object Output {
- def init {
+ def init() {
System.setOut(outRedirect)
System.setErr(errRedirect)
}
diff --git a/src/partest/scala/tools/partest/package.scala b/src/partest/scala/tools/partest/package.scala
index 5bcc66ddbd..fe33064f19 100644
--- a/src/partest/scala/tools/partest/package.scala
+++ b/src/partest/scala/tools/partest/package.scala
@@ -39,7 +39,7 @@ package object partest {
System.getProperties.toList.sorted map { case (k, v) => "%s -> %s\n".format(k, v) } mkString
}
- def showAllJVMInfo {
+ def showAllJVMInfo() {
NestUI.verbose(vmArgString)
NestUI.verbose(allPropertiesString)
}
diff --git a/src/scalacheck/org/scalacheck/Prop.scala b/src/scalacheck/org/scalacheck/Prop.scala
index 68e4b89660..199a668914 100644
--- a/src/scalacheck/org/scalacheck/Prop.scala
+++ b/src/scalacheck/org/scalacheck/Prop.scala
@@ -39,7 +39,7 @@ trait Prop {
/** Convenience method that checks this property and reports the
* result on the console. If you need to get the results from the test use
* the <code>check</code> methods in <code>Test</code> instead. */
- def check: Unit = check(Test.Params())
+ def check(): Unit = check(Test.Params())
/** Convenience method that makes it possible to use a this property
* as an application that checks itself on execution */
diff --git a/src/scalacheck/org/scalacheck/Properties.scala b/src/scalacheck/org/scalacheck/Properties.scala
index bb2fe77c47..7fceb4bd35 100644
--- a/src/scalacheck/org/scalacheck/Properties.scala
+++ b/src/scalacheck/org/scalacheck/Properties.scala
@@ -51,7 +51,7 @@ class Properties(val name: String) extends Prop {
/** Convenience method that checks the properties and reports the
* result on the console. If you need to get the results from the test use
* the <code>check</code> methods in <code>Test</code> instead. */
- override def check: Unit = check(Test.Params())
+ override def check(): Unit = check(Test.Params())
/** Convenience method that makes it possible to use a this instance
* as an application that checks itself on execution */
diff --git a/src/scalap/scala/tools/scalap/CodeWriter.scala b/src/scalap/scala/tools/scalap/CodeWriter.scala
index db9b3d570b..d895ce3836 100644
--- a/src/scalap/scala/tools/scalap/CodeWriter.scala
+++ b/src/scalap/scala/tools/scalap/CodeWriter.scala
@@ -73,7 +73,7 @@ class CodeWriter(writer: Writer) {
this
}
- def * : Unit = {}
+ def *() = {}
def println: CodeWriter = newline
diff --git a/src/scalap/scala/tools/scalap/JavaWriter.scala b/src/scalap/scala/tools/scalap/JavaWriter.scala
index 9dd867a1b4..db9d6c5ed9 100644
--- a/src/scalap/scala/tools/scalap/JavaWriter.scala
+++ b/src/scalap/scala/tools/scalap/JavaWriter.scala
@@ -172,7 +172,7 @@ class JavaWriter(classfile: Classfile, writer: Writer) extends CodeWriter(writer
}
}
- def printClassHeader {
+ def printClassHeader() {
if (isInterface(cf.flags)) {
print("trait " + getSimpleClassName(cf.classname))
} else {
@@ -185,7 +185,7 @@ class JavaWriter(classfile: Classfile, writer: Writer) extends CodeWriter(writer
}
}
- def printClass {
+ def printClass() {
val pck = getPackage(cf.classname);
if (pck.length() > 0)
println("package " + pck + ";")
diff --git a/src/scalap/scala/tools/scalap/MetaParser.scala b/src/scalap/scala/tools/scalap/MetaParser.scala
index ac76a94b9c..ca9bd93f86 100644
--- a/src/scalap/scala/tools/scalap/MetaParser.scala
+++ b/src/scalap/scala/tools/scalap/MetaParser.scala
@@ -27,7 +27,7 @@ class MetaParser(meta: String) {
token
}
- protected def parseType: Unit = {
+ protected def parseType(): Unit = {
if (token startsWith "?")
res.append(token.substring(1))
else
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
index 93c1c7a394..df78bad25e 100644
--- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
@@ -239,7 +239,7 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) {
}
def printMethod(level: Int, m: MethodSymbol, indent: () => Unit) {
- def cont = print(" = { /* compiled code */ }")
+ def cont() = print(" = { /* compiled code */ }")
val n = m.name
if (underCaseClass(m) && n == CONSTRUCTOR_NAME) return
diff --git a/src/swing/scala/swing/BufferWrapper.scala b/src/swing/scala/swing/BufferWrapper.scala
index 6f3adf08e0..04fb25f0b1 100644
--- a/src/swing/scala/swing/BufferWrapper.scala
+++ b/src/swing/scala/swing/BufferWrapper.scala
@@ -6,11 +6,10 @@
** |/ **
\* */
-
-
package scala.swing
import scala.collection.mutable.Buffer
+import scala.collection.Iterator
/**
* Default partial implementation for buffer adapters.
@@ -21,7 +20,7 @@ protected[swing] abstract class BufferWrapper[A] extends Buffer[A] { outer =>
remove(n)
insertAt(n, a)
}
- def insertAll(n: Int, elems: scala.collection.Traversable[A]) {
+ def insertAll(n: Int, elems: Traversable[A]) {
var i = n
for (el <- elems) {
insertAt(i, el)
diff --git a/src/swing/scala/swing/Component.scala b/src/swing/scala/swing/Component.scala
index fc4936cfde..5eaff35bb0 100644
--- a/src/swing/scala/swing/Component.scala
+++ b/src/swing/scala/swing/Component.scala
@@ -200,7 +200,7 @@ abstract class Component extends UIElement {
def requestFocusInWindow() = peer.requestFocusInWindow()
def hasFocus: Boolean = peer.isFocusOwner
- protected override def onFirstSubscribe {
+ protected override def onFirstSubscribe() {
super.onFirstSubscribe
// TODO: deprecated, remove after 2.8
peer.addComponentListener(new java.awt.event.ComponentListener {
diff --git a/src/swing/scala/swing/Container.scala b/src/swing/scala/swing/Container.scala
index 562d91243c..b39bfe0f5d 100644
--- a/src/swing/scala/swing/Container.scala
+++ b/src/swing/scala/swing/Container.scala
@@ -25,7 +25,7 @@ object Container {
def contents: Seq[Component] = _contents
protected class Content extends BufferWrapper[Component] {
- override def clear { peer.removeAll() }
+ override def clear() { peer.removeAll() }
override def remove(n: Int): Component = {
val c = peer.getComponent(n)
peer.remove(n)
diff --git a/src/swing/scala/swing/MainFrame.scala b/src/swing/scala/swing/MainFrame.scala
index 299f7b9293..e8b276e7fe 100644
--- a/src/swing/scala/swing/MainFrame.scala
+++ b/src/swing/scala/swing/MainFrame.scala
@@ -17,5 +17,5 @@ import event._
* framework and quits the application when closed.
*/
class MainFrame extends Frame {
- override def closeOperation { sys.exit(0) }
+ override def closeOperation() { sys.exit(0) }
}
diff --git a/src/swing/scala/swing/Publisher.scala b/src/swing/scala/swing/Publisher.scala
index ebab00463a..3c3e99fc49 100644
--- a/src/swing/scala/swing/Publisher.scala
+++ b/src/swing/scala/swing/Publisher.scala
@@ -111,7 +111,7 @@ private[swing] trait SingleRefCollection[+A <: AnyRef] extends Iterable[A] { sel
private val elems = self.underlying.iterator
private var hd: A = _
private var ahead: Boolean = false
- private def skip: Unit =
+ private def skip(): Unit =
while (!ahead && elems.hasNext) {
// make sure we have a reference to the next element,
// otherwise it might be garbage collected
diff --git a/src/swing/scala/swing/TextField.scala b/src/swing/scala/swing/TextField.scala
index f04e122fb9..789a8f49a5 100644
--- a/src/swing/scala/swing/TextField.scala
+++ b/src/swing/scala/swing/TextField.scala
@@ -47,7 +47,7 @@ class TextField(text0: String, columns0: Int) extends TextComponent with TextCom
publish(EditDone(TextField.this))
}
- protected override def onFirstSubscribe {
+ protected override def onFirstSubscribe() {
super.onFirstSubscribe
peer.addActionListener(actionListener)
peer.addFocusListener(new FocusAdapter {
@@ -55,7 +55,7 @@ class TextField(text0: String, columns0: Int) extends TextComponent with TextCom
})
}
- protected override def onLastUnsubscribe {
+ protected override def onLastUnsubscribe() {
super.onLastUnsubscribe
peer.removeActionListener(actionListener)
}
diff --git a/src/swing/scala/swing/UIElement.scala b/src/swing/scala/swing/UIElement.scala
index 8e34b0c38c..9c5120a342 100644
--- a/src/swing/scala/swing/UIElement.scala
+++ b/src/swing/scala/swing/UIElement.scala
@@ -99,7 +99,7 @@ trait UIElement extends Proxy with LazyPublisher {
def location = peer.getLocation
def bounds = peer.getBounds
def size = peer.getSize
- @deprecated("Explicit size assignement for UIElements is not supported anymore. " +
+ @deprecated("Explicit size assignment for UIElements is not supported anymore. " +
"Use a layout manager or subclass Window.", "2.8.0")
def size_=(dim: Dimension) = peer.setSize(dim)
@@ -119,7 +119,7 @@ trait UIElement extends Proxy with LazyPublisher {
def ignoreRepaint: Boolean = peer.getIgnoreRepaint
def ignoreRepaint_=(b: Boolean) { peer.setIgnoreRepaint(b) }
- protected def onFirstSubscribe {
+ protected def onFirstSubscribe() {
peer.addComponentListener(new java.awt.event.ComponentListener {
def componentHidden(e: java.awt.event.ComponentEvent) {
publish(UIElementHidden(UIElement.this))
@@ -135,5 +135,5 @@ trait UIElement extends Proxy with LazyPublisher {
}
})
}
- protected def onLastUnsubscribe {}
+ protected def onLastUnsubscribe() {}
}
diff --git a/test/files/buildmanager/t2649/t2649.check b/test/files/buildmanager/t2649/t2649.check
index 5b698ec03f..390f284fd3 100644
--- a/test/files/buildmanager/t2649/t2649.check
+++ b/test/files/buildmanager/t2649/t2649.check
@@ -3,7 +3,7 @@ compiling Set(A.scala, B.scala)
Changes: Map()
builder > A.scala
compiling Set(A.scala)
-Changes: Map(object A -> List(Changed(Definition(A.x))[method x changed from (zz: Int,yy: Int)Int to (yy: Int,zz: Int)Int flags: <method>]))
-invalidate B.scala because it references changed definition [Changed(Definition(A.x))[method x changed from (zz: Int,yy: Int)Int to (yy: Int,zz: Int)Int flags: <method>]]
+Changes: Map(object A -> List(Changed(Definition(A.x))[method x changed from (zz: Int, yy: Int)Int to (yy: Int, zz: Int)Int flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[method x changed from (zz: Int, yy: Int)Int to (yy: Int, zz: Int)Int flags: <method>]]
compiling Set(B.scala)
Changes: Map(object B -> List())
diff --git a/test/files/buildmanager/t2790/t2790.check b/test/files/buildmanager/t2790/t2790.check
index 3a57d28817..9d37ccea29 100644
--- a/test/files/buildmanager/t2790/t2790.check
+++ b/test/files/buildmanager/t2790/t2790.check
@@ -3,8 +3,8 @@ compiling Set(A.scala, B.scala)
Changes: Map()
builder > A.scala
compiling Set(A.scala)
-Changes: Map(object A -> List(Added(Definition(A.x)), Changed(Definition(A.x))[value x changed from (f: java.lang.String,g: Int)Int to (f: java.lang.String,g: Int)Int <and> (f: Int,g: Int)Int flags: <method>]))
-invalidate B.scala because it references changed definition [Changed(Definition(A.x))[value x changed from (f: java.lang.String,g: Int)Int to (f: java.lang.String,g: Int)Int <and> (f: Int,g: Int)Int flags: <method>]]
+Changes: Map(object A -> List(Added(Definition(A.x)), Changed(Definition(A.x))[value x changed from (f: java.lang.String, g: Int)Int to (f: java.lang.String, g: Int)Int <and> (f: Int, g: Int)Int flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[value x changed from (f: java.lang.String, g: Int)Int to (f: java.lang.String, g: Int)Int <and> (f: Int, g: Int)Int flags: <method>]]
compiling Set(B.scala)
B.scala:2: error: type mismatch;
found : Int(5)
diff --git a/test/files/buildmanager/t3054/foo/Foo.scala b/test/files/buildmanager/t3054/foo/Foo.scala
index c4838b9958..c0fcd97390 100644
--- a/test/files/buildmanager/t3054/foo/Foo.scala
+++ b/test/files/buildmanager/t3054/foo/Foo.scala
@@ -1,5 +1,5 @@
package foo
class Foo {
- def foo = println("foo")
+ def foo() = println("foo")
}
diff --git a/test/files/buildmanager/t4215/A.scala b/test/files/buildmanager/t4215/A.scala
index fbddd93afc..9db40b0fee 100644
--- a/test/files/buildmanager/t4215/A.scala
+++ b/test/files/buildmanager/t4215/A.scala
@@ -1,5 +1,5 @@
class A {
- def B {
+ def B() {
object C
}
}
diff --git a/test/files/continuations-neg/lazy.check b/test/files/continuations-neg/lazy.check
index bfa44c59a4..b8c6887409 100644
--- a/test/files/continuations-neg/lazy.check
+++ b/test/files/continuations-neg/lazy.check
@@ -1,6 +1,6 @@
lazy.scala:5: error: type mismatch;
found : Unit @scala.util.continuations.cpsParam[Unit,Unit]
required: Unit
- def foo = {
- ^
+ def foo() = {
+ ^
one error found
diff --git a/test/files/continuations-neg/lazy.scala b/test/files/continuations-neg/lazy.scala
index dffc57ffa0..3c8169dd46 100644
--- a/test/files/continuations-neg/lazy.scala
+++ b/test/files/continuations-neg/lazy.scala
@@ -2,14 +2,14 @@ import scala.util.continuations._
object Test {
- def foo = {
+ def foo() = {
lazy val x = shift((k:Unit=>Unit)=>k())
println(x)
}
def main(args: Array[String]) {
reset {
- foo
+ foo()
}
}
diff --git a/test/files/neg/abstract-class-2.check b/test/files/neg/abstract-class-2.check
new file mode 100644
index 0000000000..ca79dd8293
--- /dev/null
+++ b/test/files/neg/abstract-class-2.check
@@ -0,0 +1,5 @@
+abstract-class-2.scala:11: error: object creation impossible, since method f in trait S2 of type (x: P2.this.p.S1)Int is not defined
+(Note that P.this.p.S1 does not match P2.this.S1: their prefixes (i.e. enclosing instances) differ)
+ object O2 extends S2 {
+ ^
+one error found
diff --git a/test/files/neg/abstract-class-2.scala b/test/files/neg/abstract-class-2.scala
new file mode 100644
index 0000000000..19f74f3da6
--- /dev/null
+++ b/test/files/neg/abstract-class-2.scala
@@ -0,0 +1,14 @@
+class P {
+ trait S1
+ val p = new P
+
+ trait S2 {
+ def f(x: p.S1): Int
+ }
+}
+
+class P2 extends P {
+ object O2 extends S2 {
+ def f(x: S1) = 5
+ }
+}
diff --git a/test/files/neg/abstract-class-error.check b/test/files/neg/abstract-class-error.check
new file mode 100644
index 0000000000..87d148ecc5
--- /dev/null
+++ b/test/files/neg/abstract-class-error.check
@@ -0,0 +1,5 @@
+S.scala:1: error: class S needs to be abstract, since method g in class J of type (y: Int, z: java.util.List)Int is not defined
+(Note that java.util.List does not match java.util.List[String]. To implement a raw type, use java.util.List[_])
+class S extends J {
+ ^
+one error found
diff --git a/test/files/neg/abstract-class-error/J.java b/test/files/neg/abstract-class-error/J.java
new file mode 100644
index 0000000000..5877f5cc5b
--- /dev/null
+++ b/test/files/neg/abstract-class-error/J.java
@@ -0,0 +1,4 @@
+public abstract class J {
+ public abstract int f();
+ public abstract int g(int y, java.util.List z);
+} \ No newline at end of file
diff --git a/test/files/neg/abstract-class-error/S.scala b/test/files/neg/abstract-class-error/S.scala
new file mode 100644
index 0000000000..67f6d8593e
--- /dev/null
+++ b/test/files/neg/abstract-class-error/S.scala
@@ -0,0 +1,4 @@
+class S extends J {
+ def f() = 55
+ def g(y: Int, z: java.util.List[String]) = 11
+}
diff --git a/test/files/neg/accesses.check b/test/files/neg/accesses.check
index 94fcd615bc..db58af12ce 100644
--- a/test/files/neg/accesses.check
+++ b/test/files/neg/accesses.check
@@ -1,17 +1,17 @@
-accesses.scala:23: error: overriding method f2 in class A of type => Unit;
+accesses.scala:23: error: overriding method f2 in class A of type ()Unit;
method f2 has weaker access privileges; it should not be private
- private def f2: Unit = ()
+ private def f2(): Unit = ()
^
-accesses.scala:24: error: overriding method f3 in class A of type => Unit;
+accesses.scala:24: error: overriding method f3 in class A of type ()Unit;
method f3 has weaker access privileges; it should be at least protected
- private[p2] def f3: Unit = ()
+ private[p2] def f3(): Unit = ()
^
-accesses.scala:25: error: overriding method f4 in class A of type => Unit;
+accesses.scala:25: error: overriding method f4 in class A of type ()Unit;
method f4 has weaker access privileges; it should be at least private[p1]
- private[p2] def f4: Unit
+ private[p2] def f4(): Unit
^
-accesses.scala:26: error: overriding method f5 in class A of type => Unit;
+accesses.scala:26: error: overriding method f5 in class A of type ()Unit;
method f5 has weaker access privileges; it should be at least protected[p1]
- protected[p2] def f5: Unit
+ protected[p2] def f5(): Unit
^
four errors found
diff --git a/test/files/neg/accesses.scala b/test/files/neg/accesses.scala
index 2a6b45c35b..b1df6c0e6c 100644
--- a/test/files/neg/accesses.scala
+++ b/test/files/neg/accesses.scala
@@ -1,27 +1,27 @@
package test.p1.p2
abstract class A {
- private[p2] def f2: Unit
- protected def f3: Unit
- private[p1] def f4: Unit
- protected[p1] def f5: Unit
+ private[p2] def f2(): Unit
+ protected def f3(): Unit
+ private[p1] def f4(): Unit
+ protected[p1] def f5(): Unit
}
abstract class OK1 extends A {
- private[p1] def f2: Unit
- protected[p2] def f3: Unit
- private[test] def f4: Unit
- protected[test] def f5: Unit
+ private[p1] def f2(): Unit
+ protected[p2] def f3(): Unit
+ private[test] def f4(): Unit
+ protected[test] def f5(): Unit
}
abstract class OK2 extends A {
- protected[p1] def f2: Unit
- def f3: Unit
- protected[p1] def f4: Unit
- def f5: Unit
+ protected[p1] def f2(): Unit
+ def f3(): Unit
+ protected[p1] def f4(): Unit
+ def f5(): Unit
}
abstract class Err1 extends A {
- private def f2: Unit = ()
- private[p2] def f3: Unit = ()
- private[p2] def f4: Unit
- protected[p2] def f5: Unit
+ private def f2(): Unit = ()
+ private[p2] def f3(): Unit = ()
+ private[p2] def f4(): Unit
+ protected[p2] def f5(): Unit
}
diff --git a/test/files/neg/bug1960.check b/test/files/neg/bug1960.check
index 6615d90036..8e19f31ef5 100644
--- a/test/files/neg/bug1960.check
+++ b/test/files/neg/bug1960.check
@@ -1,4 +1,4 @@
bug1960.scala:5: error: parameter 'p' requires field but conflicts with p in 'TBase'
-class Aclass (p: Int) extends TBase { def g{ f(p) } }
+class Aclass (p: Int) extends TBase { def g() { f(p) } }
^
one error found
diff --git a/test/files/neg/bug1960.scala b/test/files/neg/bug1960.scala
index af7f270356..5311940b5a 100644
--- a/test/files/neg/bug1960.scala
+++ b/test/files/neg/bug1960.scala
@@ -2,4 +2,4 @@ object ClassFormatErrorExample extends App { new Aclass(1) }
trait TBase { var p:Int = 0; def f(p1: Int) {} }
-class Aclass (p: Int) extends TBase { def g{ f(p) } }
+class Aclass (p: Int) extends TBase { def g() { f(p) } }
diff --git a/test/files/neg/bug4533.check b/test/files/neg/bug4533.check
new file mode 100644
index 0000000000..e1b60aa820
--- /dev/null
+++ b/test/files/neg/bug4533.check
@@ -0,0 +1,4 @@
+bug4533.scala:6: error: erroneous or inaccessible type
+ def statusByAlarms(alarms: GenTraversableOnce[FooAlarm]) = println("hello")
+ ^
+one error found
diff --git a/test/files/neg/bug4533.scala b/test/files/neg/bug4533.scala
new file mode 100644
index 0000000000..0346b5d1d5
--- /dev/null
+++ b/test/files/neg/bug4533.scala
@@ -0,0 +1,8 @@
+package demo
+
+import scala.collection._
+
+class CrashDemo {
+ def statusByAlarms(alarms: GenTraversableOnce[FooAlarm]) = println("hello")
+}
+class FooAlarm { }
diff --git a/test/files/neg/bug630.scala b/test/files/neg/bug630.scala
index d236b51ffd..8a073963b0 100644
--- a/test/files/neg/bug630.scala
+++ b/test/files/neg/bug630.scala
@@ -1,7 +1,7 @@
trait Req1
trait Req2 {
- def test = Console.println("Test")
+ def test() = Console.println("Test")
}
trait Foo {
@@ -10,7 +10,7 @@ trait Foo {
trait Bar {
val foo : Req2
- def test = foo.test
+ def test() = foo.test
}
object Test
diff --git a/test/files/neg/exhausting.check b/test/files/neg/exhausting.check
index d3f2251f79..0bef21e077 100644
--- a/test/files/neg/exhausting.check
+++ b/test/files/neg/exhausting.check
@@ -2,7 +2,7 @@ exhausting.scala:20: error: match is not exhaustive!
missing combination * Nil
def fail1[T](xs: List[T]) = xs match {
- ^
+ ^
exhausting.scala:24: error: match is not exhaustive!
missing combination Nil
@@ -17,7 +17,7 @@ exhausting.scala:31: error: match is not exhaustive!
missing combination Bar2 Bar2
def fail4[T <: AnyRef](xx: (Foo[T], Foo[T])) = xx match {
- ^
+ ^
exhausting.scala:36: error: match is not exhaustive!
missing combination Bar1 Bar2
missing combination Bar1 Bar3
@@ -25,5 +25,5 @@ missing combination Bar2 Bar1
missing combination Bar2 Bar2
def fail5[T](xx: (Foo[T], Foo[T])) = xx match {
- ^
+ ^
5 errors found
diff --git a/test/files/neg/names-defaults-neg.check b/test/files/neg/names-defaults-neg.check
index 5d409f18a8..d2bd2d123b 100644
--- a/test/files/neg/names-defaults-neg.check
+++ b/test/files/neg/names-defaults-neg.check
@@ -1,4 +1,4 @@
-names-defaults-neg.scala:65: error: not enough arguments for method apply: (a: Int,b: String)(c: Int*)Fact in object Fact.
+names-defaults-neg.scala:65: error: not enough arguments for method apply: (a: Int, b: String)(c: Int*)Fact in object Fact.
Unspecified value parameter b.
val fac = Fact(1)(2, 3)
^
@@ -40,8 +40,8 @@ names-defaults-neg.scala:26: error: Int does not take parameters
test3(b = 3, a = 1)(3)
^
names-defaults-neg.scala:35: error: ambiguous reference to overloaded definition,
-both method f in object t1 of type (b: String,a: Int)java.lang.String
-and method f in object t1 of type (a: Int,b: String)java.lang.String
+both method f in object t1 of type (b: String, a: Int)java.lang.String
+and method f in object t1 of type (a: Int, b: String)java.lang.String
match argument types (b: java.lang.String,a: Int)
t1.f(b = "dkljf", a = 1)
^
@@ -59,7 +59,7 @@ match argument types (Int)
^
names-defaults-neg.scala:49: error: ambiguous reference to overloaded definition,
both method g in object t7 of type (a: B)java.lang.String
-and method g in object t7 of type (a: C,b: Int*)java.lang.String
+and method g in object t7 of type (a: C, b: Int*)java.lang.String
match argument types (C)
t7.g(new C()) // ambigous reference
^
@@ -73,19 +73,19 @@ names-defaults-neg.scala:55: error: when using named arguments, the vararg param
test5(b = "dlkj")
^
names-defaults-neg.scala:61: error: ambiguous reference to overloaded definition,
-both method f in object t8 of type (b: String,a: Int)java.lang.String
-and method f in object t8 of type (a: Int,b: java.lang.Object)java.lang.String
+both method f in object t8 of type (b: String, a: Int)java.lang.String
+and method f in object t8 of type (a: Int, b: java.lang.Object)java.lang.String
match argument types (a: Int,b: java.lang.String) and expected result type Any
println(t8.f(a = 0, b = "1")) // ambigous reference
^
-names-defaults-neg.scala:69: error: wrong number of arguments for <none>: (x: Int,y: String)A1
+names-defaults-neg.scala:69: error: wrong number of arguments for <none>: (x: Int, y: String)A1
A1() match { case A1(_) => () }
^
names-defaults-neg.scala:76: error: no type parameters for method test4: (x: T[T[List[T[X forSome { type X }]]]])T[T[List[T[X forSome { type X }]]]] exist so that it can be applied to arguments (List[Int])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : List[Int]
- required: ?T[ ?T[ List[?T[ X forSome { type X } ]] ] ]
+ required: ?T[?T[List[?T[X forSome { type X }]]]]
Error occurred in an application involving default arguments.
test4()
^
diff --git a/test/files/neg/patmatexhaust.check b/test/files/neg/patmatexhaust.check
index 83c4279b0a..8aa9238d2e 100644
--- a/test/files/neg/patmatexhaust.check
+++ b/test/files/neg/patmatexhaust.check
@@ -1,37 +1,38 @@
-patmatexhaust.scala:7: warning: match is not exhaustive!
+patmatexhaust.scala:7: error: match is not exhaustive!
missing combination Baz
def ma1(x:Foo) = x match {
^
-patmatexhaust.scala:11: warning: match is not exhaustive!
+patmatexhaust.scala:11: error: match is not exhaustive!
missing combination Bar
def ma2(x:Foo) = x match {
^
-patmatexhaust.scala:23: warning: match is not exhaustive!
+patmatexhaust.scala:23: error: match is not exhaustive!
missing combination Kult Kult
missing combination Qult Qult
def ma3(x:Mult) = (x,x) match { // not exhaustive
- ^
-patmatexhaust.scala:49: warning: match is not exhaustive!
+ ^
+patmatexhaust.scala:49: error: match is not exhaustive!
missing combination Gp
missing combination Gu
def ma4(x:Deep) = x match { // missing cases: Gu, Gp
^
-patmatexhaust.scala:53: warning: match is not exhaustive!
+patmatexhaust.scala:53: error: match is not exhaustive!
missing combination Gp
def ma5(x:Deep) = x match { // Gp
^
-patmatexhaust.scala:75: warning: match is not exhaustive!
+patmatexhaust.scala:59: error: match is not exhaustive!
+missing combination Nil
+
+ def ma6() = List(1,2) match { // give up
+ ^
+patmatexhaust.scala:75: error: match is not exhaustive!
missing combination B
def ma9(x: B) = x match {
^
-patmatexhaust.scala:92: error: unreachable code
- case 1 =>
- ^
-6 warnings found
-one error found
+7 errors found
diff --git a/test/files/neg/patmatexhaust.flags b/test/files/neg/patmatexhaust.flags
new file mode 100644
index 0000000000..e8fb65d50c
--- /dev/null
+++ b/test/files/neg/patmatexhaust.flags
@@ -0,0 +1 @@
+-Xfatal-warnings \ No newline at end of file
diff --git a/test/files/neg/patmatexhaust.scala b/test/files/neg/patmatexhaust.scala
index b172df8740..d49c4b207b 100644
--- a/test/files/neg/patmatexhaust.scala
+++ b/test/files/neg/patmatexhaust.scala
@@ -56,12 +56,12 @@ class TestSealedExhaustive { // compile only
case Ga =>
}
- def ma6 = List(1,2) match { // give up
+ def ma6() = List(1,2) match { // give up
case List(1,2) =>
case x :: xs =>
}
- def ma7 = List(1,2) match { //exhaustive
+ def ma7() = List(1,2) match { //exhaustive
case 1::2::Nil =>
case _ =>
}
@@ -86,10 +86,4 @@ class TestSealedExhaustive { // compile only
case C4() => true
case C2 | C6 => true
}
-
- def redundant = 1 match { // include this otherwise script won't test this in files/neg
- case 1 =>
- case 1 =>
- }
-
}
diff --git a/test/files/neg/t2910.check b/test/files/neg/t2910.check
index afff73ec08..ff190122d6 100644
--- a/test/files/neg/t2910.check
+++ b/test/files/neg/t2910.check
@@ -13,4 +13,4 @@ t2910.scala:30: error: forward reference extends over definition of value x
t2910.scala:34: error: forward reference extends over definition of variable x
lazy val f: Int = g
^
-5 errors found \ No newline at end of file
+5 errors found
diff --git a/test/files/neg/t2910.scala b/test/files/neg/t2910.scala
index 1c7ba54971..b772ee4d43 100644
--- a/test/files/neg/t2910.scala
+++ b/test/files/neg/t2910.scala
@@ -5,13 +5,13 @@ object Junk {
ret
}
- def test2 {
+ def test2() {
println(s.length)
val z = 0
lazy val s = "abc"
}
- def test4 {
+ def test4() {
lazy val x = {
x
val z = 0
diff --git a/test/files/neg/t3115.check b/test/files/neg/t3115.check
index 3da8c8d1c6..c128ff5f3f 100644
--- a/test/files/neg/t3115.check
+++ b/test/files/neg/t3115.check
@@ -1,11 +1,11 @@
t3115.scala:6: error: object Math in object sc is deprecated:
println(sc.Math)
^
-t3115.scala:7: error: object Math in package scala is deprecated: use the scala.math package object instead.
+t3115.scala:7: error: object Math is deprecated: use the scala.math package object instead.
(Example package object usage: scala.math.Pi )
println(scala.Math)
^
-t3115.scala:8: error: object Math in package scala is deprecated: use the scala.math package object instead.
+t3115.scala:8: error: object Math is deprecated: use the scala.math package object instead.
(Example package object usage: scala.math.Pi )
scala.Math.Pi
^
diff --git a/test/files/neg/t3774.check b/test/files/neg/t3774.check
index ea35c50541..cce2d7076c 100644
--- a/test/files/neg/t3774.check
+++ b/test/files/neg/t3774.check
@@ -1,6 +1,6 @@
t3774.scala:4: error: overloaded method value ++ with alternatives:
[B1 >: List[Int]](xs: scala.collection.GenTraversableOnce[((Int, Int), B1)])scala.collection.immutable.Map[(Int, Int),B1] <and>
- [B >: ((Int, Int), List[Int]),That](that: scala.collection.GenTraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Map[(Int, Int),List[Int]],B,That])That
+ [B >: ((Int, Int), List[Int]), That](that: scala.collection.GenTraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Map[(Int, Int),List[Int]],B,That])That
cannot be applied to (scala.collection.immutable.IndexedSeq[((Int, Int), scala.collection.immutable.Range.Inclusive)])
Map[(Int,Int),List[Int]]() ++ (for(x <- 0 to 1 ; y <- 0 to 1) yield {(x,y)-> (0 to 1)})
^
diff --git a/test/files/neg/t4457_1.check b/test/files/neg/t4457_1.check
new file mode 100644
index 0000000000..c6b83c6ce5
--- /dev/null
+++ b/test/files/neg/t4457_1.check
@@ -0,0 +1,7 @@
+t4457_1.scala:27: error: ambiguous reference to overloaded definition,
+both method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NZ[A])ImplicitConvAmbiguity2.AA[Float]
+and method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NE[A])ImplicitConvAmbiguity2.AA[A]
+match argument types (Float)
+ val x = aFunc(4F)
+ ^
+one error found
diff --git a/test/files/neg/t4457_1.scala b/test/files/neg/t4457_1.scala
new file mode 100644
index 0000000000..11f12379f6
--- /dev/null
+++ b/test/files/neg/t4457_1.scala
@@ -0,0 +1,33 @@
+object ImplicitConvAmbiguity2 {
+
+ class N[T]
+ class NE[T] extends N[T]
+ class NN[T] extends N[T]
+ class NQ[T] extends N[T]
+ class NZ[T] extends N[T]
+ class AA[A]
+ class BB[A]
+
+ implicit def conv1(i: Float) = new NE[Float]
+ implicit def conv3(op: AA[java.util.TooManyListenersException]) = new N[java.util.TooManyListenersException]
+ implicit def conv4(op: AA[Float]) = new N[Float]
+ implicit def conv7(i: Float) = new NZ[Float]
+ implicit def conv5(e: BB[java.util.GregorianCalendar]) = new N[java.util.GregorianCalendar]
+
+ // These two will be in conflict in typeMe1
+ def aFunc[A](a: NE[A]) = new AA[A]
+ def aFunc[A](a: NZ[A]) = new AA[Float]
+
+ def aFunc[A](a: NN[A]) = new BB[A]
+ def aFunc[A](a: NQ[A]) = new BB[A]
+
+ def bFunc[T](e1: N[T]) = {}
+
+ def typeMe1 {
+ val x = aFunc(4F)
+ bFunc(x)
+ }
+ def typeMe2 {
+ bFunc(aFunc(4F))
+ }
+}
diff --git a/test/files/neg/t4457_2.check b/test/files/neg/t4457_2.check
new file mode 100644
index 0000000000..770a355395
--- /dev/null
+++ b/test/files/neg/t4457_2.check
@@ -0,0 +1,13 @@
+t4457_2.scala:27: error: ambiguous reference to overloaded definition,
+both method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NZ[A])ImplicitConvAmbiguity2.AA[A]
+and method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NE[A])ImplicitConvAmbiguity2.AA[A]
+match argument types (Float)
+ val x = aFunc(4F)
+ ^
+t4457_2.scala:31: error: ambiguous reference to overloaded definition,
+both method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NZ[A])ImplicitConvAmbiguity2.AA[A]
+and method aFunc in object ImplicitConvAmbiguity2 of type [A](a: ImplicitConvAmbiguity2.NE[A])ImplicitConvAmbiguity2.AA[A]
+match argument types (Float)
+ bFunc(aFunc(4F))
+ ^
+two errors found
diff --git a/test/files/neg/t4457_2.scala b/test/files/neg/t4457_2.scala
new file mode 100644
index 0000000000..f3a170f1f2
--- /dev/null
+++ b/test/files/neg/t4457_2.scala
@@ -0,0 +1,33 @@
+object ImplicitConvAmbiguity2 {
+
+ class N[T]
+ class NE[T] extends N[T]
+ class NN[T] extends N[T]
+ class NQ[T] extends N[T]
+ class NZ[T] extends N[T]
+ class AA[A]
+ class BB[A]
+
+ implicit def conv1(i: Float) = new NE[Float]
+ implicit def conv3(op: AA[java.util.TooManyListenersException]) = new N[java.util.TooManyListenersException]
+ implicit def conv4(op: AA[Float]) = new N[Float]
+ implicit def conv7(i: Float) = new NZ[Float]
+ implicit def conv5(e: BB[java.util.GregorianCalendar]) = new N[java.util.GregorianCalendar]
+
+ def aFunc[A](a: NE[A]) = new AA[A]
+ def aFunc[A](a: NZ[A]) = new AA[A]
+
+ def aFunc[A](a: NN[A]) = new BB[A]
+
+ def aFunc[A](a: NQ[A]) = new BB[A]
+
+ def bFunc[T](e1: N[T]) = {}
+
+ def typeMe2 {
+ val x = aFunc(4F)
+ bFunc(x)
+ }
+ def typeMe1 {
+ bFunc(aFunc(4F))
+ }
+}
diff --git a/test/files/neg/tailrec.scala b/test/files/neg/tailrec.scala
index a77f439cfe..e0ebde9863 100644
--- a/test/files/neg/tailrec.scala
+++ b/test/files/neg/tailrec.scala
@@ -10,7 +10,7 @@ object Winners {
@tailrec def loopsucc1(x: Int): Int = loopsucc1(x - 1)
@tailrec def loopsucc2[T](x: Int): Int = loopsucc2[T](x - 1)
- def ding {
+ def ding() {
object dong {
@tailrec def loopsucc3(x: Int): Int = loopsucc3(x)
}
diff --git a/test/files/neg/tcpoly_infer_ticket1162.check b/test/files/neg/tcpoly_infer_ticket1162.check
index 03334222c1..67b79e7f3c 100644
--- a/test/files/neg/tcpoly_infer_ticket1162.check
+++ b/test/files/neg/tcpoly_infer_ticket1162.check
@@ -1,4 +1,4 @@
-tcpoly_infer_ticket1162.scala:6: error: wrong number of type parameters for method apply: [A,B,F[_]]()Test.Lift[A,B,F] in object Lift
+tcpoly_infer_ticket1162.scala:6: error: wrong number of type parameters for method apply: [A, B, F[_]]()Test.Lift[A,B,F] in object Lift
def simplify[A,B]: Expression[A,B] = Lift[A,B]()
^
one error found
diff --git a/test/files/neg/varargs.check b/test/files/neg/varargs.check
index 1352dd968c..676a611341 100644
--- a/test/files/neg/varargs.check
+++ b/test/files/neg/varargs.check
@@ -1,10 +1,10 @@
-varargs.scala:16: error: A method with a varargs annotation produces a forwarder method with the same signature (a: Int,b: Array[java.lang.String])Int as an existing method.
+varargs.scala:16: error: A method with a varargs annotation produces a forwarder method with the same signature (a: Int, b: Array[java.lang.String])Int as an existing method.
@varargs def v1(a: Int, b: String*) = a + b.length
^
varargs.scala:19: error: A method without repeated parameters cannot be annotated with the `varargs` annotation.
@varargs def nov(a: Int) = 0
^
-varargs.scala:21: error: A method with a varargs annotation produces a forwarder method with the same signature (a: Int,b: Array[java.lang.String])Int as an existing method.
+varargs.scala:21: error: A method with a varargs annotation produces a forwarder method with the same signature (a: Int, b: Array[java.lang.String])Int as an existing method.
@varargs def v2(a: Int, b: String*) = 0
^
-three errors found \ No newline at end of file
+three errors found
diff --git a/test/files/pos/t4457_1.scala b/test/files/pos/t4457_1.scala
new file mode 100644
index 0000000000..32edd6cfdc
--- /dev/null
+++ b/test/files/pos/t4457_1.scala
@@ -0,0 +1,26 @@
+object ImplicitConvAmbiguity2 {
+
+ class N[T]
+ class NE[T] extends N[T]
+ class NN[T] extends N[T]
+ class AA[A]
+ class BB[A]
+
+ implicit def conv1(i: Float) = new NE[Float]
+ implicit def conv3(op: AA[java.util.TooManyListenersException]) = new N[java.util.TooManyListenersException]
+ implicit def conv4(op: AA[Float]) = new N[Float]
+ implicit def conv5(e: BB[java.util.GregorianCalendar]) = new N[java.util.GregorianCalendar]
+
+ def aFunc[A](a: NE[A]) = new AA[A]
+ def aFunc[A](a: NN[A]) = new BB[A]
+
+ def bFunc[T](e1: N[T]) = {}
+
+ def typeMe1 {
+ val x = aFunc(4F)
+ bFunc(x)
+ }
+ def typeMe2 {
+ bFunc(aFunc(4F))
+ }
+}
diff --git a/test/files/res/bug722/Parser.scala b/test/files/res/bug722/Parser.scala
index 6d9739ed04..7f84cb2b63 100644
--- a/test/files/res/bug722/Parser.scala
+++ b/test/files/res/bug722/Parser.scala
@@ -2,7 +2,7 @@
package bug722;
trait Parser {
trait Link {
- def foo = {}
+ def foo() = {}
}
}
diff --git a/test/files/res/bug722/ScanBased.scala b/test/files/res/bug722/ScanBased.scala
index fcb853f96d..4793a04914 100644
--- a/test/files/res/bug722/ScanBased.scala
+++ b/test/files/res/bug722/ScanBased.scala
@@ -1,10 +1,10 @@
package bug722;
trait ScanBased extends Parser {
trait AdjacentLink extends Link {
- override def foo = super.foo;
+ override def foo() = super.foo;
}
trait WhitespaceLink extends AdjacentLink {
- override def foo = super.foo;
+ override def foo() = super.foo;
}
}
diff --git a/test/files/res/bug785/ScalaNewTyper.scala b/test/files/res/bug785/ScalaNewTyper.scala
index fb955572ed..d55d60a8d0 100644
--- a/test/files/res/bug785/ScalaNewTyper.scala
+++ b/test/files/res/bug785/ScalaNewTyper.scala
@@ -2,7 +2,7 @@ package bug785;
trait ScalaNewTyper {
private var typed : String = null;
trait HasSymbol {
- protected def foo : Unit = {}
+ protected def foo() : Unit = {}
}
trait HasArgsTypeParametersImpl extends HasSymbol {
private var argss : List[List[String]] = Nil;
diff --git a/test/files/run/io-position.check b/test/files/run/io-position.check
new file mode 100644
index 0000000000..09f743d750
--- /dev/null
+++ b/test/files/run/io-position.check
Binary files differ
diff --git a/test/files/run/io-position.scala b/test/files/run/io-position.scala
new file mode 100644
index 0000000000..7e570ea29e
--- /dev/null
+++ b/test/files/run/io-position.scala
@@ -0,0 +1,13 @@
+object Test {
+ Console.setErr(Console.out)
+
+ def main(args: Array[String]): Unit = {
+ try {
+ xml.parsing.ConstructingParser.fromSource(io.Source.fromString("<foo>"), false).document()
+ } catch {
+ case e:Exception => println(e.getMessage)
+ }
+ }
+
+}
+
diff --git a/test/files/run/patmat-exprs.check b/test/files/run/patmat-exprs.check
new file mode 100644
index 0000000000..b6df9385fa
--- /dev/null
+++ b/test/files/run/patmat-exprs.check
@@ -0,0 +1 @@
+((5 + 10) + 300)
diff --git a/test/files/run/patmat-exprs.scala b/test/files/run/patmat-exprs.scala
new file mode 100644
index 0000000000..f502a14832
--- /dev/null
+++ b/test/files/run/patmat-exprs.scala
@@ -0,0 +1,579 @@
+import runtime.ScalaRunTime
+
+object Test {
+ val p = new Pattern { }
+ import p._
+ implicit object IntOps extends NumericOps[Int] {
+ def zero = 0
+ def one = 1
+
+ def add(a: Int, b: Int): Int = a + b
+ def sub(a: Int, b: Int): Int = a - b
+ def mul(a: Int, b: Int): Int = a * b
+ def mul(a: Int, b: Double): Int = (a * b).toInt
+ def div(a: Int, b: Int): Int = a / b
+ def div(a: Int, b: Double): Int = (a / b).toInt
+ def similar(a: Int, b: Int): Boolean = a == b
+ def abs(a: Int): Double = math.abs(a).toDouble
+ def sqr(a: Int): Int = a * a
+ def sqrt(a: Int): Int = math.sqrt(a).toInt
+ def log(a: Int): Int = math.log(a).toInt
+ def exp(a: Int): Int = math.exp(a).toInt
+ def sin(a: Int): Int = math.sin(a).toInt
+ def cos(a: Int): Int = math.cos(a).toInt
+
+ def fromDouble(a: Double): Int = a.toInt
+ def fromInt(a: Int): Int = a
+ }
+
+ def main(args: Array[String]): Unit = {
+ println((5: Expr[Int]) + 10 + 15 * 20)
+ }
+}
+
+
+trait Pattern {
+ // For trying out 2.7.7
+ //
+ // type Numeric[T]
+ // import java.io.Serializable
+ //
+ // implicit def compat27a[T](x: Iterable[T]) = new {
+ // def iterator: Iterator[T] = x.elements
+ // def sum: Int = 5
+ // def collect[U](pf: PartialFunction[T, U]): Iterable[U] = x map pf
+ // }
+
+ /** Function that returns object of the same type it was passed */
+ trait EndoFunction[-A] {
+ def apply[B <: A](x: B): B
+ }
+
+ /** Allows for smart construction of EndoFunction from an ordinary function */
+ object EndoFunction {
+ def apply[A](f: A => A): EndoFunction[A] = new EndoFunction[A] {
+ def apply[B <: A](x: B): B = f(x).asInstanceOf[B]
+ }
+ }
+
+ trait NumericOps[T] extends Serializable {
+ def zero: T
+ def one: T
+ def two = add(one, one)
+ def three = add(two, one)
+
+ def add(a: T, b: T): T
+ def add(a: T, b: T, c: T): T = add(a, add(b, c))
+ def sub(a: T, b: T): T
+ def mul(a: T, b: T): T
+ def mul(a: T, b: Double): T
+ def div(a: T, b: T): T
+ def div(a: T, b: Double): T
+ def similar(a: T, b: T): Boolean
+ def neg(a: T) = sub(zero, a)
+ def abs(a: T): Double
+ def sqr(a: T): T
+ def sqrt(a: T): T
+ def log(a: T): T
+ def exp(a: T): T
+ def sin(a: T): T
+ def cos(a: T): T
+ def tan(a: T): T = div(sin(a), cos(a))
+
+ def fromDouble(a: Double): T
+ def fromInt(a: Int): T
+
+ def sum(terms: Iterable[T]) = terms.foldLeft(zero)(add)
+ def sum(terms: Iterator[T]) = terms.foldLeft(zero)(add)
+ def product(terms: Iterable[T]) = terms.foldLeft(one)(mul)
+ def product(terms: Iterator[T]) = terms.foldLeft(one)(mul)
+
+
+ def similar(a: Iterable[T], b: Iterable[T]): Boolean = {
+ val i1 = a.iterator
+ val i2 = b.iterator
+ while (i1.hasNext && i2.hasNext)
+ if (!similar(i1.next, i2.next))
+ return false;
+ true;
+ }
+ }
+
+ /**
+ * Simple expression interpreter with some basic symbolic manipulation.
+ * Able to evaluate derivatives.
+ */
+
+ trait Expr[T] {
+
+ import Expr._
+
+ /** Evaluates value of the expression. */
+ def eval(context: Any => Any): T
+
+ /** Symbolically calculates derivative of this expression. Does not simplify it. */
+ def derivative(variable: Var[T]): Expr[T]
+
+ /** Returns arguments of this operator */
+ def args: Iterable[Expr[_]]
+
+ /** Transforms arguments of this operator by applying given function. */
+ def mapArgs(f: EndoFunction[Expr[_]]): Expr[T]
+
+ /** Transforms this operator and its arguments by applying given function */
+ def map(f: EndoFunction[Expr[_]]): Expr[T] =
+ f(mapArgs(EndoFunction[Expr[_]](x => x.map(f))))
+
+ /** Folds all subexpressions in this expression in depth-first order */
+ def fold[A](v: A)(f: (A, Expr[_]) => A): A =
+ f(args.foldLeft(v) { (a, b) => b.fold(a)(f) }, this)
+
+ /** Replaces all occurrences of one subexpression with another one */
+ def replace(from: Expr[_], to: Expr[_]): Expr[T] =
+ map(EndoFunction[Expr[_]](x => if (x == from) to else x))
+
+ /** Returns true if this expression contains given subexpression */
+ def contains(s: Expr[_]): Boolean =
+ this == s || args.exists(_ contains s)
+
+ /** Counts number of occurrences of the given subexpression. */
+ def count(condition: Expr[_] => Boolean): Int =
+ (if (condition(this)) 1 else 0) + args.map(_.count(condition)).sum
+
+ /** Executes some code for every subexpression in the depth-first order */
+ def foreach[U](block: Expr[_] => U): Unit = {
+ args.foreach(_.foreach(block))
+ block(this)
+ }
+
+ /** Collects subexpressions successfully transformed by the given partial function, in depth-first order. */
+ def collect[U](f: PartialFunction[Expr[_], U]): List[U] = {
+ val a = args.flatMap(_.collect(f)).toList
+ if (f.isDefinedAt(this)) (f(this) :: a) else a
+ }
+
+ def leaves: List[Leaf[T]] = collect { case l: Leaf[T] => l }
+
+ def + (other: Expr[T])(implicit n: NumericOps[T]) = Add(List(this, other))
+ def - (other: Expr[T])(implicit n: NumericOps[T]) = Sub(this, other)
+ def * (other: Expr[T])(implicit n: NumericOps[T]) = Mul(this, other)
+ def / (other: Expr[T])(implicit n: NumericOps[T]) = Div(this, other)
+
+ def unary_- (implicit n: NumericOps[T]) = Neg(this)
+ def sqr(implicit n: NumericOps[T]) = Sqr(this)
+
+ def < (other: Expr[T])(implicit n: NumericOps[T], o: Ordering[T]) = LT(this, other)
+ def <= (other: Expr[T])(implicit n: NumericOps[T], o: Ordering[T]) = LE(this, other)
+ def > (other: Expr[T])(implicit n: NumericOps[T], o: Ordering[T]) = GT(this, other)
+ def >= (other: Expr[T])(implicit n: NumericOps[T], o: Ordering[T]) = GE(this, other)
+
+ private def generalize(implicit num: NumericOps[T]): Expr[T] = {
+ this match {
+ case Add2(a, b) => Add(a :: b :: Nil)
+ case Add3(a, b, c) => Add(a :: b :: c :: Nil)
+ case Sub(a, b) => Add(a :: Neg(b) :: Nil)
+ case Add(x) => Add(x flatMap {
+ case Neg(Add(y)) => y.map(Neg(_))
+ case Add(y) => y
+ case y => y :: Nil
+ })
+ case x => x
+ }
+ }
+
+ private def specialize(implicit num: NumericOps[T]): Expr[T] = {
+ this match {
+ case Add(Seq(a, b)) => Add2(a, b)
+ case Add(Seq(a, b, c)) => Add3(a, b, c)
+ case x => x
+ }
+ }
+
+ /** Eliminates common negated components of a sum */
+ private def reduceComponents(components: List[Expr[T]])(implicit num: NumericOps[T]): List[Expr[T]] = {
+ val pairs =
+ for (a <- components; b <- components if Neg(a) == b || a == Neg(b))
+ yield (a, b)
+ pairs.foldLeft(components) { (c, pair) =>
+ if (c.contains(pair._1) && c.contains(pair._2))
+ c.diff(pair._1 :: pair._2 :: Nil)
+ else
+ c
+ }
+ }
+
+
+ /** Simplifies this expression to make evaluation faster and more accurate.
+ * Performs only one pass. */
+ private def reduce(implicit num: NumericOps[T]): Expr[T] = {
+ this match {
+ case Add(Seq(Neg(x), Neg(y), Neg(z))) => Neg(Add(List(x, y, z)))
+ case Add(Seq(Mul(x, y), z)) if (x == z) => Mul(x, Add(List(y, One[T])))
+ case Add(Seq(Mul(x, y), z)) if (y == z) => Mul(y, Add(List(z, One[T])))
+ case Add(Seq(Mul(x, y), Mul(u, w))) if (x == u) => Mul(x, Add(List(y, w)))
+ case Add(Seq(Mul(x, y), Mul(u, w))) if (y == w) => Mul(y, Add(List(x, u)))
+ case Add(Seq(Add(x), Add(y))) => Add(x.toList ::: y.toList).simplify
+ case Add(Seq(Add(x), y)) => Add(y :: x.toList).simplify
+ case Add(Seq(x, Add(y))) => Add(x :: y.toList).simplify
+ case Add(x) => {
+ val noZeros = x.filter(_ != Zero[T])
+ val noOnes = noZeros.map { case y: One[_] => Const(num.one); case y => y }
+ val constant = num.sum(noOnes.collect { case c: Const[T] => c.value })
+ val rest = noOnes.filter(x => !x.isInstanceOf[Const[_]]).toList
+ val reduced = reduceComponents(rest)
+ val args = if (num.similar(constant, num.zero)) reduced else reduced ::: Const(constant) :: Nil
+ args.size match {
+ case 0 => Zero[T]
+ case 1 => args.head
+ case 2 => Add2(args(0), args(1))
+ case 3 => Add3(args(0), args(1), args(2))
+ case _ => Add(args)
+ }
+ }
+ case Sub(x: Zero[_], y) => Neg(y)
+ case Sub(x, y: Zero[_]) => x
+ case Sub(x, y) if x == y => Zero[T]
+ case Sub(Mul(x, y), z) if (x == z) => Mul(x, Sub(y, One[T]))
+ case Sub(Mul(x, y), z) if (y == z) => Mul(y, Sub(z, One[T]))
+ case Sub(Mul(x, y), Mul(u, w)) if (x == u) => Mul(x, Sub(y, w))
+ case Sub(Mul(x, y), Mul(u, w)) if (y == w) => Mul(y, Sub(x, u))
+ case Mul(x: Zero[_], y) => Zero[T]
+ case Mul(x, y: Zero[_]) => Zero[T]
+ case Mul(x: One[_], y) => y
+ case Mul(x, y: One[_]) => x
+ case Mul(Neg(x: One[_]), y) => Neg(y)
+ case Mul(x, Neg(y: One[_])) => Neg(x)
+
+ case Mul(x, y) if (x == y) => Sqr(x)
+ case Div(x: Zero[_], y) => Zero[T] // warning: possibly extends domain
+ case Div(x, y: One[_]) => x
+ case Div(Sqr(x), y) if x == y => x
+ case Div(Mul(x, y), z) if (x == z) => y
+ case Div(Mul(x, y), z) if (y == z) => y
+ case Div(Mul(Mul(x, y), z), w) if (x == w) => Mul(y, z)
+ case Div(Mul(Mul(x, y), z), w) if (y == w) => Mul(x, z)
+ case Div(Mul(z, Mul(x, y)), w) if (x == w) => Mul(y, z)
+ case Div(Mul(z, Mul(x, y)), w) if (y == w) => Mul(x, z)
+ case Div(Mul(x, y), Mul(u, w)) if (x == u) => Div(y, w)
+ case Div(Mul(x, y), Mul(u, w)) if (y == w) => Div(x, u)
+ case Div(x: One[_], y) => Inv(y)
+ case Div(x, Sqr(y)) if x == y => Inv(y)
+ case Div(Mul(x, y), Sqr(Mul(u, w))) if x == u && y == w => Inv(Mul(x, y))
+ case Div(x, y) if x == y => One[T]
+
+ case Mul(Neg(a), Neg(b)) => Mul(a, b)
+ case Div(Neg(a), Neg(b)) => Div(a, b)
+
+ case Neg(x: Zero[_]) => Zero[T]
+ case Neg(x: One[_]) => Const(num.neg(num.one))
+ case Sub(Const(x), Const(y)) => const(num.sub(x, y))
+ case Mul(Const(x), Const(y)) => const(num.mul(x, y))
+ case Div(Const(x), Const(y)) => const(num.div(x, y))
+ case Neg(Const(x)) => const(num.neg(x))
+ case Sqr(Const(x)) => const(num.sqr(x))
+
+ case Mul(Const(x), Mul(Const(y), z)) => Mul(const(num.mul(x, y)), z)
+ case Mul(Const(x), Mul(y, Const(z))) => Mul(const(num.mul(x, z)), y)
+ case Mul(Mul(Const(y), z), Const(x)) => Mul(const(num.mul(x, y)), z)
+ case Mul(Mul(y, Const(z)), Const(x)) => Mul(const(num.mul(x, z)), y)
+
+ case Const(x) if x == num.one => One[T]
+ case Const(x) if x == num.zero => Zero[T]
+
+ case Sub(x, Neg(y)) => Add(List(x, y))
+ case Sub(Neg(x), y) => Neg(Add(List(x, y)))
+ case Neg(Neg(x)) => x
+ case Neg(Mul(a: Const[T], x)) => Mul(const(num.neg(a.value)), x)
+ case Neg(Mul(x, a: Const[T])) => Mul(const(num.neg(a.value)), x)
+ case Neg(Div(Neg(a), b)) => Div(a, b)
+ case Neg(Div(a, Neg(b))) => Div(a, b)
+ case Neg(Mul(Neg(a), b)) => Mul(a, b)
+ case Neg(Mul(a, Neg(b))) => Mul(a, b)
+
+ case Log(Exp(x)) => x
+ case x => x
+ }
+ }
+
+ private def optimizeWith(f: Expr[T] => Expr[T]): Expr[T] = {
+ f(mapArgs(EndoFunction[Expr[_]](
+ a => a match { case x: Expr[T] => x.optimizeWith(f) }
+ )))
+ }
+
+ /** Simplifies this expression to make evaluation faster and more accurate.*/
+ def simplify(implicit num: NumericOps[T]): Expr[T] = {
+ val a1 = optimizeWith(_.generalize)
+ val a2 = a1.optimizeWith(_.generalize)
+ val b = a2.optimizeWith(_.reduce)
+ val c = b.optimizeWith(_.reduce)
+ val d = c.optimizeWith(_.specialize)
+ d
+ }
+ }
+
+
+ trait Leaf[T] extends Expr[T] {
+ val args = List[Expr[T]]()
+ def mapArgs(f: EndoFunction[Expr[_]]) = this
+ }
+
+ trait OneArg[T] extends Expr[T] {
+ val expr: Expr[T]
+ val args = List(expr)
+ }
+
+
+ trait TwoArg[T] extends Expr[T] {
+ val left: Expr[T]
+ val right: Expr[T]
+ val args = List(left, right)
+ }
+
+ trait ManyArg[T] extends Expr[T]
+
+ /** Marker trait for specifying that you can safely divide by this */
+ trait NonZero[T] extends Expr[T]
+
+ case class Const[T](value: T)(implicit num: NumericOps[T]) extends Leaf[T] with NonZero[T] {
+ def derivative(variable: Var[T]) = Zero[T]
+ def eval(f: Any => Any) = value
+ override def toString = value.toString
+ }
+
+
+ case class Zero[T] (implicit num: NumericOps[T]) extends Leaf[T] {
+ def derivative(variable: Var[T]) = Zero[T]
+ def eval(f: Any => Any) = num.zero
+ override def toString = "0"
+ }
+
+ case class One[T] (implicit num: NumericOps[T]) extends Leaf[T] {
+ def derivative(variable: Var[T]) = Zero[T]
+ def eval(f: Any => Any) = num.one
+ override def toString = "1"
+ }
+
+ abstract class Var[T](implicit num: NumericOps[T]) extends Leaf[T] {
+ def derivative(variable: Var[T]) = if (variable == this) One[T] else Zero[T]
+ def eval(f: Any => Any) = f(this).asInstanceOf[T]
+ }
+
+ case class NamedVar[T](name: String)(implicit num: NumericOps[T]) extends Var[T] {
+ override lazy val hashCode = ScalaRunTime._hashCode(this)
+ override def toString = name
+ }
+
+ case class Add[T](args: Iterable[Expr[T]])(implicit num: NumericOps[T]) extends ManyArg[T] {
+ def eval(f: Any => Any) = num.sum(for (i <- args.iterator) yield i.eval(f))
+ def derivative(v: Var[T]) = Add(args.map(_.derivative(v)))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Add(args map (x => f(x)))
+ override def toString = "(" + args.mkString(" + ") + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Add2[T](left: Expr[T], right: Expr[T])
+ (implicit num: NumericOps[T]) extends TwoArg[T] {
+ def eval(f: Any => Any) = num.add(left.eval(f), right.eval(f))
+ def derivative(v: Var[T]) = Add2(left.derivative(v), right.derivative(v))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Add2(f(left), f(right))
+ override def toString = "(" + left + " + " + right + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Add3[T](a1: Expr[T], a2: Expr[T], a3: Expr[T])
+ (implicit num: NumericOps[T]) extends ManyArg[T] {
+ val args = List(a1, a2, a3)
+ def eval(f: Any => Any) = num.add(a1.eval(f), a2.eval(f), a3.eval(f))
+ def derivative(v: Var[T]) = Add3(a1.derivative(v), a2.derivative(v), a3.derivative(v))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Add3(f(a1), f(a2), f(a3))
+ override def toString = "(" + a1 + " + " + a2 + " + " + a3 + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Sub[T](left: Expr[T], right: Expr[T])
+ (implicit num: NumericOps[T]) extends TwoArg[T] {
+ def derivative(v: Var[T]) = Sub(left.derivative(v), right.derivative(v))
+ def eval(f: Any => Any) = num.sub(left.eval(f), right.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Sub(f(left), f(right))
+ override def toString = "(" + left + " - " + right + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Neg[T](expr: Expr[T])
+ (implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Neg(expr.derivative(v))
+ def eval(f: Any => Any) = num.neg(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Neg(f(expr))
+ override def toString = "(-" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+
+ }
+
+ case class Mul[T](left: Expr[T], right: Expr[T])
+ (implicit num: NumericOps[T]) extends TwoArg[T] {
+ def derivative(v: Var[T]) =
+ Add(List(
+ Mul(left, right.derivative(v)),
+ Mul(right, left.derivative(v))))
+
+ def eval(f: Any => Any) = num.mul(left.eval(f), right.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Mul(f(left), f(right))
+ override def toString = "(" + left + " * " + right + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Div[T](left: Expr[T], right: Expr[T])
+ (implicit num: NumericOps[T]) extends TwoArg[T] {
+
+ // [f(x) / g(x)]' = [f(x) * 1 / g(x)]' = f'(x) * 1 / g(x) + f(x) * [1 / g(x)]' =
+ // f'(x) / g(x) + f(x) * [-1 / g(x) ^ 2] * g'(x) = (f'(x) * g(x) - f(x) * g'(x)) / g(x)^2
+ def derivative(v: Var[T]) =
+ Div(
+ Sub(
+ Mul(left.derivative(v), right),
+ Mul(left, right.derivative(v))),
+ Sqr(right)
+ )
+
+ def eval(f: Any => Any) = num.div(left.eval(f), right.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) =
+ Div(f(left), f(right))
+ override def toString = "(" + left + " / " + right + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Inv[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+
+ // [1 / f(x)]' = - f'(x) / f(x) ^ 2
+ def derivative(v: Var[T]) = Neg(Div(expr.derivative(v), Sqr(expr)))
+ def eval(f: Any => Any) = num.div(num.one, expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Inv(f(expr))
+ override def toString = "(1 / " + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Sqr[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ // [f(x) ^ 2]' = 2 * f(x) * f'(x)
+ def derivative(v: Var[T]) = Mul(Mul(Const(num.two), expr), expr.derivative(v))
+ def eval(f: Any => Any) = num.sqr(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Sqr(f(expr))
+ override def toString = expr + " ^ 2"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Log[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Div(expr.derivative(v), expr)
+ def eval(f: Any => Any) = num.log(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Log(f(expr))
+ override def toString = "log(" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Exp[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Mul(expr.derivative(v), Exp(expr))
+ def eval(f: Any => Any) = num.exp(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Exp(f(expr))
+ override def toString = "exp(" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ case class Sqrt[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Neg(Div(expr.derivative(v), Sqrt(expr)))
+ def eval(f: Any => Any) = num.sqrt(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Sqrt(f(expr))
+ override def toString = "sqrt(" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Sin[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Mul(expr.derivative(v), Cos(expr))
+ def eval(f: Any => Any) = num.sin(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Sin(f(expr))
+ override def toString = "sin(" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ case class Cos[T](expr: Expr[T])(implicit num: NumericOps[T]) extends OneArg[T] {
+ def derivative(v: Var[T]) = Neg(Mul(expr.derivative(v), Sin(expr)))
+ def eval(f: Any => Any) = num.cos(expr.eval(f))
+ def mapArgs(f: EndoFunction[Expr[_]]) = Cos(f(expr))
+ override def toString = "cos(" + expr + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+
+ abstract class Compare[T](left: Expr[T], right: Expr[T], cmp: (T, T) => Boolean)(implicit num: NumericOps[T])
+ extends Expr[Boolean] {
+ def derivative(v: Var[Boolean]) = throw new IllegalStateException("Derivative of Boolean not allowed")
+ def eval(f: Any => Any) = cmp(left.eval(f), right.eval(f))
+ val args = List(left, right)
+ }
+
+ case class LE[T](left: Expr[T], right: Expr[T])(implicit num: NumericOps[T], ord: Ordering[T])
+ extends Compare[T](left, right, ord.compare(_, _) <= 0) {
+ def mapArgs(f: EndoFunction[Expr[_]]) = LE(
+ f(left), f(right))
+ override def toString = left.toString + " <= " + right.toString
+ }
+
+ case class LT[T](left: Expr[T], right: Expr[T])(implicit num: NumericOps[T], ord: Ordering[T])
+ extends Compare[T](left, right, ord.compare(_, _) < 0) {
+ def mapArgs(f: EndoFunction[Expr[_]]) = LT(
+ f(left), f(right))
+ override def toString = left.toString + " < " + right.toString
+ }
+
+ case class GE[T](left: Expr[T], right: Expr[T])(implicit num: NumericOps[T], ord: Ordering[T])
+ extends Compare[T](left, right, ord.compare(_, _) >= 0) {
+ def mapArgs(f: EndoFunction[Expr[_]]) = GE(
+ f(left), f(right))
+ override def toString = left.toString + " >= " + right.toString
+ }
+
+ case class GT[T](left: Expr[T], right: Expr[T])(implicit num: NumericOps[T], ord: Ordering[T])
+ extends Compare[T](left, right, ord.compare(_, _) > 0) {
+ def mapArgs(f: EndoFunction[Expr[_]]) = GT(
+ f(left), f(right))
+ override def toString = left.toString + " > " + right.toString
+ }
+
+ case class IfElse[T <: Numeric[T]]
+ (condition: Expr[Boolean], left: Expr[T], right: Expr[T])(implicit num: NumericOps[T]) extends Expr[T] {
+
+ val args = List(condition, left, right)
+ def derivative(v: Var[T]) = IfElse(condition, left.derivative(v), right.derivative(v))
+ def eval(f: Any => Any) = if (condition.eval(f)) left.eval(f) else right.eval(f)
+ def mapArgs(f: EndoFunction[Expr[_]]) = IfElse(
+ f(condition).asInstanceOf[Expr[Boolean]],
+ f(left),
+ f(right))
+ override def toString = "if (" + condition + ")(" + left + ") else (" + right + ")"
+ override lazy val hashCode = ScalaRunTime._hashCode(this);
+ }
+
+ object Expr {
+ /** Creates a constant expression */
+ def const[T](value: T)(implicit num: NumericOps[T]): Leaf[T] =
+ if (num.zero == value) Zero[T]
+ else Const(value)
+
+ implicit def double2Constant[T](d: Double)(implicit num: NumericOps[T]): Leaf[T] =
+ const(num.fromDouble(d))
+
+ implicit def float2Constant[T](f: Float)(implicit num: NumericOps[T]): Leaf[T] =
+ const(num.fromDouble(f.toDouble))
+
+ implicit def int2Constant[T](i: Int)(implicit num: NumericOps[T]): Leaf[T] =
+ const(num.fromDouble(i.toDouble))
+
+ implicit def long2Constant[T](l: Long)(implicit num: NumericOps[T]): Leaf[T] =
+ const(num.fromDouble(l.toDouble))
+ }
+} \ No newline at end of file
diff --git a/test/files/run/t1500.check b/test/files/run/t1500.check
index 1032649f20..94a169333b 100644
--- a/test/files/run/t1500.check
+++ b/test/files/run/t1500.check
@@ -1,3 +1,3 @@
defined class posingAs
-resolve: [A,B](x: A @posingAs[B])B
+resolve: [A, B](x: A @posingAs[B])B
x: Any = 7