diff options
242 files changed, 2695 insertions, 2318 deletions
diff --git a/build-ant-macros.xml b/build-ant-macros.xml new file mode 100644 index 0000000000..735e91ba7b --- /dev/null +++ b/build-ant-macros.xml @@ -0,0 +1,547 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project name="build-support"> + <description> Macros for Scala's ant build </description> + + <macrodef name="optimized"> + <attribute name="name"/> + <sequential> + <antcall target="@{name}"> + <param name="scalac.args.optimise" value="-optimise"/> + </antcall> + </sequential> + </macrodef> + + <macrodef name="copy-deps" description="Copy a file set based on maven dependency resolution to a directory. Currently used by the IntelliJ config files."> + <attribute name="project"/> + <attribute name="refid" default="@{project}.fileset"/> + <sequential> + <delete dir="${build-deps.dir}/@{project}" includes="*.jar"/> + <copy todir="${build-deps.dir}/@{project}"> + <resources refid="@{refid}"/> + <mapper type="flatten"/> + </copy> + </sequential> + </macrodef> + + <!-- Set property named @{name} to the jar resolved as @{jar}_${scala.binary.version}:jar. + @{jar}_${scala.binary.version} must be a maven dependency. --> + <macrodef name="propertyForCrossedArtifact"> + <attribute name="name"/> + <attribute name="jar"/> + <sequential> + <readProperty name="@{name}" property="@{jar}_${scala.binary.version}:jar"/> + <readProperty name="@{name}-sources" property="@{jar}_${scala.binary.version}:java-source:sources"/> + <readProperty name="@{name}-javadoc" property="@{jar}_${scala.binary.version}:java-source:javadoc"/> + </sequential> + </macrodef> + + <!-- Set property named @{name} to the value of the property named @{property}. + Helper for performing nested property expansion without using the ant props lib --> + <macrodef name="readProperty"> + <attribute name="name"/> + <attribute name="property"/> + <sequential> + <property name="@{name}" value="${@{property}}"/> + </sequential> + </macrodef> + + <macrodef name="init-project-prop"> + <attribute name="project"/> + <attribute name="name"/> + <attribute name="default"/> + <sequential> + <local name="@{name}"/> + <if> + <not> + <isset property="@{project}.@{name}"/> + </not> + <then> + <property name="@{project}.@{name}" value="@{default}"/> + </then> + </if> + </sequential> + </macrodef> + + <macrodef name="clean"> + <attribute name="build"/> + <sequential> + <delete dir="${build-@{build}.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/> + </sequential> + </macrodef> + + <macrodef name="simple-javac"> + <attribute name="project"/> + <!-- project: asm/forkjoin --> + <attribute name="args" default=""/> + <attribute name="jar" default="yes"/> + <sequential> + <uptodate property="@{project}.available" targetfile="${build-libs.dir}/@{project}.complete"> + <srcfiles dir="${src.dir}/@{project}"/> + </uptodate> + <if> + <not> + <isset property="@{project}.available"/> + </not> + <then> + <stopwatch name="@{project}.timer"/> + <mkdir dir="${@{project}-classes}"/> + <javac debug="true" srcdir="${src.dir}/@{project}" destdir="${@{project}-classes}" classpath="${@{project}-classes}" includes="**/*.java" target="1.6" source="1.5" compiler="javac1.6"> + <compilerarg line="${javac.args} @{args}"/> + </javac> + <if> + <equals arg1="@{jar}" arg2="yes"/> + <then> + <jar whenmanifestonly="fail" destfile="${build-libs.dir}/@{project}.jar" basedir="${@{project}-classes}"/> + </then> + </if> + <stopwatch name="@{project}.timer" action="total"/> + <mkdir dir="${build-libs.dir}"/> + <touch file="${build-libs.dir}/@{project}.complete" verbose="no"/> + </then> + </if> + </sequential> + </macrodef> + + <macrodef name="staged-javac"> + <attribute name="stage"/> + <!-- current stage (locker, quick, strap) --> + <attribute name="project"/> + <!-- project: library/reflect/compiler/actors --> + <attribute name="destproject" default="@{project}"/> + <!-- overrides the output directory; used when building multiple projects into the same directory--> + <attribute name="args" default=""/> + <attribute name="excludes" default=""/> + <sequential> + <javac debug="true" srcdir="${src.dir}/@{project}" destdir="${build-@{stage}.dir}/classes/@{destproject}" includes="**/*.java" excludes="@{excludes}" target="1.6" source="1.5"> + <compilerarg line="${javac.args} @{args}"/> + <classpath refid="@{stage}.@{destproject}.build.path"/> + </javac> + </sequential> + </macrodef> + + <!-- Zinc assumes a one-to-one correspondence of output folder to set of source files. + When compiling different sets of source files in multiple compilations to the same output directory, + Zinc thinks source files that appeared in an earlier compilation but are absent in the current one, + were deleted and thus deletes the corresponding output files. + + Note that zinc also requires each arg to scalac to be prefixed by -S. + --> + <macrodef name="zinc"> + <attribute name="compilerpathref"/> + <attribute name="destdir"/> + <attribute name="srcdir"/> + <attribute name="srcpath" default="NOT SET"/> + <!-- needed to compile the library, "NOT SET" is just a convention to denote an optional attribute --> + <attribute name="buildpathref"/> + <attribute name="params" default=""/> + <attribute name="java-excludes" default=""/> + <sequential> + <local name="sources"/> + <pathconvert pathsep=" " property="sources"> + <fileset dir="@{srcdir}"> + <include name="**/*.java"/> + <include name="**/*.scala"/> + <exclude name="@{java-excludes}"/> + </fileset> + </pathconvert> + <local name="args"/> + <local name="sargs"/> + <if> + <not> + <equals arg1="@{srcpath}" arg2="NOT SET"/> + </not> + <then> + <property name="args" value="@{params} -sourcepath @{srcpath}"/> + </then> + </if> + <property name="args" value="@{params}"/> + <!-- default --> + <!-- HACK: prefix scalac args by -S --> + <script language="javascript"> + project.setProperty("sargs", project.getProperty("args").trim().replaceAll(" ", " -S")); + </script> + <exec osfamily="unix" executable="tools/zinc" failifexecutionfails="true" failonerror="true"> + <arg line="-nailed -compile-order JavaThenScala -scala-path ${ant.refid:@{compilerpathref}} -d @{destdir} -classpath ${toString:@{buildpathref}} ${sargs} ${sources}"/> + </exec> + </sequential> + </macrodef> + + <!-- STAGED COMPILATION MACROS --> + <macrodef name="staged-scalac"> + <attribute name="with"/> + <!-- will use path `@{with}.compiler.path` to locate scalac --> + <attribute name="stage"/> + <!-- current stage (locker, quick, strap) --> + <attribute name="project"/> + <!-- project: library/reflect/compiler/actors --> + <attribute name="srcpath" default="NOT SET"/> + <!-- needed to compile the library --> + <attribute name="args" default=""/> + <!-- additional args --> + <attribute name="destproject" default="@{project}"/> + <!-- overrides the output directory; used when building multiple projects into the same directory--> + <attribute name="srcdir" default="@{project}"/> + <attribute name="java-excludes" default=""/> + <sequential> + <!-- TODO: detect zinc anywhere on PATH + use zinc for the quick stage if it's available; + would use it for locker but something is iffy in sbt: get a class cast error on global phase --> + <if> + <and> + <available file="tools/zinc"/> + <equals arg1="@{stage}" arg2="quick"/> + <not> + <equals arg1="@{project}" arg2="continuations-plugins"/> + </not> + <!-- doesn't work in zinc because it requires the quick compiler, which isn't jarred up--> + </and> + <then> + <zinc taskname="Z.@{stage}.@{project}" compilerpathref="@{with}.compiler.path" destdir="${build-@{stage}.dir}/classes/@{destproject}" srcdir="${src.dir}/@{srcdir}" srcpath="@{srcpath}" buildpathref="@{stage}.@{project}.build.path" params="${scalac.args.@{stage}} @{args}" java-excludes="@{java-excludes}"/> + </then> + <else> + <if> + <equals arg1="@{srcpath}" arg2="NOT SET"/> + <then> + <scalacfork taskname="@{stage}.@{project}" jvmargs="${scalacfork.jvmargs}" compilerpathref="@{with}.compiler.path" destdir="${build-@{stage}.dir}/classes/@{destproject}" srcdir="${src.dir}/@{srcdir}" params="${scalac.args.@{stage}} @{args}"> + <include name="**/*.scala"/> + <compilationpath refid="@{stage}.@{project}.build.path"/> + </scalacfork> + </then> + <else> + <scalacfork taskname="@{stage}.@{project}" jvmargs="${scalacfork.jvmargs}" compilerpathref="@{with}.compiler.path" destdir="${build-@{stage}.dir}/classes/@{destproject}" srcdir="${src.dir}/@{srcdir}" srcpath="@{srcpath}" params="${scalac.args.@{stage}} @{args}"> + <include name="**/*.scala"/> + <compilationpath refid="@{stage}.@{project}.build.path"/> + </scalacfork> + </else> + </if> + </else> + </if> + </sequential> + </macrodef> + + <macrodef name="staged-uptodate"> + <attribute name="stage"/> + <attribute name="project"/> + <element name="check"/> + <element name="do"/> + <sequential> + <uptodate property="@{stage}.@{project}.available" targetfile="${build-@{stage}.dir}/@{project}.complete"> + <check/> + </uptodate> + <if> + <not> + <isset property="@{stage}.@{project}.available"/> + </not> + <then> + <do/> + <touch file="${build-@{stage}.dir}/@{project}.complete" verbose="no"/> + </then> + </if> + </sequential> + </macrodef> + + <macrodef name="staged-build"> + <attribute name="with"/> + <!-- will use path `@{with}.compiler.path` to locate scalac --> + <attribute name="stage"/> + <!-- current stage (locker, quick, strap) --> + <attribute name="project"/> + <!-- project: library/reflect/compiler/actors --> + <attribute name="srcpath" default="NOT SET"/> + <!-- needed to compile the library --> + <attribute name="args" default=""/> + <!-- additional args --> + <attribute name="includes" default="comp.includes"/> + <attribute name="java-excludes" default=""/> + <attribute name="version" default=""/> + <!-- non-empty for scaladoc: use @{version}.version.number in property file--> + <sequential> + <staged-uptodate stage="@{stage}" project="@{project}"> + <check> + <srcfiles dir="${src.dir}/@{project}"/> + </check> + <do> + <stopwatch name="@{stage}.@{project}.timer"/> + <mkdir dir="${build-@{stage}.dir}/classes/@{project}"/> + <staged-javac stage="@{stage}" project="@{project}" excludes="@{java-excludes}"/> + <!-- always compile with javac for simplicity and regularity; it's cheap --> + <staged-scalac with="@{with}" stage="@{stage}" project="@{project}" srcpath="@{srcpath}" args="@{args}" java-excludes="@{java-excludes}"/> + <if> + <equals arg1="@{version}" arg2=""/> + <then> + <propertyfile file="${build-@{stage}.dir}/classes/@{project}/@{project}.properties"> + <entry key="version.number" value="${version.number}"/> + <entry key="maven.version.number" value="${maven.version.number}"/> + <entry key="osgi.version.number" value="${osgi.version.number}"/> + <entry key="copyright.string" value="${copyright.string}"/> + </propertyfile> + </then> + <else> + <propertyfile file="${build-@{stage}.dir}/classes/@{project}/@{project}.properties"> + <entry key="version.number" value="${@{version}.version.number}"/> + <entry key="copyright.string" value="${copyright.string}"/> + </propertyfile> + </else> + </if> + <copy todir="${build-@{stage}.dir}/classes/@{project}"> + <fileset dir="${src.dir}/@{project}"> + <patternset refid="@{includes}"/> + </fileset> + </copy> + <stopwatch name="@{stage}.@{project}.timer" action="total"/> + </do> + </staged-uptodate> + </sequential> + </macrodef> + + <macrodef name="staged-bin"> + <attribute name="stage"/> + <attribute name="classpathref" default="NOT SET"/> + <sequential> + <staged-uptodate stage="@{stage}" project="bin"> + <check> + <srcfiles dir="${src.dir}"> + <include name="compiler/scala/tools/ant/templates/**"/> + </srcfiles> + </check> + <do> + <taskdef name="mk-bin" classname="scala.tools.ant.ScalaTool" classpathref="@{stage}.bin.tool.path"/> + <mkdir dir="${build-@{stage}.dir}/bin"/> + <if> + <equals arg1="@{classpathref}" arg2="NOT SET"/> + <then> + <mk-bin file="${build-@{stage}.dir}/bin/scala" class="scala.tools.nsc.MainGenericRunner" javaFlags="${java.flags}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scalac" class="scala.tools.nsc.Main" javaFlags="${java.flags}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scaladoc" class="scala.tools.nsc.ScalaDoc" javaFlags="${java.flags}"/> + <mk-bin file="${build-@{stage}.dir}/bin/fsc" class="scala.tools.nsc.CompileClient" javaFlags="${java.flags}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scalap" class="scala.tools.scalap.Main" javaFlags="${java.flags}"/> + </then> + <else> + <mk-bin file="${build-@{stage}.dir}/bin/scala" class="scala.tools.nsc.MainGenericRunner" javaFlags="${java.flags}" classpathref="@{classpathref}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scalac" class="scala.tools.nsc.Main" javaFlags="${java.flags}" classpathref="@{classpathref}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scaladoc" class="scala.tools.nsc.ScalaDoc" javaFlags="${java.flags}" classpathref="@{classpathref}"/> + <mk-bin file="${build-@{stage}.dir}/bin/fsc" class="scala.tools.nsc.CompileClient" javaFlags="${java.flags}" classpathref="@{classpathref}"/> + <mk-bin file="${build-@{stage}.dir}/bin/scalap" class="scala.tools.scalap.Main" javaFlags="${java.flags}" classpathref="@{classpathref}"/> + </else> + </if> + <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scala"/> + <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scalac"/> + <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scaladoc"/> + <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/fsc"/> + <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scalap"/> + </do> + </staged-uptodate> + </sequential> + </macrodef> + + <macrodef name="staged-pack"> + <attribute name="project"/> + <attribute name="manifest" default=""/> + <element name="pre" optional="true"/> + <element name="jar-opts" optional="true"/> + <sequential> + <local name="destfile"/> + <property name="destfile" value="${build-pack.dir}/${@{project}.targetdir}/${@{project}.targetjar}"/> + <uptodate property="pack.@{project}.available" targetfile="${destfile}"> + <srcresources> + <resources refid="pack.@{project}.files"/> + <!-- <path><pathelement location="${build-quick.dir}/@{project}.complete"/></path> --> + </srcresources> + </uptodate> + <if> + <not> + <isset property="pack.@{project}.available"/> + </not> + <then> + <mkdir dir="${build-pack.dir}/${@{project}.targetdir}"/> + <pre/> + <if> + <not> + <equals arg1="@{manifest}" arg2=""/> + </not> + <then> + <jar whenmanifestonly="fail" destfile="${destfile}" manifest="@{manifest}"> + <!-- update="true" makes no difference on my machine, so starting from scratch--> + <jar-opts/> + <path refid="pack.@{project}.files"/> + </jar> + </then> + <else> + <jar whenmanifestonly="fail" destfile="${destfile}"> + <jar-opts/> + <path refid="pack.@{project}.files"/> + </jar> + </else> + </if> + </then> + </if> + </sequential> + </macrodef> + + <macrodef name="staged-docs"> + <attribute name="project"/> + <element name="includes" implicit="true"/> + <sequential> + <staged-uptodate stage="docs" project="@{project}"> + <check> + <srcfiles dir="${src.dir}/${@{project}.srcdir}"/> + </check> + <do> + <stopwatch name="docs.@{project}.timer"/> + <mkdir dir="${build-docs.dir}/@{project}"/> + <if> + <equals arg1="${@{project}.docroot}" arg2="NOT SET"/> + <then> + <scaladoc destdir="${build-docs.dir}/@{project}" doctitle="${@{project}.description}" docfooter="epfl" docversion="${version.number}" sourcepath="${src.dir}" classpathref="docs.@{project}.build.path" srcdir="${src.dir}/${@{project}.srcdir}" addparams="${scalac.args.all}" implicits="on" diagrams="on" groups="on" rawOutput="${scaladoc.raw.output}" noPrefixes="${scaladoc.no.prefixes}" docUncompilable="${src.dir}/library-aux" skipPackages="${@{project}.skipPackages}"> + <includes/> + </scaladoc> + </then> + <else> + <scaladoc destdir="${build-docs.dir}/@{project}" doctitle="${@{project}.description}" docfooter="epfl" docversion="${version.number}" sourcepath="${src.dir}" classpathref="docs.@{project}.build.path" srcdir="${src.dir}/${@{project}.srcdir}" docRootContent="${src.dir}/@{project}/${@{project}.docroot}" addparams="${scalac.args.all}" implicits="on" diagrams="on" groups="on" rawOutput="${scaladoc.raw.output}" noPrefixes="${scaladoc.no.prefixes}" docUncompilable="${src.dir}/library-aux" skipPackages="${@{project}.skipPackages}"> + <includes/> + </scaladoc> + </else> + </if> + <stopwatch name="docs.@{project}.timer" action="total"/> + </do> + </staged-uptodate> + </sequential> + </macrodef> + + <macrodef name="make-bundle"> + <attribute name="project"/> + <element name="srcs" description="Sources for this bundle" optional="true" implicit="true"/> + <sequential> + <copy file="${src.dir}/build/bnd/${@{project}.name}.bnd" tofile="${build-osgi.dir}/${@{project}.name}.bnd" overwrite="true"> + <filterset> + <filter token="VERSION" value="${osgi.version.number}"/> + <filter token="SCALA_BINARY_VERSION" value="${scala.binary.version}"/> + <filter token="SCALA_COMPILER_DOC_VERSION" value="${scala-compiler-doc.version.number}"/> + <filter token="SCALA_COMPILER_INTERACTIVE_VERSION" value="${scala-compiler-interactive.version.number}"/> + </filterset> + </copy> + <bnd classpath="${@{project}.jar}" eclipse="false" failok="false" exceptions="true" files="${build-osgi.dir}/${@{project}.name}.bnd" output="${build-osgi.dir}"/> + <if> + <equals arg1="${@{project}.src}" arg2="true"/> + <then> + <!-- + A jar-like task that creates an OSGi source bundle. It adds the required MANIFEST.MF headers that allow + Eclipse to match sources with the corresponding binaries. + --> + <jar whenmanifestonly="fail" destfile="${build-osgi.dir}/${@{project}.name}-src.jar"> + <srcs/> + <manifest> + <attribute name="Manifest-Version" value="1.0"/> + <attribute name="Bundle-Name" value="${@{project}.description} Sources"/> + <attribute name="Bundle-SymbolicName" value="org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix}.source"/> + <attribute name="Bundle-Version" value="${@{project}.version}"/> + <attribute name="Eclipse-SourceBundle" value="org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix};version="${@{project}.version}";roots:=".""/> + </manifest> + </jar> + </then> + </if> + </sequential> + </macrodef> + + <macrodef name="copy-bundle"> + <attribute name="project"/> + <sequential> + <copy tofile="${dist.dir}/${@{project}.targetdir}/${@{project}.name}.jar" file="${build-osgi.dir}/org.scala-lang.${@{project}.package}${@{project}.name}.jar" overwrite="true"/> + <copy tofile="${dist.dir}/src/${@{project}.name}-src.jar" file="${@{project}.srcjar}" overwrite="true"/> + </sequential> + </macrodef> + + <macrodef name="mvn-package"> + <attribute name="project"/> + <sequential> + <local name="artifact-base"/> + <property name="artifact-base" value="${maven-base}/${@{project}.dir}${@{project}.name}/${@{project}.name}"/> + <mkdir dir="${maven-base}/${@{project}.dir}${@{project}.name}"/> + <copy tofile="${artifact-base}.jar" file="${build-osgi.dir}/org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix}.jar" overwrite="true"/> + <copy tofile="${artifact-base}-src.jar" file="${build-osgi.dir}/${@{project}.name}-src.jar" overwrite="true"/> + <copy tofile="${artifact-base}-pom.xml" file="${src.dir}/build/maven/${@{project}.dir}/${@{project}.name}-pom.xml" overwrite="true"/> + <if> + <not> + <isset property="docs.skip"/> + </not> + <then> + <jar destfile="${artifact-base}-docs.jar" basedir="${build-docs.dir}/@{project}" whenmanifestonly="fail"> + <include name="**/*"/> + </jar> + </then> + </if> + </sequential> + </macrodef> + + + + <macrodef name="testSuite"> + <attribute name="dir" default="${partest.dir}"/> + <attribute name="srcdir" default="files"/> <!-- TODO: make targets for `pending` and other subdirs --> + <attribute name="colors" default="${partest.colors}"/> + <attribute name="scalacOpts" default="${scalac.args.optimise}"/> + <attribute name="pcp" default="${toString:partest.compilation.path}"/> + <attribute name="kinds"/> + <sequential> + <property name="partest.dir" value="@{dir}" /> + <partest srcdir="@{srcdir}" + kinds="@{kinds}" + colors="@{colors}" + scalacOpts="@{scalacOpts}" + compilationpath="@{pcp}"/> + </sequential> + </macrodef> + + <macrodef name="bc.run-mima"> + <attribute name="jar-name"/> + <attribute name="prev"/> + <attribute name="curr"/> + <attribute name="direction"/> + <sequential> + <echo message="Checking @{direction} binary compatibility for @{jar-name} (against ${bc-reference-version})"/> + <java taskname="mima" fork="true" failonerror="true" classname="com.typesafe.tools.mima.cli.Main"> + <arg value="--prev"/> + <arg value="@{prev}"/> + <arg value="--curr"/> + <arg value="@{curr}"/> + <arg value="--filters"/> + <arg value="${basedir}/bincompat-@{direction}.whitelist.conf"/> + <arg value="--generate-filters"/> + <classpath> + <path refid="mima.classpath"/> + </classpath> + </java> + </sequential> + </macrodef> + + <macrodef name="bc.check"> + <attribute name="project"/> + <sequential> + <bc.run-mima jar-name="scala-@{project}" prev="${org.scala-lang:scala-@{project}:jar}" curr="${@{name}.jar}" direction="backward"/> + <bc.run-mima jar-name="scala-@{project}" prev="${@{name}.jar}" curr="${org.scala-lang:scala-@{project}:jar}" direction="forward"/> + </sequential> + </macrodef> + + <macrodef name="tarz"> + <attribute name="name" description="The tar file name (without extension)."/> + <element name="file-sets" description="A sequence of fileset elements to be included in the tar balls." optional="false" implicit="true"/> + <sequential> + <tar destfile="@{name}.tar" compression="none" longfile="gnu"> + <file-sets/> + </tar> + <gzip src="@{name}.tar" destfile="@{name}.tgz"/> + <if> + <not> + <equals arg1="${archives.skipxz}" arg2="true"/> + </not> + <then> + <exec executable="xz" failifexecutionfails="false"> + <arg line="-k -9e -S .xz @{name}.tar"/> + </exec> + <move file="@{name}.tar.xz" tofile="@{name}.txz" failonerror="false"/> + </then> + </if> + <delete file="@{name}.tar"/> + </sequential> + </macrodef> +</project> @@ -3,7 +3,7 @@ <project name="sabbus" default="build" xmlns:artifact="urn:maven-artifact-ant" xmlns:rsel="antlib:org.apache.tools.ant.types.resources.selectors"> - <include file="test/build-partest.xml" as="partest"/> + <include file="build-ant-macros.xml" as="macros"/> <include file="src/build/maven/maven-deploy.xml" as="maven-deploy"/> <description> @@ -14,7 +14,6 @@ SuperSabbus for Scala core, builds the scala library and compiler. It can also p - for faster builds, have a build.properties in the same directory as build.xml that says: locker.skip=1 - starr.use.released=1 --> @@ -107,12 +106,6 @@ TODO: <target name="docsclean" depends="docs.clean" description="Removes generated documentation. Distributions are untouched."/> <target name="distclean" depends="dist.clean" description="Removes all distributions. Binaries and documentation are untouched."/> - <macrodef name="optimized" > - <attribute name="name"/> - <sequential> - <antcall target="@{name}"><param name="scalac.args.optimise" value="-optimise"/></antcall> - </sequential> - </macrodef> <!-- =========================================================================== PROPERTIES @@ -143,9 +136,6 @@ TODO: <property file="${basedir}/versions.properties"/> <!-- Sets location of pre-compiled libraries --> - <property name="library.starr.jar" value="${lib.dir}/scala-library.jar"/> - <property name="reflect.starr.jar" value="${lib.dir}/scala-reflect.jar"/> - <property name="compiler.starr.jar" value="${lib.dir}/scala-compiler.jar"/> <property name="ant.jar" value="${ant.home}/lib/ant.jar"/> <!-- Sets location of build folders --> @@ -155,7 +145,6 @@ TODO: <property name="build-asm.dir" value="${build.dir}/asm"/> <property name="build-forkjoin.dir" value="${build-libs.dir}"/> <property name="build-locker.dir" value="${build.dir}/locker"/> - <property name="build-palo.dir" value="${build.dir}/palo"/> <property name="build-quick.dir" value="${build.dir}/quick"/> <property name="build-pack.dir" value="${build.dir}/pack"/> <property name="build-osgi.dir" value="${build.dir}/osgi"/> @@ -214,19 +203,27 @@ TODO: </touch> </target> - <macrodef name="copy-deps" description="Copy a file set based on maven dependency resolution to a directory. Currently used by the IntelliJ config files."> - <attribute name="project" /> - <attribute name="refid" default="@{project}.fileset"/> - <sequential> - <delete dir="${build-deps.dir}/@{project}" includes="*.jar"/> - <copy todir="${build-deps.dir}/@{project}"> - <resources refid="@{refid}" /> - <mapper type="flatten" /> - </copy> - </sequential> - </macrodef> + <target name="init.git" depends="boot"> + <!-- replacestarr needs git.commit.sha, but doesn't want to run the init target (it computes maven.version.number) --> + <exec osfamily="unix" executable="tools/get-scala-commit-sha" outputproperty="git.commit.sha" failifexecutionfails="false" /> + <exec osfamily="windows" executable="cmd.exe" outputproperty="git.commit.sha" failifexecutionfails="false"> + <arg value="/c"/> + <arg value="tools\get-scala-commit-sha.bat"/> + <arg value="-p"/> + </exec> + <exec osfamily="unix" executable="tools/get-scala-commit-date" outputproperty="git.commit.date" failifexecutionfails="false" /> + <exec osfamily="windows" executable="cmd.exe" outputproperty="git.commit.date" failifexecutionfails="false"> + <arg value="/c"/> + <arg value="tools\get-scala-commit-date.bat"/> + <arg value="-p"/> + </exec> - <target name="init" depends="boot"> + <!-- some default in case something went wrong getting the revision --> + <property name="git.commit.sha" value="unknown"/> + <property name="git.commit.date" value="unknown"/> + </target> + + <target name="init" depends="init.git"> <!-- Set up Ant contrib tasks so we can use <if><then><else> instead of the clunky `unless` attribute --> <taskdef resource="net/sf/antcontrib/antlib.xml" classpath="${lib-ant.dir}/ant-contrib.jar"/> @@ -285,12 +282,13 @@ TODO: <!-- so we don't have to wait for artifacts to synch to maven central (we don't distribute partest with Scala, so the risk of sonatype and maven being out of synch is irrelevant): --> - <!-- <artifact:remoteRepository refid="extra-repo"/> --> + <artifact:remoteRepository refid="extra-repo"/> <dependency groupId="org.scala-lang.modules" artifactId="scala-partest_${scala.binary.version}" version="${partest.version.number}" /> </artifact:dependencies> <copy-deps project="partest"/> <artifact:dependencies pathId="scalacheck.classpath" filesetId="scalacheck.fileset" versionsId="scalacheck.versions"> + <artifact:remoteRepository refid="extra-repo"/> <dependency groupId="org.scalacheck" artifactId="scalacheck_${scala.binary.version}" version="${scalacheck.version.number}" /> </artifact:dependencies> @@ -302,7 +300,7 @@ TODO: <!-- used by the test.osgi target to create osgi bundles for the xml, parser-combinator jars must specify sourcesFilesetId, javadocFilesetId to download these types of artifacts --> <artifact:dependencies pathId="external-modules.deps.classpath" sourcesFilesetId="external-modules.sources.fileset" javadocFilesetId="external-modules.javadoc.fileset"> - <!-- <artifact:remoteRepository refid="extra-repo"/> --> + <artifact:remoteRepository refid="extra-repo"/> <dependency groupId="org.scala-lang.modules" artifactId="scala-xml_${scala.binary.version}" version="${scala-xml.version.number}"/> <dependency groupId="org.scala-lang.modules" artifactId="scala-parser-combinators_${scala.binary.version}" version="${scala-parser-combinators.version.number}"/> </artifact:dependencies> @@ -320,53 +318,19 @@ TODO: </path> <copy-deps refid="external-modules-nocore" project="scaladoc"/> - - <!-- Set property named @{name} to the jar resolved as @{jar}_${scala.binary.version}:jar. - @{jar}_${scala.binary.version} must be a maven dependency. --> - <macrodef name="propertyForCrossedArtifact"> - <attribute name="name" /> - <attribute name="jar" /> - <sequential> - <readProperty name="@{name}" property="@{jar}_${scala.binary.version}:jar" /> - <readProperty name="@{name}-sources" property="@{jar}_${scala.binary.version}:java-source:sources" /> - <readProperty name="@{name}-javadoc" property="@{jar}_${scala.binary.version}:java-source:javadoc" /> - </sequential> - </macrodef> - - <!-- Set property named @{name} to the value of the property named @{property}. - Helper for performing nested property expansion without using the ant props lib --> - <macrodef name="readProperty"> - <attribute name="name" /> - <attribute name="property" /> - <sequential> - <property name="@{name}" value="${@{property}}" /> - </sequential> - </macrodef> - <propertyForCrossedArtifact name="scala-parser-combinators" jar="org.scala-lang.modules:scala-parser-combinators"/> <propertyForCrossedArtifact name="scala-xml" jar="org.scala-lang.modules:scala-xml"/> <!-- BND support --> <typedef resource="aQute/bnd/ant/taskdef.properties" classpathref="extra.tasks.classpath" /> - <!-- Download STARR via maven if `starr.use.released` is set, - and `starr.version` is specified (see the versions.properties properties file). - Want to slow down STARR changes, using only released versions. --> - <if><isset property="starr.use.released"/><then> - <echo message="Using Scala ${starr.version} for STARR."/> - <artifact:dependencies pathId="starr.core.path"> - <artifact:remoteRepository refid="extra-repo"/> - <dependency groupId="org.scala-lang" artifactId="scala-library" version="${starr.version}"/> - <dependency groupId="org.scala-lang" artifactId="scala-reflect" version="${starr.version}"/> - <dependency groupId="org.scala-lang" artifactId="scala-compiler" version="${starr.version}"/> - </artifact:dependencies></then> - <else> - <path id="starr.core.path"> - <pathelement location="${library.starr.jar}"/> - <pathelement location="${reflect.starr.jar}"/> - <pathelement location="${compiler.starr.jar}"/> - </path></else> - </if> + <echo message="Using Scala ${starr.version} for STARR."/> + <artifact:dependencies pathId="starr.compiler.path"> + <artifact:remoteRepository refid="extra-repo"/> + <dependency groupId="org.scala-lang" artifactId="scala-library" version="${starr.version}"/> + <dependency groupId="org.scala-lang" artifactId="scala-reflect" version="${starr.version}"/> + <dependency groupId="org.scala-lang" artifactId="scala-compiler" version="${starr.version}"/> + </artifact:dependencies> <property name="maven-deps-done" value="yep!"/> </then></if> @@ -415,24 +379,6 @@ TODO: <property name="osgi.version.suffix" value="${maven.version.suffix}"/> <property name="version.suffix" value="${maven.version.suffix}"/></else></if> - - <exec osfamily="unix" executable="tools/get-scala-commit-sha" outputproperty="git.commit.sha" failifexecutionfails="false" /> - <exec osfamily="windows" executable="cmd.exe" outputproperty="git.commit.sha" failifexecutionfails="false"> - <arg value="/c"/> - <arg value="tools\get-scala-commit-sha.bat"/> - <arg value="-p"/> - </exec> - <exec osfamily="unix" executable="tools/get-scala-commit-date" outputproperty="git.commit.date" failifexecutionfails="false" /> - <exec osfamily="windows" executable="cmd.exe" outputproperty="git.commit.date" failifexecutionfails="false"> - <arg value="/c"/> - <arg value="tools\get-scala-commit-date.bat"/> - <arg value="-p"/> - </exec> - - <!-- some default in case something went wrong getting the revision --> - <property name="git.commit.sha" value="unknown"/> - <property name="git.commit.date" value="unknown"/> - <!-- We use the git describe to determine the OSGi modifier for our build. --> <property name="maven.version.number" value="${version.major}.${version.minor}.${version.patch}${maven.version.suffix}"/> @@ -560,6 +506,27 @@ TODO: <echo message="canonical suffix: ${version.suffix}" /> --> <fail unless="version.suffixes.consistent" message="Version suffixes inconsistent!"/> + + <!-- used during releases to bump versions in versions.properties --> + <if><isset property="update.versions"/><then> + <echo message="Updating `versions.properties`:"/> + <echo message=" starr.version = ${starr.version}"/> + <echo message=" scala.binary.version = ${scala.binary.version}"/> + <echo message=" partest.version.number = ${partest.version.number}"/> + <echo message=" scala-xml.version.number = ${scala-xml.version.number}"/> + <echo message=" scala-parser-combinators.version.number = ${scala-parser-combinators.version.number}"/> + <echo message=" scalacheck.version.number = ${scalacheck.version.number}"/> + + <propertyfile file="versions.properties"> + <entry key="starr.version" value="${starr.version}"/> + <entry key="scala.binary.version" value="${scala.binary.version}"/> + <entry key="partest.version.number" value="${partest.version.number}"/> + <entry key="scala-xml.version.number" value="${scala-xml.version.number}"/> + <entry key="scala-parser-combinators.version.number" value="${scala-parser-combinators.version.number}"/> + <entry key="scalacheck.version.number" value="${scalacheck.version.number}"/> + </propertyfile> + </then></if> + <path id="forkjoin.classpath" path="${build-libs.dir}/classes/forkjoin"/> <path id="asm.classpath" path="${build-asm.dir}/classes"/> <property name="forkjoin-classes" refid="forkjoin.classpath"/> @@ -624,19 +591,6 @@ TODO: <property name="partest-extras.description" value="Scala Compiler Testing Tool (compiler-specific extras)"/> <property name="partest-javaagent.description" value="Scala Compiler Testing Tool (compiler-specific java agent)"/> - <macrodef name="init-project-prop"> - <attribute name="project" /> - <attribute name="name" /> - <attribute name="default" /> - <sequential> - <local name="@{name}"/> - - <if><not><isset property="@{project}.@{name}"/></not><then> - <property name="@{project}.@{name}" value="@{default}" /> - </then></if> - </sequential> - </macrodef> - <!-- projects without project-specific options: asm, forkjoin, manual, bin, repl --> <for list="actors,compiler,interactive,scaladoc,continuations-library,continuations-plugin,library,parser-combinators,partest,partest-extras,partest-javaagent,reflect,scalap,swing,xml" param="project"> <sequential> @@ -659,14 +613,13 @@ TODO: <!-- Compilers to use for the various stages. - There must be a variable of the shape @{stage}.compiler.path for all @{stage} in starr, locker, quick, strap. --> - <path id="starr.compiler.path"> - <path refid="starr.core.path"/> - <pathelement location="${lib.dir}/forkjoin.jar"/> - <path refid="aux.libs"/> - </path> + + <!-- starr is resolved (to starr.compiler.path) in the block protected by maven-deps-done + the maven task must not be executed twice, or you get a java.lang.ClassCastException: + org.apache.maven.artifact.ant.RemoteRepository cannot be cast to org.apache.maven.artifact.ant.Repository + --> <!-- To skip locker, use -Dlocker.skip=1 --> <if><isset property="locker.skip"/><then> @@ -920,9 +873,15 @@ TODO: Why, the compiler we're testing, of course, and partest with all its dependencies. --> <path id="partest.compilation.path"> + <path refid="partest.compilation.path.core"/> + <path refid="partest.compilation.path.noncore"/> + </path> + <path id="partest.compilation.path.core"> <pathelement location="${library.jar}"/> <pathelement location="${reflect.jar}"/> <pathelement location="${compiler.jar}"/> + </path> + <path id="partest.compilation.path.noncore"> <!-- TODO modularize compiler <pathelement location="${scaladoc.jar}"/> @@ -970,6 +929,7 @@ TODO: <path id="test.junit.compiler.build.path"> <pathelement location="${test.junit.classes}"/> <path refid="quick.compiler.build.path"/> + <path refid="quick.repl.build.path"/> <path refid="junit.classpath"/> </path> @@ -983,13 +943,6 @@ TODO: <path refid="forkjoin.classpath"/> </path> - <path id="palo.bin.tool.path"> - <pathelement location="${build-palo.dir}/lib/scala-library.jar"/> - <pathelement location="${build-palo.dir}/lib/scala-reflect.jar"/> - <pathelement location="${build-palo.dir}/lib/scala-compiler.jar"/> - <path refid="repl.deps.classpath"/> - </path> - <path id="test.positions.sub.build.path" path="${build-quick.dir}/classes/library"/> <!-- TODO: consolidate *.includes --> @@ -1029,8 +982,7 @@ TODO: =============================================================================--> <target name="libs.clean"> <clean build="libs"/> <clean build="asm"/> </target> <target name="quick.clean" depends="libs.clean"> <clean build="quick"/> <clean build="pack"/> <clean build="strap"/> </target> - <target name="palo.clean" depends="quick.clean"> <clean build="palo"/> </target> - <target name="locker.clean" depends="palo.clean"> <clean build="locker"/> </target> + <target name="locker.clean" depends="quick.clean"> <clean build="locker"/> </target> <target name="docs.clean"> <clean build="docs"/> <delete dir="${build.dir}/manmaker" includeemptydirs="yes" quiet="yes" failonerror="no"/> </target> <target name="dist.clean"> <delete dir="${dists.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/> </target> @@ -1044,351 +996,28 @@ TODO: <!-- Used by the scala-installer script --> <target name="allallclean" depends="all.clean, dist.clean"/> - <macrodef name="clean"> - <attribute name="build"/> - <sequential> - <delete dir="${build-@{build}.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/> - </sequential> - </macrodef> <!-- =========================================================================== LOCAL DEPENDENCIES ============================================================================ --> - <macrodef name="simple-javac" > - <attribute name="project"/> <!-- project: asm/forkjoin --> - <attribute name="args" default=""/> - <attribute name="jar" default="yes"/> - <sequential> - <uptodate property="@{project}.available" targetfile="${build-libs.dir}/@{project}.complete"> - <srcfiles dir="${src.dir}/@{project}"/></uptodate> - <if><not><isset property="@{project}.available"/></not><then> - <stopwatch name="@{project}.timer"/> - <mkdir dir="${@{project}-classes}"/> - <javac - debug="true" - srcdir="${src.dir}/@{project}" - destdir="${@{project}-classes}" - classpath="${@{project}-classes}" - includes="**/*.java" - target="1.6" source="1.5" - compiler="javac1.6"> - <compilerarg line="${javac.args} @{args}"/> - </javac> - <if><equals arg1="@{jar}" arg2="yes"/><then> - <jar whenmanifestonly="fail" destfile="${build-libs.dir}/@{project}.jar" basedir="${@{project}-classes}"/></then></if> - <stopwatch name="@{project}.timer" action="total"/> - <mkdir dir="${build-libs.dir}"/> - <touch file="${build-libs.dir}/@{project}.complete" verbose="no"/> - </then></if> - </sequential> - </macrodef> <target name="asm.done" depends="init"> <simple-javac project="asm" jar="no"/> </target> <target name="forkjoin.done" depends="init"> <simple-javac project="forkjoin" args="-XDignore.symbol.file"/></target> -<!-- =========================================================================== - STAGED COMPILATION MACROS -============================================================================ --> - <macrodef name="staged-javac" > - <attribute name="stage"/> <!-- current stage (locker, quick, strap) --> - <attribute name="project"/> <!-- project: library/reflect/compiler/actors --> - <attribute name="destproject" default="@{project}"/> <!-- overrides the output directory; used when building multiple projects into the same directory--> - <attribute name="args" default=""/> - <attribute name="excludes" default=""/> - - <sequential> - <javac - debug="true" - srcdir="${src.dir}/@{project}" - destdir="${build-@{stage}.dir}/classes/@{destproject}" - includes="**/*.java" - excludes="@{excludes}" - target="1.6" source="1.5"> - <compilerarg line="${javac.args} @{args}"/> - <classpath refid="@{stage}.@{destproject}.build.path"/> - </javac> - </sequential> - </macrodef> - - <!-- Zinc assumes a one-to-one correspondence of output folder to set of source files. - When compiling different sets of source files in multiple compilations to the same output directory, - Zinc thinks source files that appeared in an earlier compilation but are absent in the current one, - were deleted and thus deletes the corresponding output files. - - Note that zinc also requires each arg to scalac to be prefixed by -S. + <!-- For local development only. We only allow released versions of Scala for STARR. + This builds quick (core only) and publishes it with a generated version number, + saving it as starr.version in build.properties, so this compiler will be used as STARR in your next build + NOTES: + - to speed things up, you can also pass -Dlocker.skip=1 --> - <macrodef name="zinc"> - <attribute name="compilerpathref" /> - <attribute name="destdir" /> - <attribute name="srcdir" /> - <attribute name="srcpath" default="NOT SET"/> <!-- needed to compile the library, "NOT SET" is just a convention to denote an optional attribute --> - <attribute name="buildpathref" /> - <attribute name="params" default="" /> - <attribute name="java-excludes" default=""/> - - <sequential> - <local name="sources"/> - <pathconvert pathsep=" " property="sources"> - <fileset dir="@{srcdir}"> - <include name="**/*.java"/> - <include name="**/*.scala"/> - <exclude name="@{java-excludes}"/> - </fileset> - </pathconvert> - <local name="args"/> - <local name="sargs"/> - <if><not><equals arg1="@{srcpath}" arg2="NOT SET"/></not><then> - <property name="args" value="@{params} -sourcepath @{srcpath}"/> - </then></if> - <property name="args" value="@{params}"/> <!-- default --> - - <!-- HACK: prefix scalac args by -S --> - <script language="javascript"> - project.setProperty("sargs", project.getProperty("args").trim().replaceAll(" ", " -S")); - </script> - - <exec osfamily="unix" executable="tools/zinc" failifexecutionfails="true" failonerror="true"> - <arg line="-nailed -compile-order JavaThenScala -scala-path ${ant.refid:@{compilerpathref}} -d @{destdir} -classpath ${toString:@{buildpathref}} ${sargs} ${sources}"/> - </exec> - </sequential> - </macrodef> - - <macrodef name="staged-scalac" > - <attribute name="with"/> <!-- will use path `@{with}.compiler.path` to locate scalac --> - <attribute name="stage"/> <!-- current stage (locker, quick, strap) --> - <attribute name="project"/> <!-- project: library/reflect/compiler/actors --> - <attribute name="srcpath" default="NOT SET"/> <!-- needed to compile the library --> - <attribute name="args" default=""/> <!-- additional args --> - <attribute name="destproject" default="@{project}"/> <!-- overrides the output directory; used when building multiple projects into the same directory--> - <attribute name="srcdir" default="@{project}"/> - <attribute name="java-excludes" default=""/> - - <sequential> - <!-- TODO: detect zinc anywhere on PATH - use zinc for the quick stage if it's available; - would use it for locker but something is iffy in sbt: get a class cast error on global phase --> - <if><and> <available file="tools/zinc"/> - <equals arg1="@{stage}" arg2="quick"/> - <not><equals arg1="@{project}" arg2="continuations-plugins"/></not> <!-- doesn't work in zinc because it requires the quick compiler, which isn't jarred up--> - </and><then> - <zinc taskname="Z.@{stage}.@{project}" - compilerpathref="@{with}.compiler.path" - destdir="${build-@{stage}.dir}/classes/@{destproject}" - srcdir="${src.dir}/@{srcdir}" - srcpath="@{srcpath}" - buildpathref="@{stage}.@{project}.build.path" - params="${scalac.args.@{stage}} @{args}" - java-excludes="@{java-excludes}"/></then> - <else> - <if><equals arg1="@{srcpath}" arg2="NOT SET"/><then> - <scalacfork taskname="@{stage}.@{project}" - jvmargs="${scalacfork.jvmargs}" - compilerpathref="@{with}.compiler.path" - destdir="${build-@{stage}.dir}/classes/@{destproject}" - srcdir="${src.dir}/@{srcdir}" - params="${scalac.args.@{stage}} @{args}"> - <include name="**/*.scala"/> - <compilationpath refid="@{stage}.@{project}.build.path"/></scalacfork></then> - <else> - <scalacfork taskname="@{stage}.@{project}" - jvmargs="${scalacfork.jvmargs}" - compilerpathref="@{with}.compiler.path" - destdir="${build-@{stage}.dir}/classes/@{destproject}" - srcdir="${src.dir}/@{srcdir}" - srcpath="@{srcpath}" - params="${scalac.args.@{stage}} @{args}"> - <include name="**/*.scala"/> - <compilationpath refid="@{stage}.@{project}.build.path"/></scalacfork></else> - </if> - </else></if> - </sequential> - </macrodef> - - <macrodef name="staged-uptodate" > - <attribute name="stage"/> - <attribute name="project"/> - <element name="check"/> - <element name="do"/> - - <sequential> - <uptodate property="@{stage}.@{project}.available" targetfile="${build-@{stage}.dir}/@{project}.complete"> - <check/> - </uptodate> - <if><not><isset property="@{stage}.@{project}.available"/></not><then> - <do/> - <touch file="${build-@{stage}.dir}/@{project}.complete" verbose="no"/> - </then></if> - </sequential> - </macrodef> - - <macrodef name="staged-build" > - <attribute name="with"/> <!-- will use path `@{with}.compiler.path` to locate scalac --> - <attribute name="stage"/> <!-- current stage (locker, quick, strap) --> - <attribute name="project"/> <!-- project: library/reflect/compiler/actors --> - <attribute name="srcpath" default="NOT SET"/> <!-- needed to compile the library --> - <attribute name="args" default=""/> <!-- additional args --> - <attribute name="includes" default="comp.includes"/> - <attribute name="java-excludes" default=""/> - <attribute name="version" default=""/> <!-- non-empty for scaladoc: use @{version}.version.number in property file--> - - <sequential> - <staged-uptodate stage="@{stage}" project="@{project}"> - <check><srcfiles dir="${src.dir}/@{project}"/></check> - <do> - <stopwatch name="@{stage}.@{project}.timer"/> - <mkdir dir="${build-@{stage}.dir}/classes/@{project}"/> - <staged-javac stage="@{stage}" project="@{project}" excludes="@{java-excludes}"/> <!-- always compile with javac for simplicity and regularity; it's cheap --> - <staged-scalac with="@{with}" stage="@{stage}" project="@{project}" srcpath="@{srcpath}" args="@{args}" java-excludes="@{java-excludes}"/> - <if><equals arg1="@{version}" arg2=""/><then> - <propertyfile file = "${build-@{stage}.dir}/classes/@{project}/@{project}.properties"> - <entry key = "version.number" value="${version.number}"/> - <entry key = "maven.version.number" value="${maven.version.number}"/> - <entry key = "osgi.version.number" value="${osgi.version.number}"/> - <entry key = "copyright.string" value="${copyright.string}"/> - </propertyfile> - </then><else> - <propertyfile file = "${build-@{stage}.dir}/classes/@{project}/@{project}.properties"> - <entry key = "version.number" value="${@{version}.version.number}"/> - <entry key = "copyright.string" value="${copyright.string}"/> - </propertyfile> - </else></if> - <copy todir="${build-@{stage}.dir}/classes/@{project}"> - <fileset dir="${src.dir}/@{project}"> - <patternset refid="@{includes}"/> - </fileset> - </copy> - <stopwatch name="@{stage}.@{project}.timer" action="total"/> - </do> - </staged-uptodate> - </sequential> - </macrodef> - - <macrodef name="staged-bin"> - <attribute name="stage"/> - <attribute name="classpathref" default="NOT SET"/> - <sequential> - <staged-uptodate stage="@{stage}" project="bin"> - <check> - <srcfiles dir="${src.dir}"> - <include name="compiler/scala/tools/ant/templates/**"/> - </srcfiles> - </check> - <do> - <taskdef name="mk-bin" classname="scala.tools.ant.ScalaTool" classpathref="@{stage}.bin.tool.path"/> - <mkdir dir="${build-@{stage}.dir}/bin"/> - <if><equals arg1="@{classpathref}" arg2="NOT SET"/><then> - <mk-bin file="${build-@{stage}.dir}/bin/scala" class="scala.tools.nsc.MainGenericRunner" javaFlags="${java.flags}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scalac" class="scala.tools.nsc.Main" javaFlags="${java.flags}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scaladoc" class="scala.tools.nsc.ScalaDoc" javaFlags="${java.flags}"/> - <mk-bin file="${build-@{stage}.dir}/bin/fsc" class="scala.tools.nsc.CompileClient" javaFlags="${java.flags}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scalap" class="scala.tools.scalap.Main" javaFlags="${java.flags}"/> - </then><else> - <mk-bin file="${build-@{stage}.dir}/bin/scala" class="scala.tools.nsc.MainGenericRunner" javaFlags="${java.flags}" classpathref="@{classpathref}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scalac" class="scala.tools.nsc.Main" javaFlags="${java.flags}" classpathref="@{classpathref}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scaladoc" class="scala.tools.nsc.ScalaDoc" javaFlags="${java.flags}" classpathref="@{classpathref}"/> - <mk-bin file="${build-@{stage}.dir}/bin/fsc" class="scala.tools.nsc.CompileClient" javaFlags="${java.flags}" classpathref="@{classpathref}"/> - <mk-bin file="${build-@{stage}.dir}/bin/scalap" class="scala.tools.scalap.Main" javaFlags="${java.flags}" classpathref="@{classpathref}"/> - </else></if> - <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scala"/> - <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scalac"/> - <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scaladoc"/> - <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/fsc"/> - <chmod perm="ugo+rx" file="${build-@{stage}.dir}/bin/scalap"/> - </do> - </staged-uptodate> - </sequential> - </macrodef> - - <macrodef name="staged-pack"> - <attribute name="project"/> - <attribute name="manifest" default=""/> - <element name="pre" optional="true"/> - <element name="jar-opts" optional="true"/> - - <sequential> - <local name="destfile"/> <property name="destfile" value="${build-pack.dir}/${@{project}.targetdir}/${@{project}.targetjar}"/> - - <uptodate property="pack.@{project}.available" targetfile="${destfile}"> - <srcresources> - <resources refid="pack.@{project}.files"/> - <!-- <path><pathelement location="${build-quick.dir}/@{project}.complete"/></path> --> - </srcresources> - </uptodate> - <if><not><isset property="pack.@{project}.available"/></not><then> - <mkdir dir="${build-pack.dir}/${@{project}.targetdir}"/> - <pre/> - - <if><not><equals arg1="@{manifest}" arg2=""/></not><then> - <jar whenmanifestonly="fail" destfile="${destfile}" manifest="@{manifest}"> <!-- update="true" makes no difference on my machine, so starting from scratch--> - <jar-opts/> - <path refid="pack.@{project}.files"/> - </jar></then> - <else> - <jar whenmanifestonly="fail" destfile="${destfile}"> - <jar-opts/> - <path refid="pack.@{project}.files"/> - </jar> - </else></if> - </then></if> - </sequential> - </macrodef> - - <macrodef name="staged-docs"> - <attribute name="project"/> - - <element name="includes" implicit="true"/> - - <sequential> - <staged-uptodate stage="docs" project="@{project}"> - <check><srcfiles dir="${src.dir}/${@{project}.srcdir}"/></check> - <do> - <stopwatch name="docs.@{project}.timer"/> - <mkdir dir="${build-docs.dir}/@{project}"/> - <if><equals arg1="${@{project}.docroot}" arg2="NOT SET"/><then> - <scaladoc - destdir="${build-docs.dir}/@{project}" - doctitle="${@{project}.description}" - docfooter="epfl" - docversion="${version.number}" - sourcepath="${src.dir}" - classpathref="docs.@{project}.build.path" - srcdir="${src.dir}/${@{project}.srcdir}" - addparams="${scalac.args.all}" - implicits="on" - diagrams="on" - groups="on" - rawOutput="${scaladoc.raw.output}" - noPrefixes="${scaladoc.no.prefixes}" - docUncompilable="${src.dir}/library-aux" - skipPackages="${@{project}.skipPackages}"> - <includes/> - </scaladoc> - </then><else> - <scaladoc - destdir="${build-docs.dir}/@{project}" - doctitle="${@{project}.description}" - docfooter="epfl" - docversion="${version.number}" - sourcepath="${src.dir}" - classpathref="docs.@{project}.build.path" - srcdir="${src.dir}/${@{project}.srcdir}" - docRootContent="${src.dir}/@{project}/${@{project}.docroot}" - addparams="${scalac.args.all}" - implicits="on" - diagrams="on" - groups="on" - rawOutput="${scaladoc.raw.output}" - noPrefixes="${scaladoc.no.prefixes}" - docUncompilable="${src.dir}/library-aux" - skipPackages="${@{project}.skipPackages}"> - <includes/> - </scaladoc> - </else></if> - <stopwatch name="docs.@{project}.timer" action="total"/> - </do> - </staged-uptodate> - </sequential> - </macrodef> - + <target name="replacestarr" depends="init.git" description="Produces a new STARR from current sources. Publishes core locally with a generated version number, + stored in build.properties as starr.version (overriding the one in versions.properties)."> + <antcall target="publish-core-local"> + <param name="maven.version.suffix" value="-STARR-${git.commit.sha}-SNAPSHOT"/> + <param name="docs.skip" value="1"/> + <param name="scalac.args.optimise" value="-optimise"/> + <param name="update.starr.version" value="alright then"/> + </antcall> + </target> <!-- =========================================================================== @@ -1574,29 +1203,6 @@ TODO: <target name="strap-opt" description="Optimized version of strap.done."> <optimized name="strap.done"/></target> -<!-- =========================================================================== - PACKED LOCKER BUILD (PALO) -============================================================================ --> - <target name="palo.done" depends="locker.done"> - <mkdir dir="${build-palo.dir}/lib"/> - <jar whenmanifestonly="fail" destfile="${build-palo.dir}/lib/scala-library.jar"> - <fileset dir="${build-locker.dir}/classes/library"/> - <fileset dir="${forkjoin-classes}"/> - </jar> - <jar whenmanifestonly="fail" destfile="${build-palo.dir}/lib/scala-reflect.jar" manifest="${basedir}/META-INF/MANIFEST.MF" - basedir="${build-locker.dir}/classes/reflect"/> - <jar whenmanifestonly="fail" destfile="${build-palo.dir}/lib/scala-compiler.jar" manifest="${basedir}/META-INF/MANIFEST.MF"> - <fileset dir="${build-locker.dir}/classes/compiler"/> - <fileset dir="${asm-classes}"/> - </jar> - <copy todir="${build-palo.dir}/lib"> - <resources refid="repl.fileset"/> - <mapper classpathref="maven-ant-tasks.classpath" classname="org.apache.maven.artifact.ant.VersionMapper" from="${repl.deps.versions}" to="flatten"/> - </copy> - </target> - - <target name="palo.bin" depends="palo.done"> <staged-bin stage="palo"/></target> - <!-- =========================================================================== OSGi Artifacts @@ -1605,43 +1211,7 @@ TODO: This means adding manifests and enforcing the Exports clauses (removing non-exported classes!) These jars are then copied to the distribution and published to maven. --> - <macrodef name="make-bundle"> - <attribute name="project" /> - <element name="srcs" description="Sources for this bundle" optional="true" implicit="true"/> - - <sequential> - <copy file="${src.dir}/build/bnd/${@{project}.name}.bnd" tofile="${build-osgi.dir}/${@{project}.name}.bnd" overwrite="true"> - <filterset> - <filter token="VERSION" value="${osgi.version.number}" /> - <filter token="SCALA_BINARY_VERSION" value="${scala.binary.version}" /> - <filter token="SCALA_COMPILER_DOC_VERSION" value="${scala-compiler-doc.version.number}" /> - <filter token="SCALA_COMPILER_INTERACTIVE_VERSION" value="${scala-compiler-interactive.version.number}" /> - </filterset> - </copy> - <bnd classpath="${@{project}.jar}" - eclipse="false" - failok="false" - exceptions="true" - files="${build-osgi.dir}/${@{project}.name}.bnd" - output="${build-osgi.dir}"/> - <if><equals arg1="${@{project}.src}" arg2="true"/><then> - <!-- - A jar-like task that creates an OSGi source bundle. It adds the required MANIFEST.MF headers that allow - Eclipse to match sources with the corresponding binaries. - --> - <jar whenmanifestonly="fail" destfile="${build-osgi.dir}/${@{project}.name}-src.jar"> - <srcs/> - <manifest> - <attribute name="Manifest-Version" value="1.0"/> - <attribute name="Bundle-Name" value="${@{project}.description} Sources"/> - <attribute name="Bundle-SymbolicName" value="org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix}.source"/> - <attribute name="Bundle-Version" value="${@{project}.version}"/> - <attribute name="Eclipse-SourceBundle" value="org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix};version="${@{project}.version}";roots:="."" /> - </manifest> - </jar> - </then></if> - </sequential> - </macrodef> + <target name="osgi.core" depends="pack.core"> <mkdir dir="${build-osgi.dir}"/> @@ -1892,6 +1462,17 @@ TODO: <testSuite colors="8" kinds="pos neg run jvm res scalap scalacheck specialized instrumented"/> </target> + <target name="test.suite.quick" depends="init, quick.done"> + <path id="test.suite.path"> + <path refid="quick.bin.tool.path"/> + <path refid="quick.interactive.build.path"/> + <path refid="partest.compilation.path.noncore"/> + </path> + <property name="pcp" value="${toString:test.suite.path}"/> + <taskdef classpathref="test.suite.path" resource="scala/tools/partest/antlib.xml"/> + <testSuite colors="8" kinds="pos neg run jvm res scalap scalacheck specialized instrumented" pcp="${pcp}"/> + </target> + <target name="test.run" depends="test.suite.init"> <testSuite kinds="run jvm"/> </target> @@ -1936,46 +1517,7 @@ TODO: <property name="maven-deps-done-mima" value="true"/> </target> - <macrodef name="bc.run-mima"> - <attribute name="jar-name"/> - <attribute name="prev"/> - <attribute name="curr"/> - <attribute name="direction"/> - <sequential> - <echo message="Checking @{direction} binary compatibility for @{jar-name} (against ${bc-reference-version})"/> - <java taskname="mima" - fork="true" - failonerror="true" - classname="com.typesafe.tools.mima.cli.Main"> - <arg value="--prev"/> - <arg value="@{prev}"/> - <arg value="--curr"/> - <arg value="@{curr}"/> - <arg value="--filters"/> - <arg value="${basedir}/bincompat-@{direction}.whitelist.conf"/> - <arg value="--generate-filters"/> - <classpath> - <path refid="mima.classpath"/> - </classpath> - </java> - </sequential> - </macrodef> - - <macrodef name="bc.check"> - <attribute name="project"/> - <sequential> - <bc.run-mima - jar-name="scala-@{project}" - prev="${org.scala-lang:scala-@{project}:jar}" - curr="${@{name}.jar}" - direction="backward"/> - <bc.run-mima - jar-name="scala-@{project}" - prev="${@{name}.jar}" - curr="${org.scala-lang:scala-@{project}:jar}" - direction="forward"/> - </sequential> - </macrodef> + <target name="test.bc-opt" description="Optimized version of test.bc."> <optimized name="test.bc"/></target> @@ -2129,14 +1671,6 @@ TODO: <property name="dist.name" value="scala-${version.number}"/> <property name="dist.dir" value="${dists.dir}/${dist.name}"/> - <macrodef name="copy-bundle"> - <attribute name="project" /> - - <sequential> - <copy tofile="${dist.dir}/${@{project}.targetdir}/${@{project}.name}.jar" file="${build-osgi.dir}/org.scala-lang.${@{project}.package}${@{project}.name}.jar" overwrite="true"/> - <copy tofile="${dist.dir}/src/${@{project}.name}-src.jar" file="${@{project}.srcjar}" overwrite="true"/> - </sequential> - </macrodef> <mkdir dir="${dist.dir}/lib"/> <mkdir dir="${dist.dir}/${continuations-plugin.targetdir}"/> @@ -2231,28 +1765,6 @@ MAIN DISTRIBUTION PACKAGING ============================================================================ --> <target name="pack-archives.done" depends="dist.done, docs.done"> - <macrodef name="tarz"> - <attribute name="name" description="The tar file name (without extension)."/> - <element name="file-sets" description="A sequence of fileset elements to be included in the tar balls." optional="false" implicit="true"/> - - <sequential> - <tar destfile="@{name}.tar" compression="none" longfile="gnu"> - <file-sets/> - </tar> - <gzip src="@{name}.tar" destfile="@{name}.tgz"/> - <if> - <not><equals arg1="${archives.skipxz}" arg2="true" /></not> - <then> - <exec executable="xz" failifexecutionfails="false"> - <arg line="-k -9e -S .xz @{name}.tar"/> - </exec> - <move file="@{name}.tar.xz" tofile="@{name}.txz" failonerror="false"/> - </then> - </if> - <delete file="@{name}.tar" /> - </sequential> - </macrodef> - <mkdir dir="${dists.dir}/archives"/> <property name="archive-base" value="${dists.dir}/archives/${dist.name}"/> @@ -2311,25 +1823,6 @@ MAIN DISTRIBUTION PACKAGING </else></if> --> </target> - <macrodef name="mvn-package"> - <attribute name="project"/> - - <sequential> - <local name="artifact-base"/> <property name="artifact-base" value="${maven-base}/${@{project}.dir}${@{project}.name}/${@{project}.name}"/> - - <mkdir dir="${maven-base}/${@{project}.dir}${@{project}.name}"/> - <copy tofile="${artifact-base}.jar" file="${build-osgi.dir}/org.scala-lang.${@{project}.package}${@{project}.name}${@{project}.namesuffix}.jar" overwrite="true"/> - <copy tofile="${artifact-base}-src.jar" file="${build-osgi.dir}/${@{project}.name}-src.jar" overwrite="true"/> - <copy tofile="${artifact-base}-pom.xml" file="${src.dir}/build/maven/${@{project}.dir}/${@{project}.name}-pom.xml" overwrite="true"/> - - <if><not><isset property="docs.skip"/></not><then> - <jar destfile="${artifact-base}-docs.jar" basedir="${build-docs.dir}/@{project}" whenmanifestonly="fail"> - <include name="**/*"/> - </jar> - </then></if> - </sequential> - </macrodef> - <target name="pack-maven.core" depends="osgi.core, docs.core"> <property name="maven-base" value="${dists.dir}/maven/${version.number}"/> <mkdir dir="${maven-base}"/> @@ -2337,6 +1830,14 @@ MAIN DISTRIBUTION PACKAGING <mvn-package project="library"/> <mvn-package project="reflect"/> <mvn-package project="compiler"/> + + <!-- for replacestarr --> + <if><isset property="update.starr.version"/><then> + <echo message="From now on, ${maven.version.number} will be used as STARR (`build.properties`'s `starr.version` was modified)."/> + <propertyfile file = "build.properties"> + <entry key = "starr.version" value="${maven.version.number}"/> + </propertyfile> + </then></if> </target> <target name="pack-maven.base" depends="pack-maven.core, osgi.done, docs.done"> @@ -2425,123 +1926,6 @@ MAIN DISTRIBUTION PACKAGING </target> <!-- =========================================================================== - STABLE REFERENCE (STARR) -============================================================================ --> -<!-- Does not use any properties other than ${basedir}, so that it can - run without 'init' (when using 'replacestarrwin') --> - - <target name="starr.start"> - <fail message="Library in build/pack not available"> - <condition><not><and> - <available file="${library.jar}"/> - </and></not></condition> - </fail> - <fail message="Compiler in build/quick not available"> - <condition><not><and> - <available file="${build-quick.dir}/classes/compiler"/> - <available file="${build-quick.dir}/compiler.complete"/> - </and></not></condition> - </fail> - </target> - - <target name="starr.jars" depends="starr.start"> - <copy toDir="${lib.dir}" overwrite="true"> - <fileset dir="${build-pack.dir}/lib"> - <include name="scala-library.jar"/> - <include name="scala-reflect.jar"/> - <include name="scala-compiler.jar"/> - </fileset> - </copy> - </target> - - <target name="starr.src" depends="starr.jars"> - <jar whenmanifestonly="fail" destfile="${lib.dir}/scala-library-src.jar"> - <fileset dir="${src.dir}/library"/> - <fileset dir="${src.dir}/swing"/> - <fileset dir="${src.dir}/actors"/> - <fileset dir="${src.dir}/forkjoin"/> - </jar> - <jar whenmanifestonly="fail" destfile="${lib.dir}/scala-reflect-src.jar" basedir="${src.dir}/reflect"/> - <jar whenmanifestonly="fail" destfile="${lib.dir}/scala-compiler-src.jar"> - <fileset dir="${src.dir}/compiler"/> - <fileset dir="${src.dir}/asm"/> - </jar> - </target> - - <target name="starr.removesha1" depends="starr.src"> - <!-- remove SHA1 files for no starr, so we don't loose artifacts. --> - <delete> - <fileset dir="${lib.dir}"> - <include name="scala-compiler.jar.desired.sha1"/> - <include name="scala-reflect.jar.desired.sha1"/> - <include name="scala-library.jar.desired.sha1"/> - <include name="scala-library-src.jar.desired.sha1"/> - <include name="scala-reflect-src.jar.desired.sha1"/> - <include name="scala-compiler-src.jar.desired.sha1"/> - </fileset> - </delete> - </target> - - <target name="starr.done" depends="starr.jars, starr.removesha1"/> - - <target name="replacestarr" description="Replaces the Starr compiler and library by fresh ones built from current sources and tests them."> - <fail message="This target is not available on Windows. Use 'ant replacestarrwin' instead."> - <condition> - <os family="windows"/> - </condition> - </fail> - <!-- needs antcall to enforce ordering --> - <antcall target="locker.clean"/> - <antcall target="pack.done"/> - <antcall target="starr.done"/> - <antcall target="locker.clean"/> - <antcall target="test.done"/> - </target> - - <target name="replacestarr-opt" description="Replaces the Starr compiler and library by fresh, optimised ones built from current sources and tests them."> - <optimized name="replacestarr"/></target> - - <!-- Ant on Windows is not able to delete jar files that are referenced in any <path>. - See ticket 1290 on trac. --> - <target name="replacestarrwin" description="Creates a new Starr on Windows. Manually execute 'ant locker.clean build' first!"> - <fail message="This target is only available on Windows. Use 'ant replacestarr' instead."> - <condition> - <not><os family="windows"/></not> - </condition> - </fail> - <echo message="CAUTION: Make sure to execute 'ant locker.clean build' prior to calling 'replacestarrwin'."/> - <antcall target="starr.done"/> - <antcall target="locker.clean"/> - <antcall target="test.done"/> - </target> - - <target name="replacestarrwin-opt" description="Creates a new Starr on Windows. Manually execute 'ant locker.clean build' first!"> - <optimized name="replacestarrwin"/></target> - - <target name="replacelocker" description="Replaces the Locker compiler and library by fresh ones built from current sources." - depends="palo.clean, locker.unlock, palo.done"/> - - <target name="replacelocker-opt" description="Replaces the Locker compiler and library by fresh, optimised ones built from current sources."> - <optimized name="replacelocker"/></target> - - <target name="buildlocker" description="Does the same for locker as build does for quick." depends="locker.unlock, palo.bin"/> - <target name="unlocklocker" description="Same as buildlocker." depends="buildlocker"/> <!-- REMOVE --> - - <target name="fastlocker.lib" description="Buildlocker without extra fuss" depends="locker.unlock, locker.lib"> - <property name="fastlocker" value="true"/> - </target> - - <target name="fastlocker.reflect" description="Buildlocker without extra fuss" depends="locker.unlock, locker.reflect"> - <property name="fastlocker" value="true"/> - </target> - - <target name="fastlocker.comp" description="Buildlocker without extra fuss" depends="locker.unlock, locker.comp"> - <property name="fastlocker" value="true"/> - </target> - - <target name="fastlocker" description="Buildlocker without extra fuss" depends="fastlocker.comp"/> - -<!-- =========================================================================== VISUALIZATION ============================================================================ --> diff --git a/docs/examples/fors.scala b/docs/examples/fors.scala index b937e53fcd..29616b61b1 100644 --- a/docs/examples/fors.scala +++ b/docs/examples/fors.scala @@ -83,7 +83,7 @@ object fors { if b1 != b2; Elem(_, "author", _, _, Text(a1)) <- b1.toList; Elem(_, "author", _, _, Text(a2)) <- b2.toList; - if a1 == a2) yield Pair(a1, a2)) + if a1 == a2) yield (a1, a2)) def removeDuplicates[a](xs: List[a]): List[a] = if (xs.isEmpty) diff --git a/docs/examples/iterators.scala b/docs/examples/iterators.scala index e2e5e050a0..9ddb141d61 100644 --- a/docs/examples/iterators.scala +++ b/docs/examples/iterators.scala @@ -15,8 +15,8 @@ object iterators { def findGreater(xs: Array[Double], limit: Double) = xs.iterator .zip(Iterator.from(0)) - .filter{case Pair(x, i) => x > limit } - .map{case Pair(x, i) => i} + .filter{case (x, i) => x > limit } + .map{case (x, i) => i} def main(args: Array[String]) { val ar = Array/*[Double]*/(6, 2, 8, 5, 1) diff --git a/docs/examples/jolib/Ref.scala b/docs/examples/jolib/Ref.scala index 32952b4351..099a3c2df2 100644 --- a/docs/examples/jolib/Ref.scala +++ b/docs/examples/jolib/Ref.scala @@ -12,20 +12,20 @@ import concurrent.SyncVar; import concurrent.jolib._; class Ref[a](init: a) extends Join { - + object get extends Synchr[a](this) { case class C() extends SyncVar[a]; } object set extends Synchr[unit](this) { case class C(x: a) extends SyncVar[unit]; } object state extends Asynchr(this) { case class C(x: a); } rules ( - Pair(List(get, state), { case List(g @ get.C(), state.C(x) ) => + (List(get, state), { case List(g @ get.C(), state.C(x) ) => { g.set(x); state(state.C(x)) } }), - Pair(List(set, state), { case List(s @ set.C(x), state.C(y) ) => + (List(set, state), { case List(s @ set.C(x), state.C(y) ) => { s.set(()); state(state.C(x)) } }) ); state(state.C(init)); - + def Get: a = get(get.C()); def Set(x: a): unit = set(set.C(x)); } diff --git a/docs/examples/jolib/parallelOr.scala b/docs/examples/jolib/parallelOr.scala index fb8288c5b2..a0305c56bf 100644 --- a/docs/examples/jolib/parallelOr.scala +++ b/docs/examples/jolib/parallelOr.scala @@ -13,27 +13,27 @@ import concurrent.SyncVar; /** Implementation in the join-calculus of a parallel OR. */ object or extends Join { - + object res extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] }; object res1 extends Asynchr(this) { case class C(b: boolean); } object res2 extends Asynchr(this) { case class C(b: boolean); } object res1False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] }; object res2False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] }; - + rules( - Pair(List(res, res1), { case List(r @ res.C(), res1.C(b)) => + (List(res, res1), { case List(r @ res.C(), res1.C(b)) => if (b) r.set(b) else r.set(res1False(res1False.C())) }), - - Pair(List(res, res2), { case List(r @ res.C(), res2.C(b)) => + + (List(res, res2), { case List(r @ res.C(), res2.C(b)) => if (b) r.set(b) else r.set(res2False(res2False.C())) }), - - Pair(List(res1False, res2), { case List(r @ res1False.C(), res2.C(b)) => + + (List(res1False, res2), { case List(r @ res1False.C(), res2.C(b)) => r.set(b) }), - - Pair(List(res2False, res1), { case List(r @ res2False.C(), res1.C(b)) => + + (List(res2False, res1), { case List(r @ res2False.C(), res1.C(b)) => r.set(b) }) ); - + def apply(b1: => boolean, b2: => boolean): boolean = { concurrent.ops.spawn(res1(res1.C(b1))); concurrent.ops.spawn(res2(res2.C(b2))); @@ -42,7 +42,7 @@ object or extends Join { } */ object parallelOr { - + def main(args: Array[String]): unit = { def loop: boolean = { while (true) {}; true }; /* diff --git a/docs/examples/monads/callccInterpreter.scala b/docs/examples/monads/callccInterpreter.scala index 5b556bd8fa..b5008c4c1b 100644 --- a/docs/examples/monads/callccInterpreter.scala +++ b/docs/examples/monads/callccInterpreter.scala @@ -14,7 +14,7 @@ object callccInterpreter { def showM(m: M[Value]): String = (m in id).toString(); - def callCC[A](h: (A => M[A]) => M[A]) = + def callCC[A](h: (A => M[A]) => M[A]) = M[A](c => h(a => M[A](d => c(a))) in c); type Name = String; @@ -30,7 +30,7 @@ object callccInterpreter { trait Value; case object Wrong extends Value { override def toString() = "wrong" - } + } case class Num(n: Int) extends Value { override def toString() = n.toString(); } @@ -38,15 +38,15 @@ object callccInterpreter { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]]; + type Environment = List[Tuple2[Name, Value]]; def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => unitM(Num(m + n)) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => unitM(Num(m + n)) case _ => unitM(Wrong) } @@ -62,15 +62,15 @@ object callccInterpreter { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) yield c - case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e)) + case Ccc(x, t) => callCC(k => interp(t, (x, Fun(k)) :: e)) } - def test(t: Term): String = + def test(t: Term): String = showM(interp(t, List())); val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))); diff --git a/docs/examples/monads/directInterpreter.scala b/docs/examples/monads/directInterpreter.scala index 06fffba8e2..d8ca8ccfa7 100644 --- a/docs/examples/monads/directInterpreter.scala +++ b/docs/examples/monads/directInterpreter.scala @@ -20,15 +20,15 @@ object directInterpreter { case Fun(f) => "<function>" } - type Environment = List[Pair[Name, Value]]; + type Environment = List[Tuple2[Name, Value]]; def lookup(x: Name, e: Environment): Value = e match { case List() => Wrong - case Pair(y, b) :: e1 => if (x == y) b else lookup(x, e1) + case (y, b) :: e1 => if (x == y) b else lookup(x, e1) } - def add(a: Value, b: Value): Value = Pair(a, b) match { - case Pair(Num(m), Num(n)) => Num(m + n) + def add(a: Value, b: Value): Value = (a, b) match { + case (Num(m), Num(n)) => Num(m + n) case _ => Wrong } @@ -41,15 +41,15 @@ object directInterpreter { case Var(x) => lookup(x, e) case Con(n) => Num(n) case Add(l, r) => add(interp(l, e), interp(r, e)) - case Lam(x, t) => Fun(a => interp(t, Pair(x, a) :: e)) + case Lam(x, t) => Fun(a => interp(t, (x, a) :: e)) case App(f, t) => apply(interp(f, e), interp(t, e)) } - def test(t: Term): String = + def test(t: Term): String = showval(interp(t, List())); val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))); - def main(args: Array[String]) = + def main(args: Array[String]) = System.out.println(test(term0)); } diff --git a/docs/examples/monads/errorInterpreter.scala b/docs/examples/monads/errorInterpreter.scala index d3cc45627d..c15e1041e2 100644 --- a/docs/examples/monads/errorInterpreter.scala +++ b/docs/examples/monads/errorInterpreter.scala @@ -41,15 +41,15 @@ object errorInterpreter { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]] + type Environment = List[Tuple2[Name, Value]] def lookup(x: Name, e: Environment): M[Value] = e match { case List() => errorM("unbound variable: " + x); - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => unitM(Num(m + n)) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => unitM(Num(m + n)) case _ => errorM("should be numbers: " + a + "," + b) } @@ -65,7 +65,7 @@ object errorInterpreter { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) diff --git a/docs/examples/monads/simpleInterpreter.scala b/docs/examples/monads/simpleInterpreter.scala index cde3a92dbb..64636749ff 100644 --- a/docs/examples/monads/simpleInterpreter.scala +++ b/docs/examples/monads/simpleInterpreter.scala @@ -22,7 +22,7 @@ object simpleInterpreter { trait Value; case object Wrong extends Value { override def toString() = "wrong" - } + } case class Num(n: Int) extends Value { override def toString() = n.toString(); } @@ -30,15 +30,15 @@ object simpleInterpreter { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]]; + type Environment = List[Tuple2[Name, Value]]; def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => unitM(Num(m + n)) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => unitM(Num(m + n)) case _ => unitM(Wrong) } @@ -54,14 +54,14 @@ object simpleInterpreter { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) yield c } - def test(t: Term): String = + def test(t: Term): String = showM(interp(t, List())); val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))); diff --git a/docs/examples/monads/stateInterpreter.scala b/docs/examples/monads/stateInterpreter.scala index 97f3335dab..e13e9049da 100644 --- a/docs/examples/monads/stateInterpreter.scala +++ b/docs/examples/monads/stateInterpreter.scala @@ -4,20 +4,20 @@ object stateInterpreter { type State = Int; - val tickS = new M(s => Pair((), s + 1)); + val tickS = new M(s => ((), s + 1)); - case class M[A](in: State => Pair[A, State]) { - def bind[B](k: A => M[B]) = M[B]{ s0 => - val Pair(a, s1) = this in s0; k(a) in s1 + case class M[A](in: State => Tuple2[A, State]) { + def bind[B](k: A => M[B]) = M[B]{ s0 => + val (a, s1) = this in s0; k(a) in s1 } def map[B](f: A => B): M[B] = bind(x => unitM(f(x))); def flatMap[B](f: A => M[B]): M[B] = bind(f); } - def unitM[A](a: A) = M[A](s => Pair(a, s)); + def unitM[A](a: A) = M[A](s => (a, s)); def showM(m: M[Value]): String = { - val Pair(a, s1) = m in 0; + val (a, s1) = m in 0; "Value: " + a + "; Count: " + s1 } @@ -41,15 +41,15 @@ object stateInterpreter { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]]; + type Environment = List[Tuple2[Name, Value]]; def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => for (_ <- tickS) yield Num(m + n) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => for (_ <- tickS) yield Num(m + n) case _ => unitM(Wrong) } @@ -65,14 +65,14 @@ object stateInterpreter { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) yield c } - def test(t: Term): String = + def test(t: Term): String = showM(interp(t, List())); val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))); diff --git a/docs/examples/patterns.scala b/docs/examples/patterns.scala index 738deabc66..d082fcc3de 100644 --- a/docs/examples/patterns.scala +++ b/docs/examples/patterns.scala @@ -13,17 +13,17 @@ object patterns { case Leaf(x) => x } - def find[a,b](it: Iterator[Pair[a, b]], x: a): Option[b] = { + def find[a,b](it: Iterator[Tuple2[a, b]], x: a): Option[b] = { var result: Option[b] = None var found = false while (it.hasNext && !found) { - val Pair(x1, y) = it.next + val (x1, y) = it.next if (x == x1) { found = true; result = Some(y) } } result } - def printFinds[a](xs: List[Pair[a, String]], x: a) = + def printFinds[a](xs: List[Tuple2[a, String]], x: a) = find(xs.iterator, x) match { case Some(y) => System.out.println(y) case None => System.out.println("no match") @@ -31,6 +31,6 @@ object patterns { def main(args: Array[String]) { println("sum of leafs=" + sumLeaves(tree1)) - printFinds(List(Pair(3, "three"), Pair(4, "four")), 4) + printFinds(List((3, "three"), (4, "four")), 4) } } diff --git a/docs/examples/pilib/elasticBuffer.scala b/docs/examples/pilib/elasticBuffer.scala index 5fec96ab6c..c173735dbb 100644 --- a/docs/examples/pilib/elasticBuffer.scala +++ b/docs/examples/pilib/elasticBuffer.scala @@ -8,7 +8,7 @@ object elasticBuffer { * Recursive type for channels that carry a "String" channel and * an object of the type we define. */ - class MetaChan extends Chan[Pair[Chan[String], MetaChan]] + class MetaChan extends Chan[Tuple2[Chan[String], MetaChan]] def Buffer(put: Chan[String], get: Chan[String]): Unit = { @@ -18,19 +18,19 @@ object elasticBuffer { def Bl(i:Chan[String], l: MetaChan, o: Chan[String], r: MetaChan): unit = choice ( - l(Pair(o,r)) * (System.out.println("Removed one cell.")), + l((o,r)) * (System.out.println("Removed one cell.")), i * (inp => Cl(i, l, o, r, inp)) ) /** * A buffer cell containing a value, ready to receive (o,r) from the right. */ - def Cl(i: Chan[String], l: MetaChan, + def Cl(i: Chan[String], l: MetaChan, o: Chan[String], r: MetaChan, content: String): Unit = choice ( o(content) * (Bl(i,l,o,r)), i * (inp => Dl(i,l,o,r,content, inp)), - r * ( { case Pair(newo, newr) => Cl(i,l,newo,newr,content) }) + r * ( { case (newo, newr) => Cl(i,l,newo,newr,content) }) ) /** diff --git a/docs/examples/pilib/handover.scala b/docs/examples/pilib/handover.scala index c9b6156c2c..4e9a5670a0 100644 --- a/docs/examples/pilib/handover.scala +++ b/docs/examples/pilib/handover.scala @@ -13,14 +13,14 @@ object handoverRecursive { * Recursive type for channels that carry a channel "unit" and * an object of the type we define. */ - class Switch extends Chan[Pair[Chan[unit], Switch]] + class Switch extends Chan[Tuple2[Chan[unit], Switch]] /** * Car. */ def Car(talk: Chan[unit], switch: Switch): unit = choice ( - switch * ({ case Pair(t,s) => Car(t, s) }), + switch * ({ case (t,s) => Car(t, s) }), talk(()) * ( { Thread.sleep(1 + random.nextInt(1000)); System.out.println("Car emitted a message."); @@ -32,20 +32,20 @@ object handoverRecursive { * Control center. */ def Control(talk1: Chan[unit], switch1: Switch, - gain1: Switch, lose1: Switch, + gain1: Switch, lose1: Switch, talk2: Chan[unit], switch2: Switch, gain2: Switch, lose2: Switch): unit = { def Control1: unit= { Thread.sleep(1 + random.nextInt(1000)); - lose1.write(Pair(talk2, switch2)); - gain2.write(Pair(talk2, switch2)); + lose1.write((talk2, switch2)); + gain2.write((talk2, switch2)); Control2 } def Control2: unit = { Thread.sleep(1 + random.nextInt(1000)); - lose2.write(Pair(talk1, switch1)); - gain1.write(Pair(talk1, switch1)); + lose2.write((talk1, switch1)); + gain1.write((talk1, switch1)); Control1 } Control1 @@ -62,8 +62,8 @@ object handoverRecursive { System.out.println(id + " received a message.") ActiveTransmitter(id, talk, switch, gain, lose) }), - lose * ({ case Pair(t, s) => { - switch.write(Pair(t, s)) + lose * ({ case (t, s) => { + switch.write((t, s)) IdleTransmitter(id, gain, lose) }}) ); @@ -72,7 +72,7 @@ object handoverRecursive { * Idle transmitter. */ def IdleTransmitter(id: String, gain: Switch, lose: Switch): unit = { - val Pair(t, s) = gain.read; + val (t, s) = gain.read; ActiveTransmitter(id, t, s, gain, lose) } @@ -108,7 +108,7 @@ object handoverCast { def Car(talk: Chan[Any], switch: Chan[Any]): unit = choice ( switch * (o => { - val Pair(t,s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]]; + val (t,s) = o.asInstanceOf[Tuple2[Chan[Any],Chan[Any]]]; Car(t, s) }), talk(()) * ( { @@ -122,20 +122,20 @@ object handoverCast { * Control center. */ def Control(talk1: Chan[Any], switch1: Chan[Any], - gain1: Chan[Any], lose1: Chan[Any], + gain1: Chan[Any], lose1: Chan[Any], talk2: Chan[Any], switch2: Chan[Any], gain2: Chan[Any], lose2: Chan[Any]): unit = { def Control1: unit = { Thread.sleep(1 + random.nextInt(1000)); - lose1.write(Pair(talk2, switch2)); - gain2.write(Pair(talk2, switch2)); + lose1.write((talk2, switch2)); + gain2.write((talk2, switch2)); Control2 } def Control2: unit = { Thread.sleep(1 + random.nextInt(1000)); - lose2.write(Pair(talk1, switch1)); - gain1.write(Pair(talk1, switch1)); + lose2.write((talk1, switch1)); + gain1.write((talk1, switch1)); Control1 } Control1 @@ -153,8 +153,8 @@ object handoverCast { ActiveTransmitter(id, talk, switch, gain, lose) }), lose * (o => { - val Pair(t, s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]] - switch.write(Pair(t, s)) + val (t, s) = o.asInstanceOf[Tuple2[Chan[Any],Chan[Any]]] + switch.write((t, s)) IdleTransmitter(id, gain, lose) }) ) @@ -163,7 +163,7 @@ object handoverCast { * Idle transmitter. */ def IdleTransmitter(id: String, gain: Chan[Any], lose: Chan[Any]): unit = { - val Pair(t, s) = gain.read.asInstanceOf[Pair[Chan[Any],Chan[Any]]] + val (t, s) = gain.read.asInstanceOf[Tuple2[Chan[Any],Chan[Any]]] ActiveTransmitter(id, t, s, gain, lose) } diff --git a/docs/examples/pilib/piNat.scala b/docs/examples/pilib/piNat.scala index a1a0e682e1..c6d9bdaf5c 100644 --- a/docs/examples/pilib/piNat.scala +++ b/docs/examples/pilib/piNat.scala @@ -4,23 +4,23 @@ import scala.concurrent.pilib._ /** Church encoding of naturals in the Pi-calculus */ object piNat extends Application { - + /** Locations of Pi-calculus natural */ - class NatChan extends Chan[Triple[Chan[Unit], Chan[NatChan], Chan[NatChan]]] + class NatChan extends Chan[Tuple3[Chan[Unit], Chan[NatChan], Chan[NatChan]]] /** Zero */ def Z(l: NatChan): Unit = choice ( - l * { case Triple(z, sd, d) => z.write(()) } + l * { case (z, sd, d) => z.write(()) } ) /** Successor of Double */ def SD(n: NatChan, l: NatChan): Unit = choice ( - l * { case Triple(z, sd, d) => sd.write(n) } + l * { case (z, sd, d) => sd.write(n) } ) /** Double */ def D(n: NatChan, l: NatChan): Unit = choice ( - l * { case Triple(z, sd, d) => d.write(n) } + l * { case (z, sd, d) => d.write(n) } ) /** Make "l" a location representing the natural "n" */ @@ -34,7 +34,7 @@ object piNat extends Application { val z = new Chan[Unit] val sd = new Chan[NatChan] val d = new Chan[NatChan] - spawn < m.write(Triple(z, sd, d)) >; + spawn < m.write((z, sd, d)) >; choice ( z * { x => make(1, n) }, sd * { m1 => { val n1 = new NatChan; spawn < D(n1, n) >; Succ(m1, n1) } }, @@ -47,7 +47,7 @@ object piNat extends Application { val z = new Chan[Unit] val sd = new Chan[NatChan] val d = new Chan[NatChan] - spawn < l.write(Triple(z, sd, d)) >; + spawn < l.write((z, sd, d)) >; choice ( z * { x => spawn < Z(m) >; Z(n) }, sd * { l1 => { val m1 = new NatChan; val n1 = new NatChan; @@ -64,7 +64,7 @@ object piNat extends Application { val z = new Chan[Unit] val sd = new Chan[NatChan] val d = new Chan[NatChan] - spawn < n.write(Triple(z, sd, d)) >; + spawn < n.write((z, sd, d)) >; choice ( z * { x => 0 }, sd * { n1 => 2 * value(n1) + 1 }, diff --git a/docs/examples/typeinf.scala b/docs/examples/typeinf.scala index d4bc8bf3e1..ac6cc35f6b 100644 --- a/docs/examples/typeinf.scala +++ b/docs/examples/typeinf.scala @@ -53,11 +53,11 @@ object typeInfer { (emptySubst /: tyvars) ((s, tv) => s.extend(tv, newTyvar())) (tpe) } - type Env = List[Pair[String, TypeScheme]] + type Env = List[Tuple2[String, TypeScheme]] def lookup(env: Env, x: String): TypeScheme = env match { case List() => null - case Pair(y, t) :: env1 => if (x == y) t else lookup(env1, x) + case (y, t) :: env1 => if (x == y) t else lookup(env1, x) } def gen(env: Env, t: Type): TypeScheme = @@ -69,22 +69,22 @@ object typeInfer { case Tycon(k, ts) => (List[Tyvar]() /: ts) ((tvs, t) => tvs union tyvars(t)) } - def tyvars(ts: TypeScheme): List[Tyvar] = + def tyvars(ts: TypeScheme): List[Tyvar] = tyvars(ts.tpe) diff ts.tyvars; def tyvars(env: Env): List[Tyvar] = (List[Tyvar]() /: env) ((tvs, nt) => tvs union tyvars(nt._2)) - def mgu(t: Type, u: Type, s: Subst): Subst = Pair(s(t), s(u)) match { - case Pair(Tyvar(a), Tyvar(b)) if (a == b) => + def mgu(t: Type, u: Type, s: Subst): Subst = (s(t), s(u)) match { + case (Tyvar(a), Tyvar(b)) if (a == b) => s - case Pair(Tyvar(a), _) if !(tyvars(u) contains a) => + case (Tyvar(a), _) if !(tyvars(u) contains a) => s.extend(Tyvar(a), u) - case Pair(_, Tyvar(a)) => + case (_, Tyvar(a)) => mgu(u, t, s) - case Pair(Arrow(t1, t2), Arrow(u1, u2)) => + case (Arrow(t1, t2), Arrow(u1, u2)) => mgu(t1, u1, mgu(t2, u2, s)) - case Pair(Tycon(k1, ts), Tycon(k2, us)) if (k1 == k2) => + case (Tycon(k1, ts), Tycon(k2, us)) if (k1 == k2) => (s /: (ts zip us)) ((s, tu) => mgu(tu._1, tu._2, s)) case _ => throw new TypeError("cannot unify " + s(t) + " with " + s(u)) @@ -103,7 +103,7 @@ object typeInfer { case Lam(x, e1) => val a, b = newTyvar() val s1 = mgu(t, Arrow(a, b), s) - val env1 = Pair(x, TypeScheme(List(), a)) :: env + val env1 = (x, TypeScheme(List(), a)) :: env tp(env1, e1, b, s1) case App(e1, e2) => @@ -114,7 +114,7 @@ object typeInfer { case Let(x, e1, e2) => val a = newTyvar() val s1 = tp(env, e1, a, s) - tp(Pair(x, gen(env, s1(a))) :: env, e2, t, s1) + tp((x, gen(env, s1(a))) :: env, e2, t, s1) } } var current: Term = null @@ -134,18 +134,18 @@ object typeInfer { private val a = typeInfer.newTyvar() val env = List( /* - Pair("true", gen(booleanType)), - Pair("false", gen(booleanType)), - Pair("if", gen(Arrow(booleanType, Arrow(a, Arrow(a, a))))), - Pair("zero", gen(intType)), - Pair("succ", gen(Arrow(intType, intType))), - Pair("nil", gen(listType(a))), - Pair("cons", gen(Arrow(a, Arrow(listType(a), listType(a))))), - Pair("isEmpty", gen(Arrow(listType(a), booleanType))), - Pair("head", gen(Arrow(listType(a), a))), - Pair("tail", gen(Arrow(listType(a), listType(a)))), + ("true", gen(booleanType)), + ("false", gen(booleanType)), + ("if", gen(Arrow(booleanType, Arrow(a, Arrow(a, a))))), + ("zero", gen(intType)), + ("succ", gen(Arrow(intType, intType))), + ("nil", gen(listType(a))), + ("cons", gen(Arrow(a, Arrow(listType(a), listType(a))))), + ("isEmpty", gen(Arrow(listType(a), booleanType))), + ("head", gen(Arrow(listType(a), a))), + ("tail", gen(Arrow(listType(a), listType(a)))), */ - Pair("fix", gen(Arrow(Arrow(a, a), a))) + ("fix", gen(Arrow(Arrow(a, a), a))) ) } @@ -181,7 +181,7 @@ object typeInfer { yield Lam(x, t): Term ) ||| ( for ( - letid <- id if letid == "let"; + letid <- id if letid == "let"; x <- ident; _ <- wschr('='); t <- term; @@ -220,7 +220,7 @@ object typeInfer { val input = 0 def any = new Parser[char] { def apply(in: int): Parser[char]#Result = - if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None + if (in < s.length()) Some((s charAt in, in + 1)) else None } } @@ -239,7 +239,7 @@ object typeInfer { if (args.length == 1) { val ps = new ParseString(args(0)) with MiniMLParsers ps.all(ps.input) match { - case Some(Pair(term, _)) => + case Some((term, _)) => "" + term + ": " + showType(term) case None => "syntax error" diff --git a/lib/scala-compiler-src.jar.desired.sha1 b/lib/scala-compiler-src.jar.desired.sha1 deleted file mode 100644 index e3fa18b018..0000000000 --- a/lib/scala-compiler-src.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -d62bc132cba37b17c8d5ac65feb20193a3f8cc28 ?scala-compiler-src.jar diff --git a/lib/scala-compiler.jar.desired.sha1 b/lib/scala-compiler.jar.desired.sha1 deleted file mode 100644 index 68ac8d7e5c..0000000000 --- a/lib/scala-compiler.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -d049885894b93e12f034d4d871c38bfc4d026525 ?scala-compiler.jar diff --git a/lib/scala-library-src.jar.desired.sha1 b/lib/scala-library-src.jar.desired.sha1 deleted file mode 100644 index 5f74d96c66..0000000000 --- a/lib/scala-library-src.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -58db8f554695791217de332aa6500a7aa240e480 ?scala-library-src.jar diff --git a/lib/scala-library.jar.desired.sha1 b/lib/scala-library.jar.desired.sha1 deleted file mode 100644 index b7befab52a..0000000000 --- a/lib/scala-library.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -12007d1b1b913b563093b22e947e6c05fe40f3de ?scala-library.jar diff --git a/lib/scala-reflect-src.jar.desired.sha1 b/lib/scala-reflect-src.jar.desired.sha1 deleted file mode 100644 index 566111fd51..0000000000 --- a/lib/scala-reflect-src.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -c842d370d814515f15159cefa4b9c495d99bb1a9 ?scala-reflect-src.jar diff --git a/lib/scala-reflect.jar.desired.sha1 b/lib/scala-reflect.jar.desired.sha1 deleted file mode 100644 index a6cdbc18ad..0000000000 --- a/lib/scala-reflect.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -a6595b3d7589085f683d4ad5a6072a057ab15ef9 ?scala-reflect.jar diff --git a/src/actors/scala/actors/Future.scala b/src/actors/scala/actors/Future.scala index 9d123cb2d5..4421c7a07a 100644 --- a/src/actors/scala/actors/Future.scala +++ b/src/actors/scala/actors/Future.scala @@ -180,17 +180,17 @@ object Futures { var cnt = 0 val mappedFts = fts.map(ft => - Pair({cnt+=1; cnt-1}, ft)) + ({cnt+=1; cnt-1}, ft)) - val unsetFts = mappedFts.filter((p: Pair[Int, Future[Any]]) => { + val unsetFts = mappedFts.filter((p: Tuple2[Int, Future[Any]]) => { if (p._2.isSet) { resultsMap(p._1) = Some(p._2()); false } else { resultsMap(p._1) = None; true } }) - val partFuns = unsetFts.map((p: Pair[Int, Future[Any]]) => { + val partFuns = unsetFts.map((p: Tuple2[Int, Future[Any]]) => { val FutCh = p._2.inputChannel - val singleCase: PartialFunction[Any, Pair[Int, Any]] = { - case FutCh ! any => Pair(p._1, any) + val singleCase: PartialFunction[Any, Tuple2[Int, Any]] = { + case FutCh ! any => (p._1, any) } singleCase }) @@ -201,7 +201,7 @@ object Futures { } Actor.timer.schedule(timerTask, timeout) - def awaitWith(partFuns: Seq[PartialFunction[Any, Pair[Int, Any]]]) { + def awaitWith(partFuns: Seq[PartialFunction[Any, Tuple2[Int, Any]]]) { val reaction: PartialFunction[Any, Unit] = new PartialFunction[Any, Unit] { def isDefinedAt(msg: Any) = msg match { case TIMEOUT => true @@ -212,7 +212,7 @@ object Futures { case _ => { val pfOpt = partFuns find (_ isDefinedAt msg) val pf = pfOpt.get // succeeds always - val Pair(idx, subres) = pf(msg) + val (idx, subres) = pf(msg) resultsMap(idx) = Some(subres) val partFunsRest = partFuns filter (_ != pf) diff --git a/src/actors/scala/actors/remote/NetKernel.scala b/src/actors/scala/actors/remote/NetKernel.scala index 4795ff3eb6..57d7af6d26 100644 --- a/src/actors/scala/actors/remote/NetKernel.scala +++ b/src/actors/scala/actors/remote/NetKernel.scala @@ -43,8 +43,8 @@ private[remote] class NetKernel(service: Service) { private val names = new mutable.HashMap[OutputChannel[Any], Symbol] def register(name: Symbol, a: OutputChannel[Any]): Unit = synchronized { - actors += Pair(name, a) - names += Pair(a, name) + actors(name) = a + names(a) = name } def getOrCreateName(from: OutputChannel[Any]) = names.get(from) match { @@ -79,7 +79,7 @@ private[remote] class NetKernel(service: Service) { def createProxy(node: Node, sym: Symbol): Proxy = { val p = new Proxy(node, sym, this) - proxies += Pair((node, sym), p) + proxies((node, sym)) = p p } @@ -99,7 +99,7 @@ private[remote] class NetKernel(service: Service) { proxies.synchronized { proxies.get((senderNode, senderName)) match { case Some(senderProxy) => // do nothing - case None => proxies += Pair((senderNode, senderName), p) + case None => proxies((senderNode, senderName)) = p } } diff --git a/src/actors/scala/actors/remote/Proxy.scala b/src/actors/scala/actors/remote/Proxy.scala index 43a43ac99c..9949b36181 100644 --- a/src/actors/scala/actors/remote/Proxy.scala +++ b/src/actors/scala/actors/remote/Proxy.scala @@ -142,7 +142,7 @@ private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, ke // create a new reply channel... val replyCh = new Channel[Any](this) // ...that maps to session - sessionMap += Pair(replyCh, session) + sessionMap(replyCh) = session // local send out.send(msg, replyCh) @@ -178,7 +178,7 @@ private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, ke // create fresh session ID... val fresh = FreshNameCreator.newName(node+"@"+name) // ...that maps to reply channel - channelMap += Pair(fresh, sender) + channelMap(fresh) = sender kernel.forward(sender, node, name, msg, fresh) } else { kernel.forward(sender, node, name, msg, 'nosession) diff --git a/src/actors/scala/actors/remote/RemoteActor.scala b/src/actors/scala/actors/remote/RemoteActor.scala index 799076a01f..2daf9ceb43 100644 --- a/src/actors/scala/actors/remote/RemoteActor.scala +++ b/src/actors/scala/actors/remote/RemoteActor.scala @@ -64,7 +64,7 @@ object RemoteActor { val serv = TcpService(port, cl) val kern = serv.kernel val s = Actor.self(Scheduler) - kernels += Pair(s, kern) + kernels(s) = kern s.onTerminate { Debug.info("alive actor "+s+" terminated") @@ -90,7 +90,7 @@ object RemoteActor { val kernel = kernels.get(Actor.self(Scheduler)) match { case None => val serv = TcpService(TcpService.generatePort, cl) - kernels += Pair(Actor.self(Scheduler), serv.kernel) + kernels(Actor.self(Scheduler)) = serv.kernel serv.kernel case Some(k) => k diff --git a/src/actors/scala/actors/remote/TcpService.scala b/src/actors/scala/actors/remote/TcpService.scala index 75e36b2738..69e5c46c52 100644 --- a/src/actors/scala/actors/remote/TcpService.scala +++ b/src/actors/scala/actors/remote/TcpService.scala @@ -35,7 +35,7 @@ object TcpService { service case None => val service = new TcpService(port, cl) - ports += Pair(port, service) + ports(port) = service service.start() Debug.info("created service at "+service.node) service @@ -106,9 +106,9 @@ class TcpService(port: Int, cl: ClassLoader) extends Thread with Service { // when remote net kernel comes up (pendingSends.get(node): @unchecked) match { case None => - pendingSends += Pair(node, List(data)) + pendingSends(node) = List(data) case Some(msgs) if msgs.length < TcpService.BufSize => - pendingSends += Pair(node, data :: msgs) + pendingSends(node) = data :: msgs } } @@ -183,7 +183,7 @@ class TcpService(port: Int, cl: ClassLoader) extends Thread with Service { new mutable.HashMap[Node, TcpServiceWorker] private[actors] def addConnection(node: Node, worker: TcpServiceWorker) = synchronized { - connections += Pair(node, worker) + connections(node) = worker } def getConnection(n: Node) = synchronized { diff --git a/src/compiler/scala/reflect/macros/compiler/Errors.scala b/src/compiler/scala/reflect/macros/compiler/Errors.scala index 9799428b40..4c30a9a85c 100644 --- a/src/compiler/scala/reflect/macros/compiler/Errors.scala +++ b/src/compiler/scala/reflect/macros/compiler/Errors.scala @@ -10,6 +10,7 @@ trait Errors extends Traces { import global._ import analyzer._ import definitions._ + import treeInfo._ import typer.TyperErrorGen._ import typer.infer.InferErrorGen._ private val runDefinitions = currentRun.runDefinitions @@ -18,22 +19,39 @@ trait Errors extends Traces { // sanity check errors - private def implRefError(message: String) = abort(macroDdef.pos, message) + private def implRefError(message: String) = { + val Applied(culprit, _, _) = macroDdef.rhs + abort(culprit.pos, message) + } + + private def bundleRefError(message: String) = { + val Applied(core, _, _) = macroDdef.rhs + val culprit = core match { + case Select(Applied(core, _, _), _) => core + case _ => core + } + abort(culprit.pos, message) + } def MacroImplReferenceWrongShapeError() = implRefError( "macro implementation reference has wrong shape. required:\n"+ "macro [<static object>].<method name>[[<type args>]] or\n" + "macro [<macro bundle>].<method name>[[<type args>]]") + def MacroImplWrongNumberOfTypeArgumentsError() = { + val diagnostic = if (macroImpl.typeParams.length > targs.length) "has too few type arguments" else "has too many arguments" + implRefError(s"macro implementation reference $diagnostic for " + treeSymTypeMsg(macroImplRef)) + } + def MacroImplNotPublicError() = implRefError("macro implementation must be public") def MacroImplOverloadedError() = implRefError("macro implementation cannot be overloaded") - def MacroImplWrongNumberOfTypeArgumentsError() = implRefError(TypedApplyWrongNumberOfTpeParametersErrorMessage(macroImplRef)) + def MacroImplNonTagImplicitParameters(params: List[Symbol]) = implRefError("macro implementations cannot have implicit parameters other than WeakTypeTag evidences") - def MacroBundleNonStaticError() = implRefError("macro bundles must be static") + def MacroBundleNonStaticError() = bundleRefError("macro bundles must be static") - def MacroBundleWrongShapeError() = implRefError("macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member") + def MacroBundleWrongShapeError() = bundleRefError("macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member") // compatibility errors @@ -91,14 +109,12 @@ trait Errors extends Traces { private def compatibilityError(message: String) = implRefError( - "macro implementation has wrong shape:"+ + "macro implementation has incompatible shape:"+ "\n required: " + showMeth(rparamss, rret, abbreviate = true, untype = false) + "\n or : " + showMeth(rparamss, rret, abbreviate = true, untype = true) + "\n found : " + showMeth(aparamss, aret, abbreviate = false, untype = false) + "\n" + message) - def MacroImplNonTagImplicitParameters(params: List[Symbol]) = compatibilityError("macro implementations cannot have implicit parameters other than WeakTypeTag evidences") - def MacroImplParamssMismatchError() = compatibilityError("number of parameter sections differ") def MacroImplExtraParamsError(aparams: List[Symbol], rparams: List[Symbol]) = compatibilityError(lengthMsg("value", "found", aparams(rparams.length))) diff --git a/src/compiler/scala/reflect/macros/compiler/Resolvers.scala b/src/compiler/scala/reflect/macros/compiler/Resolvers.scala index 03d306f593..e4851632a5 100644 --- a/src/compiler/scala/reflect/macros/compiler/Resolvers.scala +++ b/src/compiler/scala/reflect/macros/compiler/Resolvers.scala @@ -9,7 +9,7 @@ trait Resolvers { import global._ import analyzer._ - import definitions.{EmptyPackageClass => _, _} + import definitions._ import treeInfo._ import gen._ private val runDefinitions = currentRun.runDefinitions diff --git a/src/compiler/scala/reflect/macros/compiler/Validators.scala b/src/compiler/scala/reflect/macros/compiler/Validators.scala index e77c129c51..0a56aa45e3 100644 --- a/src/compiler/scala/reflect/macros/compiler/Validators.scala +++ b/src/compiler/scala/reflect/macros/compiler/Validators.scala @@ -21,9 +21,11 @@ trait Validators { private def sanityCheck() = { if (!macroImpl.isMethod) MacroImplReferenceWrongShapeError() + if (macroImpl.typeParams.length != targs.length) MacroImplWrongNumberOfTypeArgumentsError() if (!macroImpl.isPublic) MacroImplNotPublicError() if (macroImpl.isOverloaded) MacroImplOverloadedError() - if (macroImpl.typeParams.length != targs.length) MacroImplWrongNumberOfTypeArgumentsError() + val implicitParams = aparamss.flatten filter (_.isImplicit) + if (implicitParams.nonEmpty) MacroImplNonTagImplicitParameters(implicitParams) val declaredInStaticObject = isImplMethod && (macroImplOwner.isStaticOwner || macroImplOwner.moduleClass.isStaticOwner) val declaredInTopLevelClass = isImplBundle && macroImplOwner.owner.isPackageClass if (!declaredInStaticObject && !declaredInTopLevelClass) MacroImplReferenceWrongShapeError() @@ -35,8 +37,6 @@ trait Validators { // we only check strict correspondence between value parameterss // type parameters of macro defs and macro impls don't have to coincide with each other - val implicitParams = aparamss.flatten filter (_.isImplicit) - if (implicitParams.nonEmpty) MacroImplNonTagImplicitParameters(implicitParams) if (aparamss.length != rparamss.length) MacroImplParamssMismatchError() map2(aparamss, rparamss)((aparams, rparams) => { if (aparams.length < rparams.length) MacroImplMissingParamsError(aparams, rparams) diff --git a/src/compiler/scala/tools/ant/ScalaTool.scala b/src/compiler/scala/tools/ant/ScalaTool.scala index e7ac53c8fb..bb6a933d3f 100644 --- a/src/compiler/scala/tools/ant/ScalaTool.scala +++ b/src/compiler/scala/tools/ant/ScalaTool.scala @@ -139,7 +139,7 @@ class ScalaTool extends ScalaMatchingTask { val st = s.trim val stArray = st.split("=", 2) if (stArray.length == 2) { - if (input != "") List(Pair(stArray(0), stArray(1))) else Nil + if (input != "") List((stArray(0), stArray(1))) else Nil } else buildError("Property " + st + " is not formatted properly.") @@ -170,7 +170,7 @@ class ScalaTool extends ScalaMatchingTask { private def getProperties: String = properties.map({ - case Pair(name,value) => "-D" + name + "=\"" + value + "\"" + case (name,value) => "-D" + name + "=\"" + value + "\"" }).mkString("", " ", "") /*============================================================================*\ diff --git a/src/compiler/scala/tools/ant/sabbus/Compilers.scala b/src/compiler/scala/tools/ant/sabbus/Compilers.scala index b1994233e8..a0aad49f20 100644 --- a/src/compiler/scala/tools/ant/sabbus/Compilers.scala +++ b/src/compiler/scala/tools/ant/sabbus/Compilers.scala @@ -27,7 +27,7 @@ object Compilers extends scala.collection.DefaultMap[String, Compiler] { if (debug) println("Making compiler " + id) if (debug) println(" memory before: " + freeMemoryString) val comp = new Compiler(classpath, settings) - container += Pair(id, comp) + container(id) = comp if (debug) println(" memory after: " + freeMemoryString) comp } diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala index d4ac21a6b8..4ac6672727 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala @@ -256,4 +256,44 @@ abstract class TreeGen extends scala.reflect.internal.TreeGen with TreeDSL { val stats1 = if (stats.isEmpty) List(Literal(Constant(()))) else stats mkNew(Nil, noSelfType, stats1, NoPosition, NoPosition) } + + /** + * Create a method based on a Function + * + * Used both to under `-Ydelambdafy:method` create a lifted function and + * under `-Ydelamdafy:inline` to create the apply method on the anonymous + * class. + * + * It creates a method definition with value params cloned from the + * original lambda. Then it calls a supplied function to create + * the body and types the result. Finally + * everything is wrapped up in a DefDef + * + * @param owner The owner for the new method + * @param name name for the new method + * @param additionalFlags flags to be put on the method in addition to FINAL + */ + def mkMethodFromFunction(localTyper: analyzer.Typer) + (fun: Function, owner: Symbol, name: TermName, additionalFlags: FlagSet = NoFlags) = { + val funParams = fun.vparams map (_.symbol) + val formals :+ restpe = fun.tpe.typeArgs + + val methSym = owner.newMethod(name, fun.pos, FINAL | additionalFlags) + + val paramSyms = map2(formals, fun.vparams) { + (tp, vparam) => methSym.newSyntheticValueParam(tp, vparam.name) + } + + methSym setInfo MethodType(paramSyms, restpe.deconst) + + fun.body.substituteSymbols(funParams, paramSyms) + fun.body changeOwner (fun.symbol -> methSym) + + val methDef = DefDef(methSym, fun.body) + + // Have to repack the type to avoid mismatches when existentials + // appear in the result - see SI-4869. + methDef.tpt setType localTyper.packedType(fun.body, methSym).deconst + methDef + } } diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala index ef4052d5f3..91db1bb92a 100644 --- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala +++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala @@ -732,6 +732,7 @@ self => def removeAsPlaceholder(name: Name) { placeholderParams = placeholderParams filter (_.name != name) } + def errorParam = makeParam(nme.ERROR, errorTypeTree setPos o2p(tree.pos.end)) tree match { case Ident(name) => removeAsPlaceholder(name) @@ -739,9 +740,19 @@ self => case Typed(Ident(name), tpe) if tpe.isType => // get the ident! removeAsPlaceholder(name) makeParam(name.toTermName, tpe) + case build.SyntacticTuple(as) => + val arity = as.length + val example = analyzer.exampleTuplePattern(as map { case Ident(name) => name; case _ => nme.EMPTY }) + val msg = + sm"""|not a legal formal parameter. + |Note: Tuples cannot be directly destructured in method or function parameters. + | Either create a single parameter accepting the Tuple${arity}, + | or consider a pattern matching anonymous function: `{ case $example => ... }""" + syntaxError(tree.pos, msg, skipIt = false) + errorParam case _ => syntaxError(tree.pos, "not a legal formal parameter", skipIt = false) - makeParam(nme.ERROR, errorTypeTree setPos o2p(tree.pos.end)) + errorParam } } @@ -1774,10 +1785,12 @@ self => in.nextToken() if (in.token == SUBTYPE || in.token == SUPERTYPE) wildcardType(start) else atPos(start) { Bind(tpnme.WILDCARD, EmptyTree) } - case IDENTIFIER if nme.isVariableName(in.name) => - atPos(start) { Bind(identForType(), EmptyTree) } case _ => - typ() + typ() match { + case Ident(name: TypeName) if nme.isVariableName(name) => + atPos(start) { Bind(name, EmptyTree) } + case t => t + } } } 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 60f7857d0c..939641c3eb 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala @@ -69,7 +69,7 @@ abstract class Liveness { case STORE_LOCAL(local) if (!genSet(local)) => killSet = killSet + local case _ => () } - Pair(genSet, killSet) + (genSet, killSet) } override def run() { 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 7a53293384..f10d7cdc40 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -418,7 +418,7 @@ abstract class TypeFlowAnalysis { !blackballed(concreteMethod) } if(isCandidate) { - remainingCALLs += Pair(cm, CallsiteInfo(b, receiver, result.stack.length, concreteMethod)) + remainingCALLs(cm) = CallsiteInfo(b, receiver, result.stack.length, concreteMethod) } else { remainingCALLs.remove(cm) isOnWatchlist.remove(cm) diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BCodeBodyBuilder.scala b/src/compiler/scala/tools/nsc/backend/jvm/BCodeBodyBuilder.scala index c166b0bb7e..4f9f4c9e31 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BCodeBodyBuilder.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BCodeBodyBuilder.scala @@ -741,13 +741,13 @@ abstract class BCodeBodyBuilder extends BCodeSkelBuilder { var flatKeys: List[Int] = Nil var targets: List[asm.Label] = Nil var default: asm.Label = null - var switchBlocks: List[Pair[asm.Label, Tree]] = Nil + var switchBlocks: List[Tuple2[asm.Label, Tree]] = Nil // collect switch blocks and their keys, but don't emit yet any switch-block. for (caze @ CaseDef(pat, guard, body) <- tree.cases) { assert(guard == EmptyTree, guard) val switchBlockPoint = new asm.Label - switchBlocks ::= Pair(switchBlockPoint, body) + switchBlocks ::= (switchBlockPoint, body) pat match { case Literal(value) => flatKeys ::= value.intValue @@ -772,7 +772,7 @@ abstract class BCodeBodyBuilder extends BCodeSkelBuilder { // emit switch-blocks. val postMatch = new asm.Label for (sb <- switchBlocks.reverse) { - val Pair(caseLabel, caseBody) = sb + val (caseLabel, caseBody) = sb markProgramPoint(caseLabel) genLoad(caseBody, generatedType) bc goTo postMatch @@ -790,7 +790,7 @@ abstract class BCodeBodyBuilder extends BCodeSkelBuilder { genLoad(expr, expectedType) val end = currProgramPoint() if (emitVars) { // add entries to LocalVariableTable JVM attribute - for (Pair(sym, start) <- varsInScope.reverse) { emitLocalVarScope(sym, start, end) } + for ((sym, start) <- varsInScope.reverse) { emitLocalVarScope(sym, start, end) } } varsInScope = savedScope } diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala b/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala index c22ced26a5..64ed094a47 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BCodeHelpers.scala @@ -112,7 +112,7 @@ abstract class BCodeHelpers extends BCodeTypes with BytecodeWriters { val ta = exemplars.get(a) val tb = exemplars.get(b) - val res = Pair(ta.isInterface, tb.isInterface) match { + val res = (ta.isInterface, tb.isInterface) match { case (true, true) => // exercised by test/files/run/t4761.scala if (tb.isSubtypeOf(ta.c)) ta.c @@ -759,7 +759,7 @@ abstract class BCodeHelpers extends BCodeTypes with BytecodeWriters { def emitParamAnnotations(jmethod: asm.MethodVisitor, pannotss: List[List[AnnotationInfo]]) { val annotationss = pannotss map (_ filter shouldEmitAnnotation) if (annotationss forall (_.isEmpty)) return - for (Pair(annots, idx) <- annotationss.zipWithIndex; + for ((annots, idx) <- annotationss.zipWithIndex; annot <- annots) { val AnnotationInfo(typ, args, assocs) = annot assert(args.isEmpty, args) diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BCodeSkelBuilder.scala b/src/compiler/scala/tools/nsc/backend/jvm/BCodeSkelBuilder.scala index 5fe03624cf..c921d11d00 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BCodeSkelBuilder.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BCodeSkelBuilder.scala @@ -436,7 +436,7 @@ abstract class BCodeSkelBuilder extends BCodeHelpers { var labelDef: scala.collection.Map[Symbol, LabelDef] = null// (LabelDef-sym -> LabelDef) // bookkeeping the scopes of non-synthetic local vars, to emit debug info (`emitVars`). - var varsInScope: List[Pair[Symbol, asm.Label]] = null // (local-var-sym -> start-of-scope) + var varsInScope: List[Tuple2[Symbol, asm.Label]] = null // (local-var-sym -> start-of-scope) // helpers around program-points. def lastInsn: asm.tree.AbstractInsnNode = { diff --git a/src/compiler/scala/tools/nsc/backend/jvm/BCodeTypes.scala b/src/compiler/scala/tools/nsc/backend/jvm/BCodeTypes.scala index 916d118b6e..5be5abd895 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/BCodeTypes.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/BCodeTypes.scala @@ -90,11 +90,11 @@ abstract class BCodeTypes extends BCodeIdiomatic { ) boxResultType = - for(Pair(csym, msym) <- currentRun.runDefinitions.boxMethod) + for((csym, msym) <- currentRun.runDefinitions.boxMethod) yield (msym -> classLiteral(primitiveTypeMap(csym))) unboxResultType = - for(Pair(csym, msym) <- currentRun.runDefinitions.unboxMethod) + for((csym, msym) <- currentRun.runDefinitions.unboxMethod) yield (msym -> primitiveTypeMap(csym)) // boxed classes are looked up in the `exemplars` map by jvmWiseLUB(). diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala index 5e885fdd04..e92f8c2541 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenASM.scala @@ -293,7 +293,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { def inameToSymbol(iname: String): Symbol = { val name = global.newTypeName(iname) val res0 = - if (nme.isModuleName(name)) rootMirror.getModule(name.dropModule) + if (nme.isModuleName(name)) rootMirror.getModuleByName(name.dropModule) else rootMirror.getClassByName(name.replace('/', '.')) // TODO fails for inner classes (but this hasn't been tested). assert(res0 != NoSymbol) val res = jsymbol(res0) @@ -335,7 +335,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { assert(a.isClass) assert(b.isClass) - val res = Pair(a.isInterface, b.isInterface) match { + val res = (a.isInterface, b.isInterface) match { case (true, true) => global.lub(List(a.tpe, b.tpe)).typeSymbol // TODO assert == firstCommonSuffix of resp. parents case (true, false) => @@ -1014,7 +1014,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { def emitParamAnnotations(jmethod: asm.MethodVisitor, pannotss: List[List[AnnotationInfo]]) { val annotationss = pannotss map (_ filter shouldEmitAnnotation) if (annotationss forall (_.isEmpty)) return - for (Pair(annots, idx) <- annotationss.zipWithIndex; + for ((annots, idx) <- annotationss.zipWithIndex; annot <- annots) { val AnnotationInfo(typ, args, assocs) = annot assert(args.isEmpty, args) @@ -2156,7 +2156,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { def getMerged(): scala.collection.Map[Local, List[Interval]] = { // TODO should but isn't: unbalanced start(s) of scope(s) - val shouldBeEmpty = pending filter { p => val Pair(_, st) = p; st.nonEmpty } + val shouldBeEmpty = pending filter { p => val (_, st) = p; st.nonEmpty } val merged = mutable.Map[Local, List[Interval]]() def addToMerged(lv: Local, start: Label, end: Label) { val intv = Interval(start, end) @@ -2169,7 +2169,7 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { (b) take the latest end (onePastLast if none available) (c) merge the thus made-up interval */ - for(Pair(k, st) <- shouldBeEmpty) { + for((k, st) <- shouldBeEmpty) { var start = st.toList.sortBy(_.getOffset).head if(merged.isDefinedAt(k)) { val balancedStart = merged(k).head.lstart @@ -2206,25 +2206,25 @@ abstract class GenASM extends SubComponent with BytecodeWriters with GenJVMASM { } // adding non-param locals var anonCounter = 0 - var fltnd: List[Triple[String, Local, Interval]] = Nil - for(Pair(local, ranges) <- scoping.getMerged()) { + var fltnd: List[Tuple3[String, Local, Interval]] = Nil + for((local, ranges) <- scoping.getMerged()) { var name = javaName(local.sym) if (name == null) { anonCounter += 1 name = "<anon" + anonCounter + ">" } for(intrvl <- ranges) { - fltnd ::= Triple(name, local, intrvl) + fltnd ::= (name, local, intrvl) } } // quest for deterministic output that Map.toList doesn't provide (so that ant test.stability doesn't complain). val srtd = fltnd.sortBy { kr => - val Triple(name: String, _, intrvl: Interval) = kr + val (name: String, _, intrvl: Interval) = kr - Triple(intrvl.start, intrvl.end - intrvl.start, name) // ie sort by (start, length, name) + (intrvl.start, intrvl.end - intrvl.start, name) // ie sort by (start, length, name) } - for(Triple(name, local, Interval(start, end)) <- srtd) { + for((name, local, Interval(start, end)) <- srtd) { jmethod.visitLocalVariable(name, descriptor(local.kind), null, start, end, indexOf(local)) } // "There may be no more than one LocalVariableTable attribute per local variable in the Code attribute" diff --git a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala index 0cfcea87f8..0f317422ac 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala @@ -119,7 +119,7 @@ abstract class DeadCodeElimination extends SubComponent { m foreachBlock { bb => useful(bb) = new mutable.BitSet(bb.size) var rd = rdef.in(bb) - for (Pair(i, idx) <- bb.toList.zipWithIndex) { + for ((i, idx) <- bb.toList.zipWithIndex) { // utility for adding to worklist def moveToWorkList() = moveToWorkListIf(cond = true) @@ -137,7 +137,7 @@ abstract class DeadCodeElimination extends SubComponent { i match { case LOAD_LOCAL(_) => - defs = defs + Pair(((bb, idx)), rd.vars) + defs = defs + (((bb, idx), rd.vars)) moveToWorkListIf(cond = false) case STORE_LOCAL(l) => @@ -350,7 +350,7 @@ abstract class DeadCodeElimination extends SubComponent { val oldInstr = bb.toList bb.open() bb.clear() - for (Pair(i, idx) <- oldInstr.zipWithIndex) { + for ((i, idx) <- oldInstr.zipWithIndex) { if (useful(bb)(idx)) { debuglog(" * " + i + " is useful") bb.emit(i, i.pos) diff --git a/src/compiler/scala/tools/nsc/plugins/Plugin.scala b/src/compiler/scala/tools/nsc/plugins/Plugin.scala index 1578caff26..d194c095f8 100644 --- a/src/compiler/scala/tools/nsc/plugins/Plugin.scala +++ b/src/compiler/scala/tools/nsc/plugins/Plugin.scala @@ -144,7 +144,7 @@ object Plugin { // (j, Try(descriptor)) def required(j: Path) = j -> loadDescriptionFromJar(j) - type Paired = Pair[Path, Try[PluginDescription]] + type Paired = Tuple2[Path, Try[PluginDescription]] val included: List[Paired] = (dirs flatMap (_ ifDirectory scan)).flatten val exploded: List[Paired] = jars flatMap (_ ifDirectory explode) val explicit: List[Paired] = jars flatMap (_ ifFile required) diff --git a/src/compiler/scala/tools/nsc/reporters/Reporter.scala b/src/compiler/scala/tools/nsc/reporters/Reporter.scala index 0544da5d3c..68362c066d 100644 --- a/src/compiler/scala/tools/nsc/reporters/Reporter.scala +++ b/src/compiler/scala/tools/nsc/reporters/Reporter.scala @@ -80,10 +80,4 @@ abstract class Reporter { WARNING.count = 0 cancelled = false } - - // sbt compat - @deprecated("Moved to scala.reflect.internal.util.StringOps", "2.10.0") - def countElementsAsString(n: Int, elements: String): String = StringOps.countElementsAsString(n, elements) - @deprecated("Moved to scala.reflect.internal.util.StringOps", "2.10.0") - def countAsString(n: Int): String = StringOps.countAsString(n) } diff --git a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala b/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala deleted file mode 100644 index 3aecc06b1e..0000000000 --- a/src/compiler/scala/tools/nsc/scratchpad/Mixer.scala +++ /dev/null @@ -1,99 +0,0 @@ -package scala.tools.nsc.scratchpad - -import java.io.{FileInputStream, InputStreamReader, IOException} - -import scala.collection.mutable.ArrayBuffer - -@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") -class Mixer { - - protected val stdSeparator = "//> " - protected val ctdSeparator = "//| " - protected val sepColumn = 50 - protected val tabInc = 8 - - type Comments = Seq[(Int, Array[Char])] - - def parseComments(comments: Array[Char]): Iterator[(Int, Array[Char])] = new Iterator[(Int, Array[Char])] { - var idx = 0 - def hasNext = idx < comments.length - def next() = { - val nextSpace = comments indexOf (' ', idx) - var nextNL = comments indexOf ('\n', nextSpace + 1) - if (nextNL < 0) nextNL = comments.length - val result = - (new String(comments.slice(idx, nextSpace)).toInt, comments.slice(nextSpace + 1, nextNL)) - idx = nextNL + 1 - result - } - } - - def mix(source: Array[Char], comments: Array[Char]): Array[Char] = { - val mixed = new ArrayBuffer[Char] - var written = 0 - def align() = { - var idx = mixed.lastIndexOf('\n') + 1 - var col = 0 - while (idx < mixed.length) { - col = - if (mixed(idx) == '\t') (col / tabInc) * tabInc + tabInc - else col + 1 - idx += 1 - } - if (col > sepColumn) { - mixed += '\n' - col = 0 - } - while (col < sepColumn) { - mixed += ' ' - col += 1 - } - } - for ((offset, cs) <- parseComments(comments)) { - val sep = - if (written < offset) { - for (i <- written until offset) mixed += source(i) - written = offset - stdSeparator - } else { - mixed += '\n' - ctdSeparator - } - align() - mixed ++= sep ++= cs - } - mixed ++= source.view(written, source.length) - mixed.toArray - } - -} - -object Mixer extends Mixer { - - def contents(name: String): Array[Char] = { - val page = new Array[Char](2 << 14) - val buf = new ArrayBuffer[Char] - val in = new FileInputStream(name) - val rdr = new InputStreamReader(in) - var nread = 0 - do { - nread = rdr.read(page, 0, page.length) - buf ++= (if (nread == page.length) page else page.take(nread)) - } while (nread >= 0) - buf.toArray - } - - def main(args: Array[String]) { - val mixer = new Mixer - try { - require(args.length == 2, "required arguments: file1 file2") - val source = contents(args(0)) - val comments = contents(args(1)) - val mixed = mixer.mix(source, comments) - println(mixed.mkString) - } catch { - case ex: IOException => - println("error: "+ ex.getMessage) - } - } -} diff --git a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala b/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala deleted file mode 100644 index 61c1717fea..0000000000 --- a/src/compiler/scala/tools/nsc/scratchpad/SourceInserter.scala +++ /dev/null @@ -1,21 +0,0 @@ -package scala.tools.nsc -package scratchpad - -import scala.reflect.internal.Chars._ - -@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") -object SourceInserter { - def stripRight(cs: Array[Char]): Array[Char] = { - val lines = - new String(cs) split "\n" - def leftPart(str: String) = - (str split """//>|//\|""").head - def isContinuation(str: String) = - ((str contains "//>") || (str contains "//|")) && (leftPart(str) forall isWhitespace) - def stripTrailingWS(str: String) = - str take (str lastIndexWhere (!isWhitespace(_))) + 1 - val prefixes = - lines filterNot isContinuation map leftPart map stripTrailingWS - (prefixes mkString "\n").toArray - } -} diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index 3d648ccbac..844774e75f 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -217,112 +217,33 @@ abstract class UnCurry extends InfoTransform // nullary or parameterless case fun1 if fun1 ne fun => fun1 case _ => - val parents = addSerializable(abstractFunctionForFunctionType(fun.tpe)) - val anonClass = fun.symbol.owner newAnonymousFunctionClass(fun.pos, inConstructorFlag) addAnnotation SerialVersionUIDAnnotation - anonClass setInfo ClassInfoType(parents, newScope, anonClass) - - val targs = fun.tpe.typeArgs - val (formals, restpe) = (targs.init, targs.last) + def typedFunPos(t: Tree) = localTyper.typedPos(fun.pos)(t) + val funParams = fun.vparams map (_.symbol) + def mkMethod(owner: Symbol, name: TermName, additionalFlags: FlagSet = NoFlags): DefDef = + gen.mkMethodFromFunction(localTyper)(fun, owner, name, additionalFlags) if (inlineFunctionExpansion) { - val applyMethodDef = { - val methSym = anonClass.newMethod(nme.apply, fun.pos, FINAL) - val paramSyms = map2(formals, fun.vparams) { - (tp, param) => methSym.newSyntheticValueParam(tp, param.name) - } - methSym setInfoAndEnter MethodType(paramSyms, restpe) - - fun.vparams foreach (_.symbol.owner = methSym) - fun.body changeOwner (fun.symbol -> methSym) - - val body = localTyper.typedPos(fun.pos)(fun.body) - val methDef = DefDef(methSym, List(fun.vparams), body) + val parents = addSerializable(abstractFunctionForFunctionType(fun.tpe)) + val anonClass = fun.symbol.owner newAnonymousFunctionClass(fun.pos, inConstructorFlag) addAnnotation SerialVersionUIDAnnotation + anonClass setInfo ClassInfoType(parents, newScope, anonClass) - // Have to repack the type to avoid mismatches when existentials - // appear in the result - see SI-4869. - methDef.tpt setType localTyper.packedType(body, methSym) - methDef - } + val applyMethodDef = mkMethod(anonClass, nme.apply) + anonClass.info.decls enter applyMethodDef.symbol - localTyper.typedPos(fun.pos) { + typedFunPos { Block( - List(ClassDef(anonClass, NoMods, ListOfNil, List(applyMethodDef), fun.pos)), + ClassDef(anonClass, NoMods, ListOfNil, List(applyMethodDef), fun.pos), Typed(New(anonClass.tpe), TypeTree(fun.tpe))) } } else { - /** - * Abstracts away the common functionality required to create both - * the lifted function and the apply method on the anonymous class - * It creates a method definition with value params cloned from the - * original lambda. Then it calls a supplied function to create - * the body and types the result. Finally - * everything is wrapped up in a MethodDef - * - * TODO it is intended that this common functionality be used - * whether inlineFunctionExpansion is true or not. However, it - * seems to introduce subtle ownwership changes that produce - * binary incompatible changes and so it is completely - * hidden behind the inlineFunctionExpansion for now. - * - * @param owner The owner for the new method - * @param name name for the new method - * @param additionalFlags flags to be put on the method in addition to FINAL - * @bodyF function that turns the method symbol and list of value params - * into a body for the method - */ - def createMethod(owner: Symbol, name: TermName, additionalFlags: Long)(bodyF: (Symbol, List[ValDef]) => Tree) = { - val methSym = owner.newMethod(name, fun.pos, FINAL | additionalFlags) - val vparams = fun.vparams map (_.duplicate) - - val paramSyms = map2(formals, vparams) { - (tp, vparam) => methSym.newSyntheticValueParam(tp, vparam.name) - } - foreach2(vparams, paramSyms){(valdef, sym) => valdef.symbol = sym} - vparams foreach (_.symbol.owner = methSym) - - val methodType = MethodType(paramSyms, restpe.deconst) - methSym setInfo methodType - - // TODO this is probably cleaner if bodyF only works with symbols rather than parameter ValDefs - val tempBody = bodyF(methSym, vparams) - val body = localTyper.typedPos(fun.pos)(tempBody) - val methDef = DefDef(methSym, List(vparams), body) - - // Have to repack the type to avoid mismatches when existentials - // appear in the result - see SI-4869. - methDef.tpt setType localTyper.packedType(body, methSym).deconst - methDef - } - - val methodFlags = ARTIFACT // method definition with the same arguments, return type, and body as the original lambda - val liftedMethod = createMethod(fun.symbol.owner, tpnme.ANON_FUN_NAME.toTermName, methodFlags){ - case(methSym, vparams) => - fun.body.substituteSymbols(fun.vparams map (_.symbol), vparams map (_.symbol)) - fun.body changeOwner (fun.symbol -> methSym) - } - - // callsite for the lifted method - val args = fun.vparams map { vparam => - val ident = Ident(vparam.symbol) - // if -Yeta-expand-keeps-star is turned on then T* types can get through. In order - // to forward them we need to forward x: T* ascribed as "x:_*" - if (settings.etaExpandKeepsStar && definitions.isRepeatedParamType(vparam.tpt.tpe)) - gen.wildcardStar(ident) - else - ident - } - - val funTyper = localTyper.typedPos(fun.pos) _ - - val liftedMethodCall = funTyper(Apply(liftedMethod.symbol, args:_*)) + val liftedMethod = mkMethod(fun.symbol.owner, nme.ANON_FUN_NAME, additionalFlags = ARTIFACT) // new function whose body is just a call to the lifted method - val newFun = treeCopy.Function(fun, fun.vparams, liftedMethodCall) - funTyper(Block( - List(funTyper(liftedMethod)), - super.transform(newFun) - )) + val newFun = deriveFunction(fun)(_ => typedFunPos( + gen.mkForwarder(gen.mkAttributedRef(liftedMethod.symbol), funParams :: Nil) + )) + typedFunPos(Block(liftedMethod, super.transform(newFun))) } } } diff --git a/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala b/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala index 45698c0c76..8ff7824159 100644 --- a/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala +++ b/src/compiler/scala/tools/nsc/transform/patmat/MatchOptimization.scala @@ -233,9 +233,6 @@ trait MatchOptimization extends MatchTreeMaking with MatchAnalysis { def defaultBody: Tree def defaultCase(scrutSym: Symbol = defaultSym, guard: Tree = EmptyTree, body: Tree = defaultBody): CaseDef - private def sequence[T](xs: List[Option[T]]): Option[List[T]] = - if (xs exists (_.isEmpty)) None else Some(xs.flatten) - object GuardAndBodyTreeMakers { def unapply(tms: List[TreeMaker]): Option[(Tree, Tree)] = { tms match { diff --git a/src/compiler/scala/tools/nsc/typechecker/Checkable.scala b/src/compiler/scala/tools/nsc/typechecker/Checkable.scala index 0eae17612d..94f8f509fc 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Checkable.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Checkable.scala @@ -259,10 +259,12 @@ trait Checkable { if (uncheckedOk(P0)) return def where = if (inPattern) "pattern " else "" - // singleton types not considered here - val P = P0.widen + // singleton types not considered here, dealias the pattern for SI-XXXX + val P = P0.dealiasWiden val X = X0.widen + def PString = if (P eq P0) P.toString else s"$P (the underlying of $P0)" + P match { // Prohibit top-level type tests for these, but they are ok nested (e.g. case Foldable[Nothing] => ... ) case TypeRef(_, NothingClass | NullClass | AnyValClass, _) => @@ -282,12 +284,12 @@ trait Checkable { if (checker.neverMatches) { val addendum = if (checker.neverSubClass) "" else " (but still might match its erasure)" - getContext.unit.warning(tree.pos, s"fruitless type test: a value of type $X cannot also be a $P$addendum") + getContext.unit.warning(tree.pos, s"fruitless type test: a value of type $X cannot also be a $PString$addendum") } else if (checker.isUncheckable) { val msg = ( - if (checker.uncheckableType =:= P) s"abstract type $where$P" - else s"${checker.uncheckableMessage} in type $where$P" + if (checker.uncheckableType =:= P) s"abstract type $where$PString" + else s"${checker.uncheckableMessage} in type $where$PString" ) getContext.unit.warning(tree.pos, s"$msg is unchecked since it is eliminated by erasure") } diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala index 7ecc2be9be..2472f63993 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala @@ -408,11 +408,28 @@ trait ContextErrors { setError(tree) } - def MissingParameterTypeError(fun: Tree, vparam: ValDef, pt: Type) = + def MissingParameterTypeError(fun: Tree, vparam: ValDef, pt: Type, withTupleAddendum: Boolean) = { + def issue(what: String) = { + val addendum: String = fun match { + case Function(params, _) if withTupleAddendum => + val funArity = params.length + val example = analyzer.exampleTuplePattern(params map (_.name)) + (pt baseType FunctionClass(1)) match { + case TypeRef(_, _, arg :: _) if arg.typeSymbol == TupleClass(funArity) && funArity > 1 => + sm"""| + |Note: The expected type requires a one-argument function accepting a $funArity-Tuple. + | Consider a pattern matching anoynmous function, `{ case $example => ... }`""" + case _ => "" + } + case _ => "" + } + issueNormalTypeError(vparam, what + addendum) + } if (vparam.mods.isSynthetic) fun match { case Function(_, Match(_, _)) => MissingParameterTypeAnonMatchError(vparam, pt) - case _ => issueNormalTypeError(vparam, "missing parameter type for expanded function " + fun) - } else issueNormalTypeError(vparam, "missing parameter type") + case _ => issue("missing parameter type for expanded function " + fun) + } else issue("missing parameter type") + } def MissingParameterTypeAnonMatchError(vparam: Tree, pt: Type) = issueNormalTypeError(vparam, "missing parameter type for expanded function\n"+ diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala index 5e5619d034..2be6d92ed0 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala @@ -657,7 +657,10 @@ trait Contexts { self: Analyzer => // Console.println("isAccessible(%s, %s, %s)".format(sym, pre, superAccess)) // don't have access if there is no linked class (so exclude linkedClass=NoSymbol) - def accessWithinLinked(ab: Symbol) = ab.linkedClassOfClass.fold(false)(accessWithin) + def accessWithinLinked(ab: Symbol) = { + val linked = linkedClassOfClassOf(ab, this) + linked.fold(false)(accessWithin) + } /* Are we inside definition of `ab`? */ def accessWithin(ab: Symbol) = { diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 01acbb8cc2..fdec1edcc0 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -388,11 +388,11 @@ trait Implicits { */ private def dominates(dtor: Type, dted: Type): Boolean = { def core(tp: Type): Type = tp.dealiasWiden match { - case RefinedType(parents, defs) => intersectionType(parents map core, tp.typeSymbol.owner) + case RefinedType(parents, defs) => intersectionType(parents map core, tp.typeSymbol.owner) case AnnotatedType(annots, tp, selfsym) => core(tp) - case ExistentialType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi))) - case PolyType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi))) - case _ => tp + case ExistentialType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi))) + case PolyType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi))) + case _ => tp } def stripped(tp: Type): Type = { // `t.typeSymbol` returns the symbol of the normalized type. If that normalized type @@ -401,23 +401,18 @@ trait Implicits { val syms = for (t <- tp; if t.typeSymbol.isTypeParameter) yield t.typeSymbol deriveTypeWithWildcards(syms.distinct)(tp) } - def sum(xs: List[Int]) = (0 /: xs)(_ + _) - def complexity(tp: Type): Int = tp.dealiasWiden match { - case NoPrefix => - 0 - case SingleType(pre, sym) => - if (sym.isPackage) 0 else complexity(tp.dealiasWiden) - case TypeRef(pre, sym, args) => - complexity(pre) + sum(args map complexity) + 1 - case RefinedType(parents, _) => - sum(parents map complexity) + 1 - case _ => - 1 + def complexity(tp: Type): Int = tp.dealias match { + case NoPrefix => 0 + case SingleType(pre, sym) => if (sym.isPackage) 0 else complexity(tp.dealiasWiden) + case ThisType(sym) => if (sym.isPackage) 0 else 1 + case TypeRef(pre, sym, args) => complexity(pre) + (args map complexity).sum + 1 + case RefinedType(parents, _) => (parents map complexity).sum + 1 + case _ => 1 } def overlaps(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match { case (RefinedType(parents, _), _) => parents exists (overlaps(_, tp2)) case (_, RefinedType(parents, _)) => parents exists (overlaps(tp1, _)) - case _ => tp1.typeSymbol == tp2.typeSymbol + case _ => tp1.typeSymbol == tp2.typeSymbol } val dtor1 = stripped(core(dtor)) val dted1 = stripped(core(dted)) @@ -664,6 +659,8 @@ trait Implicits { if (context.hasErrors) fail("hasMatchingSymbol reported error: " + context.firstError.get.errMsg) + else if (itree3.isErroneous) + fail("error typechecking implicit candidate") else if (isLocal && !hasMatchingSymbol(itree2)) fail("candidate implicit %s is shadowed by %s".format( info.sym.fullLocationString, itree2.symbol.fullLocationString)) diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala index e3d7bfd4f8..39e259fdfd 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala @@ -1695,4 +1695,11 @@ trait Namers extends MethodSynthesis { ) } } + + /** A version of `Symbol#linkedClassOfClass` that works with local companions, ala `companionSymbolOf`. */ + final def linkedClassOfClassOf(original: Symbol, ctx: Context): Symbol = + if (original.isModuleClass) + companionSymbolOf(original.sourceModule, ctx) + else + companionSymbolOf(original, ctx).moduleClass } diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala index 84531608e0..38065d5ea8 100644 --- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala +++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala @@ -1762,6 +1762,8 @@ abstract class RefChecks extends InfoTransform with scala.reflect.internal.trans | TypeDef(_, _, _, _) => if (result.symbol.isLocal || result.symbol.isTopLevel) varianceValidator.traverse(result) + case tt @ TypeTree() if tt.original != null => + varianceValidator.traverse(tt.original) // See SI-7872 case _ => } result diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala index 695a1e2e24..b801b644fb 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -109,6 +109,22 @@ trait TypeDiagnostics { case x => x.toString } + /** + * [a, b, c] => "(a, b, c)" + * [a, B] => "(param1, param2)" + * [a, B, c] => "(param1, ..., param2)" + */ + final def exampleTuplePattern(names: List[Name]): String = { + val arity = names.length + val varPatterNames: Option[List[String]] = sequence(names map { + case name if nme.isVariableName(name) => Some(name.decode) + case _ => None + }) + def parenthesize(a: String) = s"($a)" + def genericParams = (Seq("param1") ++ (if (arity > 2) Seq("...") else Nil) ++ Seq(s"param$arity")) + parenthesize(varPatterNames.getOrElse(genericParams).mkString(", ")) + } + def alternatives(tree: Tree): List[Type] = tree.tpe match { case OverloadedType(pre, alternatives) => alternatives map pre.memberType case _ => Nil diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala index fa704adde2..fb252c3058 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala @@ -1698,15 +1698,16 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper psym addChild context.owner else pending += ParentSealedInheritanceError(parent, psym) + val parentTypeOfThis = parent.tpe.dealias.typeOfThis - if (!(selfType <:< parent.tpe.typeOfThis) && + if (!(selfType <:< parentTypeOfThis) && !phase.erasedTypes && !context.owner.isSynthetic && // don't check synthetic concrete classes for virtuals (part of DEVIRTUALIZE) !selfType.isErroneous && !parent.tpe.isErroneous) { pending += ParentSelfTypeConformanceError(parent, selfType) - if (settings.explaintypes) explainTypes(selfType, parent.tpe.typeOfThis) + if (settings.explaintypes) explainTypes(selfType, parentTypeOfThis) } if (parents exists (p => p != parent && p.tpe.typeSymbol == psym && !psym.isError)) @@ -2905,6 +2906,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper else if (argpts.lengthCompare(numVparams) != 0) WrongNumberOfParametersError(fun, argpts) else { + var issuedMissingParameterTypeError = false foreach2(fun.vparams, argpts) { (vparam, argpt) => if (vparam.tpt.isEmpty) { vparam.tpt.tpe = @@ -2922,7 +2924,8 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper } case _ => } - MissingParameterTypeError(fun, vparam, pt) + MissingParameterTypeError(fun, vparam, pt, withTupleAddendum = !issuedMissingParameterTypeError) + issuedMissingParameterTypeError = true ErrorType } if (!vparam.tpt.pos.isDefined) vparam.tpt setPos vparam.pos.focus @@ -3834,7 +3837,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper // as we don't know which alternative to choose... here we do map2Conserve(args, tparams) { //@M! the polytype denotes the expected kind - (arg, tparam) => typedHigherKindedType(arg, mode, GenPolyType(tparam.typeParams, AnyTpe)) + (arg, tparam) => typedHigherKindedType(arg, mode, Kind.FromParams(tparam.typeParams)) } } else // @M: there's probably something wrong when args.length != tparams.length... (triggered by bug #320) // Martin, I'm using fake trees, because, if you use args or arg.map(typedType), @@ -3916,9 +3919,14 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper def typedNamedApply(orig: Tree, fun: Tree, args: List[Tree], mode: Mode, pt: Type): Tree = { def argToBinding(arg: Tree): Tree = arg match { - case AssignOrNamedArg(Ident(name), rhs) => gen.mkTuple(List(CODE.LIT(name.toString), rhs)) - case _ => gen.mkTuple(List(CODE.LIT(""), arg)) + case AssignOrNamedArg(i @ Ident(name), rhs) => + atPos(i.pos.withEnd(rhs.pos.end)) { + gen.mkTuple(List(atPos(i.pos)(CODE.LIT(name.toString)), rhs)) + } + case _ => + gen.mkTuple(List(CODE.LIT(""), arg)) } + val t = treeCopy.Apply(orig, fun, args map argToBinding) wrapErrors(t, _.typed(t, mode, pt)) } @@ -3978,7 +3986,10 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper case Some((opName, treeInfo.Applied(_, targs, _))) => val fun = gen.mkTypeApply(Select(qual, opName), targs) if (opName == nme.updateDynamic) suppressMacroExpansion(fun) // SI-7617 - atPos(qual.pos)(Apply(fun, Literal(Constant(name.decode)) :: Nil)) + val nameStringLit = atPos(treeSelection.pos.withStart(treeSelection.pos.point).makeTransparent) { + Literal(Constant(name.decode)) + } + atPos(qual.pos)(Apply(fun, List(nameStringLit))) case _ => setError(tree) } @@ -4174,7 +4185,9 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper } else if(dyna.isDynamicallyUpdatable(lhs1)) { val rhs1 = typedByValueExpr(rhs) - val t = Apply(lhs1, List(rhs1)) + val t = atPos(lhs1.pos.withEnd(rhs1.pos.end)) { + Apply(lhs1, List(rhs1)) + } dyna.wrapErrors(t, _.typed1(t, mode, pt)) } else fail() @@ -4868,14 +4881,19 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper if (sameLength(tparams, args)) { // @M: kind-arity checking is done here and in adapt, full kind-checking is in checkKindBounds (in Infer) - val args1 = - if (!isComplete) - args mapConserve (typedHigherKindedType(_, mode)) - // if symbol hasn't been fully loaded, can't check kind-arity - else map2Conserve(args, tparams) { (arg, tparam) => - //@M! the polytype denotes the expected kind - typedHigherKindedType(arg, mode, GenPolyType(tparam.typeParams, AnyTpe)) + val args1 = map2Conserve(args, tparams) { (arg, tparam) => + def ptParams = Kind.FromParams(tparam.typeParams) + + // if symbol hasn't been fully loaded, can't check kind-arity except when we're in a pattern, + // where we can (we can't take part in F-Bounds) and must (SI-8023) + val pt = if (mode.typingPatternOrTypePat) { + tparam.initialize; ptParams } + else if (isComplete) ptParams + else Kind.Wildcard + + typedHigherKindedType(arg, mode, pt) + } val argtypes = args1 map (_.tpe) foreach2(args, tparams) { (arg, tparam) => @@ -5051,7 +5069,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper // @M: fun is typed in TAPPmode because it is being applied to its actual type parameters val fun1 = typed(fun, mode.forFunMode | TAPPmode) - val tparams = fun1.symbol.typeParams + val tparams = if (fun1.symbol == null) Nil else fun1.symbol.typeParams //@M TODO: val undets_fun = context.undetparams ? // "do args first" (by restoring the context.undetparams) in order to maintain context.undetparams on the function side. @@ -5061,8 +5079,7 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper // @M maybe the well-kindedness check should be done when checking the type arguments conform to the type parameters' bounds? val args1 = if (sameLength(args, tparams)) map2Conserve(args, tparams) { - //@M! the polytype denotes the expected kind - (arg, tparam) => typedHigherKindedType(arg, mode, GenPolyType(tparam.typeParams, AnyTpe)) + (arg, tparam) => typedHigherKindedType(arg, mode, Kind.FromParams(tparam.typeParams)) } else { //@M this branch is correctly hit for an overloaded polymorphic type. It also has to handle erroneous cases. @@ -5432,9 +5449,9 @@ trait Typers extends Adaptations with Tags with TypersTracking with PatternTyper /** Types a (fully parameterized) type tree */ def typedType(tree: Tree): Tree = typedType(tree, NOmode) - /** Types a higher-kinded type tree -- pt denotes the expected kind*/ + /** Types a higher-kinded type tree -- pt denotes the expected kind and must be one of `Kind.WildCard` and `Kind.FromParams` */ def typedHigherKindedType(tree: Tree, mode: Mode, pt: Type): Tree = - if (pt.typeParams.isEmpty) typedType(tree, mode) // kind is known and it's * + if (pt != Kind.Wildcard && pt.typeParams.isEmpty) typedType(tree, mode) // kind is known and it's * else context withinTypeConstructorAllowed typed(tree, NOmode, pt) def typedHigherKindedType(tree: Tree, mode: Mode): Tree = diff --git a/src/compiler/scala/tools/nsc/util/package.scala b/src/compiler/scala/tools/nsc/util/package.scala index cb46004174..4237f36ade 100644 --- a/src/compiler/scala/tools/nsc/util/package.scala +++ b/src/compiler/scala/tools/nsc/util/package.scala @@ -90,51 +90,22 @@ package object util { lazy val trace = new SimpleTracer(System.out) - @deprecated("Moved to scala.reflect.internal.util.StringOps", "2.10.0") - val StringOps = scala.reflect.internal.util.StringOps - - @deprecated("Moved to scala.reflect.internal.util.StringOps", "2.10.0") - type StringOps = scala.reflect.internal.util.StringOps - - @deprecated("scala.reflect.internal.util.WeakHashSet", "2.10.0") - type WeakHashSet[T <: AnyRef] = scala.reflect.internal.util.WeakHashSet[T] - - @deprecated("Moved to scala.reflect.internal.util.Position", "2.10.0") - val Position = scala.reflect.internal.util.Position - + // These four deprecated since 2.10.0 are still used in (at least) + // the sbt 0.12.4 compiler interface. @deprecated("Moved to scala.reflect.internal.util.Position", "2.10.0") type Position = scala.reflect.internal.util.Position - @deprecated("Moved to scala.reflect.internal.util.NoPosition", "2.10.0") val NoPosition = scala.reflect.internal.util.NoPosition - @deprecated("Moved to scala.reflect.internal.util.FakePos", "2.10.0") val FakePos = scala.reflect.internal.util.FakePos - @deprecated("Moved to scala.reflect.internal.util.FakePos", "2.10.0") type FakePos = scala.reflect.internal.util.FakePos - @deprecated("Moved to scala.reflect.internal.util.OffsetPosition", "2.10.0") - type OffsetPosition = scala.reflect.internal.util.OffsetPosition - + // These three were still used in scala-refactoring. @deprecated("Moved to scala.reflect.internal.util.RangePosition", "2.10.0") type RangePosition = scala.reflect.internal.util.RangePosition - @deprecated("Moved to scala.reflect.internal.util.SourceFile", "2.10.0") type SourceFile = scala.reflect.internal.util.SourceFile - - @deprecated("Moved to scala.reflect.internal.util.NoSourceFile", "2.10.0") - val NoSourceFile = scala.reflect.internal.util.NoSourceFile - - @deprecated("Moved to scala.reflect.internal.util.NoFile", "2.10.0") - val NoFile = scala.reflect.internal.util.NoFile - - @deprecated("Moved to scala.reflect.internal.util.ScriptSourceFile", "2.10.0") - val ScriptSourceFile = scala.reflect.internal.util.ScriptSourceFile - - @deprecated("Moved to scala.reflect.internal.util.ScriptSourceFile", "2.10.0") - type ScriptSourceFile = scala.reflect.internal.util.ScriptSourceFile - @deprecated("Moved to scala.reflect.internal.util.BatchSourceFile", "2.10.0") type BatchSourceFile = scala.reflect.internal.util.BatchSourceFile diff --git a/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala b/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala index 3901184c25..126c14ac81 100644 --- a/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala +++ b/src/compiler/scala/tools/reflect/quasiquotes/Parsers.scala @@ -55,9 +55,7 @@ trait Parsers { self: Quasiquotes => def isHole(name: Name): Boolean = holeMap.contains(name) - override implicit def fresh: FreshNameCreator = new FreshNameCreator { - override def newName(prefix: String) = super.newName(nme.QUASIQUOTE_PREFIX + prefix) - } + override implicit def fresh: FreshNameCreator = new FreshNameCreator(nme.QUASIQUOTE_PREFIX) override val treeBuilder = new ParserTreeBuilder { override implicit def fresh: FreshNameCreator = parser.fresh @@ -189,19 +187,5 @@ trait Parsers { self: Quasiquotes => } } - // Extractor that matches names which were generated by call to - // freshTermName or freshTypeName within quasiquotes. Such names - // have qq$some$random$prefix$0 shape where qq$ part is added - // by modified fresh name creator in QuasiquoteParser. - object FreshName { - def unapply(name: Name): Option[String] = - name.toString.split("\\$").toSeq match { - case qq +: (middle :+ last) - if qq + "$" == nme.QUASIQUOTE_PREFIX - && Try(last.toInt).isSuccess && middle.nonEmpty => - Some(middle.mkString("", "$", "$")) - case _ => - None - } - } + object FreshName extends FreshNameExtractor(nme.QUASIQUOTE_PREFIX) }
\ No newline at end of file diff --git a/src/eclipse/partest/.classpath b/src/eclipse/partest/.classpath index e2a66118b9..35528a276d 100644 --- a/src/eclipse/partest/.classpath +++ b/src/eclipse/partest/.classpath @@ -5,7 +5,7 @@ <classpathentry combineaccessrules="false" kind="src" path="/repl"/> <classpathentry kind="var" path="M2_REPO/com/googlecode/java-diff-utils/diffutils/1.3.0/diffutils-1.3.0.jar"/> <classpathentry kind="var" path="M2_REPO/org/scala-tools/testing/test-interface/0.5/test-interface-0.5.jar"/> - <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-partest_2.11.0-M6/1.0.0-RC7/scala-partest_2.11.0-M6-1.0.0-RC7.jar"/> + <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-partest_2.11.0-M7/1.0.0-RC8/scala-partest_2.11.0-M7-1.0.0-RC8.jar"/> <classpathentry kind="var" path="SCALA_BASEDIR/lib/ant/ant.jar"/> <classpathentry kind="con" path="org.scala-ide.sdt.launching.SCALA_CONTAINER"/> <classpathentry kind="con" path="org.scala-ide.sdt.launching.SCALA_COMPILER_CONTAINER"/> diff --git a/src/eclipse/scaladoc/.classpath b/src/eclipse/scaladoc/.classpath index ac67fd2b03..c8f0e89b8a 100644 --- a/src/eclipse/scaladoc/.classpath +++ b/src/eclipse/scaladoc/.classpath @@ -6,8 +6,8 @@ <classpathentry combineaccessrules="false" kind="src" path="/scala-compiler"/> <classpathentry combineaccessrules="false" kind="src" path="/scala-library"/> <classpathentry combineaccessrules="false" kind="src" path="/partest-extras"/> - <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-xml_2.11.0-M6/1.0.0-RC6/scala-xml_2.11.0-M6-1.0.0-RC6.jar"/> - <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-parser-combinators_2.11.0-M6/1.0.0-RC4/scala-parser-combinators_2.11.0-M6-1.0.0-RC4.jar"/> - <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-partest_2.11.0-M6/1.0.0-RC7/scala-partest_2.11.0-M6-1.0.0-RC7.jar"/> + <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-xml_2.11.0-M7/1.0.0-RC7/scala-xml_2.11.0-M7-1.0.0-RC7.jar"/> + <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-parser-combinators_2.11.0-M7/1.0.0-RC5/scala-parser-combinators_2.11.0-M7-1.0.0-RC5.jar"/> + <classpathentry kind="var" path="M2_REPO/org/scala-lang/modules/scala-partest_2.11.0-M7/1.0.0-RC8/scala-partest_2.11.0-M7-1.0.0-RC8.jar"/> <classpathentry kind="output" path="build-quick-scaladoc"/> </classpath> diff --git a/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala b/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala index d036a6e853..69cae24808 100644 --- a/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala +++ b/src/interactive/scala/tools/nsc/interactive/CompilerControl.scala @@ -62,17 +62,6 @@ trait CompilerControl { self: Global => def onUnitOf[T](source: SourceFile)(op: RichCompilationUnit => T): T = op(unitOfFile.getOrElse(source.file, new RichCompilationUnit(source))) - /** The compilation unit corresponding to a source file - * if it does not yet exist create a new one atomically - * Note: We want to get roid of this operation as it messes compiler invariants. - */ - @deprecated("use getUnitOf(s) or onUnitOf(s) instead", "2.10.0") - def unitOf(s: SourceFile): RichCompilationUnit = getOrCreateUnitOf(s) - - /** The compilation unit corresponding to a position */ - @deprecated("use getUnitOf(pos.source) or onUnitOf(pos.source) instead", "2.10.0") - def unitOf(pos: Position): RichCompilationUnit = getOrCreateUnitOf(pos.source) - /** Removes the CompilationUnit corresponding to the given SourceFile * from consideration for recompilation. */ @@ -229,18 +218,6 @@ trait CompilerControl { self: Global => def askParsedEntered(source: SourceFile, keepLoaded: Boolean, response: Response[Tree]) = postWorkItem(new AskParsedEnteredItem(source, keepLoaded, response)) - /** Set sync var `response` to a pair consisting of - * - the fully qualified name of the first top-level object definition in the file. - * or "" if there are no object definitions. - * - the text of the instrumented program which, when run, - * prints its output and all defined values in a comment column. - * - * @param source The source file to be analyzed - * @param response The response. - */ - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - def askInstrumented(source: SourceFile, line: Int, response: Response[(String, Array[Char])]) = - postWorkItem(new AskInstrumentedItem(source, line, response)) /** Cancels current compiler run and start a fresh one where everything will be re-typechecked * (but not re-loaded). @@ -250,11 +227,6 @@ trait CompilerControl { self: Global => /** Tells the compile server to shutdown, and not to restart again */ def askShutdown() = scheduler raise ShutdownReq - @deprecated("use parseTree(source) instead", "2.10.0") // deleted 2nd parameter, as this has to run on 2.8 also. - def askParse(source: SourceFile, response: Response[Tree]) = respond(response) { - parseTree(source) - } - /** Returns parse tree for source `source`. No symbols are entered. Syntax errors are reported. * * This method is thread-safe and as such can safely run outside of the presentation @@ -419,15 +391,6 @@ trait CompilerControl { self: Global => response raise new MissingResponse } - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - case class AskInstrumentedItem(source: SourceFile, line: Int, response: Response[(String, Array[Char])]) extends WorkItem { - def apply() = self.getInstrumented(source, line, response) - override def toString = "getInstrumented "+source - - def raiseMissing() = - response raise new MissingResponse - } - /** A do-nothing work scheduler that responds immediately with MissingResponse. * * Used during compiler shutdown. diff --git a/src/interactive/scala/tools/nsc/interactive/Global.scala b/src/interactive/scala/tools/nsc/interactive/Global.scala index da838e0f83..441398e443 100644 --- a/src/interactive/scala/tools/nsc/interactive/Global.scala +++ b/src/interactive/scala/tools/nsc/interactive/Global.scala @@ -18,6 +18,7 @@ import symtab.Flags.{ACCESSOR, PARAMACCESSOR} import scala.annotation.{ elidable, tailrec } import scala.language.implicitConversions import scala.tools.nsc.typechecker.Typers +import scala.util.control.Breaks._ /** * This trait allows the IDE to have an instance of the PC that @@ -100,7 +101,6 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") with CompilerControl with ContextTrees with RichCompilationUnits - with ScratchPadMaker with Picklers { import definitions._ @@ -406,85 +406,91 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") * */ private[interactive] def pollForWork(pos: Position) { - if (!interruptsEnabled) return - if (pos == NoPosition || nodesSeen % yieldPeriod == 0) - Thread.`yield`() - - def nodeWithWork(): Option[WorkEvent] = - if (scheduler.moreWork || pendingResponse.isCancelled) Some(new WorkEvent(nodesSeen, System.currentTimeMillis)) - else None - - nodesSeen += 1 - logreplay("atnode", nodeWithWork()) match { - case Some(WorkEvent(id, _)) => - debugLog("some work at node "+id+" current = "+nodesSeen) -// assert(id >= nodesSeen) - moreWorkAtNode = id - case None => - } + var loop: Boolean = true + while (loop) { + breakable{ + loop = false + if (!interruptsEnabled) return + if (pos == NoPosition || nodesSeen % yieldPeriod == 0) + Thread.`yield`() + + def nodeWithWork(): Option[WorkEvent] = + if (scheduler.moreWork || pendingResponse.isCancelled) Some(new WorkEvent(nodesSeen, System.currentTimeMillis)) + else None + + nodesSeen += 1 + logreplay("atnode", nodeWithWork()) match { + case Some(WorkEvent(id, _)) => + debugLog("some work at node "+id+" current = "+nodesSeen) + // assert(id >= nodesSeen) + moreWorkAtNode = id + case None => + } - if (nodesSeen >= moreWorkAtNode) { - - logreplay("asked", scheduler.pollInterrupt()) match { - case Some(ir) => - try { - interruptsEnabled = false - debugLog("ask started"+timeStep) - ir.execute() - } finally { - debugLog("ask finished"+timeStep) - interruptsEnabled = true + if (nodesSeen >= moreWorkAtNode) { + + logreplay("asked", scheduler.pollInterrupt()) match { + case Some(ir) => + try { + interruptsEnabled = false + debugLog("ask started"+timeStep) + ir.execute() + } finally { + debugLog("ask finished"+timeStep) + interruptsEnabled = true + } + loop = true; break + case _ => } - pollForWork(pos) - case _ => - } - - if (logreplay("cancelled", pendingResponse.isCancelled)) { - throw CancelException - } - - logreplay("exception thrown", scheduler.pollThrowable()) match { - case Some(ex: FreshRunReq) => - newTyperRun() - minRunId = currentRunId - demandNewCompilerRun() - - case Some(ShutdownReq) => - scheduler.synchronized { // lock the work queue so no more items are posted while we clean it up - val units = scheduler.dequeueAll { - case item: WorkItem => Some(item.raiseMissing()) - case _ => Some(()) - } - - // don't forget to service interrupt requests - scheduler.dequeueAllInterrupts(_.execute()) - - debugLog("ShutdownReq: cleaning work queue (%d items)".format(units.size)) - debugLog("Cleanup up responses (%d loadedType pending, %d parsedEntered pending)" - .format(waitLoadedTypeResponses.size, getParsedEnteredResponses.size)) - checkNoResponsesOutstanding() - log.flush() - scheduler = new NoWorkScheduler - throw ShutdownReq + if (logreplay("cancelled", pendingResponse.isCancelled)) { + throw CancelException } - case Some(ex: Throwable) => log.flush(); throw ex - case _ => - } - - lastWasReload = false + logreplay("exception thrown", scheduler.pollThrowable()) match { + case Some(ex: FreshRunReq) => + newTyperRun() + minRunId = currentRunId + demandNewCompilerRun() + + case Some(ShutdownReq) => + scheduler.synchronized { // lock the work queue so no more items are posted while we clean it up + val units = scheduler.dequeueAll { + case item: WorkItem => Some(item.raiseMissing()) + case _ => Some(()) + } + + // don't forget to service interrupt requests + scheduler.dequeueAllInterrupts(_.execute()) + + debugLog("ShutdownReq: cleaning work queue (%d items)".format(units.size)) + debugLog("Cleanup up responses (%d loadedType pending, %d parsedEntered pending)" + .format(waitLoadedTypeResponses.size, getParsedEnteredResponses.size)) + checkNoResponsesOutstanding() + + log.flush() + scheduler = new NoWorkScheduler + throw ShutdownReq + } + + case Some(ex: Throwable) => log.flush(); throw ex + case _ => + } - logreplay("workitem", scheduler.nextWorkItem()) match { - case Some(action) => - try { - debugLog("picked up work item at "+pos+": "+action+timeStep) - action() - debugLog("done with work item: "+action) - } finally { - debugLog("quitting work item: "+action+timeStep) + lastWasReload = false + + logreplay("workitem", scheduler.nextWorkItem()) match { + case Some(action) => + try { + debugLog("picked up work item at "+pos+": "+action+timeStep) + action() + debugLog("done with work item: "+action) + } finally { + debugLog("quitting work item: "+action+timeStep) + } + case None => } - case None => + } } } } @@ -1171,18 +1177,6 @@ class Global(settings: Settings, _reporter: Reporter, projectName: String = "") } } - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - def getInstrumented(source: SourceFile, line: Int, response: Response[(String, Array[Char])]) { - try { - interruptsEnabled = false - respond(response) { - instrument(source, line) - } - } finally { - interruptsEnabled = true - } - } - // ---------------- Helper classes --------------------------- /** The typer run */ diff --git a/src/interactive/scala/tools/nsc/interactive/REPL.scala b/src/interactive/scala/tools/nsc/interactive/REPL.scala index 33981771ec..8e9b0ceee0 100644 --- a/src/interactive/scala/tools/nsc/interactive/REPL.scala +++ b/src/interactive/scala/tools/nsc/interactive/REPL.scala @@ -9,7 +9,6 @@ package interactive import scala.reflect.internal.util._ import scala.tools.nsc.reporters._ import scala.tools.nsc.io._ -import scala.tools.nsc.scratchpad.SourceInserter import java.io.FileWriter /** Interface of interactive compiler to a client such as an IDE @@ -89,8 +88,6 @@ object REPL { val completeResult = new Response[List[comp.Member]] val typedResult = new Response[comp.Tree] val structureResult = new Response[comp.Tree] - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - val instrumentedResult = new Response[(String, Array[Char])] def makePos(file: String, off1: String, off2: String) = { val source = toSourceFile(file) @@ -112,52 +109,6 @@ object REPL { show(structureResult) } - /** Write instrumented source file to disk. - * @param iFullName The full name of the first top-level object in source - * @param iContents An Array[Char] containing the instrumented source - * @return The name of the instrumented source file - */ - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - def writeInstrumented(iFullName: String, suffix: String, iContents: Array[Char]): String = { - val iSimpleName = iFullName drop ((iFullName lastIndexOf '.') + 1) - val iSourceName = iSimpleName + suffix - val ifile = new FileWriter(iSourceName) - ifile.write(iContents) - ifile.close() - iSourceName - } - - /** The method for implementing worksheet functionality. - * @param arguments a file name, followed by optional command line arguments that are passed - * to the compiler that processes the instrumented source. - * @param line A line number that controls uop to which line results should be produced - * If line = -1, results are produced for all expressions in the worksheet. - * @return The generated file content containing original source in the left column - * and outputs in the right column, or None if the presentation compiler - * does not respond to askInstrumented. - */ - @deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") - def instrument(arguments: List[String], line: Int): Option[(String, String)] = { - val source = toSourceFile(arguments.head) - // strip right hand side comment column and any trailing spaces from all lines - val strippedContents = SourceInserter.stripRight(source.content) - val strippedSource = new BatchSourceFile(source.file, strippedContents) - println("stripped source = "+strippedSource+":"+strippedContents.mkString) - comp.askReload(List(strippedSource), reloadResult) - comp.askInstrumented(strippedSource, line, instrumentedResult) - using(instrumentedResult) { - case (iFullName, iContents) => - println(s"instrumented source $iFullName = ${iContents.mkString}") - val iSourceName = writeInstrumented(iFullName, "$instrumented.scala", iContents) - val sSourceName = writeInstrumented(iFullName, "$stripped.scala", strippedContents) - (iSourceName, sSourceName) -/* - * val vdirOpt = compileInstrumented(iSourceName, arguments.tail) - runInstrumented(vdirOpt, iFullName, strippedSource.content) - */ - } - } - loop { line => (line split " ").toList match { case "reload" :: args => @@ -177,10 +128,6 @@ object REPL { doComplete(makePos(file, off1, off2)) case List("complete", file, off1) => doComplete(makePos(file, off1, off1)) - case "instrument" :: arguments => - println(instrument(arguments, -1)) - case "instrumentTo" :: line :: arguments => - println(instrument(arguments, line.toInt)) case List("quit") => comp.askShutdown() sys.exit(1) @@ -195,8 +142,6 @@ object REPL { | typeat <file> <pos> | complete <file> <start-pos> <end-pos> | compile <file> <pos> - | instrument <file> <arg>* - | instrumentTo <line-num> <file> <arg>* | structure <file> | quit |""".stripMargin) diff --git a/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala b/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala deleted file mode 100644 index 2400b97d97..0000000000 --- a/src/interactive/scala/tools/nsc/interactive/ScratchPadMaker.scala +++ /dev/null @@ -1,201 +0,0 @@ -package scala -package tools.nsc -package interactive - -import scala.reflect.internal.util.{SourceFile, BatchSourceFile, RangePosition} -import scala.collection.mutable.ArrayBuffer -import scala.reflect.internal.Chars.{isLineBreakChar, isWhitespace} -import ast.parser.Tokens._ - -@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") -trait ScratchPadMaker { self: Global => - - import definitions._ - - private case class Patch(offset: Int, text: String) - - private class Patcher(contents: Array[Char], lex: LexicalStructure, endOffset: Int) extends Traverser { - var objectName: String = "" - - private val patches = new ArrayBuffer[Patch] - private val toPrint = new ArrayBuffer[String] - private var skipped = 0 - private var resNum: Int = -1 - - private def nextRes(): String = { - resNum += 1 - "res$"+resNum - } - - private def nameType(name: String, tpe: Type): String = { - // if name ends in symbol character, add a space to separate it from the following ':' - val pad = if (Character.isLetter(name.last) || Character.isDigit(name.last)) "" else " " - name+pad+": "+tpe - } - - private def nameType(sym: Symbol): String = nameType(sym.name.decoded, sym.tpe) - - private def literal(str: String) = "\"\"\""+str+"\"\"\"" - - private val prologue = ";import scala.runtime.WorksheetSupport._; def main(args: Array[String])=$execute{" - - private val epilogue = "}" - - private def applyPendingPatches(offset: Int) = { - if (skipped == 0) patches += Patch(offset, prologue) - for (msg <- toPrint) patches += Patch(offset, ";System.out.println("+msg+")") - toPrint.clear() - } - - /** The position where to insert an instrumentation statement in front of given statement. - * This is at the latest `stat.pos.start`. But in order not to mess with column numbers - * in position we try to insert it at the end of the previous token instead. - * Furthermore, `(' tokens have to be skipped because they do not show up - * in statement range positions. - */ - private def instrumentPos(start: Int): Int = { - val (prevToken, prevStart, prevEnd) = lex.locate(start - 1) - if (prevStart >= start) start - else if (prevToken == LPAREN) instrumentPos(prevStart) - else prevEnd - } - - private def addSkip(stat: Tree): Unit = { - val ipos = instrumentPos(stat.pos.start) - if (stat.pos.start > skipped) applyPendingPatches(ipos) - if (stat.pos.start >= endOffset) - patches += Patch(ipos, ";$stop()") - var end = stat.pos.end - if (end > skipped) { - while (end < contents.length && !isLineBreakChar(contents(end))) end += 1 - patches += Patch(ipos, ";$skip("+(end-skipped)+"); ") - skipped = end - } - } - - private def addSandbox(expr: Tree) = {} -// patches += (Patch(expr.pos.start, "sandbox("), Patch(expr.pos.end, ")")) - - private def resultString(prefix: String, expr: String) = - literal(prefix + " = ") + " + $show(" + expr + ")" - - private def traverseStat(stat: Tree) = - if (stat.pos.isInstanceOf[RangePosition]) { - stat match { - case ValDef(_, _, _, rhs) => - addSkip(stat) - if (stat.symbol.isLazy) - toPrint += literal(nameType(stat.symbol) + " = <lazy>") - else if (!stat.symbol.isSynthetic) { - addSandbox(rhs) - toPrint += resultString(nameType(stat.symbol), stat.symbol.name.toString) - } - case DefDef(_, _, _, _, _, _) => - addSkip(stat) - toPrint += literal(nameType(stat.symbol)) - case Annotated(_, arg) => - traverse(arg) - case DocDef(_, defn) => - traverse(defn) - case _ => - if (stat.isTerm) { - addSkip(stat) - if (stat.tpe.typeSymbol == UnitClass) { - addSandbox(stat) - } else { - val resName = nextRes() - val dispResName = resName filter ('$' != _) - val offset = instrumentPos(stat.pos.start) - patches += Patch(offset, "val " + resName + " = ") - addSandbox(stat) - toPrint += resultString(nameType(dispResName, stat.tpe), resName) - } - } - } - } - - override def traverse(tree: Tree): Unit = tree match { - case PackageDef(_, _) => - super.traverse(tree) - case ModuleDef(_, name, Template(_, _, body)) => - val topLevel = objectName.isEmpty - if (topLevel) { - objectName = tree.symbol.fullName - body foreach traverseStat - if (skipped != 0) { // don't issue prologue and epilogue if there are no instrumented statements - applyPendingPatches(skipped) - patches += Patch(skipped, epilogue) - } - } - case _ => - } - - /** The patched text. - * @require traverse is run first - */ - def result: Array[Char] = { - val reslen = contents.length + (patches map (_.text.length)).sum - val res = Array.ofDim[Char](reslen) - var lastOffset = 0 - var from = 0 - var to = 0 - for (Patch(offset, text) <- patches) { - val delta = offset - lastOffset - assert(delta >= 0) - Array.copy(contents, from, res, to, delta) - from += delta - to += delta - lastOffset = offset - text.copyToArray(res, to) - to += text.length - } - assert(contents.length - from == reslen - to) - Array.copy(contents, from, res, to, contents.length - from) - res - } - } - - class LexicalStructure(source: SourceFile) { - val token = new ArrayBuffer[Int] - val startOffset = new ArrayBuffer[Int] - val endOffset = new ArrayBuffer[Int] - private val scanner = new syntaxAnalyzer.UnitScanner(new CompilationUnit(source)) - scanner.init() - while (scanner.token != EOF) { - startOffset += scanner.offset - token += scanner.token - scanner.nextToken() - endOffset += scanner.lastOffset - } - - /** @return token that starts before or at offset, its startOffset, its endOffset - */ - def locate(offset: Int): (Int, Int, Int) = { - var lo = 0 - var hi = token.length - 1 - while (lo < hi) { - val mid = (lo + hi + 1) / 2 - if (startOffset(mid) <= offset) lo = mid - else hi = mid - 1 - } - (token(lo), startOffset(lo), endOffset(lo)) - } - } - - /** Compute an instrumented version of a sourcefile. - * @param source The given sourcefile. - * @param line The line up to which results should be printed, -1 = whole document. - * @return A pair consisting of - * - the fully qualified name of the first top-level object definition in the file. - * or "" if there are no object definitions. - * - the text of the instrumented program which, when run, - * prints its output and all defined values in a comment column. - */ - protected def instrument(source: SourceFile, line: Int): (String, Array[Char]) = { - val tree = typedTree(source, forceReload = true) - val endOffset = if (line < 0) source.length else source.lineToOffset(line + 1) - val patcher = new Patcher(source.content, new LexicalStructure(source), endOffset) - patcher.traverse(tree) - (patcher.objectName, patcher.result) - } -} diff --git a/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala b/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala index 451cf70bc2..bc490d8d45 100644 --- a/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala +++ b/src/interactive/scala/tools/nsc/interactive/tests/core/CoreTestDefs.scala @@ -40,9 +40,6 @@ private[tests] trait CoreTestDefs extends PresentationCompilerTestDef with AskScopeCompletionAt { - def memberPrinter(member: compiler.Member): String = - "[accessible: %5s] ".format(member.accessible) + "`" + (member.sym.toString() + member.tpe.toString()).trim() + "`" - override def runTest() { askAllSources(ScopeCompletionMarker) { pos => askScopeCompletionAt(pos) diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala index cd96b5182c..8900450fa3 100644 --- a/src/library/scala/Predef.scala +++ b/src/library/scala/Predef.scala @@ -26,8 +26,6 @@ import scala.io.ReadStdin * [[scala.collection.immutable.Set]], and the [[scala.collection.immutable.List]] * constructors ([[scala.collection.immutable.::]] and * [[scala.collection.immutable.Nil]]). - * The types `Pair` (a [[scala.Tuple2]]) and `Triple` (a [[scala.Tuple3]]), with - * simple constructors, are also provided. * * === Console I/O === * Predef provides a number of simple functions for console I/O, such as @@ -230,13 +228,17 @@ object Predef extends LowPriorityImplicits with DeprecatedPredef { // tupling ------------------------------------------------------------ + @deprecated("Use built-in tuple syntax or Tuple2 instead", "2.11.0") type Pair[+A, +B] = Tuple2[A, B] + @deprecated("Use built-in tuple syntax or Tuple2 instead", "2.11.0") object Pair { def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x) } + @deprecated("Use built-in tuple syntax or Tuple3 instead", "2.11.0") type Triple[+A, +B, +C] = Tuple3[A, B, C] + @deprecated("Use built-in tuple syntax or Tuple3 instead", "2.11.0") object Triple { def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x) diff --git a/src/library/scala/Responder.scala b/src/library/scala/Responder.scala index 0a42ddb0ea..8a658e252a 100644 --- a/src/library/scala/Responder.scala +++ b/src/library/scala/Responder.scala @@ -18,6 +18,7 @@ package scala * @see class Responder * @since 2.1 */ +@deprecated("This object will be removed", "2.11.0") object Responder { /** Creates a responder that answer continuations with the constant `a`. @@ -58,6 +59,7 @@ object Responder { * @version 1.0 * @since 2.1 */ +@deprecated("This class will be removed", "2.11.0") abstract class Responder[+A] extends Serializable { def respond(k: A => Unit): Unit diff --git a/src/library/scala/annotation/migration.scala b/src/library/scala/annotation/migration.scala index 65bee4c2cb..e71be00f32 100644 --- a/src/library/scala/annotation/migration.scala +++ b/src/library/scala/annotation/migration.scala @@ -25,7 +25,4 @@ package scala.annotation * * @since 2.8 */ - private[scala] final class migration(message: String, changedIn: String) extends scala.annotation.StaticAnnotation { - @deprecated("Use the constructor taking two Strings instead.", "2.10.0") - def this(majorVersion: Int, minorVersion: Int, message: String) = this(message, majorVersion + "." + minorVersion) - } + private[scala] final class migration(message: String, changedIn: String) extends scala.annotation.StaticAnnotation diff --git a/src/library/scala/collection/IterableViewLike.scala b/src/library/scala/collection/IterableViewLike.scala index b9450173d8..668190f700 100644 --- a/src/library/scala/collection/IterableViewLike.scala +++ b/src/library/scala/collection/IterableViewLike.scala @@ -146,5 +146,14 @@ trait IterableViewLike[+A, override def sliding(size: Int, step: Int): Iterator[This] = self.iterator.sliding(size, step) map (x => newForced(x).asInstanceOf[This]) + override def sliding(size: Int): Iterator[This] = + sliding(size, 1) // we could inherit this, but that implies knowledge of the way the super class is implemented. + + override def dropRight(n: Int): This = + take(thisSeq.length - n) + + override def takeRight(n: Int): This = + drop(thisSeq.length - n) + override def stringPrefix = "IterableView" } diff --git a/src/library/scala/collection/SeqViewLike.scala b/src/library/scala/collection/SeqViewLike.scala index c1c9052aa2..5e31ac4a53 100644 --- a/src/library/scala/collection/SeqViewLike.scala +++ b/src/library/scala/collection/SeqViewLike.scala @@ -245,5 +245,20 @@ trait SeqViewLike[+A, override def sorted[B >: A](implicit ord: Ordering[B]): This = newForced(thisSeq sorted ord).asInstanceOf[This] + override def sortWith(lt: (A, A) => Boolean): This = + newForced(thisSeq sortWith lt).asInstanceOf[This] + + override def sortBy[B](f: (A) => B)(implicit ord: Ordering[B]): This = + newForced(thisSeq sortBy f).asInstanceOf[This] + + override def combinations(n: Int): Iterator[This] = + (thisSeq combinations n).map(as => newForced(as).asInstanceOf[This]) + + override def permutations: Iterator[This] = + thisSeq.permutations.map(as => newForced(as).asInstanceOf[This]) + + override def distinct: This = + newForced(thisSeq.distinct).asInstanceOf[This] + override def stringPrefix = "SeqView" } diff --git a/src/library/scala/collection/TraversableViewLike.scala b/src/library/scala/collection/TraversableViewLike.scala index b6a268e00b..5926c69ebf 100644 --- a/src/library/scala/collection/TraversableViewLike.scala +++ b/src/library/scala/collection/TraversableViewLike.scala @@ -291,5 +291,18 @@ trait TraversableViewLike[+A, override def unzip3[A1, A2, A3](implicit asTriple: A => (A1, A2, A3)) = (newMapped(x => asTriple(x)._1), newMapped(x => asTriple(x)._2), newMapped(x => asTriple(x)._3)) // TODO - Performance improvements. + override def filterNot(p: (A) => Boolean): This = + newFiltered(a => !(p(a))) + + override def inits: Iterator[This] = + thisSeq.inits.map(as => newForced(as).asInstanceOf[This]) + + override def tails: Iterator[This] = + thisSeq.tails.map(as => newForced(as).asInstanceOf[This]) + + override def tail: This = + // super.tail would also work as it is currently implemented in terms of drop(Int). + if (isEmpty) super.tail else newDropped(1) + override def toString = viewToString } diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala index 34b2346851..00f398a4b0 100644 --- a/src/library/scala/collection/immutable/Range.scala +++ b/src/library/scala/collection/immutable/Range.scala @@ -117,22 +117,6 @@ extends scala.collection.AbstractSeq[Int] fail() } - @deprecated("Range.foreach() is now self-contained, making this auxiliary method redundant.", "2.10.1") - def validateRangeBoundaries(f: Int => Any): Boolean = { - validateMaxLength() - - start != Int.MinValue || end != Int.MinValue || { - var count = 0 - var num = start - while (count < numRangeElements) { - f(num) - count += 1 - num += step - } - false - } - } - final def apply(idx: Int): Int = { validateMaxLength() if (idx < 0 || idx >= numRangeElements) throw new IndexOutOfBoundsException(idx.toString) diff --git a/src/library/scala/collection/immutable/Vector.scala b/src/library/scala/collection/immutable/Vector.scala index 0a100578c0..c7da447f72 100644 --- a/src/library/scala/collection/immutable/Vector.scala +++ b/src/library/scala/collection/immutable/Vector.scala @@ -59,7 +59,7 @@ object Vector extends IndexedSeqFactory[Vector] { * @define mayNotTerminateInf * @define willNotTerminateInf */ -final class Vector[+A](private[collection] val startIndex: Int, private[collection] val endIndex: Int, focus: Int) +final class Vector[+A] private[immutable] (private[collection] val startIndex: Int, private[collection] val endIndex: Int, focus: Int) extends AbstractSeq[A] with IndexedSeq[A] with GenericTraversableTemplate[A, Vector] @@ -227,7 +227,7 @@ override def companion: GenericCompanion[Vector] = Vector val ri = this.reverseIterator while (ri.hasNext) v = ri.next +: v v.asInstanceOf[That] - case _ => super.++(that) + case _ => super.++(again) } } } diff --git a/src/library/scala/collection/mutable/IndexedSeqView.scala b/src/library/scala/collection/mutable/IndexedSeqView.scala index 36c1076b87..31a4749960 100644 --- a/src/library/scala/collection/mutable/IndexedSeqView.scala +++ b/src/library/scala/collection/mutable/IndexedSeqView.scala @@ -93,6 +93,7 @@ self => override def span(p: A => Boolean): (This, This) = (newTakenWhile(p), newDroppedWhile(p)) override def splitAt(n: Int): (This, This) = (take(n), drop(n)) // !!! override def reverse: This = newReversed + override def tail: IndexedSeqView[A, Coll] = if (isEmpty) super.tail else slice(1, length) } /** An object containing the necessary implicit definitions to make diff --git a/src/library/scala/concurrent/impl/Promise.scala b/src/library/scala/concurrent/impl/Promise.scala index 418d859d79..b15601058e 100644 --- a/src/library/scala/concurrent/impl/Promise.scala +++ b/src/library/scala/concurrent/impl/Promise.scala @@ -82,11 +82,11 @@ private[concurrent] object Promise { * 2. Complete, with a result. * 3. Linked to another DefaultPromise. * - * If a DefaultPromise is linked it another DefaultPromise then it will + * If a DefaultPromise is linked to another DefaultPromise, it will * delegate all its operations to that other promise. This means that two * DefaultPromises that are linked will appear, to external callers, to have - * exactly the same state and behaviour. E.g. they will both appear to be - * either complete or incomplete, and with the same values. + * exactly the same state and behaviour. For instance, both will appear as + * incomplete, or as complete with the same result value. * * A DefaultPromise stores its state entirely in the AnyRef cell exposed by * AbstractPromise. The type of object stored in the cell fully describes the diff --git a/src/library/scala/math/BigDecimal.scala b/src/library/scala/math/BigDecimal.scala index 0a2da16523..d783dd29f5 100644 --- a/src/library/scala/math/BigDecimal.scala +++ b/src/library/scala/math/BigDecimal.scala @@ -158,8 +158,7 @@ object BigDecimal { * @author Stephane Micheloud * @version 1.0 */ -@deprecatedInheritance("This class will be made final.", "2.10.0") -class BigDecimal( +final class BigDecimal( val bigDecimal: BigDec, val mc: MathContext) extends ScalaNumber with ScalaNumericConversions with Serializable { diff --git a/src/library/scala/math/BigInt.scala b/src/library/scala/math/BigInt.scala index b25dbefebd..5e70bdc2f6 100644 --- a/src/library/scala/math/BigInt.scala +++ b/src/library/scala/math/BigInt.scala @@ -109,8 +109,7 @@ object BigInt { * @author Martin Odersky * @version 1.0, 15/07/2003 */ -@deprecatedInheritance("This class will be made final.", "2.10.0") -class BigInt(val bigInteger: BigInteger) extends ScalaNumber with ScalaNumericConversions with Serializable { +final class BigInt(val bigInteger: BigInteger) extends ScalaNumber with ScalaNumericConversions with Serializable { /** Returns the hash code for this BigInt. */ override def hashCode(): Int = if (isValidLong) unifiedPrimitiveHashcode() diff --git a/src/library/scala/reflect/ClassManifestDeprecatedApis.scala b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala index 798746851a..ca7a3cddb8 100644 --- a/src/library/scala/reflect/ClassManifestDeprecatedApis.scala +++ b/src/library/scala/reflect/ClassManifestDeprecatedApis.scala @@ -16,6 +16,7 @@ import java.lang.{ Class => jClass } trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { self: ClassManifest[T] => + // Still in use in target test.junit.comp. @deprecated("Use runtimeClass instead", "2.10.0") def erasure: jClass[_] = runtimeClass @@ -64,12 +65,12 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { // when the erasure is the same, even before considering variance. !cannotMatch && { // this part is wrong for not considering variance - if (this.erasure == that.erasure) + if (this.runtimeClass == that.runtimeClass) subargs(this.typeArguments, that.typeArguments) // this part is wrong for punting unless the rhs has no type // arguments, but it's better than a blindfolded pinata swing. else - that.typeArguments.isEmpty && subtype(this.erasure, that.erasure) + that.typeArguments.isEmpty && subtype(this.runtimeClass, that.runtimeClass) } } @@ -91,29 +92,29 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { @deprecated("Use wrap instead", "2.10.0") def arrayManifest: ClassManifest[Array[T]] = - ClassManifest.classType[Array[T]](arrayClass[T](erasure), this) + ClassManifest.classType[Array[T]](arrayClass[T](runtimeClass), this) override def newArray(len: Int): Array[T] = - java.lang.reflect.Array.newInstance(erasure, len).asInstanceOf[Array[T]] + java.lang.reflect.Array.newInstance(runtimeClass, len).asInstanceOf[Array[T]] @deprecated("Use wrap.newArray instead", "2.10.0") def newArray2(len: Int): Array[Array[T]] = - java.lang.reflect.Array.newInstance(arrayClass[T](erasure), len) + java.lang.reflect.Array.newInstance(arrayClass[T](runtimeClass), len) .asInstanceOf[Array[Array[T]]] @deprecated("Use wrap.wrap.newArray instead", "2.10.0") def newArray3(len: Int): Array[Array[Array[T]]] = - java.lang.reflect.Array.newInstance(arrayClass[Array[T]](arrayClass[T](erasure)), len) + java.lang.reflect.Array.newInstance(arrayClass[Array[T]](arrayClass[T](runtimeClass)), len) .asInstanceOf[Array[Array[Array[T]]]] @deprecated("Use wrap.wrap.wrap.newArray instead", "2.10.0") def newArray4(len: Int): Array[Array[Array[Array[T]]]] = - java.lang.reflect.Array.newInstance(arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](erasure))), len) + java.lang.reflect.Array.newInstance(arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](runtimeClass))), len) .asInstanceOf[Array[Array[Array[Array[T]]]]] @deprecated("Use wrap.wrap.wrap.wrap.newArray instead", "2.10.0") def newArray5(len: Int): Array[Array[Array[Array[Array[T]]]]] = - java.lang.reflect.Array.newInstance(arrayClass[Array[Array[Array[T]]]](arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](erasure)))), len) + java.lang.reflect.Array.newInstance(arrayClass[Array[Array[Array[T]]]](arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](runtimeClass)))), len) .asInstanceOf[Array[Array[Array[Array[Array[T]]]]]] @deprecated("Create WrappedArray directly instead", "2.10.0") @@ -131,7 +132,7 @@ trait ClassManifestDeprecatedApis[T] extends OptManifest[T] { protected def argString = if (typeArguments.nonEmpty) typeArguments.mkString("[", ", ", "]") - else if (erasure.isArray) "["+ClassManifest.fromClass(erasure.getComponentType)+"]" + else if (runtimeClass.isArray) "["+ClassManifest.fromClass(runtimeClass.getComponentType)+"]" else "" } @@ -221,7 +222,7 @@ object ClassManifestFactory { */ def abstractType[T](prefix: OptManifest[_], name: String, upperbound: ClassManifest[_], args: OptManifest[_]*): ClassManifest[T] = new ClassManifest[T] { - override def runtimeClass = upperbound.erasure + override def runtimeClass = upperbound.runtimeClass override val typeArguments = args.toList override def toString = prefix.toString+"#"+name+argString } @@ -236,6 +237,6 @@ private class ClassTypeManifest[T]( { override def toString = (if (prefix.isEmpty) "" else prefix.get.toString+"#") + - (if (erasure.isArray) "Array" else erasure.getName) + + (if (runtimeClass.isArray) "Array" else runtimeClass.getName) + argString }
\ No newline at end of file diff --git a/src/library/scala/reflect/Manifest.scala b/src/library/scala/reflect/Manifest.scala index 3bc76da295..803c980058 100644 --- a/src/library/scala/reflect/Manifest.scala +++ b/src/library/scala/reflect/Manifest.scala @@ -46,7 +46,7 @@ trait Manifest[T] extends ClassManifest[T] with Equals { override def typeArguments: List[Manifest[_]] = Nil override def arrayManifest: Manifest[Array[T]] = - Manifest.classType[Array[T]](arrayClass[T](erasure), this) + Manifest.classType[Array[T]](arrayClass[T](runtimeClass), this) override def canEqual(that: Any): Boolean = that match { case _: Manifest[_] => true @@ -56,10 +56,10 @@ trait Manifest[T] extends ClassManifest[T] with Equals { * faster than <:< and rules out most comparisons. */ override def equals(that: Any): Boolean = that match { - case m: Manifest[_] => (m canEqual this) && (this.erasure == m.erasure) && (this <:< m) && (m <:< this) + case m: Manifest[_] => (m canEqual this) && (this.runtimeClass == m.runtimeClass) && (this <:< m) && (m <:< this) case _ => false } - override def hashCode = this.erasure.## + override def hashCode = this.runtimeClass.## } // TODO undeprecated until Scala reflection becomes non-experimental @@ -238,7 +238,7 @@ object ManifestFactory { override val typeArguments: List[Manifest[_]]) extends Manifest[T] { override def toString = (if (prefix.isEmpty) "" else prefix.get.toString+"#") + - (if (erasure.isArray) "Array" else erasure.getName) + + (if (runtimeClass.isArray) "Array" else runtimeClass.getName) + argString } @@ -259,7 +259,7 @@ object ManifestFactory { */ def wildcardType[T](lowerBound: Manifest[_], upperBound: Manifest[_]): Manifest[T] = new Manifest[T] { - def runtimeClass = upperBound.erasure + def runtimeClass = upperBound.runtimeClass override def toString = "_" + (if (lowerBound eq Nothing) "" else " >: "+lowerBound) + @@ -269,7 +269,7 @@ object ManifestFactory { /** Manifest for the intersection type `parents_0 with ... with parents_n'. */ def intersectionType[T](parents: Manifest[_]*): Manifest[T] = new Manifest[T] { - def runtimeClass = parents.head.erasure + def runtimeClass = parents.head.runtimeClass override def toString = parents.mkString(" with ") } } diff --git a/src/library/scala/runtime/WorksheetSupport.scala b/src/library/scala/runtime/WorksheetSupport.scala deleted file mode 100644 index d86f8873aa..0000000000 --- a/src/library/scala/runtime/WorksheetSupport.scala +++ /dev/null @@ -1,93 +0,0 @@ -package scala.runtime -import java.io.{OutputStream, PrintStream} -import scala.runtime.ScalaRunTime.stringOf - -/** A utility object that's needed by the code that executes a worksheet. - */ -@deprecated("SI-6458: Instrumentation logic will be moved out of the compiler.","2.10.0") -object WorksheetSupport { - - /** The offset in the source which should be printed */ - private var currentOffset = 0 - - /** A stream that flushes in regular intervals so that output can be captured - * in real time. The flush interval is determined by the field "flushInterval". - * By default it is 30ms. - */ - private class FlushedOutputStream(out: OutputStream) extends OutputStream { - protected def flushInterval = 30000000L // interval between flushes, by default 30ms - protected def width = 80 // output width, by default 80 characters - protected def tabInc = 8 // tab increment, by default 8 characters - private var lastFlush: Long = 0L - private var col = -1 - override def write(b: Array[Byte], off: Int, len: Int) = { - for (idx <- off until (off + len min b.length)) writeOne(b(idx).toInt) - flush() - } - override def write(c: Int) { - writeOne(c) - flush() - } - override def flush() { - val current = System.nanoTime - if (current - lastFlush >= flushInterval) { - out.flush() - lastFlush = current - } - } - def writeOne(c: Int) { - if (col < 0) { - col = 0 - write((currentOffset+" ").getBytes) - } - out.write(c) - col = - if (c == '\n') -1 - else if (c == '\t') (col / tabInc) * tabInc + tabInc - else col + 1 - if (col >= width) writeOne('\n') - } - def ensureNewLine() = if (col > 0) writeOne('\n') - } - - private val flushedOut = new FlushedOutputStream(System.out) - private val printOut = new PrintStream(flushedOut) - - private def redirected(op: => Unit) = { - val oldSysOut = System.out - val oldSysErr = System.err - val oldConsOut = Console.out - val oldConsErr = Console.err - System.setOut(printOut) - System.setErr(printOut) - Console.setOut(printOut) - Console.setErr(printOut) - try op - finally { - printOut.close() - System.setOut(oldSysOut) - System.setErr(oldSysErr) - Console.setOut(oldConsOut) - Console.setErr(oldConsErr) - } - } - - def $execute(op: => Unit) = redirected { - try op - catch { - case ex: StopException => ; - case ex: Throwable => ex.printStackTrace() - } - } - - def $skip(n: Int) = { - flushedOut.ensureNewLine() - currentOffset += n - } - - def $stop() = throw new StopException - - def $show(x: Any): String = stringOf(x) -} - -class StopException extends Exception diff --git a/src/library/scala/util/control/NonFatal.scala b/src/library/scala/util/control/NonFatal.scala index 11fb988e8e..9d3dfea074 100644 --- a/src/library/scala/util/control/NonFatal.scala +++ b/src/library/scala/util/control/NonFatal.scala @@ -11,9 +11,8 @@ package util.control /** * Extractor of non-fatal Throwables. Will not match fatal errors like `VirtualMachineError` - * (for example, `OutOfMemoryError`, a subclass of `VirtualMachineError`), `ThreadDeath`, + * (for example, `OutOfMemoryError` and `StackOverflowError`, subclasses of `VirtualMachineError`), `ThreadDeath`, * `LinkageError`, `InterruptedException`, `ControlThrowable`. - * However, `StackOverflowError` is matched, i.e. considered non-fatal. * * Note that [[scala.util.control.ControlThrowable]], an internal Throwable, is not matched by * `NonFatal` (and would therefore be thrown). @@ -34,7 +33,6 @@ object NonFatal { * Returns true if the provided `Throwable` is to be considered non-fatal, or false if it is to be considered fatal */ def apply(t: Throwable): Boolean = t match { - case _: StackOverflowError => true // StackOverflowError ok even though it is a VirtualMachineError // VirtualMachineError includes OutOfMemoryError and other fatal errors case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false case _ => true diff --git a/src/library/scala/util/hashing/MurmurHash3.scala b/src/library/scala/util/hashing/MurmurHash3.scala index c85664349e..1bfaeb255b 100644 --- a/src/library/scala/util/hashing/MurmurHash3.scala +++ b/src/library/scala/util/hashing/MurmurHash3.scala @@ -275,12 +275,4 @@ object MurmurHash3 extends MurmurHash3 { finalizeHash(h, n) } */ - - @deprecated("Use unorderedHash", "2.10.0") - final def symmetricHash[T](xs: scala.collection.GenTraversableOnce[T], seed: Int = symmetricSeed): Int = - unorderedHash(xs.seq, seed) - - @deprecated("Use orderedHash", "2.10.0") - final def traversableHash[T](xs: scala.collection.GenTraversableOnce[T], seed: Int = traversableSeed): Int = - orderedHash(xs.seq, seed) } diff --git a/src/library/scala/util/matching/Regex.scala b/src/library/scala/util/matching/Regex.scala index 439b30e714..22dbb37789 100644 --- a/src/library/scala/util/matching/Regex.scala +++ b/src/library/scala/util/matching/Regex.scala @@ -188,9 +188,9 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends * @param s The string to match * @return The matches */ - def unapplySeq(s: CharSequence): Option[Seq[String]] = { + def unapplySeq(s: CharSequence): Option[List[String]] = { val m = pattern matcher s - if (runMatcher(m)) Some(1 to m.groupCount map m.group) + if (runMatcher(m)) Some((1 to m.groupCount).toList map m.group) else None } @@ -225,10 +225,10 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends * @param c The Char to match * @return The match */ - def unapplySeq(c: Char): Option[Seq[Char]] = { + def unapplySeq(c: Char): Option[List[Char]] = { val m = pattern matcher c.toString if (runMatcher(m)) { - if (m.groupCount > 0) Some(m group 1) else Some(Nil) + if (m.groupCount > 0) Some((m group 1).toList) else Some(Nil) } else None } @@ -238,9 +238,9 @@ class Regex private[matching](val pattern: Pattern, groupNames: String*) extends * Otherwise, this Regex is applied to the previously matched input, * and the result of that match is used. */ - def unapplySeq(m: Match): Option[Seq[String]] = + def unapplySeq(m: Match): Option[List[String]] = if (m.matched == null) None - else if (m.matcher.pattern == this.pattern) Some(1 to m.groupCount map m.group) + else if (m.matcher.pattern == this.pattern) Some((1 to m.groupCount).toList map m.group) else unapplySeq(m.matched) /** Tries to match target. diff --git a/src/reflect/scala/reflect/api/JavaUniverse.scala b/src/reflect/scala/reflect/api/JavaUniverse.scala index 6fc76c9693..df5e0699a5 100644 --- a/src/reflect/scala/reflect/api/JavaUniverse.scala +++ b/src/reflect/scala/reflect/api/JavaUniverse.scala @@ -34,7 +34,7 @@ trait JavaUniverse extends Universe with JavaMirrors { self => mirror.universe match { case ju: JavaUniverse => val jm = mirror.asInstanceOf[ju.Mirror] - val sym = jm.classSymbol(manifest.erasure) + val sym = jm.classSymbol(manifest.runtimeClass) val tpe = if (manifest.typeArguments.isEmpty) sym.toType else ju.appliedType(sym.toTypeConstructor, manifest.typeArguments map (targ => ju.manifestToTypeTag(jm, targ)) map (_.in(jm).tpe)) diff --git a/src/reflect/scala/reflect/internal/Definitions.scala b/src/reflect/scala/reflect/internal/Definitions.scala index 563f23cb3b..19f06894c8 100644 --- a/src/reflect/scala/reflect/internal/Definitions.scala +++ b/src/reflect/scala/reflect/internal/Definitions.scala @@ -16,7 +16,7 @@ import scala.reflect.api.{Universe => ApiUniverse} trait Definitions extends api.StandardDefinitions { self: SymbolTable => - import rootMirror.{getModule, getPackage, getClassByName, getRequiredClass, getRequiredModule, getClassIfDefined, getModuleIfDefined, getPackageObject, getPackageIfDefined, getPackageObjectIfDefined, requiredClass, requiredModule} + import rootMirror.{getModuleByName, getPackage, getClassByName, getRequiredClass, getRequiredModule, getClassIfDefined, getModuleIfDefined, getPackageObject, getPackageIfDefined, getPackageObjectIfDefined, requiredClass, requiredModule} object definitions extends DefinitionsClass @@ -87,7 +87,7 @@ trait Definitions extends api.StandardDefinitions { lazy val abbrvTag = symbolsMap(ScalaValueClasses, nameToTag) withDefaultValue OBJECT_TAG lazy val numericWeight = symbolsMapFilt(ScalaValueClasses, nameToWeight.keySet, nameToWeight) - lazy val boxedModule = classesMap(x => getModule(boxedName(x))) + lazy val boxedModule = classesMap(x => getModuleByName(boxedName(x))) lazy val boxedClass = classesMap(x => getClassByName(boxedName(x))) lazy val refClass = classesMap(x => getRequiredClass("scala.runtime." + x + "Ref")) lazy val volatileRefClass = classesMap(x => getRequiredClass("scala.runtime.Volatile" + x + "Ref")) @@ -153,18 +153,6 @@ trait Definitions extends api.StandardDefinitions { private var isInitialized = false def isDefinitionsInitialized = isInitialized - @deprecated("Moved to rootMirror.RootPackage", "2.10.0") - val RootPackage: ModuleSymbol = rootMirror.RootPackage - - @deprecated("Moved to rootMirror.RootClass", "2.10.0") - val RootClass: ClassSymbol = rootMirror.RootClass - - @deprecated("Moved to rootMirror.EmptyPackage", "2.10.0") - val EmptyPackage: ModuleSymbol = rootMirror.EmptyPackage - - @deprecated("Moved to rootMirror.EmptyPackageClass", "2.10.0") - val EmptyPackageClass: ClassSymbol = rootMirror.EmptyPackageClass - // It becomes tricky to create dedicated objects for other symbols because // of initialization order issues. lazy val JavaLangPackage = getPackage("java.lang") diff --git a/src/reflect/scala/reflect/internal/FreshNames.scala b/src/reflect/scala/reflect/internal/FreshNames.scala new file mode 100644 index 0000000000..bb488aa2a8 --- /dev/null +++ b/src/reflect/scala/reflect/internal/FreshNames.scala @@ -0,0 +1,35 @@ +/* NSC -- new Scala compiler + * Copyright 2005-2013 LAMP/EPFL + */ + +package scala +package reflect +package internal + +import scala.reflect.internal.util.FreshNameCreator + +trait FreshNames { self: Names => + // default fresh name creator used to abstract over currentUnit.fresh and runtime fresh name creator + def currentFreshNameCreator: FreshNameCreator + + // create fresh term/type name using implicit fresh name creator + def freshTermName(prefix: String = "x$")(implicit creator: FreshNameCreator): TermName = newTermName(creator.newName(prefix)) + def freshTypeName(prefix: String)(implicit creator: FreshNameCreator): TypeName = newTypeName(creator.newName(prefix)) + + // Extractor that matches names which were generated by some + // FreshNameCreator with known prefix. Extracts user-specified + // prefix that was used as a parameter to newName by stripping + // global creator prefix and unique number in the end of the name. + class FreshNameExtractor(creatorPrefix: String = "") { + // quote prefix so that it can be used with replaceFirst + // which expects regExp rather than simple string + val quotedCreatorPrefix = java.util.regex.Pattern.quote(creatorPrefix) + + def unapply(name: Name): Option[String] = { + val sname = name.toString + // name should start with creatorPrefix and end with number + if (!sname.startsWith(creatorPrefix) || !sname.matches("^.*\\d*$")) None + else Some(NameTransformer.decode(sname.replaceFirst(quotedCreatorPrefix, "").replaceAll("\\d*$", ""))) + } + } +}
\ No newline at end of file diff --git a/src/reflect/scala/reflect/internal/Kinds.scala b/src/reflect/scala/reflect/internal/Kinds.scala index d48a6c6322..8ae201f045 100644 --- a/src/reflect/scala/reflect/internal/Kinds.scala +++ b/src/reflect/scala/reflect/internal/Kinds.scala @@ -326,6 +326,8 @@ trait Kinds { private[internal] object StringState { def empty: StringState = StringState(Seq()) } + def FromParams(tparams: List[Symbol]): Type = GenPolyType(tparams, AnyTpe) + def Wildcard: Type = WildcardType } class ProperTypeKind(val bounds: TypeBounds) extends Kind { import Kind.StringState diff --git a/src/reflect/scala/reflect/internal/Mirrors.scala b/src/reflect/scala/reflect/internal/Mirrors.scala index e122fa498b..3a630b6a16 100644 --- a/src/reflect/scala/reflect/internal/Mirrors.scala +++ b/src/reflect/scala/reflect/internal/Mirrors.scala @@ -96,10 +96,6 @@ trait Mirrors extends api.Mirrors { } } - @deprecated("Use getClassByName", "2.10.0") - def getClass(fullname: Name): ClassSymbol = - getClassByName(fullname) - def getClassByName(fullname: Name): ClassSymbol = ensureClassSymbol(fullname.toString, getModuleOrClass(fullname.toTypeName)) @@ -131,15 +127,11 @@ trait Mirrors extends api.Mirrors { case _ => MissingRequirementError.notFound("object " + fullname) } - @deprecated("Use getModuleByName", "2.10.0") - def getModule(fullname: Name): ModuleSymbol = - getModuleByName(fullname) - def getModuleByName(fullname: Name): ModuleSymbol = ensureModuleSymbol(fullname.toString, getModuleOrClass(fullname.toTermName), allowPackages = true) def getRequiredModule(fullname: String): ModuleSymbol = - getModule(newTermNameCached(fullname)) + getModuleByName(newTermNameCached(fullname)) // TODO: What syntax do we think should work here? Say you have an object // like scala.Predef. You can't say requiredModule[scala.Predef] since there's @@ -155,7 +147,7 @@ trait Mirrors extends api.Mirrors { getModuleIfDefined(newTermNameCached(fullname)) def getModuleIfDefined(fullname: Name): Symbol = - wrapMissing(getModule(fullname.toTermName)) + wrapMissing(getModuleByName(fullname.toTermName)) /** @inheritdoc * diff --git a/src/reflect/scala/reflect/internal/SymbolTable.scala b/src/reflect/scala/reflect/internal/SymbolTable.scala index 4998580a7d..c3f3e35fb3 100644 --- a/src/reflect/scala/reflect/internal/SymbolTable.scala +++ b/src/reflect/scala/reflect/internal/SymbolTable.scala @@ -42,6 +42,7 @@ abstract class SymbolTable extends macros.Universe with BuildUtils with PrivateWithin with pickling.Translations + with FreshNames { val gen = new TreeGen { val global: SymbolTable.this.type = SymbolTable.this } @@ -398,11 +399,6 @@ abstract class SymbolTable extends macros.Universe * Adds the `sm` String interpolator to a [[scala.StringContext]]. */ implicit val StringContextStripMarginOps: StringContext => StringContextStripMarginOps = util.StringContextStripMarginOps - - // fresh name creation - def currentFreshNameCreator: FreshNameCreator - def freshTermName(prefix: String = "x$")(implicit creator: FreshNameCreator): TermName = newTermName(creator.newName(prefix)) - def freshTypeName(prefix: String)(implicit creator: FreshNameCreator): TypeName = newTypeName(creator.newName(prefix)) } object SymbolTableStats { diff --git a/src/reflect/scala/reflect/internal/Symbols.scala b/src/reflect/scala/reflect/internal/Symbols.scala index bd17c18119..85bc3158f6 100644 --- a/src/reflect/scala/reflect/internal/Symbols.scala +++ b/src/reflect/scala/reflect/internal/Symbols.scala @@ -452,23 +452,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => case _ => new StubTermSymbol(this, name.toTermName, missingMessage) } - @deprecated("Use the other signature", "2.10.0") - def newClass(pos: Position, name: TypeName): Symbol = newClass(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newModuleClass(pos: Position, name: TypeName): Symbol = newModuleClass(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newLabel(pos: Position, name: TermName): MethodSymbol = newLabel(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newValue(pos: Position, name: TermName): TermSymbol = newTermSymbol(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newAliasType(pos: Position, name: TypeName): Symbol = newAliasType(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newAbstractType(pos: Position, name: TypeName): Symbol = newAbstractType(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newExistential(pos: Position, name: TypeName): Symbol = newExistential(name, pos) - @deprecated("Use the other signature", "2.10.0") - def newMethod(pos: Position, name: TermName): MethodSymbol = newMethod(name, pos) - // ----- locking and unlocking ------------------------------------------------------ // True if the symbol is unlocked. @@ -2047,10 +2030,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => else if (isMethod || isClass) this else owner.logicallyEnclosingMember - /** Kept for source compatibility with 2.9. Scala IDE for Eclipse relies on this. */ - @deprecated("Use enclosingTopLevelClass", "2.10.0") - def toplevelClass: Symbol = enclosingTopLevelClass - /** The top-level class containing this symbol. */ def enclosingTopLevelClass: Symbol = if (isTopLevel) { @@ -2365,9 +2344,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => def associatedFile: AbstractFile = enclosingTopLevelClass.associatedFile def associatedFile_=(f: AbstractFile) { abort("associatedFile_= inapplicable for " + this) } - @deprecated("Use associatedFile_= instead", "2.10.0") - def sourceFile_=(f: AbstractFile): Unit = associatedFile_=(f) - /** If this is a sealed class, its known direct subclasses. * Otherwise, the empty set. */ diff --git a/src/reflect/scala/reflect/internal/TreeInfo.scala b/src/reflect/scala/reflect/internal/TreeInfo.scala index 8982fd4246..8fdf4dc27a 100644 --- a/src/reflect/scala/reflect/internal/TreeInfo.scala +++ b/src/reflect/scala/reflect/internal/TreeInfo.scala @@ -199,7 +199,8 @@ abstract class TreeInfo { * don't reuse it for important matters like inlining * decisions. */ - def isPureExprForWarningPurposes(tree: Tree) = tree match { + def isPureExprForWarningPurposes(tree: Tree): Boolean = tree match { + case Typed(expr, _) => isPureExprForWarningPurposes(expr) case EmptyTree | Literal(Constant(())) => false case _ => def isWarnableRefTree = tree match { @@ -848,7 +849,7 @@ abstract class TreeInfo { }) def isMacroApplication(tree: Tree): Boolean = - !tree.isDef && tree.symbol != null && tree.symbol.isMacro && !tree.symbol.isErroneous + !tree.isDef && tree.symbol != null && tree.symbol.isTermMacro && !tree.symbol.isErroneous def isMacroApplicationOrBlock(tree: Tree): Boolean = tree match { case Block(_, expr) => isMacroApplicationOrBlock(expr) diff --git a/src/reflect/scala/reflect/internal/Trees.scala b/src/reflect/scala/reflect/internal/Trees.scala index af0af8afe8..d191fbd38f 100644 --- a/src/reflect/scala/reflect/internal/Trees.scala +++ b/src/reflect/scala/reflect/internal/Trees.scala @@ -590,7 +590,7 @@ trait Trees extends api.Trees { def TypeTree(tp: Type): TypeTree = TypeTree() setType tp private def TypeTreeMemberType(sym: Symbol): TypeTree = { // Needed for pos/t4970*.scala. See SI-7853 - val resType = (sym.owner.thisType memberType sym).finalResultType + val resType = (if (sym.isLocal) sym.tpe else (sym.owner.thisType memberType sym)).finalResultType atPos(sym.pos.focus)(TypeTree(resType)) } @@ -1804,6 +1804,12 @@ trait Trees extends api.Trees { case t => sys.error("Not a LabelDef: " + t + "/" + t.getClass) } + def deriveFunction(func: Tree)(applyToRhs: Tree => Tree): Function = func match { + case Function(params0, rhs0) => + treeCopy.Function(func, params0, applyToRhs(rhs0)) + case t => + sys.error("Not a Function: " + t + "/" + t.getClass) + } // -------------- Classtags -------------------------------------------------------- diff --git a/src/reflect/scala/reflect/internal/Variances.scala b/src/reflect/scala/reflect/internal/Variances.scala index 5280467055..cd09e83cd3 100644 --- a/src/reflect/scala/reflect/internal/Variances.scala +++ b/src/reflect/scala/reflect/internal/Variances.scala @@ -162,6 +162,16 @@ trait Variances { traverseTreess(vparamss) case Template(_, _, _) => super.traverse(tree) + case CompoundTypeTree(templ) => + super.traverse(tree) + + // SI-7872 These two cases make sure we don't miss variance exploits + // in originals, e.g. in `foo[({type l[+a] = List[a]})#l]` + case tt @ TypeTree() if tt.original != null => + super.traverse(tt.original) + case tt : TypTree => + super.traverse(tt) + case _ => } } diff --git a/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala b/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala index 9a54ad8217..f5aa048e6a 100644 --- a/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala +++ b/src/reflect/scala/reflect/internal/tpe/TypeMaps.scala @@ -717,6 +717,12 @@ private[internal] trait TypeMaps { else appliedType(tcon.typeConstructor, args) case SingleType(NoPrefix, sym) => substFor(sym) + case ClassInfoType(parents, decls, sym) => + val parents1 = parents mapConserve this + // We don't touch decls here; they will be touched when an enclosing TreeSubstitutor + // transforms the tree that defines them. + if (parents1 eq parents) tp + else ClassInfoType(parents1, decls, sym) case _ => tp } diff --git a/src/reflect/scala/reflect/internal/util/Collections.scala b/src/reflect/scala/reflect/internal/util/Collections.scala index 738baddc08..7cc2952c96 100644 --- a/src/reflect/scala/reflect/internal/util/Collections.scala +++ b/src/reflect/scala/reflect/internal/util/Collections.scala @@ -244,6 +244,11 @@ trait Collections { true } + final def sequence[A](as: List[Option[A]]): Option[List[A]] = { + if (as.exists (_.isEmpty)) None + else Some(as.flatten) + } + final def transposeSafe[A](ass: List[List[A]]): Option[List[List[A]]] = try { Some(ass.transpose) } catch { diff --git a/src/reflect/scala/reflect/internal/util/FreshNameCreator.scala b/src/reflect/scala/reflect/internal/util/FreshNameCreator.scala index 3e54de8e1e..8442c1015f 100644 --- a/src/reflect/scala/reflect/internal/util/FreshNameCreator.scala +++ b/src/reflect/scala/reflect/internal/util/FreshNameCreator.scala @@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicLong import scala.collection.mutable import scala.reflect.NameTransformer -class FreshNameCreator { +class FreshNameCreator(creatorPrefix: String = "") { protected val counters = new ConcurrentHashMap[String, AtomicLong]() /** @@ -21,7 +21,8 @@ class FreshNameCreator { */ def newName(prefix: String): String = { val safePrefix = NameTransformer.encode(prefix) - counters.putIfAbsent(safePrefix, new AtomicLong(0)); - safePrefix + counters.get(safePrefix).incrementAndGet(); + counters.putIfAbsent(safePrefix, new AtomicLong(0)) + val idx = counters.get(safePrefix).incrementAndGet() + s"$creatorPrefix$safePrefix$idx" } } diff --git a/src/reflect/scala/reflect/runtime/JavaUniverseForce.scala b/src/reflect/scala/reflect/runtime/JavaUniverseForce.scala index bce506ee0a..344f7682c1 100644 --- a/src/reflect/scala/reflect/runtime/JavaUniverseForce.scala +++ b/src/reflect/scala/reflect/runtime/JavaUniverseForce.scala @@ -51,6 +51,7 @@ trait JavaUniverseForce { self: runtime.JavaUniverse => // inaccessible: this.SimpleNameOrdering this.traceSymbols this.perRunCaches + this.FreshNameExtractor this.FixedMirrorTreeCreator this.FixedMirrorTypeCreator this.CompoundTypeTreeOriginalAttachment diff --git a/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala b/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala index cf03ecb480..d8efcda8b5 100644 --- a/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala +++ b/src/repl/scala/tools/nsc/interpreter/ConsoleReaderHelper.scala @@ -8,7 +8,9 @@ package interpreter import jline.console.{ ConsoleReader, CursorBuffer } -trait ConsoleReaderHelper extends ConsoleReader { +trait ConsoleReaderHelper { _: ConsoleReader with Tabulator => + def isAcross: Boolean + def terminal = getTerminal() def width = terminal.getWidth() def height = terminal.getHeight() @@ -16,7 +18,8 @@ trait ConsoleReaderHelper extends ConsoleReader { def readOneKey(prompt: String): Int def eraseLine(): Unit - private val marginSize = 3 + val marginSize = 3 + private def morePrompt = "--More--" private def emulateMore(): Int = { val key = readOneKey(morePrompt) @@ -38,19 +41,12 @@ trait ConsoleReaderHelper extends ConsoleReader { } override def printColumns(items: JCollection[_ <: CharSequence]): Unit = - printColumns(items: List[String]) - - def printColumns(items: List[String]): Unit = { - if (items forall (_ == "")) - return + printColumns_(items: List[String]) - val longest = items map (_.length) max + private def printColumns_(items: List[String]): Unit = if (items exists (_ != "")) { + val grouped = tabulate(items) var linesLeft = if (isPaginationEnabled()) height - 1 else Int.MaxValue - val columnSize = longest + marginSize - val padded = items map ("%-" + columnSize + "s" format _) - val groupSize = 1 max (width / columnSize) // make sure it doesn't divide to 0 - - padded grouped groupSize foreach { xs => + grouped foreach { xs => println(xs.mkString) linesLeft -= 1 if (linesLeft <= 0) { @@ -61,3 +57,104 @@ trait ConsoleReaderHelper extends ConsoleReader { } } } + +trait Tabulator { + def isAcross: Boolean + def width: Int + def marginSize: Int + + protected def fits(items: Seq[String], width: Int): Boolean = ( + (items map (_.length)).sum + (items.length - 1) * marginSize < width + ) + def tabulate(items: Seq[String]): Seq[Seq[String]] = ( + if (fits(items, width)) Seq(Seq(items mkString " " * marginSize)) + else printMultiLineColumns(items) + ) + protected def columnize(ss: Seq[String]): Seq[Seq[String]] = ss map (s => Seq(s)) + protected def printMultiLineColumns(items: Seq[String]): Seq[Seq[String]] = { + import SimpleMath._ + val longest = (items map (_.length)).max + val columnWidth = longest + marginSize + val maxcols = ( + if (columnWidth >= width) 1 + else 1 max (width / columnWidth) // make sure it doesn't divide to 0 + ) + val nrows = items.size /% maxcols + val ncols = items.size /% nrows + val groupSize = ncols + val padded = items map (s"%-${columnWidth}s" format _) + val xwise = isAcross || ncols >= items.length + val grouped: Seq[Seq[String]] = + if (groupSize == 1) columnize(items) + else if (xwise) (padded grouped groupSize).toSeq + else { + val h = 1 max padded.size /% groupSize + val cols = (padded grouped h).toList + for (i <- 0 until h) yield + for (j <- 0 until groupSize) yield + if (i < cols(j).size) cols(j)(i) else "" + } + grouped + } +} + +/** Adjust the column width and number of columns to minimize the row count. */ +trait VariColumnTabulator extends Tabulator { + override protected def printMultiLineColumns(items: Seq[String]): Seq[Seq[String]] = { + import SimpleMath._ + val longest = (items map (_.length)).max + val shortest = (items map (_.length)).min + val fattest = longest + marginSize + val skinny = shortest + marginSize + + // given ncols, calculate nrows and a list of column widths, or none if not possible + // if ncols > items.size, then columnWidths.size == items.size + def layout(ncols: Int): Option[(Int, Seq[Int], Seq[Seq[String]])] = { + val nrows = items.size /% ncols + val xwise = isAcross || ncols >= items.length + def maxima(sss: Seq[Seq[String]]) = + (0 until (ncols min items.size)) map (i => (sss map (ss => ss(i).length)).max) + def resulting(rows: Seq[Seq[String]]) = { + val columnWidths = maxima(rows) map (_ + marginSize) + val linelen = columnWidths.sum + if (linelen <= width) Some((nrows, columnWidths, rows)) + else None + } + if (ncols == 1) resulting(columnize(items)) + else if (xwise) resulting((items grouped ncols).toSeq) + else { + val cols = (items grouped nrows).toList + val rows = for (i <- 0 until nrows) yield + for (j <- 0 until ncols) yield + if (j < cols.size && i < cols(j).size) cols(j)(i) else "" + resulting(rows) + } + } + + if (fattest >= width) { + columnize(items) + } else { + // if every col is widest, we have at least this many cols + val mincols = 1 max (width / fattest) + // if every other col is skinniest, we have at most this many cols + val maxcols = 1 + ((width - fattest) / skinny) + val possibles = (mincols to maxcols).map(n => layout(n)).flatten + val minrows = (possibles map (_._1)).min + + // select the min ncols that results in minrows + val (_, columnWidths, sss) = (possibles find (_._1 == minrows)).get + + // format to column width + sss map (ss => ss.zipWithIndex map { + case (s, i) => s"%-${columnWidths(i)}s" format s + }) + } + } +} + +private[interpreter] object SimpleMath { + implicit class DivRem(private val i: Int) extends AnyVal { + /** i/n + if (i % n != 0) 1 else 0 */ + def /%(n: Int): Int = (i + n - 1) / n + } +} diff --git a/src/repl/scala/tools/nsc/interpreter/IMain.scala b/src/repl/scala/tools/nsc/interpreter/IMain.scala index 0d55423247..8fba1e538e 100644 --- a/src/repl/scala/tools/nsc/interpreter/IMain.scala +++ b/src/repl/scala/tools/nsc/interpreter/IMain.scala @@ -9,10 +9,11 @@ package interpreter import PartialFunction.cond import scala.language.implicitConversions +import scala.beans.BeanProperty import scala.collection.mutable import scala.concurrent.{ Future, ExecutionContext } import scala.reflect.runtime.{ universe => ru } -import scala.reflect.{ BeanProperty, ClassTag, classTag } +import scala.reflect.{ ClassTag, classTag } import scala.reflect.internal.util.{ BatchSourceFile, SourceFile } import scala.tools.util.PathResolver import scala.tools.nsc.io.AbstractFile diff --git a/src/repl/scala/tools/nsc/interpreter/JLineReader.scala b/src/repl/scala/tools/nsc/interpreter/JLineReader.scala index 8b0c6d78fa..b6e834a1ed 100644 --- a/src/repl/scala/tools/nsc/interpreter/JLineReader.scala +++ b/src/repl/scala/tools/nsc/interpreter/JLineReader.scala @@ -33,7 +33,11 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { } } - class JLineConsoleReader extends ConsoleReader with ConsoleReaderHelper { + class JLineConsoleReader extends ConsoleReader with ConsoleReaderHelper with VariColumnTabulator { + val isAcross = interpreter.`package`.isAcross + + this setPaginationEnabled interpreter.`package`.isPaged + // ASAP this setExpandEvents false diff --git a/src/repl/scala/tools/nsc/interpreter/JavapClass.scala b/src/repl/scala/tools/nsc/interpreter/JavapClass.scala index 50c90968af..496d5face1 100644 --- a/src/repl/scala/tools/nsc/interpreter/JavapClass.scala +++ b/src/repl/scala/tools/nsc/interpreter/JavapClass.scala @@ -180,7 +180,7 @@ class JavapClass( /** Base class for javap tool adapters for java 6 and 7. */ abstract class JavapTool { type ByteAry = Array[Byte] - type Input = Pair[String, Try[ByteAry]] + type Input = Tuple2[String, Try[ByteAry]] /** Run the tool. */ def apply(raw: Boolean, options: Seq[String])(inputs: Seq[Input]): List[JpResult] diff --git a/src/repl/scala/tools/nsc/interpreter/ReplConfig.scala b/src/repl/scala/tools/nsc/interpreter/ReplConfig.scala index 3392ea0b5e..046d6ecbfb 100644 --- a/src/repl/scala/tools/nsc/interpreter/ReplConfig.scala +++ b/src/repl/scala/tools/nsc/interpreter/ReplConfig.scala @@ -46,4 +46,8 @@ trait ReplConfig { def isReplDebug: Boolean = replProps.debug || isReplTrace def isReplInfo: Boolean = replProps.info || isReplDebug def isReplPower: Boolean = replProps.power + + private def csv(p: String, v: String) = p split "," contains v + def isPaged: Boolean = replProps.format.isSet && csv(replProps.format.get, "paged") + def isAcross: Boolean = replProps.format.isSet && csv(replProps.format.get, "across") } diff --git a/src/repl/scala/tools/nsc/interpreter/ReplProps.scala b/src/repl/scala/tools/nsc/interpreter/ReplProps.scala index 2364918494..36e6dbbccc 100644 --- a/src/repl/scala/tools/nsc/interpreter/ReplProps.scala +++ b/src/repl/scala/tools/nsc/interpreter/ReplProps.scala @@ -18,6 +18,13 @@ class ReplProps { val trace = bool("scala.repl.trace") val power = bool("scala.repl.power") + /** CSV of paged,across to enable pagination or `-x` style + * columns, "across" instead of down the column. Since + * pagination turns off columnar output, these flags are + * currently mutually exclusive. + */ + val format = Prop[String]("scala.repl.format") + val replAutorunCode = Prop[JFile]("scala.repl.autoruncode") val powerInitCode = Prop[JFile]("scala.repl.power.initcode") val powerBanner = Prop[JFile]("scala.repl.power.banner") diff --git a/src/scaladoc/scala/tools/ant/Scaladoc.scala b/src/scaladoc/scala/tools/ant/Scaladoc.scala index fd6d637212..36a1405b11 100644 --- a/src/scaladoc/scala/tools/ant/Scaladoc.scala +++ b/src/scaladoc/scala/tools/ant/Scaladoc.scala @@ -574,7 +574,7 @@ class Scaladoc extends ScalaMatchingTask { \*============================================================================*/ /** Initializes settings and source files */ - protected def initialize: Pair[Settings, List[File]] = { + protected def initialize: Tuple2[Settings, List[File]] = { // Tests if all mandatory attributes are set and valid. if (origin.isEmpty) buildError("Attribute 'srcdir' is not set.") if (getOrigin.isEmpty) buildError("Attribute 'srcdir' is not set.") @@ -660,14 +660,14 @@ class Scaladoc extends ScalaMatchingTask { log("Scaladoc params = '" + addParams + "'", Project.MSG_DEBUG) docSettings processArgumentString addParams - Pair(docSettings, sourceFiles) + (docSettings, sourceFiles) } def safeBuildError(message: String): Unit = if (nofail) log(message) else buildError(message) /** Performs the compilation. */ override def execute() = { - val Pair(docSettings, sourceFiles) = initialize + val (docSettings, sourceFiles) = initialize val reporter = new ConsoleReporter(docSettings) try { val docProcessor = new scala.tools.nsc.doc.DocFactory(reporter, docSettings) diff --git a/src/scalap/scala/tools/scalap/Arguments.scala b/src/scalap/scala/tools/scalap/Arguments.scala index 41346d13c0..cb0a92b6b3 100644 --- a/src/scalap/scala/tools/scalap/Arguments.scala +++ b/src/scalap/scala/tools/scalap/Arguments.scala @@ -46,8 +46,8 @@ object Arguments { } def parseBinding(str: String, separator: Char): (String, String) = (str indexOf separator) match { - case -1 => argumentError("missing '" + separator + "' in binding '" + str + "'") ; Pair("", "") - case idx => Pair((str take idx).trim, (str drop (idx + 1)).trim) + case -1 => argumentError("missing '" + separator + "' in binding '" + str + "'") ; ("", "") + case idx => ((str take idx).trim, (str drop (idx + 1)).trim) } def parse(args: Array[String]): Arguments = { @@ -141,7 +141,7 @@ class Arguments { if (key.length > 0) bindings.getOrElseUpdate(tag, new mutable.HashMap)(key) = value - def addBinding(tag: String, binding: Pair[String, String]): Unit = + def addBinding(tag: String, binding: Tuple2[String, String]): Unit = addBinding(tag, binding._1, binding._2) def addOther(arg: String): Unit = others += arg diff --git a/test/build-partest.xml b/test/build-partest.xml deleted file mode 100755 index 22ad85ac03..0000000000 --- a/test/build-partest.xml +++ /dev/null @@ -1,20 +0,0 @@ -<project name="partest" basedir="."> - <dirname property="partest.basedir" file="${ant.file.partest}"/> - <property file="${partest.basedir}/included.properties"/> - - <macrodef name="testSuite"> - <attribute name="dir" default="${partest.basedir}/test"/> - <attribute name="srcdir" default="files"/> <!-- TODO: make targets for `pending` and other subdirs --> - <attribute name="colors" default="${partest.colors}"/> - <attribute name="scalacOpts" default="${scalac.args.optimise}"/> - <attribute name="kinds"/> - <sequential> - <property name="partest.dir" value="@{dir}" /> - <partest srcdir="@{srcdir}" - kinds="@{kinds}" - colors="@{colors}" - scalacOpts="@{scalacOpts}" - compilationpathref="partest.compilation.path"/> - </sequential> - </macrodef> -</project> diff --git a/test/disabled/run/lisp.scala b/test/disabled/run/lisp.scala index 06e68f508a..73f24da757 100644 --- a/test/disabled/run/lisp.scala +++ b/test/disabled/run/lisp.scala @@ -12,11 +12,11 @@ class LispTokenizer(s: String) extends Iterator[String] { while (i < s.length() && s.charAt(i) <= ' ') i += 1 i < s.length() } - def next: String = + def next: String = if (hasNext) { val start = i if (isDelimiter(s charAt i)) i += 1 - else + else do i = i + 1 while (!isDelimiter(s charAt i)) s.substring(start, i) @@ -190,10 +190,10 @@ object LispCaseClasses extends Lisp { def extendEnv(env: Environment, ps: List[String], args: List[Data]): Environment = - Pair(ps, args) match { - case Pair(List(), List()) => + (ps, args) match { + case (List(), List()) => env - case Pair(p :: ps1, arg :: args1) => + case (p :: ps1, arg :: args1) => extendEnv(env.extend(p, arg), ps1, args1) case _ => lispError("wrong number of arguments") @@ -381,10 +381,10 @@ object LispAny extends Lisp { def extendEnv(env: Environment, ps: List[String], args: List[Data]): Environment = - Pair(ps, args) match { - case Pair(List(), List()) => + (ps, args) match { + case (List(), List()) => env - case Pair(p :: ps1, arg :: args1) => + case (p :: ps1, arg :: args1) => extendEnv(env.extend(p, arg), ps1, args1) case _ => lispError("wrong number of arguments") diff --git a/test/files/android/HelloAndroid.scala b/test/files/android/HelloAndroid.scala deleted file mode 100644 index 9fd145a4f1..0000000000 --- a/test/files/android/HelloAndroid.scala +++ /dev/null @@ -1,16 +0,0 @@ -//package examples.hello3 - -import android.app.Activity -import android.os.Bundle -import android.widget.TextView - -//class HelloAndroid extends Activity { -class Test extends Activity { - /** Called when the activity is first created. */ - override def onCreate(icicle: Bundle) { - super.onCreate(icicle) - val tv = new TextView(this) - tv setText "Hello, Android (Scala)" - setContentView(tv) - } -} diff --git a/test/files/android/HelloAndroid.xml b/test/files/android/HelloAndroid.xml deleted file mode 100644 index 41907b16a3..0000000000 --- a/test/files/android/HelloAndroid.xml +++ /dev/null @@ -1,11 +0,0 @@ -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package=""> - <application> - <activity class="HelloAndroid" android:label="HelloAndroid"> - <intent-filter> - <action android:value="android.intent.action.MAIN" /> - <category android:value="android.intent.category.LAUNCHER" /> - </intent-filter> - </activity> - </application> -</manifest> diff --git a/test/files/jvm/non-fatal-tests.scala b/test/files/jvm/non-fatal-tests.scala index 791b1d3100..1ff7ee516e 100644 --- a/test/files/jvm/non-fatal-tests.scala +++ b/test/files/jvm/non-fatal-tests.scala @@ -4,8 +4,7 @@ trait NonFatalTests { //NonFatals val nonFatals: Seq[Throwable] = - Seq(new StackOverflowError, - new RuntimeException, + Seq(new RuntimeException, new Exception, new Throwable, new NotImplementedError) @@ -13,6 +12,7 @@ trait NonFatalTests { //Fatals val fatals: Seq[Throwable] = Seq(new InterruptedException, + new StackOverflowError, new OutOfMemoryError, new LinkageError, new VirtualMachineError {}, diff --git a/test/files/jvm/typerep.scala b/test/files/jvm/typerep.scala index 1d6f0b7907..4f900d98d7 100644 --- a/test/files/jvm/typerep.scala +++ b/test/files/jvm/typerep.scala @@ -86,7 +86,7 @@ object testArrays { object testTuples { println(getType((3, "abc"))) - println(getType(Triple('a', 'b', "c"))) + println(getType(('a', 'b', "c"))) println(getType(((3, "abc"), (4, "xyz")))) println(getType(((Some('b'), 3), (Some('a'), 4)))) //println(getType(((Some('b'), 3), (None, 4)))) diff --git a/test/files/neg/applydynamic_sip.check b/test/files/neg/applydynamic_sip.check index f28f26c147..2cb2e7f095 100644 --- a/test/files/neg/applydynamic_sip.check +++ b/test/files/neg/applydynamic_sip.check @@ -22,21 +22,21 @@ applydynamic_sip.scala:18: error: type mismatch; error after rewriting to Test.this.bad1.selectDynamic("sel") possible cause: maybe a wrong Dynamic method signature? bad1.sel - ^ + ^ applydynamic_sip.scala:19: error: type mismatch; found : String("sel") required: Int error after rewriting to Test.this.bad1.applyDynamic("sel") possible cause: maybe a wrong Dynamic method signature? bad1.sel(1) - ^ + ^ applydynamic_sip.scala:20: error: type mismatch; found : String("sel") required: Int error after rewriting to Test.this.bad1.applyDynamicNamed("sel") possible cause: maybe a wrong Dynamic method signature? bad1.sel(a = 1) - ^ + ^ applydynamic_sip.scala:20: error: reassignment to val bad1.sel(a = 1) ^ @@ -46,7 +46,7 @@ applydynamic_sip.scala:21: error: type mismatch; error after rewriting to Test.this.bad1.updateDynamic("sel") possible cause: maybe a wrong Dynamic method signature? bad1.sel = 1 - ^ + ^ applydynamic_sip.scala:29: error: Int does not take parameters error after rewriting to Test.this.bad2.selectDynamic("sel") possible cause: maybe a wrong Dynamic method signature? diff --git a/test/files/neg/class-of-double-targs.check b/test/files/neg/class-of-double-targs.check new file mode 100644 index 0000000000..f7e2094f97 --- /dev/null +++ b/test/files/neg/class-of-double-targs.check @@ -0,0 +1,4 @@ +class-of-double-targs.scala:2: error: expression of type Class[Int](classOf[scala.Int]) does not take type parameters. + classOf[Int][Int] + ^ +one error found diff --git a/test/files/neg/class-of-double-targs.scala b/test/files/neg/class-of-double-targs.scala new file mode 100644 index 0000000000..26a2fa8381 --- /dev/null +++ b/test/files/neg/class-of-double-targs.scala @@ -0,0 +1,3 @@ +object Test { + classOf[Int][Int] +} diff --git a/test/files/neg/macro-bundle-class.check b/test/files/neg/macro-bundle-class.check index 8fd04f1303..7108c15b8d 100644 --- a/test/files/neg/macro-bundle-class.check +++ b/test/files/neg/macro-bundle-class.check @@ -1,4 +1,4 @@ macro-bundle-class.scala:10: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle.impl - ^ + ^ one error found diff --git a/test/files/neg/macro-bundle-mixbox.check b/test/files/neg/macro-bundle-mixbox.check index 4f8cedcece..c3136d9369 100644 --- a/test/files/neg/macro-bundle-mixbox.check +++ b/test/files/neg/macro-bundle-mixbox.check @@ -1,4 +1,4 @@ macro-bundle-mixbox.scala:9: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle.impl - ^ + ^ one error found diff --git a/test/files/neg/macro-bundle-object.check b/test/files/neg/macro-bundle-object.check index e148e86969..293f40a178 100644 --- a/test/files/neg/macro-bundle-object.check +++ b/test/files/neg/macro-bundle-object.check @@ -1,8 +1,8 @@ -macro-bundle-object.scala:10: error: macro implementation has wrong shape: +macro-bundle-object.scala:10: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : : Nothing number of parameter sections differ def foo = macro Bundle.impl - ^ + ^ one error found diff --git a/test/files/neg/macro-bundle-polymorphic.check b/test/files/neg/macro-bundle-polymorphic.check index 07c5f551b1..e024fcde93 100644 --- a/test/files/neg/macro-bundle-polymorphic.check +++ b/test/files/neg/macro-bundle-polymorphic.check @@ -1,10 +1,10 @@ macro-bundle-polymorphic.scala:9: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle.impl - ^ + ^ macro-bundle-polymorphic.scala:10: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle[Int].impl - ^ + ^ macro-bundle-polymorphic.scala:11: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle[Int, Nothing].impl - ^ + ^ three errors found diff --git a/test/files/neg/macro-bundle-trait.check b/test/files/neg/macro-bundle-trait.check index bf906a5310..3cb7985013 100644 --- a/test/files/neg/macro-bundle-trait.check +++ b/test/files/neg/macro-bundle-trait.check @@ -1,4 +1,4 @@ macro-bundle-trait.scala:11: error: macro bundles must be monomorphic traits extending either BlackboxMacro or WhiteboxMacro and not implementing their `val c: BlackboxContext/WhiteboxContext` member def foo = macro Bundle.impl - ^ + ^ one error found diff --git a/test/files/neg/macro-invalidimpl.check b/test/files/neg/macro-invalidimpl.check index 432da4d00b..5eff401bef 100644 --- a/test/files/neg/macro-invalidimpl.check +++ b/test/files/neg/macro-invalidimpl.check @@ -2,22 +2,22 @@ Macros_Test_2.scala:5: error: macro implementation reference has wrong shape. re macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo(x: Any) = macro impls.foo - ^ + ^ Macros_Test_2.scala:10: error: macro implementation reference has wrong shape. required: macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo(x: Any) = macro impls.foo - ^ + ^ Macros_Test_2.scala:18: error: macro implementation reference has wrong shape. required: macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo(x: Any) = macro Impls3.foo - ^ + ^ Macros_Test_2.scala:22: error: macro implementation reference has wrong shape. required: macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo(x: Any) = macro Impls4.foo - ^ + ^ Macros_Test_2.scala:26: error: ambiguous reference to overloaded definition, both method foo in object Impls5 of type (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Any], y: c.Expr[Any])Nothing and method foo in object Impls5 of type (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Any])Nothing @@ -30,24 +30,24 @@ and method foo in object Impls5 of type (c: scala.reflect.macros.BlackboxContex match expected type ? def foo(x: Any, y: Any) = macro Impls5.foo ^ -Macros_Test_2.scala:31: error: macro implementation has wrong shape: +Macros_Test_2.scala:31: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Unit] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(): c.Expr[Unit] number of parameter sections differ def foo1 = macro Impls6.fooEmpty - ^ -Macros_Test_2.scala:32: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:32: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(): c.Expr[Unit] or : (c: scala.reflect.macros.BlackboxContext)(): c.Tree found : (c: scala.reflect.macros.BlackboxContext): c.Expr[Unit] number of parameter sections differ def bar1() = macro Impls6.fooNullary - ^ + ^ Macros_Test_2.scala:36: error: type arguments [String] do not conform to method foo's type parameter bounds [U <: Int] def foo = macro Impls7.foo[String] ^ Macros_Test_2.scala:53: error: macro implementation must be public def foo = macro Impls8.impl - ^ + ^ 10 errors found diff --git a/test/files/neg/macro-invalidret.check b/test/files/neg/macro-invalidret.check index 19adc70fb3..ea003a17ec 100644 --- a/test/files/neg/macro-invalidret.check +++ b/test/files/neg/macro-invalidret.check @@ -1,15 +1,15 @@ -Macros_Test_2.scala:2: error: macro implementation has wrong shape: +Macros_Test_2.scala:2: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (c: scala.reflect.macros.BlackboxContext): Int type mismatch for return type: Int does not conform to c.Expr[Any] def foo1 = macro Impls.foo1 - ^ -Macros_Test_2.scala:3: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:3: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (c: scala.reflect.macros.BlackboxContext): reflect.runtime.universe.Literal type mismatch for return type: reflect.runtime.universe.Literal does not conform to c.Expr[Any] def foo2 = macro Impls.foo2 - ^ + ^ two errors found diff --git a/test/files/neg/macro-invalidshape.check b/test/files/neg/macro-invalidshape.check index 1938f5ae47..aa694df6d6 100644 --- a/test/files/neg/macro-invalidshape.check +++ b/test/files/neg/macro-invalidshape.check @@ -2,12 +2,12 @@ Macros_Test_2.scala:2: error: macro implementation reference has wrong shape. re macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo1(x: Any) = macro 2 - ^ + ^ Macros_Test_2.scala:3: error: macro implementation reference has wrong shape. required: macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo2(x: Any) = macro Impls.foo(null)(null) - ^ + ^ Macros_Test_2.scala:4: error: missing arguments for method foo in object Impls; follow this method with `_' if you want to treat it as a partially applied function def foo3(x: Any) = macro {2; Impls.foo} @@ -16,5 +16,5 @@ Macros_Test_2.scala:7: error: macro implementation reference has wrong shape. re macro [<static object>].<method name>[[<type args>]] or macro [<macro bundle>].<method name>[[<type args>]] def foo = macro impl - ^ + ^ four errors found diff --git a/test/files/neg/macro-invalidsig-params-badtype.check b/test/files/neg/macro-invalidsig-params-badtype.check index e0cd63fbe4..6d72185ff2 100644 --- a/test/files/neg/macro-invalidsig-params-badtype.check +++ b/test/files/neg/macro-invalidsig-params-badtype.check @@ -1,8 +1,8 @@ -Impls_Macros_1.scala:8: error: macro implementation has wrong shape: +Impls_Macros_1.scala:8: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(x: Int): Nothing type mismatch for parameter x: c.Expr[Int] does not conform to Int def foo(x: Int) = macro Impls.foo - ^ + ^ one error found diff --git a/test/files/neg/macro-invalidsig.check b/test/files/neg/macro-invalidsig.check index 42b8db5628..e09d46146d 100644 --- a/test/files/neg/macro-invalidsig.check +++ b/test/files/neg/macro-invalidsig.check @@ -1,92 +1,84 @@ -Macros_Test_2.scala:2: error: macro implementation has wrong shape: - required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] - or : (c: scala.reflect.macros.BlackboxContext): c.Tree - found : (c: scala.reflect.macros.BlackboxContext)(implicit evidence$2: Numeric[U]): c.universe.Literal -macro implementations cannot have implicit parameters other than WeakTypeTag evidences +Macros_Test_2.scala:2: error: macro implementations cannot have implicit parameters other than WeakTypeTag evidences def foo[U] = macro Impls1.foo[U] - ^ -Macros_Test_2.scala:6: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:6: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : : Nothing number of parameter sections differ def foo = macro Impls2.foo - ^ -Macros_Test_2.scala:10: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:10: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (c: scala.reflect.api.Universe): Nothing type mismatch for parameter c: scala.reflect.macros.BlackboxContext does not conform to scala.reflect.api.Universe def foo = macro Impls3.foo - ^ -Macros_Test_2.scala:14: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:14: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (cs: scala.reflect.macros.BlackboxContext*): Nothing types incompatible for parameter cs: corresponding is not a vararg parameter def foo = macro Impls4.foo - ^ -Macros_Test_2.scala:18: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:18: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Any]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext): Nothing number of parameter sections differ def foo(x: Any) = macro Impls5.foo - ^ -Macros_Test_2.scala:22: error: macro implementation has wrong shape: - required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int]): c.Expr[Unit] - or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree): c.Tree - found : (c: scala.reflect.macros.BlackboxContext)(implicit x: c.Expr[Int]): c.Expr[Unit] -macro implementations cannot have implicit parameters other than WeakTypeTag evidences + ^ +Macros_Test_2.scala:22: error: macro implementations cannot have implicit parameters other than WeakTypeTag evidences def foo[U](x: Int) = macro Impls6.foo[T, U] - ^ -Macros_Test_2.scala:26: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:26: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int], y: c.Expr[Int]): Nothing parameter lists have different length, found extra parameter y: c.Expr[Int] def foo(x: Int) = macro Impls7.foo - ^ -Macros_Test_2.scala:30: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:30: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(x: c.universe.Symbol): Nothing type mismatch for parameter x: c.Expr[Int] does not conform to c.universe.Symbol def foo(x: Int) = macro Impls8.foo - ^ -Macros_Test_2.scala:34: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:34: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int], y: c.Expr[Int]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree, y: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(xs: c.Expr[Int]*): Nothing parameter lists have different length, required extra parameter y: c.Expr[Int] def foo(x: Int, y: Int) = macro Impls9.foo - ^ -Macros_Test_2.scala:38: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:38: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(x: c.Expr[Int], y: c.Expr[Int]): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext)(x: c.Tree, y: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(y: c.Expr[Int], x: c.Expr[Int]): Nothing parameter names differ: x != y def foo(x: Int, y: Int) = macro Impls10.foo - ^ -Macros_Test_2.scala:42: error: macro implementation has wrong shape: + ^ +Macros_Test_2.scala:42: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext): c.Expr[Any] or : (c: scala.reflect.macros.BlackboxContext): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(U: c.universe.Type): Nothing number of parameter sections differ def foo[U] = macro Impls11.foo[U] - ^ + ^ Macros_Test_2.scala:46: error: type arguments [U] do not conform to method foo's type parameter bounds [U <: String] def foo[U] = macro Impls12.foo[U] ^ Macros_Test_2.scala:50: error: type arguments [U] do not conform to method foo's type parameter bounds [U <: String] def foo[U <: Int] = macro Impls13.foo[U] ^ -Macros_Test_2.scala:54: error: wrong number of type parameters for method foo: [U](c: scala.reflect.macros.BlackboxContext)(implicit evidence$4: c.WeakTypeTag[U])Nothing +Macros_Test_2.scala:54: error: macro implementation reference has too few type arguments for method foo: [U](c: scala.reflect.macros.BlackboxContext)(implicit evidence$4: c.WeakTypeTag[U])Nothing def foo = macro Impls14.foo - ^ -Macros_Test_2.scala:59: error: wrong number of type parameters for method foo: [T, U, V](c: scala.reflect.macros.BlackboxContext)(implicit evidence$5: c.WeakTypeTag[T], implicit evidence$6: c.WeakTypeTag[U], implicit V: c.WeakTypeTag[V])c.Expr[Unit] + ^ +Macros_Test_2.scala:59: error: macro implementation reference has too few type arguments for method foo: [T, U, V](c: scala.reflect.macros.BlackboxContext)(implicit evidence$5: c.WeakTypeTag[T], implicit evidence$6: c.WeakTypeTag[U], implicit V: c.WeakTypeTag[V])c.Expr[Unit] def foo15[V] = macro Impls15.foo - ^ + ^ Macros_Test_2.scala:60: error: wrong number of type parameters for method foo: [T, U, V](c: scala.reflect.macros.BlackboxContext)(implicit evidence$7: c.WeakTypeTag[T], implicit evidence$8: c.WeakTypeTag[U], implicit V: c.WeakTypeTag[V])c.Expr[Unit] def foo16[V] = macro Impls16.foo[V] ^ diff --git a/test/files/neg/macro-quasiquotes.check b/test/files/neg/macro-quasiquotes.check index d000bb5316..338ad42b23 100644 --- a/test/files/neg/macro-quasiquotes.check +++ b/test/files/neg/macro-quasiquotes.check @@ -1,8 +1,8 @@ -Macros_1.scala:14: error: macro implementation has wrong shape: +Macros_1.scala:14: error: macro implementation has incompatible shape: required: (x: Impls.this.c.Expr[Int]): Impls.this.c.Expr[Any] or : (x: Impls.this.c.Tree): Impls.this.c.Tree found : (x: Impls.this.c.universe.Block): Impls.this.c.Tree type mismatch for parameter x: Impls.this.c.Expr[Int] does not conform to Impls.this.c.universe.Block def m3(x: Int) = macro Impls.impl3 - ^ + ^ one error found diff --git a/test/files/neg/missing-param-type-tuple.check b/test/files/neg/missing-param-type-tuple.check new file mode 100644 index 0000000000..bc46ba1023 --- /dev/null +++ b/test/files/neg/missing-param-type-tuple.check @@ -0,0 +1,31 @@ +missing-param-type-tuple.scala:3: error: missing parameter type +Note: The expected type requires a one-argument function accepting a 2-Tuple. + Consider a pattern matching anoynmous function, `{ case (a, b) => ... }` + val x: ((Int, Int)) => Int = (a, b) => 0 + ^ +missing-param-type-tuple.scala:3: error: missing parameter type + val x: ((Int, Int)) => Int = (a, b) => 0 + ^ +missing-param-type-tuple.scala:5: error: missing parameter type +Note: The expected type requires a one-argument function accepting a 3-Tuple. + Consider a pattern matching anoynmous function, `{ case (param1, ..., param3) => ... }` + val y: ((Int, Int, Int)) => Int = (a, b, !!) => 0 + ^ +missing-param-type-tuple.scala:5: error: missing parameter type + val y: ((Int, Int, Int)) => Int = (a, b, !!) => 0 + ^ +missing-param-type-tuple.scala:5: error: missing parameter type + val y: ((Int, Int, Int)) => Int = (a, b, !!) => 0 + ^ +missing-param-type-tuple.scala:7: error: missing parameter type +Note: The expected type requires a one-argument function accepting a 3-Tuple. + Consider a pattern matching anoynmous function, `{ case (param1, ..., param3) => ... }` + val z: ((Int, Int, Int)) => Int = (a, NotAVariablePatternName, c) => 0 + ^ +missing-param-type-tuple.scala:7: error: missing parameter type + val z: ((Int, Int, Int)) => Int = (a, NotAVariablePatternName, c) => 0 + ^ +missing-param-type-tuple.scala:7: error: missing parameter type + val z: ((Int, Int, Int)) => Int = (a, NotAVariablePatternName, c) => 0 + ^ +8 errors found diff --git a/test/files/neg/missing-param-type-tuple.scala b/test/files/neg/missing-param-type-tuple.scala new file mode 100644 index 0000000000..72c0c82034 --- /dev/null +++ b/test/files/neg/missing-param-type-tuple.scala @@ -0,0 +1,8 @@ +class C { + + val x: ((Int, Int)) => Int = (a, b) => 0 + + val y: ((Int, Int, Int)) => Int = (a, b, !!) => 0 + + val z: ((Int, Int, Int)) => Int = (a, NotAVariablePatternName, c) => 0 +} diff --git a/test/files/neg/not-a-legal-formal-parameter-tuple.check b/test/files/neg/not-a-legal-formal-parameter-tuple.check new file mode 100644 index 0000000000..2b906b8ff3 --- /dev/null +++ b/test/files/neg/not-a-legal-formal-parameter-tuple.check @@ -0,0 +1,19 @@ +not-a-legal-formal-parameter-tuple.scala:2: error: not a legal formal parameter. +Note: Tuples cannot be directly destructured in method or function parameters. + Either create a single parameter accepting the Tuple2, + or consider a pattern matching anonymous function: `{ case (a, b) => ... } + val x: ((Int, Int) => Int) = (((a, b)) => a) + ^ +not-a-legal-formal-parameter-tuple.scala:3: error: not a legal formal parameter. +Note: Tuples cannot be directly destructured in method or function parameters. + Either create a single parameter accepting the Tuple2, + or consider a pattern matching anonymous function: `{ case (param1, param2) => ... } + val y: ((Int, Int, Int) => Int) = (((a, !!)) => a) + ^ +not-a-legal-formal-parameter-tuple.scala:4: error: not a legal formal parameter. +Note: Tuples cannot be directly destructured in method or function parameters. + Either create a single parameter accepting the Tuple3, + or consider a pattern matching anonymous function: `{ case (param1, ..., param3) => ... } + val z: ((Int, Int, Int) => Int) = (((a, NotAPatternVariableName, c)) => a) + ^ +three errors found diff --git a/test/files/neg/not-a-legal-formal-parameter-tuple.scala b/test/files/neg/not-a-legal-formal-parameter-tuple.scala new file mode 100644 index 0000000000..c7a13557df --- /dev/null +++ b/test/files/neg/not-a-legal-formal-parameter-tuple.scala @@ -0,0 +1,5 @@ +class C { + val x: ((Int, Int) => Int) = (((a, b)) => a) + val y: ((Int, Int, Int) => Int) = (((a, !!)) => a) + val z: ((Int, Int, Int) => Int) = (((a, NotAPatternVariableName, c)) => a) +} diff --git a/test/files/neg/patmatexhaust.scala b/test/files/neg/patmatexhaust.scala index aa7dac7d7d..f937197829 100644 --- a/test/files/neg/patmatexhaust.scala +++ b/test/files/neg/patmatexhaust.scala @@ -22,9 +22,9 @@ class TestSealedExhaustive { // compile only def ma3(x:Mult) = (x,x) match { // not exhaustive case (Kult(_), Qult()) => // Kult missing - //case Pair(Kult(_), Kult(_)) => + //case (Kult(_), Kult(_)) => case (Qult(), Kult(_)) => // Qult missing - //case Pair(Qult(), Qult()) => + //case (Qult(), Qult()) => } def ma3u(x:Mult) = ((x,x) : @unchecked) match { // not exhaustive, but not checked! diff --git a/test/files/neg/t3692-new.check b/test/files/neg/t3692-new.check index 9b96449930..bb8692f3ca 100644 --- a/test/files/neg/t3692-new.check +++ b/test/files/neg/t3692-new.check @@ -1,10 +1,10 @@ -t3692-new.scala:14: warning: non-variable type argument Int in type pattern Map[Int,Int] is unchecked since it is eliminated by erasure +t3692-new.scala:14: warning: non-variable type argument Int in type pattern scala.collection.immutable.Map[Int,Int] (the underlying of Map[Int,Int]) is unchecked since it is eliminated by erasure case m0: Map[Int, Int] => new java.util.HashMap[Integer, Integer] ^ -t3692-new.scala:15: warning: non-variable type argument Int in type pattern Map[Int,V] is unchecked since it is eliminated by erasure +t3692-new.scala:15: warning: non-variable type argument Int in type pattern scala.collection.immutable.Map[Int,V] (the underlying of Map[Int,V]) is unchecked since it is eliminated by erasure case m1: Map[Int, V] => new java.util.HashMap[Integer, V] ^ -t3692-new.scala:16: warning: non-variable type argument Int in type pattern Map[T,Int] is unchecked since it is eliminated by erasure +t3692-new.scala:16: warning: non-variable type argument Int in type pattern scala.collection.immutable.Map[T,Int] (the underlying of Map[T,Int]) is unchecked since it is eliminated by erasure case m2: Map[T, Int] => new java.util.HashMap[T, Integer] ^ t3692-new.scala:15: warning: unreachable code diff --git a/test/files/neg/t414.scala b/test/files/neg/t414.scala index 1662b9a105..86646d13c2 100644 --- a/test/files/neg/t414.scala +++ b/test/files/neg/t414.scala @@ -1,5 +1,5 @@ case class Empty[a]() extends IntMap[a]; -case class Node[a](left: IntMap[a], keyVal: Pair[Int, a], right: IntMap[a]) extends IntMap[a]; +case class Node[a](left: IntMap[a], keyVal: Tuple2[Int, a], right: IntMap[a]) extends IntMap[a]; abstract class IntMap[a] { def lookup(key: Int): a = this match { case Empty => diff --git a/test/files/neg/t5689.check b/test/files/neg/t5689.check index e74de40280..9271f709ca 100644 --- a/test/files/neg/t5689.check +++ b/test/files/neg/t5689.check @@ -1,8 +1,8 @@ -t5689.scala:4: error: macro implementation has wrong shape: +t5689.scala:4: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(i: c.Expr[Double]): c.Expr[String] or : (c: scala.reflect.macros.BlackboxContext)(i: c.Tree): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(i: c.Expr[Double]): c.Expr[Int] type mismatch for return type: c.Expr[Int] does not conform to c.Expr[String] def returnsString(i: Double): String = macro returnsIntImpl - ^ + ^ one error found diff --git a/test/files/neg/t5702-neg-bad-and-wild.check b/test/files/neg/t5702-neg-bad-and-wild.check index ff9e5e5703..a52136dbf8 100644 --- a/test/files/neg/t5702-neg-bad-and-wild.check +++ b/test/files/neg/t5702-neg-bad-and-wild.check @@ -23,6 +23,6 @@ t5702-neg-bad-and-wild.scala:23: error: bad simple pattern: bad use of _* (a seq val K(ns @ _*, x) = k // bad use of _* (a sequence pattern must be the last pattern) ^ t5702-neg-bad-and-wild.scala:24: error: bad simple pattern: bad use of _* (sequence pattern not allowed) - val (b, _ * ) = Pair(5,6) // bad use of _* (sequence pattern not allowed) + val (b, _ * ) = (5,6) // bad use of _* (sequence pattern not allowed) ^ 9 errors found diff --git a/test/files/neg/t5702-neg-bad-and-wild.scala b/test/files/neg/t5702-neg-bad-and-wild.scala index 3833a002b1..aadda37da7 100644 --- a/test/files/neg/t5702-neg-bad-and-wild.scala +++ b/test/files/neg/t5702-neg-bad-and-wild.scala @@ -21,7 +21,7 @@ object Test { //gowild.scala:14: error: star patterns must correspond with varargs parameters val K(is @ _*) = k val K(ns @ _*, x) = k // bad use of _* (a sequence pattern must be the last pattern) - val (b, _ * ) = Pair(5,6) // bad use of _* (sequence pattern not allowed) + val (b, _ * ) = (5,6) // bad use of _* (sequence pattern not allowed) // no longer complains //bad-and-wild.scala:15: error: ')' expected but '}' found. } diff --git a/test/files/neg/t6123-explaintypes-macros.check b/test/files/neg/t6123-explaintypes-macros.check index 9a0402039b..ef545fcc32 100644 --- a/test/files/neg/t6123-explaintypes-macros.check +++ b/test/files/neg/t6123-explaintypes-macros.check @@ -1,10 +1,10 @@ c.universe.Expr[Any]* <: c.universe.Expr[String]*? false -BadMac_2.scala:6: error: macro implementation has wrong shape: +BadMac_2.scala:6: error: macro implementation has incompatible shape: required: (c: scala.reflect.macros.BlackboxContext)(format: c.Expr[String], params: c.Expr[Any]*): c.Expr[Unit] or : (c: scala.reflect.macros.BlackboxContext)(format: c.Tree, params: Tree*): c.Tree found : (c: scala.reflect.macros.BlackboxContext)(format: c.Expr[String], params: c.Expr[String]*): c.Expr[Unit] type mismatch for parameter params: c.Expr[Any]* does not conform to c.Expr[String]* def printf(format: String, params: Any*): Unit = macro printf_impl - ^ + ^ one error found diff --git a/test/files/neg/t7872.check b/test/files/neg/t7872.check new file mode 100644 index 0000000000..57d9772abc --- /dev/null +++ b/test/files/neg/t7872.check @@ -0,0 +1,10 @@ +t7872.scala:6: error: contravariant type a occurs in covariant position in type [-a]Cov[a] of type l + type x = {type l[-a] = Cov[a]} + ^ +t7872.scala:8: error: covariant type a occurs in contravariant position in type [+a]Inv[a] of type l + foo[({type l[+a] = Inv[a]})#l] + ^ +t7872.scala:5: error: contravariant type a occurs in covariant position in type [-a]Cov[a] of type l + type l[-a] = Cov[a] + ^ +three errors found diff --git a/test/files/neg/t7872.scala b/test/files/neg/t7872.scala new file mode 100644 index 0000000000..66d22a0715 --- /dev/null +++ b/test/files/neg/t7872.scala @@ -0,0 +1,9 @@ +trait Cov[+A] +trait Inv[-A] + +object varianceExploit { + type l[-a] = Cov[a] + type x = {type l[-a] = Cov[a]} + def foo[M[_]] = () + foo[({type l[+a] = Inv[a]})#l] +} diff --git a/test/files/neg/t7872b.check b/test/files/neg/t7872b.check new file mode 100644 index 0000000000..0dc4e76301 --- /dev/null +++ b/test/files/neg/t7872b.check @@ -0,0 +1,7 @@ +t7872b.scala:8: error: contravariant type a occurs in covariant position in type [-a]List[a] of type l + def oops1 = down[({type l[-a] = List[a]})#l](List('whatever: Object)).head + "oops" + ^ +t7872b.scala:19: error: covariant type a occurs in contravariant position in type [+a]coinv.Stringer[a] of type l + def oops2 = up[({type l[+a] = Stringer[a]})#l]("printed: " + _) + ^ +two errors found diff --git a/test/files/neg/t7872b.scala b/test/files/neg/t7872b.scala new file mode 100644 index 0000000000..307a1470c5 --- /dev/null +++ b/test/files/neg/t7872b.scala @@ -0,0 +1,23 @@ +object coinv { + def up[F[+_]](fa: F[String]): F[Object] = fa + def down[F[-_]](fa: F[Object]): F[String] = fa + + up(List("hi")) + + // should not compile; `l' is unsound + def oops1 = down[({type l[-a] = List[a]})#l](List('whatever: Object)).head + "oops" + // scala> oops1 + // java.lang.ClassCastException: scala.Symbol cannot be cast to java.lang.String + // at com.nocandysw.coinv$.oops1(coinv.scala:12) + + type Stringer[-A] = A => String + down[Stringer](_.toString) + // [error] type A is contravariant, but type _ is declared covariant + // up[Stringer]("printed: " + _) + + // should not compile; `l' is unsound + def oops2 = up[({type l[+a] = Stringer[a]})#l]("printed: " + _) + // scala> oops2(Some(33)) + // java.lang.ClassCastException: scala.Some cannot be cast to java.lang.String + // at com.nocandysw.coinv$$anonfun$oops2$1.apply(coinv.scala:20) +} diff --git a/test/files/neg/t7872c.check b/test/files/neg/t7872c.check new file mode 100644 index 0000000000..469449dbd5 --- /dev/null +++ b/test/files/neg/t7872c.check @@ -0,0 +1,11 @@ +t7872c.scala:7: error: inferred kinds of the type arguments (List) do not conform to the expected kinds of the type parameters (type F). +List's type parameters do not match type F's expected parameters: +type A is covariant, but type _ is declared contravariant + down(List('whatever: Object)) + ^ +t7872c.scala:7: error: type mismatch; + found : List[Object] + required: F[Object] + down(List('whatever: Object)) + ^ +two errors found diff --git a/test/files/neg/t7872c.scala b/test/files/neg/t7872c.scala new file mode 100644 index 0000000000..fa12a523b5 --- /dev/null +++ b/test/files/neg/t7872c.scala @@ -0,0 +1,8 @@ +object coinv { + def up[F[+_]](fa: F[String]): F[Object] = fa + def down[F[-_]](fa: F[Object]): F[String] = fa + + up(List("hi")) + // [error] type A is covariant, but type _ is declared contravariant + down(List('whatever: Object)) +} diff --git a/test/files/neg/t7967.check b/test/files/neg/t7967.check new file mode 100644 index 0000000000..cde950dcdf --- /dev/null +++ b/test/files/neg/t7967.check @@ -0,0 +1,9 @@ +t7967.scala:6: error: illegal inheritance; + self-type C does not conform to C's selftype C with B + new C {} // fails + ^ +t7967.scala:8: error: illegal inheritance; + self-type Test.CC does not conform to Test.CC's selftype Test.CC + new CC {} // should fail, doesn't + ^ +two errors found diff --git a/test/files/neg/t7967.scala b/test/files/neg/t7967.scala new file mode 100644 index 0000000000..4f13347948 --- /dev/null +++ b/test/files/neg/t7967.scala @@ -0,0 +1,9 @@ + +trait B +trait C {self: B =>} + +object Test { + new C {} // fails + type CC = C + new CC {} // should fail, doesn't +} diff --git a/test/files/neg/t7984.check b/test/files/neg/t7984.check new file mode 100644 index 0000000000..0cfd7d1619 --- /dev/null +++ b/test/files/neg/t7984.check @@ -0,0 +1,6 @@ +t7984.scala:4: warning: non-variable type argument Int in type pattern List[Int] (the underlying of Test.this.ListInt) is unchecked since it is eliminated by erasure + case is: ListInt => is.head + ^ +error: No warnings can be incurred under -Xfatal-warnings. +one warning found +one error found diff --git a/test/files/neg/t7984.flags b/test/files/neg/t7984.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/neg/t7984.flags @@ -0,0 +1 @@ +-Xfatal-warnings
\ No newline at end of file diff --git a/test/files/neg/t7984.scala b/test/files/neg/t7984.scala new file mode 100644 index 0000000000..ca09a89fc7 --- /dev/null +++ b/test/files/neg/t7984.scala @@ -0,0 +1,7 @@ +class Test { + type ListInt = List[Int] + List[Any]("") match { + case is: ListInt => is.head + case _ => + } +} diff --git a/test/files/neg/t997.scala b/test/files/neg/t997.scala index e8d10f4317..1198738f24 100644 --- a/test/files/neg/t997.scala +++ b/test/files/neg/t997.scala @@ -1,5 +1,5 @@ // An extractor with 2 results -object Foo { def unapply(x : String) = Some(Pair(x, x)) } +object Foo { def unapply(x : String) = Some((x, x)) } object Test extends App { diff --git a/test/files/neg/unchecked-suppress.check b/test/files/neg/unchecked-suppress.check index 038105918e..d3dc86014b 100644 --- a/test/files/neg/unchecked-suppress.check +++ b/test/files/neg/unchecked-suppress.check @@ -1,7 +1,7 @@ -unchecked-suppress.scala:4: warning: non-variable type argument Int in type pattern Set[Int] is unchecked since it is eliminated by erasure +unchecked-suppress.scala:4: warning: non-variable type argument Int in type pattern scala.collection.immutable.Set[Int] (the underlying of Set[Int]) is unchecked since it is eliminated by erasure case xs: Set[Int] => xs.head // unchecked ^ -unchecked-suppress.scala:5: warning: non-variable type argument String in type pattern Map[String @unchecked,String] is unchecked since it is eliminated by erasure +unchecked-suppress.scala:5: warning: non-variable type argument String in type pattern scala.collection.immutable.Map[String @unchecked,String] (the underlying of Map[String @unchecked,String]) is unchecked since it is eliminated by erasure case xs: Map[String @unchecked, String] => xs.head // one unchecked, one okay ^ unchecked-suppress.scala:7: warning: non-variable type argument Int in type pattern (Int, Int) => Int is unchecked since it is eliminated by erasure diff --git a/test/files/neg/unchecked.check b/test/files/neg/unchecked.check index 570f02f219..033cffb18f 100644 --- a/test/files/neg/unchecked.check +++ b/test/files/neg/unchecked.check @@ -1,10 +1,10 @@ -unchecked.scala:18: warning: non-variable type argument String in type pattern Iterable[String] is unchecked since it is eliminated by erasure +unchecked.scala:18: warning: non-variable type argument String in type pattern Iterable[String] (the underlying of Iterable[String]) is unchecked since it is eliminated by erasure case xs: Iterable[String] => xs.head // unchecked ^ -unchecked.scala:22: warning: non-variable type argument Any in type pattern Set[Any] is unchecked since it is eliminated by erasure +unchecked.scala:22: warning: non-variable type argument Any in type pattern scala.collection.immutable.Set[Any] (the underlying of Set[Any]) is unchecked since it is eliminated by erasure case xs: Set[Any] => xs.head // unchecked ^ -unchecked.scala:26: warning: non-variable type argument Any in type pattern Map[Any,Any] is unchecked since it is eliminated by erasure +unchecked.scala:26: warning: non-variable type argument Any in type pattern scala.collection.immutable.Map[Any,Any] (the underlying of Map[Any,Any]) is unchecked since it is eliminated by erasure case xs: Map[Any, Any] => xs.head // unchecked ^ unchecked.scala:35: warning: non-variable type argument List[Nothing] in type pattern Test.Contra[List[Nothing]] is unchecked since it is eliminated by erasure diff --git a/test/files/neg/unchecked3.check b/test/files/neg/unchecked3.check index a7582a8930..0a526050fc 100644 --- a/test/files/neg/unchecked3.check +++ b/test/files/neg/unchecked3.check @@ -31,7 +31,7 @@ unchecked3.scala:62: warning: non-variable type argument Array[String] in type p unchecked3.scala:63: warning: non-variable type argument String in type pattern Array[Array[List[String]]] is unchecked since it is eliminated by erasure /* warn */ case _: Array[Array[List[String]]] => () ^ -unchecked3.scala:75: warning: abstract type A in type pattern Set[Q.this.A] is unchecked since it is eliminated by erasure +unchecked3.scala:75: warning: abstract type A in type pattern scala.collection.immutable.Set[Q.this.A] (the underlying of Set[Q.this.A]) is unchecked since it is eliminated by erasure /* warn */ case xs: Set[A] => xs.head ^ unchecked3.scala:62: warning: unreachable code diff --git a/test/files/neg/variances.check b/test/files/neg/variances.check index 7d965e94dc..cb1a60a632 100644 --- a/test/files/neg/variances.check +++ b/test/files/neg/variances.check @@ -1,6 +1,9 @@ variances.scala:4: error: covariant type A occurs in contravariant position in type test.Vector[A] of value x def append(x: Vector[A]): Vector[A] ^ +variances.scala:75: error: covariant type A occurs in contravariant position in type => A => A of value m + val m: A => A + ^ variances.scala:18: error: covariant type A occurs in contravariant position in type A of value a private def setA3(a : A) = this.a = a ^ @@ -19,4 +22,4 @@ variances.scala:89: error: covariant type T occurs in invariant position in type variances.scala:90: error: covariant type T occurs in contravariant position in type => test.TestAlias.B[C.this.A] of method foo def foo: B[A] ^ -7 errors found +8 errors found diff --git a/test/files/neg/wellkinded_wrongarity.check b/test/files/neg/wellkinded_wrongarity.check index 1dc38db5c1..b9f033b453 100644 --- a/test/files/neg/wellkinded_wrongarity.check +++ b/test/files/neg/wellkinded_wrongarity.check @@ -1,4 +1,4 @@ -wellkinded_wrongarity.scala:5: error: Pair takes two type parameters, expected: one -object mp extends Monad[Pair] +wellkinded_wrongarity.scala:5: error: Tuple2 takes two type parameters, expected: one +object mp extends Monad[Tuple2] ^ one error found diff --git a/test/files/neg/wellkinded_wrongarity.scala b/test/files/neg/wellkinded_wrongarity.scala index 2bb0e2ce8a..39c7601d53 100644 --- a/test/files/neg/wellkinded_wrongarity.scala +++ b/test/files/neg/wellkinded_wrongarity.scala @@ -2,4 +2,4 @@ class Monad[m[x]] -object mp extends Monad[Pair] +object mp extends Monad[Tuple2] diff --git a/test/files/pos/bounds.scala b/test/files/pos/bounds.scala index cfea4626c3..26bc84a1b9 100644 --- a/test/files/pos/bounds.scala +++ b/test/files/pos/bounds.scala @@ -1,11 +1,11 @@ trait Map[A, +C] { - def ++ [B1 >: C] (kvs: Iterable[Pair[A, B1]]): Map[A, B1] = this - def ++ [B1 >: C] (kvs: Iterator[Pair[A, B1]]): Map[A, B1] = this + def ++ [B1 >: C] (kvs: Iterable[Tuple2[A, B1]]): Map[A, B1] = this + def ++ [B1 >: C] (kvs: Iterator[Tuple2[A, B1]]): Map[A, B1] = this } class ListMap[A, +B] extends Map[A, B] {} object ListMap { def empty[X, Y] = new ListMap[X, Y] - def apply[A1, B2](elems: Pair[A1, B2]*): Map[A1, B2] = empty[A1,B2].++(elems.iterator) + def apply[A1, B2](elems: Tuple2[A1, B2]*): Map[A1, B2] = empty[A1,B2].++(elems.iterator) } diff --git a/test/files/pos/macro-implicit-invalidate-on-error.check b/test/files/pos/macro-implicit-invalidate-on-error.check new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/test/files/pos/macro-implicit-invalidate-on-error.check diff --git a/test/files/pos/macro-implicit-invalidate-on-error.scala b/test/files/pos/macro-implicit-invalidate-on-error.scala new file mode 100644 index 0000000000..22cd2d34b4 --- /dev/null +++ b/test/files/pos/macro-implicit-invalidate-on-error.scala @@ -0,0 +1,28 @@ +package scala.reflect +package api + +import scala.language.experimental.macros +import scala.reflect.macros.Context + +trait Liftable[T] { + def apply(universe: api.Universe, value: T): universe.Tree +} + +object Liftable { + implicit def liftCaseClass[T <: Product]: Liftable[T] = macro liftCaseClassImpl[T] + + def liftCaseClassImpl[T: c.WeakTypeTag](c: Context): c.Expr[Liftable[T]] = { + import c.universe._ + val tpe = weakTypeOf[T] + if (!tpe.typeSymbol.asClass.isCaseClass) c.abort(c.enclosingPosition, "denied") + val p = List(q"Literal(Constant(1))") + c.Expr[Liftable[T]] { q""" + new scala.reflect.api.Liftable[$tpe] { + def apply(universe: scala.reflect.api.Universe, value: $tpe): universe.Tree = { + import universe._ + Apply(Select(Ident(TermName("C")), TermName("apply")), List(..$p)) + } + } + """ } + } +} diff --git a/test/files/pos/patmat.scala b/test/files/pos/patmat.scala index 4e652b146e..51b879abf2 100644 --- a/test/files/pos/patmat.scala +++ b/test/files/pos/patmat.scala @@ -3,8 +3,8 @@ object ZipFun { //just compilation - def zipFun[a, b](xs: List[a], ys: List[b]): List[Pair[a, b]] = (Pair(xs, ys): @unchecked) match { - // !!! case Pair(List(), _), Pair(_, List()) => List() + def zipFun[a, b](xs: List[a], ys: List[b]): List[Tuple2[a, b]] = ((xs, ys): @unchecked) match { + // !!! case (List(), _), (_, List()) => List() case (x :: xs1, y :: ys1) => (x, y) :: zipFun(xs1, ys1) } } diff --git a/test/files/pos/spec-doubledef-new.scala b/test/files/pos/spec-doubledef-new.scala index ad9c6399a5..589ceb33b2 100644 --- a/test/files/pos/spec-doubledef-new.scala +++ b/test/files/pos/spec-doubledef-new.scala @@ -19,12 +19,12 @@ abstract class B[T, @specialized(scala.Int) U : TypeTag, @specialized(scala.Int) val u: U val v: V - def f(t: T, v2: V): Pair[U, V] = { + def f(t: T, v2: V): Tuple2[U, V] = { val m: Array[U] = null if (m.isEmpty) { - Pair(u, v) + (u, v) } else { - Pair(u, v2) + (u, v2) } } }
\ No newline at end of file diff --git a/test/files/pos/spec-doubledef-old.scala b/test/files/pos/spec-doubledef-old.scala index 86b0d857d3..bde259e4fa 100644 --- a/test/files/pos/spec-doubledef-old.scala +++ b/test/files/pos/spec-doubledef-old.scala @@ -17,12 +17,12 @@ abstract class B[T, @specialized(scala.Int) U : Manifest, @specialized(scala.Int val u: U val v: V - def f(t: T, v2: V): Pair[U, V] = { + def f(t: T, v2: V): Tuple2[U, V] = { val m: Array[U] = null if (m.isEmpty) { - Pair(u, v) + (u, v) } else { - Pair(u, v2) + (u, v2) } } } diff --git a/test/files/pos/t0064.scala b/test/files/pos/t0064.scala index c2ce4bf6d0..1eeca8dcad 100644 --- a/test/files/pos/t0064.scala +++ b/test/files/pos/t0064.scala @@ -1,6 +1,6 @@ object B { def main(Args:Array[String]) = { - val Pair(_,x) = Pair(1,2); + val (_,x) = (1,2); x + 1; } } diff --git a/test/files/pos/t247.scala b/test/files/pos/t247.scala index e976404e61..fdcafeb2c6 100644 --- a/test/files/pos/t247.scala +++ b/test/files/pos/t247.scala @@ -16,11 +16,11 @@ class Tree[KEY,Entry](order:Order[KEY]) { def size =0; } -class TreeMap[KEY,VALUE](_factory:TreeMapFactory[KEY]) extends Tree[KEY,Pair[KEY,VALUE]](_factory.order) with scala.collection.DefaultMap[KEY, VALUE] with Map[KEY, VALUE] { +class TreeMap[KEY,VALUE](_factory:TreeMapFactory[KEY]) extends Tree[KEY,Tuple2[KEY,VALUE]](_factory.order) with scala.collection.DefaultMap[KEY, VALUE] with Map[KEY, VALUE] { val factory = _factory val order = _factory.order; def this(newOrder:Order[KEY]) = this(new TreeMapFactory[KEY](newOrder)); def get(key:KEY) = null; - def iterator:Iterator[Pair[KEY,VALUE]] = null; + def iterator:Iterator[Tuple2[KEY,VALUE]] = null; override def size = super[Tree].size } diff --git a/test/files/pos/t443.scala b/test/files/pos/t443.scala index 5b5e3ea828..cdaefe9ecd 100644 --- a/test/files/pos/t443.scala +++ b/test/files/pos/t443.scala @@ -1,10 +1,10 @@ object Test { - def lookup(): Option[Pair[String, String]] = - ((null: Option[Pair[String, String]]) : @unchecked) match { - case Some(Pair(_, _)) => + def lookup(): Option[Tuple2[String, String]] = + ((null: Option[Tuple2[String, String]]) : @unchecked) match { + case Some((_, _)) => if (true) - Some(Pair(null, null)) + Some((null, null)) else lookup() match { case Some(_) => Some(null) diff --git a/test/files/pos/t4579.scala b/test/files/pos/t4579.scala index 8951ec011f..cd1553f02a 100644 --- a/test/files/pos/t4579.scala +++ b/test/files/pos/t4579.scala @@ -190,10 +190,10 @@ object LispCaseClasses extends Lisp { def extendEnv(env: Environment, ps: List[String], args: List[Data]): Environment = - Pair(ps, args) match { - case Pair(List(), List()) => + (ps, args) match { + case (List(), List()) => env - case Pair(p :: ps1, arg :: args1) => + case (p :: ps1, arg :: args1) => extendEnv(env.extend(p, arg), ps1, args1) case _ => lispError("wrong number of arguments") @@ -381,10 +381,10 @@ object LispAny extends Lisp { def extendEnv(env: Environment, ps: List[String], args: List[Data]): Environment = - Pair(ps, args) match { - case Pair(List(), List()) => + (ps, args) match { + case (List(), List()) => env - case Pair(p :: ps1, arg :: args1) => + case (p :: ps1, arg :: args1) => extendEnv(env.extend(p, arg), ps1, args1) case _ => lispError("wrong number of arguments") diff --git a/test/files/pos/t5120.scala b/test/files/pos/t5120.scala index 6731af14e4..86d4470bd5 100644 --- a/test/files/pos/t5120.scala +++ b/test/files/pos/t5120.scala @@ -5,9 +5,9 @@ class Test { class ScopedKey[T] class Value[T] - class Compiled[T](val settings: Seq[Pair[T]]) + class Compiled[T](val settings: Seq[Tuple2[T]]) - case class Pair[T](k: ScopedKey[T], v: ScopedKey[T]) + case class Tuple2[T](k: ScopedKey[T], v: ScopedKey[T]) def transform[T](x: T) = x diff --git a/test/files/pos/t7983.scala b/test/files/pos/t7983.scala new file mode 100644 index 0000000000..a583e538c5 --- /dev/null +++ b/test/files/pos/t7983.scala @@ -0,0 +1,31 @@ +package foo.bar.baz // the package nesting level material to this bug + +class DivergenceTest { + + trait ColumnBase[T] + + trait ShapeLevel + trait Flat extends ShapeLevel + trait Lower extends Flat + + class Shape2[Level <: ShapeLevel, -M, U] + + implicit final def columnBaseShape[Level >: Flat <: ShapeLevel, T, C <: ColumnBase[_]] + (implicit ev: C <:< ColumnBase[T] + ): Shape2[Level, C, T] = ??? + + implicit final def intShape[Level <: ShapeLevel, T]: Shape2[Level, Int, Int] = ??? + implicit final def tuple2Shape[Level <: ShapeLevel, M1,M2, U1,U2] + (implicit u1: Shape2[_ <: Level, M1, U1], + u2: Shape2[_ <: Level, M2, U2] + ): Shape2[Level, (M1,M2), (U1,U2)] = ??? + + def foo { + class Coffees extends ColumnBase[Int] + + def map1[F, T](f: F)(implicit shape: Shape2[_ <: Flat, F, T]) = ??? + + map1(((1, null: Coffees), 1)) + map1(((null: Coffees, 1), 1)) // fails with implicit divergence error in 2.11.0-M6, works under 2.10.3 + } +} diff --git a/test/files/pos/t7987/Macro_1.scala b/test/files/pos/t7987/Macro_1.scala new file mode 100644 index 0000000000..81f717b9c4 --- /dev/null +++ b/test/files/pos/t7987/Macro_1.scala @@ -0,0 +1,6 @@ +import scala.language.experimental._ + +object Macro { + def apply[A](a: A): A = macro impl[A] + def impl[A](c: reflect.macros.Context)(a: c.Expr[A]): c.Expr[A] = a +} diff --git a/test/files/pos/t7987/Test_2.scala b/test/files/pos/t7987/Test_2.scala new file mode 100644 index 0000000000..5896fdb517 --- /dev/null +++ b/test/files/pos/t7987/Test_2.scala @@ -0,0 +1,12 @@ +class C[T] { + def foo = 0 +} + +object Test { + implicit def AnyToC[T](a: Any): C[T] = new C[T] + // was: "macro not expanded" + Macro { + "".foo + () + } +} diff --git a/test/files/pos/t8001.check b/test/files/pos/t8001.check new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/test/files/pos/t8001.check diff --git a/test/files/pos/t8001.flags b/test/files/pos/t8001.flags new file mode 100644 index 0000000000..e8fb65d50c --- /dev/null +++ b/test/files/pos/t8001.flags @@ -0,0 +1 @@ +-Xfatal-warnings
\ No newline at end of file diff --git a/test/files/pos/t8001/Macros_1.scala b/test/files/pos/t8001/Macros_1.scala new file mode 100644 index 0000000000..1f8dab51c1 --- /dev/null +++ b/test/files/pos/t8001/Macros_1.scala @@ -0,0 +1,10 @@ +import scala.language.experimental.macros +import scala.reflect.macros.BlackboxContext + +object Macros { + def foo = macro impl + def impl(c: BlackboxContext) = { + import c.universe._ + q"()" + } +}
\ No newline at end of file diff --git a/test/files/pos/t8001/Test_2.scala b/test/files/pos/t8001/Test_2.scala new file mode 100644 index 0000000000..6d72d96070 --- /dev/null +++ b/test/files/pos/t8001/Test_2.scala @@ -0,0 +1,4 @@ +object Test extends App { + Macros.foo + (): Unit +}
\ No newline at end of file diff --git a/test/files/pos/t8002-nested-scope.scala b/test/files/pos/t8002-nested-scope.scala new file mode 100644 index 0000000000..a2088bce7a --- /dev/null +++ b/test/files/pos/t8002-nested-scope.scala @@ -0,0 +1,20 @@ +// This test serves to capture the status quo, but should really +// emit an accessibiltiy error. + +// `Namers#companionSymbolOf` seems too lenient, and currently doesn't +// implement the same-scope checks mentioned: +// +// https://github.com/scala/scala/pull/2816#issuecomment-22555206 +// +class C { + def foo = { + class C { private def x = 0 } + + { + val a = 0 + object C { + new C().x + } + } + } +} diff --git a/test/files/pos/t8011.scala b/test/files/pos/t8011.scala new file mode 100644 index 0000000000..76bd7acd14 --- /dev/null +++ b/test/files/pos/t8011.scala @@ -0,0 +1,8 @@ +class ThingOps1(val x: String) extends AnyVal { + def fn[A]: Any = { + new X[A] { def foo(a: A) = a } + 0 + } +} + +trait X[B] { def foo(a: B): Any }
\ No newline at end of file diff --git a/test/files/pos/t8023.scala b/test/files/pos/t8023.scala new file mode 100644 index 0000000000..86824084ed --- /dev/null +++ b/test/files/pos/t8023.scala @@ -0,0 +1,22 @@ +import language._ + + +object Test { + def foo = (null: Any) match { + case a: A[k] => + // error: kinds of the type arguments (k) do not conform to the + // expected kinds of the type parameters (type K) in class B. + new B[k]() + } +} + +class A[K[L[_]]] + +class B[K[M[_]]] + + +object Test2 { + def foo = (null: Any) match { + case a: A[k] => new B[k]() // this one worked before as the info of `A` was complete + } +} diff --git a/test/files/pos/t8023b.scala b/test/files/pos/t8023b.scala new file mode 100644 index 0000000000..94c9b2f8d2 --- /dev/null +++ b/test/files/pos/t8023b.scala @@ -0,0 +1,2 @@ +// this fails with naive attempts to fix SI-8023 +trait T[A <: T[A]] diff --git a/test/files/pos/tcpoly_bounds1.scala b/test/files/pos/tcpoly_bounds1.scala index 5874cc664d..63263cb152 100644 --- a/test/files/pos/tcpoly_bounds1.scala +++ b/test/files/pos/tcpoly_bounds1.scala @@ -1,7 +1,7 @@ -class Foo[t[x]<: Pair[Int, x]] +class Foo[t[x]<: Tuple2[Int, x]] // -class MyPair[z](a: Int, b: z) extends Pair[Int, z](a,b) +class MyPair[z](a: Int, b: z) extends Tuple2[Int, z](a,b) object foo extends Foo[MyPair] diff --git a/test/files/pos/typealiases.scala b/test/files/pos/typealiases.scala index d03b521f77..93d1dce4dc 100644 --- a/test/files/pos/typealiases.scala +++ b/test/files/pos/typealiases.scala @@ -14,7 +14,7 @@ trait Test[T] { object main extends Test[Int] { val pair1 = (1,1) - implicit def topair(x: Int): Pair[Int, Int] = (x,x) + implicit def topair(x: Int): Tuple2[Int, Int] = (x,x) val pair2: MyPair[Int] = 1 val x: Short = 1 } diff --git a/test/files/pos/unapplyNeedsMemberType.scala b/test/files/pos/unapplyNeedsMemberType.scala index b423257e04..3a96e189af 100644 --- a/test/files/pos/unapplyNeedsMemberType.scala +++ b/test/files/pos/unapplyNeedsMemberType.scala @@ -19,7 +19,7 @@ class Join[a] extends Gunk[a] { def append(s1: Seq, s2: Seq): Seq = s1 // mock implementation def unapply_Cons(s: Any) = s match { - case App(Cons(x, xs), ys) => Some(Pair(x, append(xs, ys))) + case App(Cons(x, xs), ys) => Some((x, append(xs, ys))) case _ => null } } diff --git a/test/files/pos/valdefs.scala b/test/files/pos/valdefs.scala index 85ffa132b7..c8f78cd2bf 100644 --- a/test/files/pos/valdefs.scala +++ b/test/files/pos/valdefs.scala @@ -11,6 +11,6 @@ object test { } abstract class Sub2() extends Base() { - override val Pair(x, y) = Pair("abc", 2.0); + override val (x, y) = ("abc", 2.0); } } diff --git a/test/files/positions/ExcludedPrefix1.scala b/test/files/positions/ExcludedPrefix1.scala index f3562c37f0..b3182eae78 100644 --- a/test/files/positions/ExcludedPrefix1.scala +++ b/test/files/positions/ExcludedPrefix1.scala @@ -35,7 +35,7 @@ object ExcludedPrefix1 { (i, j) = (0, 0) - val Pair( + val ( k, l) = (0, 0) } diff --git a/test/files/positions/Overlap4.scala b/test/files/positions/Overlap4.scala index 0049293954..f54837295b 100644 --- a/test/files/positions/Overlap4.scala +++ b/test/files/positions/Overlap4.scala @@ -1,3 +1,3 @@ object Overlap4 { - val Pair(a, b) = (0, 0) + val (a, b) = (0, 0) } diff --git a/test/files/positions/Scaladoc7.scala b/test/files/positions/Scaladoc7.scala index 6175222e3f..0198d4d6ac 100644 --- a/test/files/positions/Scaladoc7.scala +++ b/test/files/positions/Scaladoc7.scala @@ -2,5 +2,5 @@ object Scaladoc7 { /** * Foo */ - val Pair(i, j) = (1, 2) + val (i, j) = (1, 2) } diff --git a/test/files/presentation/callcc-interpreter.check b/test/files/presentation/callcc-interpreter.check index f031c52c86..1f868097ca 100644 --- a/test/files/presentation/callcc-interpreter.check +++ b/test/files/presentation/callcc-interpreter.check @@ -1,8 +1,8 @@ reload: CallccInterpreter.scala -askTypeCompletion at CallccInterpreter.scala(51,38) +askTypeCompletion at CallccInterpreter.scala(51,34) ================================================================================ -[response] askTypeCompletion at (51,38) +[response] askTypeCompletion at (51,34) retrieved 59 members abstract trait Term extends AnyRef abstract trait Value extends AnyRef @@ -83,8 +83,8 @@ def showM(m: callccInterpreter.M[callccInterpreter.Value]): String = m.in.apply( askType at CallccInterpreter.scala(50,30) ================================================================================ [response] askTypeAt (50,30) -def add(a: callccInterpreter.Value, b: callccInterpreter.Value): callccInterpreter.M[_ >: callccInterpreter.Num with callccInterpreter.Wrong.type <: Product with Serializable with callccInterpreter.Value] = scala.this.Predef.Pair.apply[callccInterpreter.Value, callccInterpreter.Value](a, b) match { - case scala.this.Predef.Pair.unapply[callccInterpreter.Value, callccInterpreter.Value](<unapply-selector>) <unapply> ((n: Int)callccInterpreter.Num((m @ _)), (n: Int)callccInterpreter.Num((n @ _))) => this.unitM[callccInterpreter.Num](callccInterpreter.this.Num.apply(m.+(n))) +def add(a: callccInterpreter.Value, b: callccInterpreter.Value): callccInterpreter.M[_ >: callccInterpreter.Num with callccInterpreter.Wrong.type <: Product with Serializable with callccInterpreter.Value] = scala.Tuple2.apply[callccInterpreter.Value, callccInterpreter.Value](a, b) match { + case (_1: callccInterpreter.Value, _2: callccInterpreter.Value)(callccInterpreter.Value, callccInterpreter.Value)((n: Int)callccInterpreter.Num((m @ _)), (n: Int)callccInterpreter.Num((n @ _))) => this.unitM[callccInterpreter.Num](callccInterpreter.this.Num.apply(m.+(n))) case _ => callccInterpreter.this.unitM[callccInterpreter.Wrong.type](callccInterpreter.this.Wrong) } ================================================================================ diff --git a/test/files/presentation/callcc-interpreter/src/CallccInterpreter.scala b/test/files/presentation/callcc-interpreter/src/CallccInterpreter.scala index ce3b996b96..d498fe0b17 100644 --- a/test/files/presentation/callcc-interpreter/src/CallccInterpreter.scala +++ b/test/files/presentation/callcc-interpreter/src/CallccInterpreter.scala @@ -40,15 +40,15 @@ object callccInterpreter { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]] + type Environment = List[Tuple2[Name, Value]] def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value) /*?*/ = Pair(a, b) match { - case Pair(Num(m), Num(n)) => this./*!*/unitM(Num(m + n)) + def add(a: Value, b: Value) /*?*/ = (a, b) match { + case (Num(m), Num(n)) => this./*!*/unitM(Num(m + n)) case _ => unitM(Wrong) } @@ -60,16 +60,20 @@ object callccInterpreter { def interp(t: Term, e: Environment): M[Value] = t match { case Var(x) => lookup(x, e) case Con(n) => unitM(Num(n)) - case Add(l, r) => for (val a <- interp(l, e); - val b <- interp(r, e); - val c <- add(a, b)) - yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) - case App(f, t) => for (val a <- interp(f, e); - val b <- interp(t, e); - val c <- apply(a, b)) - yield c - case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e)) + case Add(l, r) => + for { + a <- interp(l, e) + b <- interp(r, e) + c <- add(a, b) + } yield c + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) + case App(f, t) => + for { + a <- interp(f, e) + b <- interp(t, e) + c <- apply(a, b) + } yield c + case Ccc(x, t) => callCC(k => interp(t, (x, Fun(k)) :: e)) } def test(t: Term): String = showM(interp(t, List())) diff --git a/test/files/run/Course-2002-05.scala b/test/files/run/Course-2002-05.scala index e6764b92c8..80317bc757 100644 --- a/test/files/run/Course-2002-05.scala +++ b/test/files/run/Course-2002-05.scala @@ -3,15 +3,15 @@ //############################################################################ object M0 { - def partition[a](xs: List[a], pred: a => Boolean): Pair[List[a], List[a]] = { + def partition[a](xs: List[a], pred: a => Boolean): Tuple2[List[a], List[a]] = { if (xs.isEmpty) - Pair(List(),List()) + (List(),List()) else { val tailPartition = partition(xs.tail, pred); if (pred(xs.head)) - Pair(xs.head :: tailPartition._1, tailPartition._2) + (xs.head :: tailPartition._1, tailPartition._2) else - Pair(tailPartition._1, xs.head :: tailPartition._2) + (tailPartition._1, xs.head :: tailPartition._2) } } @@ -49,9 +49,9 @@ object M0 { //############################################################################ object M1 { - def partition[a](xs: List[a], pred: a => Boolean): Pair[List[a], List[a]] = { - xs.foldRight[Pair[List[a], List[a]]](Pair(List(), List())) { - (x, p) => if (pred (x)) Pair(x :: p._1, p._2) else Pair(p._1, x :: p._2) + def partition[a](xs: List[a], pred: a => Boolean): Tuple2[List[a], List[a]] = { + xs.foldRight[Tuple2[List[a], List[a]]]((List(), List())) { + (x, p) => if (pred (x)) (x :: p._1, p._2) else (p._1, x :: p._2) } } @@ -136,7 +136,7 @@ object M3 { def adjoinRow(placement: Placement): List[Placement] = range(1, n) .filter (column => isSafe(column, placement)) - .map (column => Pair(row, column) :: placement); + .map (column => (row, column) :: placement); placeQueens(row - 1) flatMap adjoinRow } diff --git a/test/files/run/Course-2002-06.scala b/test/files/run/Course-2002-06.scala index e4fb86a966..908a934041 100644 --- a/test/files/run/Course-2002-06.scala +++ b/test/files/run/Course-2002-06.scala @@ -55,7 +55,7 @@ abstract class Graphics(_width: Double, _height: Double) { } /** Draw a list of segments on the picture.*/ - def drawSegments(frm: Frame)(segments: List[Pair[Vector, Vector]]): Unit = + def drawSegments(frm: Frame)(segments: List[Tuple2[Vector, Vector]]): Unit = if (segments.isEmpty) () else { drawSegment(frm)(segments.head._1, segments.head._2); diff --git a/test/files/run/Course-2002-07.scala b/test/files/run/Course-2002-07.scala index 055ff74d81..2d9457653f 100644 --- a/test/files/run/Course-2002-07.scala +++ b/test/files/run/Course-2002-07.scala @@ -181,10 +181,10 @@ object M4 { object M5 { - def zipFun[a,b](xs:List[a], ys:List[b]):List[Pair[a,b]] = Pair(xs,ys) match { - case Pair(List(), _) => List() - case Pair(_, List()) => List() - case Pair(x :: xs1, y :: ys1) => Pair(x, y) :: zipFun(xs1, ys1) + def zipFun[a,b](xs:List[a], ys:List[b]):List[Tuple2[a,b]] = (xs,ys) match { + case (List(), _) => List() + case (_, List()) => List() + case (x :: xs1, y :: ys1) => (x, y) :: zipFun(xs1, ys1) } def test_zipFun[a,b](xs: List[a], ys: List[b]) = { @@ -216,9 +216,9 @@ object M5 { object M6 { - def zipFun[a,b](xs:List[a], ys:List[b]):List[Pair[a,b]] = (Pair(xs,ys): @unchecked) match { - // !!! case Pair(List(), _), Pair(_, List()) => List() - case Pair(x :: xs1, y :: ys1) => Pair(x, y) :: zipFun(xs1, ys1) + def zipFun[a,b](xs:List[a], ys:List[b]):List[Tuple2[a,b]] = ((xs,ys): @unchecked) match { + // !!! case (List(), _), (_, List()) => List() + case (x :: xs1, y :: ys1) => (x, y) :: zipFun(xs1, ys1) } def test_zipFun[a,b](xs: List[a], ys: List[b]) = { @@ -374,9 +374,9 @@ object M9 { object MA { - def lookup[k,v](xs: List[Pair[k,v]], k: k): v = xs match { + def lookup[k,v](xs: List[Tuple2[k,v]], k: k): v = xs match { case List() => sys.error("no value for " + k) - case Pair(k1,v1) :: xs1 => if (k1 == k) v1 else lookup(xs1, k) + case (k1,v1) :: xs1 => if (k1 == k) v1 else lookup(xs1, k) } trait Expr { @@ -437,8 +437,8 @@ object MA { val g1 = g0 derive x; Console.println("g (x) = " + g0); Console.println("g'(x) = " + g1); - Console.println("g (3) = " + evalvars(List(Pair("x",3)))(g0)); - Console.println("g'(3) = " + evalvars(List(Pair("x",3)))(g1)); + Console.println("g (3) = " + evalvars(List(("x",3)))(g0)); + Console.println("g'(3) = " + evalvars(List(("x",3)))(g1)); Console.println; } @@ -453,26 +453,26 @@ object Utils { if (y == 1) x else if (y % 2 == 0) power0(x*x,y/2) else x*power0(x, y-1); def power(x: Int, y: Int): Int = (x,y) match { - case Pair(0,0) => sys.error("power(0,0)") - case Pair(0,_) => 0 - case Pair(1,_) => 1 - case Pair(_,0) => 1 - case Pair(_,1) => x - case Pair(_,2) => x*x - case Pair(_,_) => if (y < 0) 1/power0(x,y) else power0(x,y) + case (0,0) => sys.error("power(0,0)") + case (0,_) => 0 + case (1,_) => 1 + case (_,0) => 1 + case (_,1) => x + case (_,2) => x*x + case (_,_) => if (y < 0) 1/power0(x,y) else power0(x,y) } def lookup(entries: List[(String,Int)], key: String): Int = entries match { case List() => sys.error("no value for " + key) - case Pair(k,v) :: _ if (k == key) => v + case (k,v) :: _ if (k == key) => v case _ :: rest => lookup(rest, key) } def compare(xs: List[String], ys: List[String]): Int = (xs, ys) match { - case Pair(List(), List()) => 0 - case Pair(List(), _ ) => -1 - case Pair(_ , List()) => +1 - case Pair(x::xs , y::ys ) => { + case (List(), List()) => 0 + case (List(), _ ) => -1 + case (_ , List()) => +1 + case (x::xs , y::ys ) => { val diff = x.compareTo(y); if (diff != 0) diff else compare(xs,ys) } @@ -508,18 +508,18 @@ object MB { private def +< (that: Expr): Boolean = (this +<? that) < 0; private def +<= (that: Expr): Boolean = (this +<? that) <= 0; - private def +<? (that: Expr): Int = Pair(this,that) match { - case Pair(Add(_,_), _ ) => 0 - case Pair(_ , Add(_,_)) => 0 - case Pair(_ , _ ) => compare(this.vars,that.vars) + private def +<? (that: Expr): Int = (this,that) match { + case (Add(_,_), _ ) => 0 + case (_ , Add(_,_)) => 0 + case (_ , _ ) => compare(this.vars,that.vars) } - def + (that: Expr): Expr = if (that +<= this) Pair(this,that) match { - case Pair(_ , Lit(0) ) => this - case Pair(Lit(l) , Lit(r) ) => Lit(l + r) - case Pair(_ , Add(rl,rr)) => (this + rl) + rr - case Pair(Add(ll,lr), _ ) if (lr +<= that) => ll + (that + lr) - case Pair(_ , _ ) => { + def + (that: Expr): Expr = if (that +<= this) (this,that) match { + case (_ , Lit(0) ) => this + case (Lit(l) , Lit(r) ) => Lit(l + r) + case (_ , Add(rl,rr)) => (this + rl) + rr + case (Add(ll,lr), _ ) if (lr +<= that) => ll + (that + lr) + case (_ , _ ) => { val l = this.term; val r = that.term; if (l equ r) Lit(this.count + that.count) * r else Add(this, that) @@ -528,41 +528,41 @@ object MB { private def *< (that: Expr): Boolean = (this *<? that) < 0; private def *<= (that: Expr): Boolean = (this *<? that) <= 0; - private def *<? (that: Expr): Int = Pair(this,that) match { - case Pair(Mul(_,_), _ ) => 0 - case Pair(_ , Mul(_,_)) => 0 - case Pair(Add(_,_), Add(_,_)) => 0 - case Pair(Add(_,_), _ ) => -1 - case Pair(_ , Add(_,_)) => +1 - case Pair(Lit(_) , Lit(_) ) => 0 - case Pair(Lit(_) , _ ) => -1 - case Pair(_ , Lit(_) ) => +1 - case Pair(Var(l) , Var(r) ) => l.compareTo(r) - case Pair(Var(_) , Pow(r,_)) => if (this *<= r) -1 else +1 - case Pair(Pow(l,_), Var(_) ) => if (l *< that) -1 else +1 - case Pair(Pow(l,_), Pow(r,_)) => l *<? r + private def *<? (that: Expr): Int = (this,that) match { + case (Mul(_,_), _ ) => 0 + case (_ , Mul(_,_)) => 0 + case (Add(_,_), Add(_,_)) => 0 + case (Add(_,_), _ ) => -1 + case (_ , Add(_,_)) => +1 + case (Lit(_) , Lit(_) ) => 0 + case (Lit(_) , _ ) => -1 + case (_ , Lit(_) ) => +1 + case (Var(l) , Var(r) ) => l.compareTo(r) + case (Var(_) , Pow(r,_)) => if (this *<= r) -1 else +1 + case (Pow(l,_), Var(_) ) => if (l *< that) -1 else +1 + case (Pow(l,_), Pow(r,_)) => l *<? r } - def * (that: Expr): Expr = if (this *<= that) Pair(this,that) match { - case Pair(Lit(0) , _ ) => this - case Pair(Lit(1) , _ ) => that - case Pair(Mul(ll,lr), r ) => ll * (lr * r) - case Pair(Add(ll,lr), r ) => ll * r + lr * r - case Pair(Lit(l) , Lit(r) ) => Lit(l * r) - case Pair(Var(_) , Var(_) ) if (this equ that) => Pow(this,2) - case Pair(Var(_) , Pow(r,n) ) if (this equ r) => Pow(this,n + 1) - case Pair(Pow(ll,lr), Pow(rl,rr)) if (ll equ rl) => Pow(ll,lr + rr) - case Pair(l , Mul(rl,rr)) if (rl *<= l) => (rl * l) * rr - case Pair(_ , _ ) => Mul(this,that) + def * (that: Expr): Expr = if (this *<= that) (this,that) match { + case (Lit(0) , _ ) => this + case (Lit(1) , _ ) => that + case (Mul(ll,lr), r ) => ll * (lr * r) + case (Add(ll,lr), r ) => ll * r + lr * r + case (Lit(l) , Lit(r) ) => Lit(l * r) + case (Var(_) , Var(_) ) if (this equ that) => Pow(this,2) + case (Var(_) , Pow(r,n) ) if (this equ r) => Pow(this,n + 1) + case (Pow(ll,lr), Pow(rl,rr)) if (ll equ rl) => Pow(ll,lr + rr) + case (l , Mul(rl,rr)) if (rl *<= l) => (rl * l) * rr + case (_ , _ ) => Mul(this,that) } else that * this; def ^ (that: Int): Expr = (this,that) match { - case Pair(_ ,1) => this - case Pair(Lit(i) ,n) => Lit(power(i,n)) - case Pair(Var(_) ,n) => Pow(this,n) - case Pair(Add(_,_),n) => this * (this ^ (n - 1)) - case Pair(Mul(l,r),n) => (l ^ n) * (r ^ n) - case Pair(Pow(e,m),n) => Pow(e,m + n) + case (_ ,1) => this + case (Lit(i) ,n) => Lit(power(i,n)) + case (Var(_) ,n) => Pow(this,n) + case (Add(_,_),n) => this * (this ^ (n - 1)) + case (Mul(l,r),n) => (l ^ n) * (r ^ n) + case (Pow(e,m),n) => Pow(e,m + n) } def derive(v: Var): Expr = this match { @@ -581,12 +581,12 @@ object MB { case Pow(l, r) => power(l.evaluate(vars), r) } - def equ(that: Expr): Boolean = Pair(this,that) match { - case Pair(Lit(l) ,Lit(r)) => l == r - case Pair(Var(l) ,Var(r)) => l == r - case Pair(Add(ll,lr),Add(rl,rr)) => (ll equ rl) && (lr equ rr) - case Pair(Mul(ll,lr),Mul(rl,rr)) => (ll equ rl) && (lr equ rr) - case Pair(Pow(ll,lr),Pow(rl,rr)) => (ll equ rl) && (lr == rr) + def equ(that: Expr): Boolean = (this,that) match { + case (Lit(l) ,Lit(r)) => l == r + case (Var(l) ,Var(r)) => l == r + case (Add(ll,lr),Add(rl,rr)) => (ll equ rl) && (lr equ rr) + case (Mul(ll,lr),Mul(rl,rr)) => (ll equ rl) && (lr equ rr) + case (Pow(ll,lr),Pow(rl,rr)) => (ll equ rl) && (lr == rr) case _ => false } @@ -667,7 +667,7 @@ object MB { Console.println; def check(n: String, f: Expr, x: Int, e: Int) { - val a: Int = f.evaluate(List(Pair("x",x))); + val a: Int = f.evaluate(List(("x",x))); val s: String = if (a == e) "ok" else "KO(" + e + ")"; Console.println(n + "(" + x + ") = " + a + " " + s); } diff --git a/test/files/run/Course-2002-08.scala b/test/files/run/Course-2002-08.scala index 38b8363661..5e21edaba3 100644 --- a/test/files/run/Course-2002-08.scala +++ b/test/files/run/Course-2002-08.scala @@ -163,7 +163,7 @@ object M5 { } abstract class Simulation() { - private type Agenda = List[Pair[Int, Action]]; + private type Agenda = List[Tuple2[Int, Action]]; private var agenda: Agenda = List(); private var curtime = 0; def currentTime: Int = curtime; @@ -171,17 +171,17 @@ object M5 { def afterDelay(delay: Int)(action: Action): Unit = { def insert(ag: Agenda, time: Int): Agenda = ag match { case List() => - List(Pair(time, action)) - case Pair(t, act) :: ag1 => - if (time < t) Pair(time, action) :: ag - else Pair(t, act) :: insert(ag1, time) + List((time, action)) + case (t, act) :: ag1 => + if (time < t) (time, action) :: ag + else (t, act) :: insert(ag1, time) } agenda = insert(agenda, curtime + delay) } private def next: Unit = agenda match { case List() => () - case Pair(time, action) :: ag1 => { + case (time, action) :: ag1 => { agenda = ag1; curtime = time; action(); @@ -413,7 +413,7 @@ object M5 { class Simulator() { type Action = () => Unit; - type Agenda = List[Pair[Int, Action]]; + type Agenda = List[Tuple2[Int, Action]]; private var agenda: Agenda = List(); private var curtime = 0; @@ -421,17 +421,17 @@ class Simulator() { def afterDelay(delay: Int)(action: Action) = { def insert(ag: Agenda, time: Int): Agenda = ag match { case List() => - List(Pair(time, action)) - case Pair(t, act) :: ag1 => - if (time < t) Pair(time, action) :: ag - else Pair(t, act) :: insert(ag1, time) + List((time, action)) + case (t, act) :: ag1 => + if (time < t) (time, action) :: ag + else (t, act) :: insert(ag1, time) } agenda = insert(agenda, curtime + delay) } def next: Unit = agenda match { case List() => () - case Pair(time, action) :: rest => { + case (time, action) :: rest => { agenda = rest; curtime = time; action(); @@ -567,8 +567,8 @@ class Main() extends CircuitSimulator() { demux(in, ctrl.reverse, out.reverse); probe("in", in); - for (Pair(x,c) <- range(0,n) zip ctrl) { probe("ctrl" + x, c) } - for (Pair(x,o) <- range(0,outNum) zip out) { probe("out" + x, o) } + for ((x,c) <- range(0,n) zip ctrl) { probe("ctrl" + x, c) } + for ((x,o) <- range(0,outNum) zip out) { probe("out" + x, o) } in.setSignal(true); run; diff --git a/test/files/run/Course-2002-09.scala b/test/files/run/Course-2002-09.scala index 87f91111d8..704f2ec0aa 100644 --- a/test/files/run/Course-2002-09.scala +++ b/test/files/run/Course-2002-09.scala @@ -13,11 +13,11 @@ object NoConstraint extends Constraint { } class Adder(a1: Quantity,a2: Quantity,sum: Quantity) extends Constraint { - def newValue = Triple(a1.getValue, a2.getValue, sum.getValue) match { - case Triple(Some(x1), Some(x2), _ ) => sum.setValue(x1 + x2, this) - case Triple(Some(x1), _ , Some(r)) => a2.setValue(r - x1, this) - case Triple(_ , Some(x2), Some(r)) => a1.setValue(r - x2, this) - case _ => + def newValue = (a1.getValue, a2.getValue, sum.getValue) match { + case (Some(x1), Some(x2), _ ) => sum.setValue(x1 + x2, this) + case (Some(x1), _ , Some(r)) => a2.setValue(r - x1, this) + case (_ , Some(x2), Some(r)) => a1.setValue(r - x2, this) + case _ => } def dropValue: Unit = { a1.forgetValue(this); a2.forgetValue(this); sum.forgetValue(this); @@ -29,13 +29,13 @@ class Adder(a1: Quantity,a2: Quantity,sum: Quantity) extends Constraint { class Multiplier(m1: Quantity, m2: Quantity, prod: Quantity) extends Constraint { - def newValue = Triple(m1.getValue, m2.getValue, prod.getValue) match { - case Triple(Some(0d), _ , _ ) => prod.setValue(0, this); - case Triple(_ , Some(0d), _ ) => prod.setValue(0, this); - case Triple(Some(x1), Some(x2), _ ) => prod.setValue(x1 * x2, this) - case Triple(Some(x1), _ , Some(r)) => m2.setValue(r / x1, this) - case Triple(_, Some(x2), Some(r)) => m1.setValue(r / x2, this) - case _ => + def newValue = (m1.getValue, m2.getValue, prod.getValue) match { + case (Some(0d), _ , _ ) => prod.setValue(0, this); + case (_ , Some(0d), _ ) => prod.setValue(0, this); + case (Some(x1), Some(x2), _ ) => prod.setValue(x1 * x2, this) + case (Some(x1), _ , Some(r)) => m2.setValue(r / x1, this) + case (_, Some(x2), Some(r)) => m1.setValue(r / x2, this) + case _ => } def dropValue: Unit = { m1.forgetValue(this); m2.forgetValue(this); prod.forgetValue(this); @@ -46,11 +46,11 @@ class Multiplier(m1: Quantity, m2: Quantity, prod: Quantity) } class Squarer(square: Quantity, root: Quantity) extends Constraint { - def newValue: Unit = Pair(square.getValue, root.getValue) match { - case Pair(Some(x), _ )if (x < 0) => sys.error("Square of negative number") - case Pair(Some(x), _ ) => root.setValue(Math.sqrt(x), this) - case Pair(_ , Some(x)) => square.setValue(x*x, this) - case _ => + def newValue: Unit = (square.getValue, root.getValue) match { + case (Some(x), _ )if (x < 0) => sys.error("Square of negative number") + case (Some(x), _ ) => root.setValue(Math.sqrt(x), this) + case (_ , Some(x)) => square.setValue(x*x, this) + case _ => } def dropValue: Unit = { square.forgetValue(this); root.forgetValue(this); @@ -60,9 +60,9 @@ class Squarer(square: Quantity, root: Quantity) extends Constraint { } class Eq(a: Quantity, b: Quantity) extends Constraint { - def newValue = (Pair(a.getValue, b.getValue): @unchecked) match { - case Pair(Some(x), _ ) => b.setValue(x, this); - case Pair(_ , Some(y)) => a.setValue(y, this); + def newValue = ((a.getValue, b.getValue): @unchecked) match { + case (Some(x), _ ) => b.setValue(x, this); + case (_ , Some(y)) => a.setValue(y, this); } def dropValue { a.forgetValue(this); b.forgetValue(this); diff --git a/test/files/run/Course-2002-13.scala b/test/files/run/Course-2002-13.scala index 4bd3614fb0..a596a33873 100644 --- a/test/files/run/Course-2002-13.scala +++ b/test/files/run/Course-2002-13.scala @@ -74,18 +74,18 @@ object Terms { val NoTerm = Con("<none>", List()); - def unify1(x: Term, y: Term, s: Subst): Option[Subst] = Pair(x, y) match { - case Pair(Var(a), Var(b)) if (a == b) => + def unify1(x: Term, y: Term, s: Subst): Option[Subst] = (x, y) match { + case (Var(a), Var(b)) if (a == b) => Some(s) - case Pair(Var(a), _) => lookup(s, a) match { + case (Var(a), _) => lookup(s, a) match { case Some(x1) => unify(x1, y, s) case None => if (y.tyvars contains a) None else Some(Binding(a, y) :: s) } - case Pair(_, Var(b)) => lookup(s, b) match { + case (_, Var(b)) => lookup(s, b) match { case Some(y1) => unify(x, y1, s) case None => if (x.tyvars contains b) None else Some(Binding(b, x) :: s) } - case Pair(Con(a, xs), Con(b, ys)) if (a == b) => + case (Con(a, xs), Con(b, ys)) if (a == b) => unify(xs, ys, s) case _ => None } @@ -96,9 +96,9 @@ object Terms { ss } - def unify(xs: List[Term], ys: List[Term], s: Subst): Option[Subst] = Pair(xs, ys) match { - case Pair(List(), List()) => Some(s) - case Pair(x :: xs1, y :: ys1) => + def unify(xs: List[Term], ys: List[Term], s: Subst): Option[Subst] = (xs, ys) match { + case (List(), List()) => Some(s) + case (x :: xs1, y :: ys1) => unify(x, y, s) match { case Some(s1) => unify(xs1, ys1, s1) case None => None diff --git a/test/files/run/bugs.scala b/test/files/run/bugs.scala index ba8449c299..02849b5817 100644 --- a/test/files/run/bugs.scala +++ b/test/files/run/bugs.scala @@ -46,7 +46,7 @@ object Bug135Test { def test(args: Array[String]) { val myMap:TreeMap[Int, String] = new TreeMap - val map1 = myMap + Pair(42, "The answer") + val map1 = myMap + ((42, "The answer")) println(map1.get(42)) } diff --git a/test/files/run/ctries-old/main.scala b/test/files/run/ctries-old/main.scala index f714bcdcdc..77161fed2f 100644 --- a/test/files/run/ctries-old/main.scala +++ b/test/files/run/ctries-old/main.scala @@ -38,7 +38,7 @@ trait Spec { var produced = false try body catch { - case e: Throwable => if (e.getClass == implicitly[ClassManifest[T]].erasure) produced = true + case e: Throwable => if (e.getClass == implicitly[ClassManifest[T]].runtimeClass) produced = true } finally { assert(produced, "Did not produce exception of type: " + implicitly[ClassManifest[T]]) } diff --git a/test/files/run/delambdafy-dependent-on-param-subst-2.scala b/test/files/run/delambdafy-dependent-on-param-subst-2.scala new file mode 100644 index 0000000000..7b6fc597e8 --- /dev/null +++ b/test/files/run/delambdafy-dependent-on-param-subst-2.scala @@ -0,0 +1,20 @@ +trait M[-X] { + def m(x: X): Boolean +} + +class C +class A { class C } + +object Test { + def main(args: Array[String]) { + val a = new A + + // class O extends M[a.C] { def m(x: a.C) = true } + // (new O: M[Null]).m(null) // Okay + + ((a: A) => { + class N extends M[a.C] { def m(x: a.C) = true } + new N: M[Null] + }).apply(a).m(null) // NPE, missing bridge + } +} diff --git a/test/files/run/delambdafy-dependent-on-param-subst.flags b/test/files/run/delambdafy-dependent-on-param-subst.flags new file mode 100644 index 0000000000..2b27e19830 --- /dev/null +++ b/test/files/run/delambdafy-dependent-on-param-subst.flags @@ -0,0 +1 @@ +-Ydelambdafy:method
\ No newline at end of file diff --git a/test/files/run/delambdafy-dependent-on-param-subst.scala b/test/files/run/delambdafy-dependent-on-param-subst.scala new file mode 100644 index 0000000000..7b6fc597e8 --- /dev/null +++ b/test/files/run/delambdafy-dependent-on-param-subst.scala @@ -0,0 +1,20 @@ +trait M[-X] { + def m(x: X): Boolean +} + +class C +class A { class C } + +object Test { + def main(args: Array[String]) { + val a = new A + + // class O extends M[a.C] { def m(x: a.C) = true } + // (new O: M[Null]).m(null) // Okay + + ((a: A) => { + class N extends M[a.C] { def m(x: a.C) = true } + new N: M[Null] + }).apply(a).m(null) // NPE, missing bridge + } +} diff --git a/test/files/run/dynamic-applyDynamic.check b/test/files/run/dynamic-applyDynamic.check new file mode 100644 index 0000000000..ae6996f8fc --- /dev/null +++ b/test/files/run/dynamic-applyDynamic.check @@ -0,0 +1,14 @@ +[[syntax trees at end of typer]] // newSource1.scala +[0:67]package [0:0]<empty> { + [0:67]object X extends [9:67][67]scala.AnyRef { + [67]def <init>(): [9]X.type = [67]{ + [67][67][67]X.super.<init>(); + [9]() + }; + [17:30]private[this] val d: [21]D = [25:30][25:30][25:30]new [29:30]D(); + [21]<stable> <accessor> def d: [21]D = [21][21]X.this.d; + [37:49][37:38][37:38][37]X.this.d.applyDynamic(<39:45>"method")([46:48]10); + [56:61]<56:57><56:57>[56]X.this.d.applyDynamic(<56:57>"apply")([58:60]10) + } +} + diff --git a/test/files/run/dynamic-applyDynamic.scala b/test/files/run/dynamic-applyDynamic.scala new file mode 100644 index 0000000000..b06041194c --- /dev/null +++ b/test/files/run/dynamic-applyDynamic.scala @@ -0,0 +1,26 @@ +import scala.tools.partest.DirectTest + +object Test extends DirectTest { + + override def extraSettings: String = + s"-usejavacp -Xprint-pos -Xprint:typer -Yrangepos -Ystop-after:typer -d ${testOutput.path}" + + override def code = """ + object X { + val d = new D + d.method(10) + d(10) + } + """.trim + + override def show(): Unit = { + Console.withErr(System.out) { + compile() + } + } +} + +import language.dynamics +class D extends Dynamic { + def applyDynamic(name: String)(value: Any) = ??? +}
\ No newline at end of file diff --git a/test/files/run/dynamic-applyDynamicNamed.check b/test/files/run/dynamic-applyDynamicNamed.check new file mode 100644 index 0000000000..c4e050ba17 --- /dev/null +++ b/test/files/run/dynamic-applyDynamicNamed.check @@ -0,0 +1,14 @@ +[[syntax trees at end of typer]] // newSource1.scala +[0:97]package [0:0]<empty> { + [0:97]object X extends [9:97][97]scala.AnyRef { + [97]def <init>(): [9]X.type = [97]{ + [97][97][97]X.super.<init>(); + [9]() + }; + [17:30]private[this] val d: [21]D = [25:30][25:30][25:30]new [29:30]D(); + [21]<stable> <accessor> def d: [21]D = [21][21]X.this.d; + [37:70][37:38][37:38][37]X.this.d.applyDynamicNamed(<39:43>"meth")([44:55][44][44]scala.Tuple2.apply[[44]String, [44]Int]([44:50]"value1", [53:55]10), [57:69][57][57]scala.Tuple2.apply[[57]String, [57]Int]([57:63]"value2", [66:69]100)); + [77:91]<77:78><77:78>[77]X.this.d.applyDynamicNamed(<77:78>"apply")([79:90][79][79]scala.Tuple2.apply[[79]String, [79]Int]([79:85]"value1", [88:90]10)) + } +} + diff --git a/test/files/run/dynamic-applyDynamicNamed.scala b/test/files/run/dynamic-applyDynamicNamed.scala new file mode 100644 index 0000000000..cc59f9058b --- /dev/null +++ b/test/files/run/dynamic-applyDynamicNamed.scala @@ -0,0 +1,26 @@ +import scala.tools.partest.DirectTest + +object Test extends DirectTest { + + override def extraSettings: String = + s"-usejavacp -Xprint-pos -Xprint:typer -Yrangepos -Ystop-after:typer -d ${testOutput.path}" + + override def code = """ + object X { + val d = new D + d.meth(value1 = 10, value2 = 100) + d(value1 = 10) + } + """.trim + + override def show(): Unit = { + Console.withErr(System.out) { + compile() + } + } +} + +import language.dynamics +class D extends Dynamic { + def applyDynamicNamed(name: String)(value: (String, Any)*) = ??? +} diff --git a/test/files/run/dynamic-selectDynamic.check b/test/files/run/dynamic-selectDynamic.check new file mode 100644 index 0000000000..9635ca4e6f --- /dev/null +++ b/test/files/run/dynamic-selectDynamic.check @@ -0,0 +1,13 @@ +[[syntax trees at end of typer]] // newSource1.scala +[0:50]package [0:0]<empty> { + [0:50]object X extends [9:50][50]scala.AnyRef { + [50]def <init>(): [9]X.type = [50]{ + [50][50][50]X.super.<init>(); + [9]() + }; + [17:30]private[this] val d: [21]D = [25:30][25:30][25:30]new [29:30]D(); + [21]<stable> <accessor> def d: [21]D = [21][21]X.this.d; + [37:38][37:38][37]X.this.d.selectDynamic(<39:44>"field") + } +} + diff --git a/test/files/run/dynamic-selectDynamic.scala b/test/files/run/dynamic-selectDynamic.scala new file mode 100644 index 0000000000..bd6c138c50 --- /dev/null +++ b/test/files/run/dynamic-selectDynamic.scala @@ -0,0 +1,25 @@ +import scala.tools.partest.DirectTest + +object Test extends DirectTest { + + override def extraSettings: String = + s"-usejavacp -Xprint-pos -Xprint:typer -Yrangepos -Ystop-after:typer -d ${testOutput.path}" + + override def code = """ + object X { + val d = new D + d.field + } + """.trim + + override def show(): Unit = { + Console.withErr(System.out) { + compile() + } + } +} + +import language.dynamics +class D extends Dynamic { + def selectDynamic(name: String) = ??? +} diff --git a/test/files/run/dynamic-updateDynamic.check b/test/files/run/dynamic-updateDynamic.check new file mode 100644 index 0000000000..154fea34cb --- /dev/null +++ b/test/files/run/dynamic-updateDynamic.check @@ -0,0 +1,14 @@ +[[syntax trees at end of typer]] // newSource1.scala +[0:69]package [0:0]<empty> { + [0:69]object X extends [9:69][69]scala.AnyRef { + [69]def <init>(): [9]X.type = [69]{ + [69][69][69]X.super.<init>(); + [9]() + }; + [17:30]private[this] val d: [21]D = [25:30][25:30][25:30]new [29:30]D(); + [21]<stable> <accessor> def d: [21]D = [21][21]X.this.d; + [37:49][37:38][37:38][37]X.this.d.updateDynamic(<39:44>"field")([47:49]10); + [56:57][56:57][56]X.this.d.selectDynamic(<58:63>"field") + } +} + diff --git a/test/files/run/dynamic-updateDynamic.scala b/test/files/run/dynamic-updateDynamic.scala new file mode 100644 index 0000000000..80fe0ea35f --- /dev/null +++ b/test/files/run/dynamic-updateDynamic.scala @@ -0,0 +1,28 @@ +import scala.tools.partest.DirectTest + +object Test extends DirectTest { + + override def extraSettings: String = + s"-usejavacp -Xprint-pos -Xprint:typer -Yrangepos -Ystop-after:typer -d ${testOutput.path}" + + override def code = """ + object X { + val d = new D + d.field = 10 + d.field + } + """.trim + + override def show(): Unit = { + Console.withErr(System.out) { + compile() + } + } +} + +import language.dynamics +class D extends Dynamic { + def selectDynamic(name: String): Any = ??? + def updateDynamic(name: String)(value: Any): Unit = ??? +} + diff --git a/test/files/run/getClassTest-old.scala b/test/files/run/getClassTest-old.scala index 789dd4d162..cd1b6b07f6 100644 --- a/test/files/run/getClassTest-old.scala +++ b/test/files/run/getClassTest-old.scala @@ -53,7 +53,7 @@ class MoreAnyRefs { @deprecated("Suppress warnings", since="2.11") object Test { def returnTypes[T: Manifest] = ( - manifest[T].erasure.getMethods.toList + manifest[T].runtimeClass.getMethods.toList filter (_.getName startsWith "f") sortBy (_.getName) map (m => m.getName + ": " + m.getGenericReturnType.toString) diff --git a/test/files/run/macro-system-properties.check b/test/files/run/macro-system-properties.check index b102d319ec..ea4c5a664a 100644 --- a/test/files/run/macro-system-properties.check +++ b/test/files/run/macro-system-properties.check @@ -14,15 +14,9 @@ scala> object GrabContext { defined object GrabContext scala> object Test { class C(implicit a: Any) { GrabContext.grab } } -<console>:12: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses - object Test { class C(implicit a: Any) { GrabContext.grab } } - ^ defined object Test scala> object Test { class C(implicit a: Any) { GrabContext.grab } } -<console>:12: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses - object Test { class C(implicit a: Any) { GrabContext.grab } } - ^ defined object Test scala> diff --git a/test/files/run/map_test.scala b/test/files/run/map_test.scala index 1ea864ed58..b76dfb4577 100644 --- a/test/files/run/map_test.scala +++ b/test/files/run/map_test.scala @@ -20,7 +20,7 @@ object Test extends App { val map2 = map1.updated(17,"A small random number") val map3 = map2.updated(666,"A bigger random number") val map4 = map3.updated(4711,"A big random number") - map1 == myMap + Pair(42, "The answer") + map1 == myMap + ((42, "The answer")) var i = 0 var map = map4 while(i < 43) { diff --git a/test/files/run/patmatnew.scala b/test/files/run/patmatnew.scala index b212e10f8d..3c0d00dc6c 100644 --- a/test/files/run/patmatnew.scala +++ b/test/files/run/patmatnew.scala @@ -46,7 +46,7 @@ object Test { object SimpleUnapply { def run() { // from sortedmap, old version List((1, 2)).head match { - case kv@Pair(key, _) => kv.toString + " " + key.toString + case kv@(key, _) => kv.toString + " " + key.toString } } @@ -400,9 +400,9 @@ object Test { // these are exhaustive matches // should not generate any warnings def f[A](z: (Option[A], Option[A])) = z match { - case Pair(None, Some(x)) => 1 - case Pair(Some(x), None) => 2 - case Pair(Some(x), Some(y)) => 3 + case (None, Some(x)) => 1 + case (Some(x), None) => 2 + case (Some(x), Some(y)) => 3 case _ => 4 } @@ -419,9 +419,9 @@ object Test { } def h[A](x: (Option[A], Option[A])) = x match { - case Pair(None, _: Some[_]) => 1 - case Pair(_: Some[_], None) => 2 - case Pair(_: Some[_], _: Some[_]) => 3 + case (None, _: Some[_]) => 1 + case (_: Some[_], None) => 2 + case (_: Some[_], _: Some[_]) => 3 case _ => 4 } @@ -539,17 +539,17 @@ object Test { case class Operator(x: Int); val EQ = new Operator(2); - def analyze(x: Pair[Operator, Int]) = x match { - case Pair(EQ, 0) => "0" - case Pair(EQ, 1) => "1" - case Pair(EQ, 2) => "2" + def analyze(x: Tuple2[Operator, Int]) = x match { + case (EQ, 0) => "0" + case (EQ, 1) => "1" + case (EQ, 2) => "2" } def run() { - val x = Pair(EQ, 0); + val x = (EQ, 0); assertEquals("0", analyze(x)); // should print "0" - val y = Pair(EQ, 1); + val y = (EQ, 1); assertEquals("1", analyze(y)); // should print "1" - val z = Pair(EQ, 2); + val z = (EQ, 2); assertEquals("2", analyze(z)); // should print "2" } } diff --git a/test/files/run/t3888.scala b/test/files/run/t3888.scala index 19771041fc..8701b42ff0 100644 --- a/test/files/run/t3888.scala +++ b/test/files/run/t3888.scala @@ -24,6 +24,6 @@ object Test { } } -class P extends Pair(1, 1) { +class P extends Tuple2(1, 1) { override def equals(x: Any) = true } diff --git a/test/files/run/t4332.check b/test/files/run/t4332.check new file mode 100644 index 0000000000..ff9d9b8647 --- /dev/null +++ b/test/files/run/t4332.check @@ -0,0 +1,25 @@ + +====================================================================== +Checking scala.collection.TraversableView +====================================================================== + + +====================================================================== +Checking scala.collection.IterableView +====================================================================== + + +====================================================================== +Checking scala.collection.SeqView +====================================================================== + + +====================================================================== +Checking scala.collection.mutable.IndexedSeqView +====================================================================== + + +====================================================================== +Checking scala.collection.immutable.StreamView +====================================================================== + diff --git a/test/files/run/t4332.scala b/test/files/run/t4332.scala new file mode 100644 index 0000000000..5a67922911 --- /dev/null +++ b/test/files/run/t4332.scala @@ -0,0 +1,44 @@ +import scala.tools.partest._ + +object Test extends DirectTest { + override def code = "" + lazy val global = newCompiler("-usejavacp") + import global._, definitions._ + + override def show() { + new global.Run() + // Once we plug all of the view gaps, the output should be empty! + checkViews() + } + + def isExempt(sym: Symbol) = { + val exempt = Set("view", "repr", "sliceWithKnownDelta", "sliceWithKnownBound", "transform") + (exempt contains sym.name.decoded) + } + + def checkView(viewType: Type, viewLikeType: Type) { + val sep = "=" * 70 + println(s"\n$sep\nChecking ${viewType.typeSymbol.fullName}\n$sep") + val termMembers = viewType.nonPrivateMembers.toList filter (_.isTerm) map fullyInitializeSymbol + val inheritedFromGenericCollection + = termMembers filterNot (_.owner.name.decoded contains "ViewLike") filterNot (_.owner == viewType.typeSymbol) + def returnsView(sym: Symbol) = viewType.memberType(sym).finalResultType contains viewType.typeSymbol + val needOverride = inheritedFromGenericCollection filterNot isExempt filter returnsView + + val grouped = needOverride.groupBy(_.owner).toSeq.sortBy { case (owner, _) => viewType baseTypeIndex owner } + val report = grouped.map { + case (owner, syms) => s"\n$owner\n${"-" * 70}\n${syms.map(_.defString).sorted.mkString("\n")}" + }.mkString("\n") + println(report) + } + + def checkViews() { + import collection._ + checkView(typeOf[TraversableView[_, _]], typeOf[TraversableViewLike[_, _, _]]) + checkView(typeOf[IterableView[_, _]], typeOf[IterableViewLike[_, _, _]]) + checkView(typeOf[SeqView[_, _]], typeOf[SeqViewLike[_, _, _]]) + checkView(typeOf[mutable.IndexedSeqView[_, _]], typeOf[SeqViewLike[_, _, _]]) + checkView(typeOf[immutable.StreamView[_, _]], typeOf[immutable.StreamViewLike[_, _, _]]) + // Parallel views not checked, assuming we will drop them in 2.11 + } +} diff --git a/test/files/run/t4332b.scala b/test/files/run/t4332b.scala new file mode 100644 index 0000000000..8ee069ca2d --- /dev/null +++ b/test/files/run/t4332b.scala @@ -0,0 +1,35 @@ +object Test extends App { + def check(expected: Any, actual: Any, msg: String = "") = { + if (expected != actual) + sys.error(s"($actual != $expected) $msg") + } + val ls = List(1, 3, 2, 1) + for (N <- -1 to (ls.length + 1)) { + check(ls.takeRight(N), ls.view.takeRight(N).toList, s"takeRight($N)") + check(ls.dropRight(N), ls.view.dropRight(N).toList, s"dropRight($N)") + } + for (N <- 1 to (ls.length + 1)) { + check(ls.sliding(N).toList, ls.view.sliding(N).toList.map(_.toList), s"sliding($N)") + check(ls.sliding(N, 2).toList, ls.view.sliding(N, 2).toList.map(_.toList), s"sliding($N, 2)") + } + for (b <- List(true, false)) + check(ls.filterNot(x => true), ls.view.filterNot(x => true), s"filterNot($b)") + + check(ls.inits.toList, ls.view.inits.toList.map(_.toList), "inits") + check(ls.tails.toList, ls.view.tails.toList.map(_.toList), "tails") + + check(ls.combinations(2).toList.map(_.toList), ls.view.combinations(2).toList.map(_.toList), "combinations(2)") + check(ls.permutations.toList.map(_.toList), ls.view.permutations.toList.map(_.toList), "permutations") + + check(ls.sortBy(_ * -1), ls.view.sortBy(_ * -1).toList, "sortBy") + check(ls.sortWith((x, y) => y < x), ls.view.sortWith((x, y) => y < x).toList, "sortWith") + check(ls.sorted, ls.view.sorted.toList, "sorted") + + check(ls.distinct, ls.view.distinct.toList, "distinct") + + check(ls.tail, ls.view.tail.toList, "tail") + + import collection.mutable.Buffer + check(Buffer(1, 2, 3).tail, Buffer(1, 2, 3).view.tail.toList, "Buffer#tail") + check(Buffer(1, 2, 3).tail.length, Buffer(1, 2, 3).view.tail.length, "Buffer#tail#length") +} diff --git a/test/files/run/t6329_repl_bug.check b/test/files/run/t6329_repl_bug.check new file mode 100644 index 0000000000..44c41cfd03 --- /dev/null +++ b/test/files/run/t6329_repl_bug.check @@ -0,0 +1,17 @@ +Type in expressions to have them evaluated. +Type :help for more information. + +scala> import scala.reflect.runtime.universe._ +import scala.reflect.runtime.universe._ + +scala> import scala.reflect.runtime._ +import scala.reflect.runtime._ + +scala> classManifest[List[_]] +warning: there were 1 deprecation warning(s); re-run with -deprecation for details +res0: scala.reflect.ClassTag[List[_]] = scala.collection.immutable.List[<?>] + +scala> scala.reflect.classTag[List[_]] +res1: scala.reflect.ClassTag[List[_]] = scala.collection.immutable.List + +scala> diff --git a/test/files/run/t6329_repl_bug.pending b/test/files/run/t6329_repl_bug.scala index 9997d1771e..9997d1771e 100644 --- a/test/files/run/t6329_repl_bug.pending +++ b/test/files/run/t6329_repl_bug.scala diff --git a/test/files/run/t6329_vanilla_bug.check b/test/files/run/t6329_vanilla_bug.check new file mode 100644 index 0000000000..640d168a8a --- /dev/null +++ b/test/files/run/t6329_vanilla_bug.check @@ -0,0 +1,3 @@ +warning: there were 1 deprecation warning(s); re-run with -deprecation for details +scala.collection.immutable.List[<?>] +scala.collection.immutable.List diff --git a/test/files/run/t6329_vanilla_bug.pending b/test/files/run/t6329_vanilla_bug.scala index 404f90bf6e..404f90bf6e 100644 --- a/test/files/run/t6329_vanilla_bug.pending +++ b/test/files/run/t6329_vanilla_bug.scala diff --git a/test/files/run/t7985.scala b/test/files/run/t7985.scala new file mode 100644 index 0000000000..5fe270f9c0 --- /dev/null +++ b/test/files/run/t7985.scala @@ -0,0 +1,3 @@ +object Test extends App { + Array(1) match { case _: Array[scala.Int] => } +} diff --git a/test/files/run/t7985b.scala b/test/files/run/t7985b.scala new file mode 100644 index 0000000000..aaf649eb28 --- /dev/null +++ b/test/files/run/t7985b.scala @@ -0,0 +1,5 @@ +class a { type X = Int } + +object Test extends App { + Array(1) match { case _: Array[a#X] => } +} diff --git a/test/files/run/t8002.scala b/test/files/run/t8002.scala new file mode 100644 index 0000000000..f24a213dea --- /dev/null +++ b/test/files/run/t8002.scala @@ -0,0 +1,19 @@ +object Test extends App { + val a: Any = { + class A private () { private def x = 0; A.y }; + object A { + def a = new A().x + private def y = 0 + } + A.a + } + def b: Any = { + object A { + def a = new A().x + private def y = 0 + } + class A private () { private def x = 0; A.y }; + A.a + } + b +} diff --git a/test/files/run/tailcalls.scala b/test/files/run/tailcalls.scala index e5d8891cc7..1653b14de9 100644 --- a/test/files/run/tailcalls.scala +++ b/test/files/run/tailcalls.scala @@ -169,7 +169,7 @@ class TailCall[S](s: S) { aux[T](x, y); } final def g3[T](x: Int, y: Int, zs: List[T]): Int = { - def aux[U](n: Int, v: Int, ls: List[Pair[T,U]]): Int = + def aux[U](n: Int, v: Int, ls: List[Tuple2[T,U]]): Int = if (n == 0) v else aux(n - 1, v - 1, ls); aux(x, y, Nil); } diff --git a/test/files/run/tcpoly_parseridioms.check b/test/files/run/tcpoly_parseridioms.check index ab829e0a0e..8bd0a086d6 100644 --- a/test/files/run/tcpoly_parseridioms.check +++ b/test/files/run/tcpoly_parseridioms.check @@ -4,8 +4,8 @@ It would fail on the following input: ParseResult() ^ tcpoly_parseridioms.scala:17: warning: match may not be exhaustive. It would fail on the following input: ParseResult() - def apply(in: Input): ParseResult[Pair[T, U]] = a(in) match { - ^ + def apply(in: Input): ParseResult[Tuple2[T, U]] = a(in) match { + ^ tcpoly_parseridioms.scala:30: warning: match may not be exhaustive. It would fail on the following input: ParseResult() case Failure(_, _) => b(in) match { diff --git a/test/files/run/tcpoly_parseridioms.scala b/test/files/run/tcpoly_parseridioms.scala index c8bcf693a1..d22f68b558 100644 --- a/test/files/run/tcpoly_parseridioms.scala +++ b/test/files/run/tcpoly_parseridioms.scala @@ -13,10 +13,10 @@ trait Parsers { } // sequence - def sq[T, U](a: => Parser[T], b: => Parser[U]): Parser[Pair[T, U]] = new Parser[Pair[T, U]] { - def apply(in: Input): ParseResult[Pair[T, U]] = a(in) match { + def sq[T, U](a: => Parser[T], b: => Parser[U]): Parser[Tuple2[T, U]] = new Parser[Tuple2[T, U]] { + def apply(in: Input): ParseResult[Tuple2[T, U]] = a(in) match { case Success(next, x) => b(next) match { - case Success(next2, y) => Success(next2, Pair(x,y)) + case Success(next2, y) => Success(next2, (x,y)) case Failure(_, msg) => Failure(in, msg) } case Failure(_, msg) => Failure(in, msg) @@ -49,7 +49,7 @@ trait Parsers { } } - def apply_++[s, tt](fun: Parser[s => tt], arg: Parser[s]): Parser[tt] = lift[Pair[s=>tt, s], tt]({case Pair(f, a) => f(a)})(sq(fun, arg)) + def apply_++[s, tt](fun: Parser[s => tt], arg: Parser[s]): Parser[tt] = lift[Tuple2[s=>tt, s], tt]({case (f, a) => f(a)})(sq(fun, arg)) def success[u](v: u): Parser[u] = new Parser[u] { def apply(in: Input) = Success(in, v) diff --git a/test/files/run/value-class-partial-func-depmet.scala b/test/files/run/value-class-partial-func-depmet.scala new file mode 100644 index 0000000000..12ff64ed36 --- /dev/null +++ b/test/files/run/value-class-partial-func-depmet.scala @@ -0,0 +1,24 @@ +class C +class A { class C } + +object Test { + def main(args: Array[String]) { + val a = new A + + new VC("").foo(a) + } +} + +class VC(val a: Any) extends AnyVal { + def foo(a: A) = { + val pf: PartialFunction[a.C, Any] = { case x => x } + (pf: PartialFunction[Null, Any]).isDefinedAt(null) + } +} + +// 2.11.0-M6 +// test/files/run/value-class-partial-func-depmet.scala:14: error: overriding method applyOrElse in trait PartialFunction of type [A1 <: a.C, B1 >: Any](x: A1, default: A1 => B1)B1; +// method applyOrElse has incompatible type +// val pf: PartialFunction[a.C, Any] = { case x => x } +// ^ +// one error found diff --git a/test/files/run/withIndex.scala b/test/files/run/withIndex.scala index 910b1f1f9e..ebf1941c95 100644 --- a/test/files/run/withIndex.scala +++ b/test/files/run/withIndex.scala @@ -11,7 +11,7 @@ object Test { Console.println(str.zipWithIndex.toList) assert { ary.zipWithIndex match { - case _: Array[Pair[_,_]] => true + case _: Array[Tuple2[_,_]] => true case _ => false } } diff --git a/test/files/scalacheck/CheckCollections.scala b/test/files/scalacheck/CheckCollections.scala index 108040b900..329d505b47 100644 --- a/test/files/scalacheck/CheckCollections.scala +++ b/test/files/scalacheck/CheckCollections.scala @@ -1,4 +1,4 @@ -import org.scalacheck.{ ConsoleReporter, Properties } +import org.scalacheck.Properties import org.scalacheck.Prop._ import scala.reflect.internal.util.Collections._ @@ -49,11 +49,4 @@ object Test extends Properties("reflect.internal.util.Collections") { for { (label, prop) <- tests } property(label) = prop - - import org.scalacheck.{ Test => STest } - - def runTests() = - STest.checkProperties( - STest.Params(testCallback = ConsoleReporter(0)), this) - } diff --git a/test/files/scalacheck/CheckEither.scala b/test/files/scalacheck/CheckEither.scala index 4d0cab4693..48f732a22d 100644 --- a/test/files/scalacheck/CheckEither.scala +++ b/test/files/scalacheck/CheckEither.scala @@ -1,10 +1,8 @@ -import org.scalacheck.{ Arbitrary, ConsoleReporter, Prop, Properties } +import org.scalacheck.{ Arbitrary, Prop, Properties } import org.scalacheck.Arbitrary.{arbitrary, arbThrowable} import org.scalacheck.Gen.oneOf -import org.scalacheck.util.StdRand import org.scalacheck.Prop._ -import org.scalacheck.Test.{Params, check} -import org.scalacheck.ConsoleReporter.testStatsEx +import org.scalacheck.Test.check import Function.tupled object Test extends Properties("Either") { @@ -178,10 +176,4 @@ object Test extends Properties("Either") { for ((label, prop) <- tests) { property(label) = prop } - - import org.scalacheck.{ Test => STest } - - def runTests() = { - STest.checkProperties(STest.Params(testCallback = ConsoleReporter(0)), this) - } } diff --git a/test/files/scalacheck/array-new.scala b/test/files/scalacheck/array-new.scala index e13a47a5d5..d8c69ead78 100644 --- a/test/files/scalacheck/array-new.scala +++ b/test/files/scalacheck/array-new.scala @@ -1,4 +1,4 @@ -import scala.reflect.{ClassTag, classTag} +import scala.reflect.ClassTag // new style: use ClassTag import org.scalacheck._ import Prop._ import Gen._ diff --git a/test/files/scalacheck/quasiquotes/ArbitraryTreesAndNames.scala b/test/files/scalacheck/quasiquotes/ArbitraryTreesAndNames.scala index c4b93dae48..7905a2ca15 100644 --- a/test/files/scalacheck/quasiquotes/ArbitraryTreesAndNames.scala +++ b/test/files/scalacheck/quasiquotes/ArbitraryTreesAndNames.scala @@ -222,7 +222,7 @@ trait ArbitraryTreesAndNames { yield ValDef(mods, name, tpt, rhs) def genTree(size: Int): Gen[Tree] = - if (size <= 1) oneOf(EmptyTree, genTreeIsTerm(size), genTreeIsType(size)) + if (size <= 1) oneOf(EmptyTree: Gen[Tree], genTreeIsTerm(size), genTreeIsType(size)) else oneOf(genTree(1), // these trees are neither terms nor types genPackageDef(size - 1), genModuleDef(size - 1), @@ -273,8 +273,8 @@ trait ArbitraryTreesAndNames { def apply(universe: Universe, value: TreeIsType): universe.Tree = value.tree.asInstanceOf[universe.Tree] } - implicit def treeIsTerm2tree(tit: TreeIsTerm) = tit.tree - implicit def treeIsType2tree(tit: TreeIsType) = tit.tree + implicit def treeIsTerm2tree(tit: TreeIsTerm): Tree = tit.tree + implicit def treeIsType2tree(tit: TreeIsType): Tree = tit.tree implicit val arbConstant: Arbitrary[Constant] = Arbitrary(genConstant) implicit val arbModifiers: Arbitrary[Modifiers] = Arbitrary(genModifiers) diff --git a/test/files/scalacheck/quasiquotes/QuasiquoteProperties.scala b/test/files/scalacheck/quasiquotes/QuasiquoteProperties.scala index b2bce124ee..b331c4b6b6 100644 --- a/test/files/scalacheck/quasiquotes/QuasiquoteProperties.scala +++ b/test/files/scalacheck/quasiquotes/QuasiquoteProperties.scala @@ -18,13 +18,12 @@ trait Helpers { object simplify extends Transformer { object SimplifiedName { - def unapply[T <: Name](name: T): Option[T] = - name.toString.split("\\$").toSeq match { - case first :+ last if scala.util.Try(last.toInt).isSuccess && first.nonEmpty => - val value = first.mkString("", "$", "$") - Some((if (name.isTermName) TermName(value) else TypeName(value)).asInstanceOf[T]) - case _ => None - } + val st = scala.reflect.runtime.universe.asInstanceOf[scala.reflect.internal.SymbolTable] + val FreshName = new st.FreshNameExtractor + def unapply[T <: Name](name: T): Option[T] = name.asInstanceOf[st.Name] match { + case FreshName(prefix) => + Some((if (name.isTermName) TermName(prefix) else TypeName(prefix)).asInstanceOf[T]) + } } override def transform(tree: Tree): Tree = tree match { @@ -59,7 +58,7 @@ trait Helpers { } def assertThrows[T <: AnyRef](f: => Any)(implicit manifest: Manifest[T]): Unit = { - val clazz = manifest.erasure.asInstanceOf[Class[T]] + val clazz = manifest.runtimeClass.asInstanceOf[Class[T]] val thrown = try { f diff --git a/test/files/scalacheck/si4147.scala b/test/files/scalacheck/si4147.scala index 05507b1b18..72f6e9afd5 100644 --- a/test/files/scalacheck/si4147.scala +++ b/test/files/scalacheck/si4147.scala @@ -1,8 +1,6 @@ import org.scalacheck.Prop.{forAll, throws} import org.scalacheck.Properties -import org.scalacheck.ConsoleReporter.testStatsEx import org.scalacheck.Gen -import org.scalacheck.ConsoleReporter import collection.mutable @@ -66,5 +64,5 @@ object Test extends Properties("Mutable TreeSet") { } property("ordering must not be null") = - throws(mutable.TreeSet.empty[Int](null), classOf[NullPointerException]) + throws(classOf[NullPointerException])(mutable.TreeSet.empty[Int](null)) } diff --git a/test/files/scalacheck/t2460.scala b/test/files/scalacheck/t2460.scala index 196b43789f..ab2911447a 100644 --- a/test/files/scalacheck/t2460.scala +++ b/test/files/scalacheck/t2460.scala @@ -1,6 +1,5 @@ import org.scalacheck.Prop.forAll import org.scalacheck.Properties -import org.scalacheck.ConsoleReporter.testStatsEx import org.scalacheck.{Test => SCTest} import org.scalacheck.Gen @@ -25,8 +24,4 @@ object Test extends Properties("Regex : Ticket 2460") { ("numberOfGroup", numberOfGroup), ("nameOfGroup", nameOfGroup) ) - - /*tests foreach { - case (name, p) => testStatsEx(name, SCTest.check(p)) - }*/ } diff --git a/test/files/scalacheck/treeset.scala b/test/files/scalacheck/treeset.scala index 7fca3ed5e4..4b9b77dd7e 100644 --- a/test/files/scalacheck/treeset.scala +++ b/test/files/scalacheck/treeset.scala @@ -151,5 +151,5 @@ object Test extends Properties("TreeSet") { } property("ordering must not be null") = - throws(TreeSet.empty[Int](null), classOf[NullPointerException]) + throws(classOf[NullPointerException])(TreeSet.empty[Int](null)) } diff --git a/test/junit/scala/collection/VectorTest.scala b/test/junit/scala/collection/VectorTest.scala new file mode 100644 index 0000000000..e9c4d44a72 --- /dev/null +++ b/test/junit/scala/collection/VectorTest.scala @@ -0,0 +1,51 @@ +package scala.collection.mutable + +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import org.junit.Test +import scala.collection.mutable + +@RunWith(classOf[JUnit4]) +/* Test for SI-8014 and ++ in general */ +class VectorTest { + val noVec = Vector.empty[Int] + val smallVec = Vector.range(0,3) + val bigVec = Vector.range(0,64) + val smsm = Vector.tabulate(2 * smallVec.length)(i => (i % smallVec.length)) + val smbig = Vector.tabulate(smallVec.length + bigVec.length)(i => + if (i < smallVec.length) i else i - smallVec.length + ) + val bigsm = Vector.tabulate(smallVec.length + bigVec.length)(i => + if (i < bigVec.length) i else i - bigVec.length + ) + val bigbig = Vector.tabulate(2 * bigVec.length)(i => (i % bigVec.length)) + + + val vecs = List(noVec, smallVec, bigVec) + val ans = List( + vecs, + List(smallVec, smsm, smbig), + List(bigVec, bigsm, bigbig) + ) + + @Test + def vectorCat() { + val cats = vecs.map(a => vecs.map(a ++ _)) + assert( cats == ans ) + } + + @Test + def iteratorCat() { + def its = vecs.map(_.toList.toIterator) + val cats = vecs.map(a => its.map(a ++ _)) + println(cats) + assert( cats == ans ) + } + + @Test + def arrayCat() { + val ars = vecs.map(_.toArray) + val cats = vecs.map(a => ars.map(a ++ _)) + assert( cats == ans ) + } +} diff --git a/test/junit/scala/tools/nsc/interpreter/TabulatorTest.scala b/test/junit/scala/tools/nsc/interpreter/TabulatorTest.scala new file mode 100644 index 0000000000..21e338eac0 --- /dev/null +++ b/test/junit/scala/tools/nsc/interpreter/TabulatorTest.scala @@ -0,0 +1,85 @@ +package scala.tools.nsc +package interpreter + +//import org.junit.Assert._ +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +case class Tabby(width: Int = 80, isAcross: Boolean = false, marginSize: Int = 3) extends Tabulator +case class VTabby(width: Int = 80, isAcross: Boolean = false, marginSize: Int = 3) extends VariColumnTabulator + +@RunWith(classOf[JUnit4]) +class TabulatorTest { + + @Test def oneliner() = { + val sut = Tabby() + val items = List("a", "b", "c") + val res = sut tabulate items + assert(res.size == 1) + assert(res(0).size == 1) + assert(res(0)(0) startsWith "a") + assert(res(0)(0) endsWith "c") + } + @Test def twoliner() = { + val sut = Tabby(width = 40) + val items = List("a" * 15, "b" * 15, "c" * 15) + val res = sut tabulate items + assert(res.size == 2) + assert(res(0).size == 2) + assert(res(1).size == 2) // trailing empty strings + assert(res(1)(0) startsWith "b") + } + @Test def twolinerx() = { + val sut = Tabby(width = 40, isAcross = true) + val items = List("a" * 15, "b" * 15, "c" * 15) + val res = sut tabulate items + assert(res.size == 2) + assert(res(0).size == 2) + assert(res(1).size == 1) // no trailing empty strings + assert(res(1)(0) startsWith "c") + } + // before, two 9-width cols don't fit in 20 + // but now, 5-col and 9-col do fit. + @Test def twolinerVariable() = { + val sut = VTabby(width = 20) + val items = (1 to 9) map (i => i.toString * i) + val rows = sut tabulate items + assert(rows.size == 5) + assert(rows(0).size == 2) + assert(rows(0)(0).size == 8) // width is 55555 plus margin of 3 + } + @Test def sys() = { + val sut = VTabby(width = 40) + val items = List("BooleanProp", "PropImpl", "addShutdownHook", "error", + "process", "CreatorImpl", "ShutdownHookThread", "allThreads", + "exit", "props", "Prop", "SystemProperties", + "env", "package", "runtime") + val rows = sut tabulate items + assert(rows.size == 8) + assert(rows(0).size == 2) + assert(rows(0)(0).size == "ShutdownHookThread".length + sut.marginSize) // 21 + } + @Test def syswide() = { + val sut = VTabby(width = 120) + val items = List("BooleanProp", "PropImpl", "addShutdownHook", "error", + "process", "CreatorImpl", "ShutdownHookThread", "allThreads", + "exit", "props", "Prop", "SystemProperties", + "env", "package", "runtime") + val rows = sut tabulate items + assert(rows.size == 2) + assert(rows(0).size == 8) + assert(rows(0)(0).size == "BooleanProp".length + sut.marginSize) // 14 + } + @Test def resultFits() = { + val sut = VTabby(width = 10) + // each of two lines would fit, but layout is two cols of width six > 10 + // therefore, should choose ncols = 1 + val items = List("a", "bcd", + "efg", "h") + val rows = sut tabulate items + assert(rows.size == 4) + assert(rows(0).size == 1) + assert(rows(0)(0).size == "efg".length + sut.marginSize) // 6 + } +} diff --git a/test/junit/scala/tools/nsc/symtab/FreshNameExtractorTest.scala b/test/junit/scala/tools/nsc/symtab/FreshNameExtractorTest.scala new file mode 100644 index 0000000000..cf09abdfff --- /dev/null +++ b/test/junit/scala/tools/nsc/symtab/FreshNameExtractorTest.scala @@ -0,0 +1,47 @@ +package scala.tools.nsc +package symtab + +import org.junit.Assert._ +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +import scala.tools.testing.AssertUtil.assertThrows +import scala.reflect.internal.util.FreshNameCreator + +@RunWith(classOf[JUnit4]) +class FreshNameExtractorTest { + object symbolTable extends SymbolTableForUnitTesting + import symbolTable._ + + val prefixes = List("foo$", "x$", "bar", "bippy$baz$") + + @Test + def extractionPreservesPrefix = + ("" :: prefixes).foreach { creatorPrefix => + prefixes.foreach { newPrefix => + val Creator = new FreshNameCreator(creatorPrefix) + val Extractor = new FreshNameExtractor(creatorPrefix) + val Extractor(extractedPrefix) = TermName(Creator.newName(newPrefix)) + assertEquals(newPrefix, extractedPrefix) + } + } + + @Test + def extractionFailsOnCreatorPrefixMismatch = { + val Creator = new FreshNameCreator(prefixes.head) + val Extractor = new FreshNameExtractor(prefixes.tail.head) + assertThrows[MatchError] { + val Extractor(_) = TermName(Creator.newName("foo")) + } + } + + @Test + def extractionsFailsIfNameDoesntEndWithNumber = { + val Creator = new FreshNameCreator(prefixes.head) + val Extractor = new FreshNameExtractor(prefixes.head) + assertThrows[MatchError] { + val Extractor(_) = TermName(Creator.newName("foo") + "bar") + } + } +}
\ No newline at end of file diff --git a/test/junit/scala/util/matching/RegexTest.scala b/test/junit/scala/util/matching/RegexTest.scala new file mode 100644 index 0000000000..d25842cc57 --- /dev/null +++ b/test/junit/scala/util/matching/RegexTest.scala @@ -0,0 +1,30 @@ + +package scala.util.matching + +import org.junit.Assert._ +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(classOf[JUnit4]) +class RegexTest { + @Test def t8022CharSequence(): Unit = { + val full = """.*: (.)$""".r + val text = " When I use this operator: *" + // Testing 2.10.x compatibility of the return types of unapplySeq + val x :: Nil = full.unapplySeq(text: Any).get + val y :: Nil = full.unapplySeq(text: CharSequence).get + assertEquals("*", x) + assertEquals("*", y) + } + + @Test def t8022Match(): Unit = { + val R = """(\d)""".r + val matchh = R.findFirstMatchIn("a1").get + // Testing 2.10.x compatibility of the return types of unapplySeq + val x :: Nil = R.unapplySeq(matchh: Any).get + val y :: Nil = R.unapplySeq(matchh).get + assertEquals("1", x) + assertEquals("1", y) + } +} diff --git a/test/pending/run/reify_callccinterpreter.scala b/test/pending/run/reify_callccinterpreter.scala index d9f7736769..82c70da28f 100644 --- a/test/pending/run/reify_callccinterpreter.scala +++ b/test/pending/run/reify_callccinterpreter.scala @@ -43,15 +43,15 @@ object Test extends App { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]]; + type Environment = List[Tuple2[Name, Value]]; def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => unitM(Num(m + n)) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => unitM(Num(m + n)) case _ => unitM(Wrong) } @@ -67,12 +67,12 @@ object Test extends App { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) yield c - case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e)) + case Ccc(x, t) => callCC(k => interp(t, (x, Fun(k)) :: e)) } def test(t: Term): String = showM(interp(t, List())) diff --git a/test/pending/run/reify_simpleinterpreter.scala b/test/pending/run/reify_simpleinterpreter.scala index 6cf87ea7c5..1f6d6c8da7 100644 --- a/test/pending/run/reify_simpleinterpreter.scala +++ b/test/pending/run/reify_simpleinterpreter.scala @@ -32,15 +32,15 @@ object Test extends App { override def toString() = "<function>" } - type Environment = List[Pair[Name, Value]] + type Environment = List[Tuple2[Name, Value]] def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) - case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) + case (y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } - def add(a: Value, b: Value): M[Value] = Pair(a, b) match { - case Pair(Num(m), Num(n)) => unitM(Num(m + n)) + def add(a: Value, b: Value): M[Value] = (a, b) match { + case (Num(m), Num(n)) => unitM(Num(m + n)) case _ => unitM(Wrong) } @@ -56,7 +56,7 @@ object Test extends App { b <- interp(r, e); c <- add(a, b)) yield c - case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) + case Lam(x, t) => unitM(Fun(a => interp(t, (x, a) :: e))) case App(f, t) => for (a <- interp(f, e); b <- interp(t, e); c <- apply(a, b)) diff --git a/test/pending/shootout/fasta.scala b/test/pending/shootout/fasta.scala index 8b711083a5..ae99ba5936 100644 --- a/test/pending/shootout/fasta.scala +++ b/test/pending/shootout/fasta.scala @@ -5,7 +5,7 @@ import java.io._ -object fasta { +object fasta { def main(args: Array[String]) = { val ALU = @@ -18,31 +18,31 @@ object fasta { "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA" val _IUB = Array( - Pair('a', 0.27), - Pair('c', 0.12), - Pair('g', 0.12), - Pair('t', 0.27), - - Pair('B', 0.02), - Pair('D', 0.02), - Pair('H', 0.02), - Pair('K', 0.02), - Pair('M', 0.02), - Pair('N', 0.02), - Pair('R', 0.02), - Pair('S', 0.02), - Pair('V', 0.02), - Pair('W', 0.02), - Pair('Y', 0.02) + ('a', 0.27), + ('c', 0.12), + ('g', 0.12), + ('t', 0.27), + + ('B', 0.02), + ('D', 0.02), + ('H', 0.02), + ('K', 0.02), + ('M', 0.02), + ('N', 0.02), + ('R', 0.02), + ('S', 0.02), + ('V', 0.02), + ('W', 0.02), + ('Y', 0.02) ) val IUB = makeCumulative(_IUB) val _HomoSapiens = Array( - Pair('a', 0.3029549426680), - Pair('c', 0.1979883004921), - Pair('g', 0.1975473066391), - Pair('t', 0.3015094502008) + ('a', 0.3029549426680), + ('c', 0.1979883004921), + ('g', 0.1975473066391), + ('t', 0.3015094502008) ) val HomoSapiens = makeCumulative(_HomoSapiens) @@ -61,15 +61,15 @@ object fasta { s.writeRandomSequence(HomoSapiens,n*5) s.close - } + } - def makeCumulative(a: Array[Pair[Char,Double]]) = { + def makeCumulative(a: Array[Tuple2[Char,Double]]) = { var cp = 0.0 a map (frequency => - frequency match { - case Pair(code,percent) => - cp = cp + percent; new Frequency(code.toByte,cp) - } + frequency match { + case (code,percent) => + cp = cp + percent; new Frequency(code.toByte,cp) + } ) } @@ -79,7 +79,7 @@ object fasta { // We could use instances of Pair or Tuple2 but specific labels // make the code more readable than index numbers -class Frequency(_code: Byte, _percent: Double){ +class Frequency(_code: Byte, _percent: Double){ var code = _code; var percent = _percent; } @@ -101,13 +101,13 @@ class FastaOutputStream(out: OutputStream) extends BufferedOutputStream(out) { val m = if (n < LineLength) n else LineLength var i = 0 - while (i < m){ + while (i < m){ if (k == kn) k = 0 val b = alu(k) if (count < buf.length){ buf(count) = b; count = count + 1 } else { write(b) } // flush buffer k = k+1 - i = i+1 + i = i+1 } write(nl) @@ -122,11 +122,11 @@ class FastaOutputStream(out: OutputStream) extends BufferedOutputStream(out) { val m = if (n < LineLength) n else LineLength var i = 0 - while (i < m){ + while (i < m){ val b = selectRandom(distribution) if (count < buf.length){ buf(count) = b; count = count + 1 } else { write(b) } // flush buffer - i = i+1 + i = i+1 } if (count < buf.length){ buf(count) = nl; count = count + 1 } diff --git a/test/pending/shootout/revcomp.scala-2.scala b/test/pending/shootout/revcomp.scala-2.scala index 92260ad021..03fb25af1b 100644 --- a/test/pending/shootout/revcomp.scala-2.scala +++ b/test/pending/shootout/revcomp.scala-2.scala @@ -6,7 +6,7 @@ import java.io._ import scala.collection.mutable.Stack -object revcomp { +object revcomp { val IUB = IUBCodeComplements @@ -16,7 +16,7 @@ object revcomp { val a: Array[Byte] = new Array( 'z'.toByte ) for (indexValue <- code zip comp) - indexValue match { case Pair(i,v) => a(i) = v } + indexValue match { case (i,v) => a(i) = v } a } @@ -49,18 +49,18 @@ object revcomp { if (desc.length > 0) complementReverseWrite(desc, lines, w) w.close - } + } - def complementReverseWrite(desc: String, lines: LineStack, + def complementReverseWrite(desc: String, lines: LineStack, w: BufferedOutputStream) = { def inplaceComplementReverse(b: Array[Byte]) = { - var i = 0 + var i = 0 var j = b.length - 1 while (i < j){ - val swap = b(i) - b(i) = IUB( b(j) ) + val swap = b(i) + b(i) = IUB( b(j) ) b(j) = IUB( swap ) i = i + 1 j = j - 1 @@ -79,11 +79,11 @@ object revcomp { while (!lines.isEmpty) { val line = lines.pop inplaceComplementReverse(line) - + if (isSplitLine){ if (isFirstLine){ w.write(line); isFirstLine = false } else { w.write(line,0,n-k); w.write(nl); w.write(line,n-k,k) } - } + } else { w.write(line); w.write(nl) } } if (isSplitLine && !isFirstLine) w.write(nl) diff --git a/test/pending/shootout/revcomp.scala-3.scala b/test/pending/shootout/revcomp.scala-3.scala index ae12f0499b..39a0409127 100644 --- a/test/pending/shootout/revcomp.scala-3.scala +++ b/test/pending/shootout/revcomp.scala-3.scala @@ -6,7 +6,7 @@ import java.io._ import scala.collection.mutable.Stack -object revcomp { +object revcomp { def main(args: Array[String]) = { val out = new FastaOutputStream(System.out) val in = new FastaInputStream(System.in) @@ -17,12 +17,12 @@ object revcomp { in.close out.close - } + } } trait FastaByteStream { - val nl = '\n'.toByte + val nl = '\n'.toByte type Line = Array[Byte] type LineStack = Stack[Line] @@ -31,13 +31,13 @@ trait FastaByteStream { // extend the Java BufferedInputStream class -final class FastaInputStream(in: InputStream) +final class FastaInputStream(in: InputStream) extends BufferedInputStream(in) with FastaByteStream { val gt = '>'.toByte val sc = ';'.toByte - def readSequenceStack(): Pair[Line,LineStack] = { + def readSequenceStack(): Tuple2[Line,LineStack] = { var header: Line = null val lines: LineStack = new Stack @@ -49,14 +49,14 @@ final class FastaInputStream(in: InputStream) header = line } else { pos = pos - line.length - 1 // reposition to start of line - return Pair(header,lines) + return (header,lines) } } else { if (c != sc) lines push line // ';' } line = readLine() } - return Pair(header,lines) + return (header,lines) } def readLine() = { @@ -65,7 +65,7 @@ final class FastaInputStream(in: InputStream) else { mark(128) // mark the start of the line if (count == 0) read() // fill buffer - + var i = markpos while (i < count && buf(i) != nl) i = i + 1 @@ -74,11 +74,11 @@ final class FastaInputStream(in: InputStream) while (i < count && buf(i) != nl) i = i + 1 } - if (i < count){ + if (i < count){ bytes = new Array(i - markpos) System.arraycopy(buf, markpos, bytes, 0, i - markpos); pos = i+1 - } + } } bytes } @@ -87,7 +87,7 @@ final class FastaInputStream(in: InputStream) // extend the Java BufferedOutputStream class -final class FastaOutputStream(in: OutputStream) +final class FastaOutputStream(in: OutputStream) extends BufferedOutputStream(in) with FastaByteStream { private val IUB = IUBCodeComplements @@ -98,19 +98,19 @@ final class FastaOutputStream(in: OutputStream) val iub: Array[Byte] = new Array( 'z'.toByte ) for (indexValue <- code zip comp) - indexValue match { case Pair(i,v) => iub(i) = v } + indexValue match { case (i,v) => iub(i) = v } iub } - def writeReverseComplement(sequence: Pair[Line,LineStack]) = { + def writeReverseComplement(sequence: Tuple2[Line,LineStack]) = { def inplaceComplementReverse(b: Array[Byte]) = { - var i = 0 + var i = 0 var j = b.length - 1 while (i < j){ - val swap = b(i) - b(i) = IUB( b(j) ) + val swap = b(i) + b(i) = IUB( b(j) ) b(j) = IUB( swap ) i = i + 1 j = j - 1 @@ -119,7 +119,7 @@ final class FastaOutputStream(in: OutputStream) } sequence match { - case Pair(header,lines) => { + case (header,lines) => { write(header); write(nl) @@ -131,11 +131,11 @@ final class FastaOutputStream(in: OutputStream) while (!lines.isEmpty) { val line = lines.pop inplaceComplementReverse(line) - + if (isSplitLine){ - if (isFirstLine){ write(line); isFirstLine = false } + if (isFirstLine){ write(line); isFirstLine = false } else { write(line,0,LineLength-k); write(nl); write(line,LineLength-k,k) } - } + } else { write(line); write(nl) } } diff --git a/versions.properties b/versions.properties index 29cbbad884..76eea52681 100644 --- a/versions.properties +++ b/versions.properties @@ -1,13 +1,13 @@ -starr.version=2.11.0-M6 +starr.version=2.11.0-M7 starr.use.released=1 # These are the versions of the modules that go with this release. # These properties are used during PR validation and in dbuild builds. -scala.binary.version=2.11.0-M6 -partest.version.number=1.0.0-RC7 -scala-xml.version.number=1.0.0-RC6 -scala-parser-combinators.version.number=1.0.0-RC4 -scalacheck.version.number=1.10.1 +scala.binary.version=2.11.0-M7 +partest.version.number=1.0.0-RC8 +scala-xml.version.number=1.0.0-RC7 +scala-parser-combinators.version.number=1.0.0-RC5 +scalacheck.version.number=1.11.1 # TODO: modularize the compiler #scala-compiler-doc.version.number=1.0.0-RC1 |