summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rw-r--r--test/benchmarks/src/main/scala/scala/collection/immutable/HashMapBenchmark.scala56
-rw-r--r--test/benchmarks/src/main/scala/scala/collection/immutable/ListBenchmark.scala72
-rw-r--r--test/files/neg/literals.check14
-rw-r--r--test/files/neg/literals.scala13
-rw-r--r--test/files/neg/nested-fn-print.check2
-rw-r--r--test/files/neg/quasiquotes-syntax-error-position.check3
-rw-r--r--test/files/neg/t10066.check7
-rw-r--r--test/files/neg/t10066.scala38
-rw-r--r--test/files/neg/t10097.check10
-rw-r--r--test/files/neg/t10097.flags1
-rw-r--r--test/files/neg/t10097.scala4
-rw-r--r--test/files/neg/t10097b.check6
-rw-r--r--test/files/neg/t10097b.flags1
-rw-r--r--test/files/neg/t10097b.scala3
-rw-r--r--test/files/neg/t565.check2
-rw-r--r--test/files/neg/t8217-local-alias-requires-rhs.check6
-rw-r--r--test/files/neg/t8685.check5
-rw-r--r--test/files/neg/t8704.check11
-rw-r--r--test/files/neg/t8704.flags1
-rw-r--r--test/files/neg/t8704.scala7
-rw-r--r--test/files/neg/t9636.check6
-rw-r--r--test/files/neg/t9636.flags1
-rw-r--r--test/files/neg/t9636.scala17
-rw-r--r--test/files/neg/t9675.check27
-rw-r--r--test/files/neg/t9675.flags1
-rw-r--r--test/files/neg/t9675.scala24
-rw-r--r--test/files/neg/trailing-commas.check130
-rw-r--r--test/files/neg/trailing-commas.scala56
-rw-r--r--test/files/neg/warn-inferred-any.check2
-rw-r--r--test/files/pos/overloaded_ho_fun.scala15
-rw-r--r--test/files/pos/sam_erasure_boundedwild.scala11
-rw-r--r--test/files/pos/t10066.scala38
-rw-r--r--test/files/pos/t10154.scala11
-rw-r--r--test/files/pos/t10154b.scala16
-rw-r--r--test/files/pos/t9331.scala6
-rw-r--r--test/files/pos/trailing-commas.scala155
-rw-r--r--test/files/run/elidable-opt.check2
-rw-r--r--test/files/run/elidable.check2
-rw-r--r--test/files/run/elidable.scala42
-rw-r--r--test/files/run/existentials-in-compiler.check68
-rw-r--r--test/files/run/existentials-in-compiler.scala2
-rw-r--r--test/files/run/hash-hash-hash-hash.scala5
-rw-r--r--test/files/run/iq.scala8
-rw-r--r--test/files/run/literals.scala15
-rw-r--r--test/files/run/patmat-exprs.scala4
-rw-r--r--test/files/run/repl-colon-type.check8
-rw-r--r--test/files/run/t10026.check1
-rw-r--r--test/files/run/t10026.scala11
-rw-r--r--test/files/run/t10072.scala18
-rw-r--r--test/files/run/t10097.check3
-rw-r--r--test/files/run/t10097.flags1
-rw-r--r--test/files/run/t10097.scala6
-rw-r--r--test/files/run/t1459.check3
-rw-r--r--test/files/run/t1459/InheritingPrinter.scala6
-rw-r--r--test/files/run/t1459/JavaPrinter.java7
-rw-r--r--test/files/run/t1459/ScalaPrinter.scala6
-rw-r--r--test/files/run/t1459/Test.java15
-rw-r--r--test/files/run/t1459/VarArg.java3
-rw-r--r--test/files/run/t1459generic.check4
-rw-r--r--test/files/run/t1459generic/Impl.scala4
-rw-r--r--test/files/run/t1459generic/Test.java10
-rw-r--r--test/files/run/t1459generic/VarargGeneric.java7
-rw-r--r--test/files/run/t4700.check44
-rw-r--r--test/files/run/t4700.scala22
-rw-r--r--test/files/run/t5907.scala2
-rw-r--r--test/files/run/t9013/Test.java20
-rw-r--r--test/files/run/t9013/test.scala18
-rw-r--r--test/files/run/t9114.scala31
-rw-r--r--test/files/run/t9880-9881.check36
-rw-r--r--test/files/run/t9880-9881.scala29
-rw-r--r--test/files/run/trailing-commas.check9
-rw-r--r--test/files/run/trailing-commas.scala7
-rw-r--r--test/files/run/unit-block-hash-hash.scala12
-rw-r--r--test/junit/scala/collection/IndexedSeqTest.scala578
-rw-r--r--test/junit/scala/collection/concurrent/TrieMapTest.scala54
-rw-r--r--test/junit/scala/collection/immutable/StreamTest.scala6
-rw-r--r--test/junit/scala/collection/mutable/BitSetTest.scala12
-rw-r--r--test/junit/scala/reflect/internal/NamesTest.scala25
-rw-r--r--test/junit/scala/reflect/internal/PrintersTest.scala2
-rw-r--r--test/junit/scala/tools/nsc/classpath/JrtClassPathTest.scala41
-rwxr-xr-xtest/partest152
-rw-r--r--test/scalacheck/duration.scala5
-rw-r--r--test/simplejson/__init__.py318
-rw-r--r--test/simplejson/decoder.py354
-rw-r--r--test/simplejson/encoder.py440
-rw-r--r--test/simplejson/scanner.py65
-rw-r--r--test/simplejson/tool.py37
87 files changed, 1918 insertions, 1440 deletions
diff --git a/test/benchmarks/src/main/scala/scala/collection/immutable/HashMapBenchmark.scala b/test/benchmarks/src/main/scala/scala/collection/immutable/HashMapBenchmark.scala
new file mode 100644
index 0000000000..134cd6879b
--- /dev/null
+++ b/test/benchmarks/src/main/scala/scala/collection/immutable/HashMapBenchmark.scala
@@ -0,0 +1,56 @@
+package scala.collection.immutable
+
+import org.openjdk.jmh.annotations._
+import org.openjdk.jmh.infra._
+import org.openjdk.jmh.runner.IterationType
+import benchmark._
+import java.util.concurrent.TimeUnit
+
+@BenchmarkMode(Array(Mode.AverageTime))
+@Fork(2)
+@Threads(1)
+@Warmup(iterations = 10)
+@Measurement(iterations = 10)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Benchmark)
+class HashMapBenchmark {
+ @Param(Array("10", "100", "1000"))
+ var size: Int = _
+
+ var existingKeys: Array[Any] = _
+ var missingKeys: Array[Any] = _
+
+ @Setup(Level.Trial) def initKeys(): Unit = {
+ existingKeys = (0 to size).map(i => (i % 4) match {
+ case 0 => i.toString
+ case 1 => i.toChar
+ case 2 => i.toDouble
+ case 3 => i.toInt
+ }).toArray
+ missingKeys = (size to 2 * size).toArray
+ }
+
+ var map: collection.immutable.HashMap[Any, Any] = null
+
+ @Setup(Level.Trial) def initialize = {
+ map = collection.immutable.HashMap(existingKeys.map(x => (x, x)) : _*)
+ }
+
+ @Benchmark def contains(bh: Blackhole): Unit = {
+ var i = 0;
+ while (i < size) {
+ bh.consume(map.contains(existingKeys(i)))
+ bh.consume(map.contains(missingKeys(i)))
+ i += 1
+ }
+ }
+
+ @Benchmark def get(bh: Blackhole): Unit = {
+ var i = 0;
+ while (i < size) {
+ bh.consume(map.get(existingKeys(i)))
+ bh.consume(map.get(missingKeys(i)))
+ i += 1
+ }
+ }
+}
diff --git a/test/benchmarks/src/main/scala/scala/collection/immutable/ListBenchmark.scala b/test/benchmarks/src/main/scala/scala/collection/immutable/ListBenchmark.scala
new file mode 100644
index 0000000000..94844dcae2
--- /dev/null
+++ b/test/benchmarks/src/main/scala/scala/collection/immutable/ListBenchmark.scala
@@ -0,0 +1,72 @@
+package scala.collection.immutable
+
+import java.util.concurrent.TimeUnit
+
+import org.openjdk.jmh.annotations._
+
+object ListBenchmark {
+ case class Content(value: Int)
+}
+
+@BenchmarkMode(Array(Mode.AverageTime))
+@Fork(2)
+@Threads(1)
+@Warmup(iterations = 10)
+@Measurement(iterations = 10)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@State(Scope.Benchmark)
+class ListBenchmark {
+ import ListBenchmark._
+ @Param(Array("0", "1", "10", "100", "1000"))
+ var size: Int = _
+
+ var values: List[Content] = _
+ var mid: Content = _
+ var last: Content = _
+
+
+ @Setup(Level.Trial) def initKeys(): Unit = {
+ values = List.tabulate(size)(v => Content(v))
+ mid = Content(size / 2)
+ last = Content(Math.max(0,size -1))
+ }
+
+ @Benchmark def filter_includeAll: Any = {
+ values.filter(v => true)
+ }
+
+ @Benchmark def filter_excludeAll: Any = {
+ values.filter(_ => false)
+ }
+
+ @Benchmark def filter_exc_mid: Any = {
+ values.filter(v => v.value != mid.value)
+ }
+
+ @Benchmark def filter_from_mid: Any = {
+ values.filter(v => v.value <= mid.value)
+ }
+
+ @Benchmark def filter_exc_last: Any = {
+ values.filter(v => v.value != last.value)
+ }
+
+ @Benchmark def filter_only_last: Any = {
+ values.filter(v => v.value == last.value)
+ }
+
+ @Setup(Level.Trial) def initKeys(): Unit = {
+ values = List.tabulate(size)(n => if (n == size / 2) "mid" else "")
+ }
+
+ @Benchmark def mapConserve_identity: Any = {
+ values.mapConserve(x => x)
+ }
+
+ @Benchmark def mapConserve_modifyAll: Any = {
+ values.mapConserve(x => "replace")
+ }
+ @Benchmark def mapConserve_modifyMid: Any = {
+ values.mapConserve(x => if (x == "mid") "replace" else x)
+ }
+}
diff --git a/test/files/neg/literals.check b/test/files/neg/literals.check
index 148a9346c5..79b6d47782 100644
--- a/test/files/neg/literals.check
+++ b/test/files/neg/literals.check
@@ -19,6 +19,18 @@ literals.scala:23: error: missing integer number
literals.scala:27: error: Decimal integer literals may not have a leading zero. (Octal syntax is obsolete.)
def tooManyZeros: Int = 00 // line 26: no leading zero
^
+literals.scala:40: error: floating point number too small
+ def tooTiny: Float = { 0.7e-45f } // floating point number too small
+ ^
+literals.scala:42: error: double precision floating point number too small
+ def twoTiny: Double = { 2.0e-324 } // double precision floating point number too small
+ ^
+literals.scala:44: error: floating point number too large
+ def tooHuge: Float = { 3.4028236E38f } // floating point number too large
+ ^
+literals.scala:46: error: double precision floating point number too large
+ def twoHuge: Double = { 1.7976931348623159e308 } // double precision floating point number too large
+ ^
literals.scala:14: error: identifier expected but '}' found.
def orphanDot: Int = { 9. } // line 12: ident expected
^
@@ -37,4 +49,4 @@ literals.scala:29: error: ';' expected but 'def' found.
literals.scala:33: error: identifier expected but 'def' found.
def zeroOfNineDot: Int = 09. // line 32: malformed integer, ident expected
^
-13 errors found
+17 errors found
diff --git a/test/files/neg/literals.scala b/test/files/neg/literals.scala
index 3df7f0b408..22d5d9acd1 100644
--- a/test/files/neg/literals.scala
+++ b/test/files/neg/literals.scala
@@ -1,6 +1,6 @@
/* This took me literally all day.
-*/
+ */
trait RejectedLiterals {
def missingHex: Int = { 0x } // line 4: was: not reported, taken as zero
@@ -34,3 +34,14 @@ trait Braceless {
def noHexFloat: Double = 0x1.2 // line 34: ';' expected but double literal found.
}
+
+trait MoreSadness {
+
+ def tooTiny: Float = { 0.7e-45f } // floating point number too small
+
+ def twoTiny: Double = { 2.0e-324 } // double precision floating point number too small
+
+ def tooHuge: Float = { 3.4028236E38f } // floating point number too large
+
+ def twoHuge: Double = { 1.7976931348623159e308 } // double precision floating point number too large
+}
diff --git a/test/files/neg/nested-fn-print.check b/test/files/neg/nested-fn-print.check
index ea278554d4..feeac0733f 100644
--- a/test/files/neg/nested-fn-print.check
+++ b/test/files/neg/nested-fn-print.check
@@ -1,4 +1,4 @@
-nested-fn-print.scala:4: error: only classes can have declared but undefined members
+nested-fn-print.scala:4: error: only traits and abstract classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
var x3: Int => Double
^
diff --git a/test/files/neg/quasiquotes-syntax-error-position.check b/test/files/neg/quasiquotes-syntax-error-position.check
index 9fd6ce0417..b12a7d13d6 100644
--- a/test/files/neg/quasiquotes-syntax-error-position.check
+++ b/test/files/neg/quasiquotes-syntax-error-position.check
@@ -16,8 +16,7 @@ quasiquotes-syntax-error-position.scala:9: error: '{' expected but end of quote
quasiquotes-syntax-error-position.scala:10: error: ';' expected but '@' found.
q"foo@$a"
^
-quasiquotes-syntax-error-position.scala:11: error: case classes without a parameter list are not allowed;
-use either case objects or case classes with an explicit `()' as a parameter list.
+quasiquotes-syntax-error-position.scala:11: error: case classes must have a parameter list; try 'case class A()' or 'case object A'
q"case class A"
^
quasiquotes-syntax-error-position.scala:12: error: identifier expected but ']' found.
diff --git a/test/files/neg/t10066.check b/test/files/neg/t10066.check
new file mode 100644
index 0000000000..3555205d83
--- /dev/null
+++ b/test/files/neg/t10066.check
@@ -0,0 +1,7 @@
+t10066.scala:33: error: could not find implicit value for parameter extractor: dynamicrash.Extractor[String]
+ println(storage.foo[String])
+ ^
+t10066.scala:37: error: could not find implicit value for parameter extractor: dynamicrash.Extractor[A]
+ println(storage.foo)
+ ^
+two errors found
diff --git a/test/files/neg/t10066.scala b/test/files/neg/t10066.scala
new file mode 100644
index 0000000000..ef52f333dd
--- /dev/null
+++ b/test/files/neg/t10066.scala
@@ -0,0 +1,38 @@
+package dynamicrash
+
+import scala.language.dynamics
+
+class Config
+
+trait Extractor[A] {
+ def extract(config: Config, name: String): A
+}
+
+object Extractor {
+ // note missing "implicit"
+ val stringExtractor = new Extractor[String] {
+ override def extract(config: Config, name: String): String = ???
+ }
+}
+
+class Workspace extends Dynamic {
+ val config: Config = new Config
+
+ def selectDynamic[A](name: String)(implicit extractor: Extractor[A]): A =
+ extractor.extract(config, name)
+}
+
+object Main {
+ val storage = new Workspace
+
+ // this line works fine
+ // val a = storage.foo
+
+ // this line crashes the compiler ("head of empty list")
+ // in ContextErrors$InferencerContextErrors$InferErrorGen$.NotWithinBoundsErrorMessage
+ println(storage.foo[String])
+
+ // this line crashes the compiler in different way ("unknown type")
+ // in the backend, warning: an unexpected type representation reached the compiler backend while compiling Test.scala: <error>
+ println(storage.foo)
+}
diff --git a/test/files/neg/t10097.check b/test/files/neg/t10097.check
new file mode 100644
index 0000000000..1f70546b57
--- /dev/null
+++ b/test/files/neg/t10097.check
@@ -0,0 +1,10 @@
+t10097.scala:2: error: case classes must have a non-implicit parameter list; try 'case class C()(...)'
+case class C(implicit val c: Int)
+ ^
+t10097.scala:4: error: case classes must have a non-implicit parameter list; try 'case class D()(...)(...)'
+case class D(implicit c: Int)(s: String)
+ ^
+t10097.scala:4: error: an implicit parameter section must be last
+case class D(implicit c: Int)(s: String)
+ ^
+three errors found
diff --git a/test/files/neg/t10097.flags b/test/files/neg/t10097.flags
new file mode 100644
index 0000000000..714bbf5125
--- /dev/null
+++ b/test/files/neg/t10097.flags
@@ -0,0 +1 @@
+-Xsource:2.13
diff --git a/test/files/neg/t10097.scala b/test/files/neg/t10097.scala
new file mode 100644
index 0000000000..b2f05e2972
--- /dev/null
+++ b/test/files/neg/t10097.scala
@@ -0,0 +1,4 @@
+
+case class C(implicit val c: Int)
+
+case class D(implicit c: Int)(s: String)
diff --git a/test/files/neg/t10097b.check b/test/files/neg/t10097b.check
new file mode 100644
index 0000000000..14535fee34
--- /dev/null
+++ b/test/files/neg/t10097b.check
@@ -0,0 +1,6 @@
+t10097b.scala:2: warning: case classes should have a non-implicit parameter list; adapting to 'case class C()(...)'
+case class C(implicit val c: Int)
+ ^
+error: No warnings can be incurred under -Xfatal-warnings.
+one warning found
+one error found
diff --git a/test/files/neg/t10097b.flags b/test/files/neg/t10097b.flags
new file mode 100644
index 0000000000..c6bfaf1f64
--- /dev/null
+++ b/test/files/neg/t10097b.flags
@@ -0,0 +1 @@
+-deprecation -Xfatal-warnings
diff --git a/test/files/neg/t10097b.scala b/test/files/neg/t10097b.scala
new file mode 100644
index 0000000000..f166db6792
--- /dev/null
+++ b/test/files/neg/t10097b.scala
@@ -0,0 +1,3 @@
+
+case class C(implicit val c: Int)
+
diff --git a/test/files/neg/t565.check b/test/files/neg/t565.check
index 136cc94b6f..d7657c0f5d 100644
--- a/test/files/neg/t565.check
+++ b/test/files/neg/t565.check
@@ -1,4 +1,4 @@
-t565.scala:2: error: only classes can have declared but undefined members
+t565.scala:2: error: only traits and abstract classes can have declared but undefined members
(Note that variables need to be initialized to be defined)
var s0: String
^
diff --git a/test/files/neg/t8217-local-alias-requires-rhs.check b/test/files/neg/t8217-local-alias-requires-rhs.check
index d970400ff6..383b1f8d63 100644
--- a/test/files/neg/t8217-local-alias-requires-rhs.check
+++ b/test/files/neg/t8217-local-alias-requires-rhs.check
@@ -1,10 +1,10 @@
-t8217-local-alias-requires-rhs.scala:3: error: only classes can have declared but undefined members
+t8217-local-alias-requires-rhs.scala:3: error: only traits and abstract classes can have declared but undefined members
type A
^
-t8217-local-alias-requires-rhs.scala:6: error: only classes can have declared but undefined members
+t8217-local-alias-requires-rhs.scala:6: error: only traits and abstract classes can have declared but undefined members
type B
^
-t8217-local-alias-requires-rhs.scala:14: error: only classes can have declared but undefined members
+t8217-local-alias-requires-rhs.scala:14: error: only traits and abstract classes can have declared but undefined members
def this(a: Any) = { this(); type C }
^
three errors found
diff --git a/test/files/neg/t8685.check b/test/files/neg/t8685.check
index 685fd2e951..a31e2e265a 100644
--- a/test/files/neg/t8685.check
+++ b/test/files/neg/t8685.check
@@ -4,6 +4,9 @@ case class D @deprecated("ctor D is depr", since="now") (i: Int)
t8685.scala:35: warning: class C is deprecated (since now): class C is depr
def f = C(42)
^
+t8685.scala:36: warning: constructor D in class D is deprecated (since now): ctor D is depr
+ def g = D(42)
+ ^
t8685.scala:37: warning: object E is deprecated (since now): module E is depr
def h = E(42)
^
@@ -41,5 +44,5 @@ t8685.scala:53: warning: class K in object J is deprecated (since now): Inner K
def l = new J.K(42)
^
error: No warnings can be incurred under -Xfatal-warnings.
-14 warnings found
+15 warnings found
one error found
diff --git a/test/files/neg/t8704.check b/test/files/neg/t8704.check
new file mode 100644
index 0000000000..b567a8bb17
--- /dev/null
+++ b/test/files/neg/t8704.check
@@ -0,0 +1,11 @@
+t8704.scala:7: warning: 2 parameter sections are effectively implicit
+class D(private implicit val i: Int)(implicit s: String)
+ ^
+t8704.scala:3: error: an implicit parameter section must be last
+class C(i: Int)(implicit j: Int)(implicit k: Int)(n: Int) {
+ ^
+t8704.scala:3: error: multiple implicit parameter sections are not allowed
+class C(i: Int)(implicit j: Int)(implicit k: Int)(n: Int) {
+ ^
+one warning found
+two errors found
diff --git a/test/files/neg/t8704.flags b/test/files/neg/t8704.flags
new file mode 100644
index 0000000000..f175a06c74
--- /dev/null
+++ b/test/files/neg/t8704.flags
@@ -0,0 +1 @@
+-Ywarn-extra-implicit
diff --git a/test/files/neg/t8704.scala b/test/files/neg/t8704.scala
new file mode 100644
index 0000000000..db43bfcaa5
--- /dev/null
+++ b/test/files/neg/t8704.scala
@@ -0,0 +1,7 @@
+
+
+class C(i: Int)(implicit j: Int)(implicit k: Int)(n: Int) {
+ def f = n
+}
+
+class D(private implicit val i: Int)(implicit s: String)
diff --git a/test/files/neg/t9636.check b/test/files/neg/t9636.check
new file mode 100644
index 0000000000..f36d1d32b2
--- /dev/null
+++ b/test/files/neg/t9636.check
@@ -0,0 +1,6 @@
+t9636.scala:11: warning: a type was inferred to be `AnyVal`; this may indicate a programming error.
+ if (signature.sameElements(Array(0x1F, 0x8B))) {
+ ^
+error: No warnings can be incurred under -Xfatal-warnings.
+one warning found
+one error found
diff --git a/test/files/neg/t9636.flags b/test/files/neg/t9636.flags
new file mode 100644
index 0000000000..7949c2afa2
--- /dev/null
+++ b/test/files/neg/t9636.flags
@@ -0,0 +1 @@
+-Xlint -Xfatal-warnings
diff --git a/test/files/neg/t9636.scala b/test/files/neg/t9636.scala
new file mode 100644
index 0000000000..7ad5fb3e9e
--- /dev/null
+++ b/test/files/neg/t9636.scala
@@ -0,0 +1,17 @@
+
+import java.io._
+import java.util.zip._
+
+class C {
+ def isWrapper(is: FileInputStream): InputStream = {
+ val pb = new PushbackInputStream(is, 2)
+ val signature = new Array[Byte](2)
+ pb.read(signature)
+ pb.unread(signature)
+ if (signature.sameElements(Array(0x1F, 0x8B))) {
+ new GZIPInputStream(new BufferedInputStream(pb))
+ } else {
+ pb
+ }
+ }
+}
diff --git a/test/files/neg/t9675.check b/test/files/neg/t9675.check
new file mode 100644
index 0000000000..255477499c
--- /dev/null
+++ b/test/files/neg/t9675.check
@@ -0,0 +1,27 @@
+t9675.scala:4: warning: comparing values of types Test.A and String using `!=' will always yield true
+ val func1 = (x: A) => { x != "x" }
+ ^
+t9675.scala:6: warning: comparing values of types Test.A and String using `!=' will always yield true
+ val func2 = (x: A) => { x != "x" }: Boolean
+ ^
+t9675.scala:8: warning: comparing values of types Test.A and String using `!=' will always yield true
+ val func3: Function1[A, Boolean] = (x) => { x != "x" }
+ ^
+t9675.scala:11: warning: comparing values of types Test.A and String using `!=' will always yield true
+ def apply(x: A): Boolean = { x != "x" }
+ ^
+t9675.scala:14: warning: comparing values of types Test.A and String using `!=' will always yield true
+ def method(x: A): Boolean = { x != "x" }
+ ^
+t9675.scala:18: warning: comparing values of types Test.A and String using `!=' will always yield true
+ A("x") != "x"
+ ^
+t9675.scala:20: warning: comparing values of types Test.A and String using `!=' will always yield true
+ val func5: Function1[A, Boolean] = (x) => { x != "x" }
+ ^
+t9675.scala:22: warning: comparing values of types Test.A and String using `!=' will always yield true
+ List(A("x")).foreach((item: A) => item != "x")
+ ^
+error: No warnings can be incurred under -Xfatal-warnings.
+8 warnings found
+one error found
diff --git a/test/files/neg/t9675.flags b/test/files/neg/t9675.flags
new file mode 100644
index 0000000000..85d8eb2ba2
--- /dev/null
+++ b/test/files/neg/t9675.flags
@@ -0,0 +1 @@
+-Xfatal-warnings
diff --git a/test/files/neg/t9675.scala b/test/files/neg/t9675.scala
new file mode 100644
index 0000000000..f76b74b6ac
--- /dev/null
+++ b/test/files/neg/t9675.scala
@@ -0,0 +1,24 @@
+object Test {
+ case class A(x: String)
+
+ val func1 = (x: A) => { x != "x" }
+
+ val func2 = (x: A) => { x != "x" }: Boolean
+
+ val func3: Function1[A, Boolean] = (x) => { x != "x" }
+
+ val func4 = new Function1[A, Boolean] {
+ def apply(x: A): Boolean = { x != "x" }
+ }
+
+ def method(x: A): Boolean = { x != "x" }
+ case class PersonInfo(rankPayEtc: Unit)
+
+ def main(args: Array[String]) {
+ A("x") != "x"
+
+ val func5: Function1[A, Boolean] = (x) => { x != "x" }
+
+ List(A("x")).foreach((item: A) => item != "x")
+ }
+}
diff --git a/test/files/neg/trailing-commas.check b/test/files/neg/trailing-commas.check
new file mode 100644
index 0000000000..e2677dc3f5
--- /dev/null
+++ b/test/files/neg/trailing-commas.check
@@ -0,0 +1,130 @@
+trailing-commas.scala:10: error: illegal start of simple expression
+trait ArgumentExprs1 { f(23, "bar", )(Ev0, Ev1) }
+ ^
+trailing-commas.scala:10: error: ')' expected but '}' found.
+trait ArgumentExprs1 { f(23, "bar", )(Ev0, Ev1) }
+ ^
+trailing-commas.scala:11: error: illegal start of simple expression
+trait ArgumentExprs2 { f(23, "bar")(Ev0, Ev1, ) }
+ ^
+trailing-commas.scala:11: error: ')' expected but '}' found.
+trait ArgumentExprs2 { f(23, "bar")(Ev0, Ev1, ) }
+ ^
+trailing-commas.scala:12: error: illegal start of simple expression
+trait ArgumentExprs3 { new C(23, "bar", )(Ev0, Ev1) }
+ ^
+trailing-commas.scala:12: error: ')' expected but '}' found.
+trait ArgumentExprs3 { new C(23, "bar", )(Ev0, Ev1) }
+ ^
+trailing-commas.scala:13: error: illegal start of simple expression
+trait ArgumentExprs4 { new C(23, "bar")(Ev0, Ev1, ) }
+ ^
+trailing-commas.scala:13: error: ')' expected but '}' found.
+trait ArgumentExprs4 { new C(23, "bar")(Ev0, Ev1, ) }
+ ^
+trailing-commas.scala:15: error: identifier expected but ')' found.
+trait Params1 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+ ^
+trailing-commas.scala:15: error: ':' expected but '}' found.
+trait Params1 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+ ^
+trailing-commas.scala:16: error: identifier expected but ')' found.
+trait Params2 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+ ^
+trailing-commas.scala:16: error: ':' expected but '}' found.
+trait Params2 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+ ^
+trailing-commas.scala:17: error: identifier expected but ')' found.
+trait ClassParams1 { final class C(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1) }
+ ^
+trailing-commas.scala:17: error: ':' expected but '}' found.
+trait ClassParams1 { final class C(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1) }
+ ^
+trailing-commas.scala:18: error: identifier expected but ')' found.
+trait ClassParams2 { final class C(foo: Int, bar: String)(implicit ev0: Ev0, ev1: Ev1, ) }
+ ^
+trailing-commas.scala:18: error: ':' expected but '}' found.
+trait ClassParams2 { final class C(foo: Int, bar: String)(implicit ev0: Ev0, ev1: Ev1, ) }
+ ^
+trailing-commas.scala:20: error: illegal start of simple expression
+trait SimpleExpr { (23, "bar", ) }
+ ^
+trailing-commas.scala:20: error: ')' expected but '}' found.
+trait SimpleExpr { (23, "bar", ) }
+ ^
+trailing-commas.scala:22: error: identifier expected but ']' found.
+trait TypeArgs { def f: C[Int, String, ] }
+ ^
+trailing-commas.scala:22: error: ']' expected but '}' found.
+trait TypeArgs { def f: C[Int, String, ] }
+ ^
+trailing-commas.scala:23: error: identifier expected but ']' found.
+trait TypeParamClause { type C[A, B, ] }
+ ^
+trailing-commas.scala:23: error: ']' expected but '}' found.
+trait TypeParamClause { type C[A, B, ] }
+ ^
+trailing-commas.scala:24: error: identifier expected but ']' found.
+trait FunTypeParamClause { def f[A, B, ] }
+ ^
+trailing-commas.scala:24: error: ']' expected but '}' found.
+trait FunTypeParamClause { def f[A, B, ] }
+ ^
+trailing-commas.scala:26: error: identifier expected but ')' found.
+trait SimpleType { def f: (Int, String, ) }
+ ^
+trailing-commas.scala:26: error: ')' expected but '}' found.
+trait SimpleType { def f: (Int, String, ) }
+ ^
+trailing-commas.scala:27: error: identifier expected but ')' found.
+trait FunctionArgTypes { def f: (Int, String, ) => Boolean }
+ ^
+trailing-commas.scala:27: error: ')' expected but '}' found.
+trait FunctionArgTypes { def f: (Int, String, ) => Boolean }
+ ^
+trailing-commas.scala:29: error: illegal start of simple pattern
+trait SimplePattern { val (foo, bar, ) = null: Any }
+ ^
+trailing-commas.scala:31: error: identifier expected but '}' found.
+trait ImportSelectors { import foo.{ Ev0, Ev1, } }
+ ^
+trailing-commas.scala:33: error: identifier expected but '}' found.
+trait Import { import foo.Ev0, foo.Ev1, }
+ ^
+trailing-commas.scala:35: error: illegal start of simple pattern
+trait ValDcl { val foo, bar, = 23 }
+ ^
+trailing-commas.scala:35: error: '=' expected but '}' found.
+trait ValDcl { val foo, bar, = 23 }
+ ^
+trailing-commas.scala:36: error: illegal start of simple pattern
+trait VarDcl { var foo, bar, = 23 }
+ ^
+trailing-commas.scala:36: error: '=' expected but '}' found.
+trait VarDcl { var foo, bar, = 23 }
+ ^
+trailing-commas.scala:37: error: illegal start of simple pattern
+trait VarDef { var foo, bar, = _ }
+ ^
+trailing-commas.scala:37: error: '=' expected but '}' found.
+trait VarDef { var foo, bar, = _ }
+ ^
+trailing-commas.scala:38: error: illegal start of simple pattern
+trait PatDef { val Foo(foo), Bar(bar), = bippy }
+ ^
+trailing-commas.scala:38: error: '=' expected but '}' found.
+trait PatDef { val Foo(foo), Bar(bar), = bippy }
+ ^
+trailing-commas.scala:45: error: illegal start of simple expression
+trait SimpleExpr2 { (23, ) }
+ ^
+trailing-commas.scala:45: error: ')' expected but '}' found.
+trait SimpleExpr2 { (23, ) }
+ ^
+trailing-commas.scala:48: error: identifier expected but ')' found.
+trait SimpleType2 { def f: (Int, ) }
+ ^
+trailing-commas.scala:48: error: ')' expected but '}' found.
+trait SimpleType2 { def f: (Int, ) }
+ ^
+43 errors found
diff --git a/test/files/neg/trailing-commas.scala b/test/files/neg/trailing-commas.scala
new file mode 100644
index 0000000000..a873cb1e39
--- /dev/null
+++ b/test/files/neg/trailing-commas.scala
@@ -0,0 +1,56 @@
+package foo
+
+// Note: Using traits to get distinct errors
+// (instead of sharing one single "')' expected but '}' found." at the end)
+
+
+
+//// Multi-line only cases: make sure trailing commas are only supported when multi-line
+
+trait ArgumentExprs1 { f(23, "bar", )(Ev0, Ev1) }
+trait ArgumentExprs2 { f(23, "bar")(Ev0, Ev1, ) }
+trait ArgumentExprs3 { new C(23, "bar", )(Ev0, Ev1) }
+trait ArgumentExprs4 { new C(23, "bar")(Ev0, Ev1, ) }
+
+trait Params1 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+trait Params2 { def f(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1, ) = 1 }
+trait ClassParams1 { final class C(foo: Int, bar: String, )(implicit ev0: Ev0, ev1: Ev1) }
+trait ClassParams2 { final class C(foo: Int, bar: String)(implicit ev0: Ev0, ev1: Ev1, ) }
+
+trait SimpleExpr { (23, "bar", ) }
+
+trait TypeArgs { def f: C[Int, String, ] }
+trait TypeParamClause { type C[A, B, ] }
+trait FunTypeParamClause { def f[A, B, ] }
+
+trait SimpleType { def f: (Int, String, ) }
+trait FunctionArgTypes { def f: (Int, String, ) => Boolean }
+
+trait SimplePattern { val (foo, bar, ) = null: Any }
+
+trait ImportSelectors { import foo.{ Ev0, Ev1, } }
+
+trait Import { import foo.Ev0, foo.Ev1, }
+
+trait ValDcl { val foo, bar, = 23 }
+trait VarDcl { var foo, bar, = 23 }
+trait VarDef { var foo, bar, = _ }
+trait PatDef { val Foo(foo), Bar(bar), = bippy }
+
+
+
+//// The Tuple 1 cases
+
+// the Tuple1 value case: make sure that the possible "(23, )" syntax for Tuple1 doesn't compile to "23"
+trait SimpleExpr2 { (23, ) }
+
+// the Tuple1 type case: make sure that the possible "(Int, )" syntax for Tuple1[Int] doesn't compile to "Int"
+trait SimpleType2 { def f: (Int, ) }
+
+
+
+//// Test utilities
+object `package` {
+ sealed trait Ev0; implicit object Ev0 extends Ev0
+ sealed trait Ev1; implicit object Ev1 extends Ev1
+}
diff --git a/test/files/neg/warn-inferred-any.check b/test/files/neg/warn-inferred-any.check
index 8ad81d1529..2b321a83c9 100644
--- a/test/files/neg/warn-inferred-any.check
+++ b/test/files/neg/warn-inferred-any.check
@@ -9,7 +9,7 @@ warn-inferred-any.scala:17: warning: a type was inferred to be `AnyVal`; this ma
^
warn-inferred-any.scala:25: warning: a type was inferred to be `Any`; this may indicate a programming error.
def za = f(1, "one")
- ^
+ ^
error: No warnings can be incurred under -Xfatal-warnings.
four warnings found
one error found
diff --git a/test/files/pos/overloaded_ho_fun.scala b/test/files/pos/overloaded_ho_fun.scala
index 2699ad35f8..17176715f0 100644
--- a/test/files/pos/overloaded_ho_fun.scala
+++ b/test/files/pos/overloaded_ho_fun.scala
@@ -49,3 +49,18 @@ object sorting {
// def andThen[C](g: Bijection[B, C]): Bijection[A, C] = ???
// def compose[T](g: Bijection[T, A]) = g andThen this
// }
+
+object SI10194 {
+ trait X[A] {
+ def map[B](f: A => B): Unit
+ }
+
+ trait Y[A] extends X[A] {
+ def map[B](f: A => B)(implicit ordering: Ordering[B]): Unit
+ }
+
+ trait Z[A] extends Y[A]
+
+ (null: Y[Int]).map(x => x.toString) // compiled
+ (null: Z[Int]).map(x => x.toString) // didn't compile
+}
diff --git a/test/files/pos/sam_erasure_boundedwild.scala b/test/files/pos/sam_erasure_boundedwild.scala
new file mode 100644
index 0000000000..1ec27e0ea4
--- /dev/null
+++ b/test/files/pos/sam_erasure_boundedwild.scala
@@ -0,0 +1,11 @@
+class Test {
+ trait Q[T] {
+ def toArray[T](x: Array[T]): Array[T]
+ def toArray(): Array[T]
+ }
+
+ def crashTyper: Array[_] = {
+ val x : Q[_] = ???
+ x.toArray // crashes while doing overload resolution
+ }
+} \ No newline at end of file
diff --git a/test/files/pos/t10066.scala b/test/files/pos/t10066.scala
new file mode 100644
index 0000000000..bef85cb08c
--- /dev/null
+++ b/test/files/pos/t10066.scala
@@ -0,0 +1,38 @@
+package dynamicrash
+
+import scala.language.dynamics
+
+class Config
+
+trait Extractor[A] {
+ def extract(config: Config, name: String): A
+}
+
+object Extractor {
+ // this has "implicit", unlike the corresponding neg test
+ implicit val stringExtractor = new Extractor[String] {
+ override def extract(config: Config, name: String): String = ???
+ }
+}
+
+class Workspace extends Dynamic {
+ val config: Config = new Config
+
+ def selectDynamic[A](name: String)(implicit extractor: Extractor[A]): A =
+ extractor.extract(config, name)
+}
+
+object Main {
+ val storage = new Workspace
+
+ // this line works fine
+ // val a = storage.foo
+
+ // this line crashes the compiler ("head of empty list")
+ // in ContextErrors$InferencerContextErrors$InferErrorGen$.NotWithinBoundsErrorMessage
+ println(storage.foo[String])
+
+ // this line crashes the compiler in different way ("unknown type")
+ // in the backend, warning: an unexpected type representation reached the compiler backend while compiling Test.scala: <error>
+ println(storage.foo)
+}
diff --git a/test/files/pos/t10154.scala b/test/files/pos/t10154.scala
new file mode 100644
index 0000000000..51616b71d6
--- /dev/null
+++ b/test/files/pos/t10154.scala
@@ -0,0 +1,11 @@
+trait Bar2[T]
+
+object Test2 {
+ def wrap {
+ object Foo {
+ implicit def fooBar: Bar2[Foo.type] = ???
+ }
+
+ implicitly[Bar2[Foo.type]]
+ }
+}
diff --git a/test/files/pos/t10154b.scala b/test/files/pos/t10154b.scala
new file mode 100644
index 0000000000..809a286c0e
--- /dev/null
+++ b/test/files/pos/t10154b.scala
@@ -0,0 +1,16 @@
+ import scala.language.existentials
+
+ class Bar[T]
+ class Test {
+ def method = {
+ object Foo {
+ implicit def x: Bar[Foo.type] = new Bar[Foo.type]
+ }
+ type T = Foo.type
+
+ {
+ object Foo
+ implicitly[Bar[T]]
+ }
+ }
+}
diff --git a/test/files/pos/t9331.scala b/test/files/pos/t9331.scala
new file mode 100644
index 0000000000..00a667886f
--- /dev/null
+++ b/test/files/pos/t9331.scala
@@ -0,0 +1,6 @@
+import scala.language.higherKinds
+
+trait Proxy[+T]
+case class Stuff[+P[PP] <: Proxy[PP]]() {
+ // canEqual was incorrectly synthetized and started reporting a kind error.
+}
diff --git a/test/files/pos/trailing-commas.scala b/test/files/pos/trailing-commas.scala
new file mode 100644
index 0000000000..b9401fe49d
--- /dev/null
+++ b/test/files/pos/trailing-commas.scala
@@ -0,0 +1,155 @@
+package foo
+
+trait ArgumentExprs1 {
+ def f(foo: Int, bar: String)(implicit ev0: Ev0, ev1: Ev1) = 1
+ f(
+ 23,
+ "bar",
+ )(
+ Ev0,
+ Ev1,
+ )
+
+ // test arg exprs in the presence of varargs
+ def g(x: Int, y: Int*) = 1
+ g(1,2,
+ )
+ g(1,List(2, 3): _*,
+ )
+}
+
+trait ArgumentExprs2 {
+ class C(foo: Int, bar: String)(implicit ev0: Ev0, ev1: Ev1)
+ new C(
+ 23,
+ "bar",
+ )(
+ Ev0,
+ Ev1,
+ )
+}
+
+trait Params {
+ def f(
+ foo: Int,
+ bar: String,
+ )(implicit
+ ev0: Ev0,
+ ev1: Ev1,
+ )
+}
+
+trait ClassParams {
+ class C(
+ foo: Int,
+ bar: String,
+ )(implicit
+ ev0: Ev0,
+ ev1: Ev1,
+ )
+
+ // test class params in the precense of varargs
+ case class D(i: Int*,
+ )
+}
+
+trait SimpleExpr1 {
+ def f: (Int, String) = (
+ 23,
+ "bar",
+ )
+
+ // the Tuple1 value case, the trailing comma is ignored so the type is Int and the value 23
+ def g: Int = (
+ 23,
+ )
+}
+
+trait TypeArgs {
+ class C[A, B]
+ def f: C[
+ Int,
+ String,
+ ]
+}
+
+trait TypeParamClause {
+ class C[
+ A,
+ B,
+ ]
+}
+
+trait FunTypeParamClause {
+ def f[
+ A,
+ B,
+ ]
+}
+
+trait SimpleType {
+ def f: (
+ Int,
+ String,
+ )
+
+ // the Tuple1 type case, the trailing comma is ignored so the type is Int and the value 23
+ def g: (
+ Int,
+ ) = 23
+}
+
+trait FunctionArgTypes {
+ def f: (
+ Int,
+ String,
+ ) => Boolean
+}
+
+trait SimplePattern {
+ val (
+ foo,
+ bar,
+ ) = null: Any
+
+ // test '@' syntax in patterns
+ Some(1) match {
+ case Some(x @ 1,
+ ) => x
+ }
+
+ // test ': _*' syntax in patterns
+ List(1, 2, 3) match {
+ case List(1, 2, _ @ _*,
+ ) => 1
+ }
+
+ // test varargs in patterns
+ val List(x, y, _*,
+ ) = 42 :: 17 :: Nil
+}
+
+trait ImportSelectors {
+ import foo.{
+ Ev0,
+ Ev1,
+ }
+}
+
+trait Bindings {
+ def g(f: (Int, String) => Boolean)
+
+ g((
+ foo,
+ bar,
+ ) => true)
+}
+
+// Import, ids, ValDcl, VarDcl, VarDef, PatDef use commas, but not inside paren, bracket or brace,
+// so they don't support an optional trailing comma
+
+// test utilities
+object `package` {
+ sealed trait Ev0; implicit object Ev0 extends Ev0
+ sealed trait Ev1; implicit object Ev1 extends Ev1
+}
diff --git a/test/files/run/elidable-opt.check b/test/files/run/elidable-opt.check
index 88cf98e0d1..969b9a420a 100644
--- a/test/files/run/elidable-opt.check
+++ b/test/files/run/elidable-opt.check
@@ -11,4 +11,4 @@ false
0
0.0
0.0
-null
+
diff --git a/test/files/run/elidable.check b/test/files/run/elidable.check
index 88cf98e0d1..969b9a420a 100644
--- a/test/files/run/elidable.check
+++ b/test/files/run/elidable.check
@@ -11,4 +11,4 @@ false
0
0.0
0.0
-null
+
diff --git a/test/files/run/elidable.scala b/test/files/run/elidable.scala
index 02785972bb..fed1c7b392 100644
--- a/test/files/run/elidable.scala
+++ b/test/files/run/elidable.scala
@@ -3,31 +3,36 @@ import elidable._
// runs -Xelide-below WARNING or 900
+object Fail {
+ def fail(msg: String): Unit = throw new IllegalStateException(s"Expected failure: $msg")
+}
+import Fail.fail
+
trait T {
@elidable(FINEST) def f1()
@elidable(SEVERE) def f2()
- @elidable(FINEST) def f3() = assert(false, "Should have been elided.")
+ @elidable(FINEST) def f3() = fail("Should have been elided.")
def f4()
}
class C extends T {
def f1() = println("Good for me, I was not elided. C.f1")
def f2() = println("Good for me, I was not elided. C.f2")
- @elidable(FINEST) def f4() = assert(false, "Should have been elided.")
+ @elidable(FINEST) def f4() = fail("Should have been elided.")
}
object O {
- @elidable(FINEST) def f1() = assert(false, "Should have been elided.")
- @elidable(INFO) def f2() = assert(false, "Should have been elided.")
+ @elidable(FINEST) def f1() = fail("Should have been elided.")
+ @elidable(INFO) def f2() = fail("Should have been elided.")
@elidable(SEVERE) def f3() = println("Good for me, I was not elided. O.f3")
- @elidable(INFO) def f4 = assert(false, "Should have been elided (no parens).")
+ @elidable(INFO) def f4 = fail("Should have been elided (no parens).")
}
object Test {
- @elidable(FINEST) def f1() = assert(false, "Should have been elided.")
- @elidable(INFO) def f2() = assert(false, "Should have been elided.")
+ @elidable(FINEST) def f1() = fail("Should have been elided.")
+ @elidable(INFO) def f2() = fail("Should have been elided.")
@elidable(SEVERE) def f3() = println("Good for me, I was not elided. Test.f3")
- @elidable(INFO) def f4 = assert(false, "Should have been elided (no parens).")
+ @elidable(INFO) def f4 = fail("Should have been elided (no parens).")
@elidable(FINEST) def f5() = {}
@elidable(FINEST) def f6() = true
@@ -38,12 +43,12 @@ object Test {
@elidable(FINEST) def fb() = 1l
@elidable(FINEST) def fc() = 1.0f
@elidable(FINEST) def fd() = 1.0
- @elidable(FINEST) def fe() = "s"
+ @elidable(FINEST) def fe() = { fail("Should have been elided to empty string.") ; "hello, world" }
/* variable elisions? see test/files/neg/t10068.scala
- @elidable(INFO) val goner1: Int = { assert(false, "Should have been elided.") ; 42 }
- @elidable(INFO) lazy val goner2: Int = { assert(false, "Should have been elided.") ; 42 }
- @elidable(INFO) var goner3: Int = { assert(false, "Should have been elided.") ; 42 }
+ @elidable(INFO) val goner1: Int = { fail("Should have been elided.") ; 42 }
+ @elidable(INFO) lazy val goner2: Int = { fail("Should have been elided.") ; 42 }
+ @elidable(INFO) var goner3: Int = { fail("Should have been elided.") ; 42 }
@elidable(INFO) var goner4: Nothing = _
*/
@@ -74,6 +79,19 @@ object Test {
println(fc())
println(fd())
println(fe())
+ if (!fe().isEmpty) fail(s"Not empty: [${fe()}]")
+/*
+()
+false
+0
+0
+0
+0
+0
+0.0
+0.0
+ // was: null
+*/
// this one won't show up in the output because a call to f1 is elidable when accessed through T
(c:T).f1()
diff --git a/test/files/run/existentials-in-compiler.check b/test/files/run/existentials-in-compiler.check
index b0d852865d..8800df0823 100644
--- a/test/files/run/existentials-in-compiler.check
+++ b/test/files/run/existentials-in-compiler.check
@@ -2,28 +2,28 @@ abstract trait Bippy[A <: AnyRef, B] extends AnyRef
extest.Bippy[_ <: AnyRef, _]
abstract trait BippyBud[A <: AnyRef, B, C <: List[A]] extends AnyRef
- extest.BippyBud[A,B,C] forSome { A <: AnyRef; B; C <: List[A] }
+ extest.BippyBud[?0,?1,?2] forSome { type ?0 <: AnyRef; type ?1; type ?2 <: List[?0] }
abstract trait BippyLike[A <: AnyRef, B <: List[A], This <: extest.BippyLike[A,B,This] with extest.Bippy[A,B]] extends AnyRef
- extest.BippyLike[A,B,This] forSome { A <: AnyRef; B <: List[A]; This <: extest.BippyLike[A,B,This] with extest.Bippy[A,B] }
+ extest.BippyLike[?0,?1,?2] forSome { type ?0 <: AnyRef; type ?1 <: List[?0]; type ?2 <: extest.BippyLike[?0,?1,?2] with extest.Bippy[?0,?1] }
abstract trait Contra[-A >: AnyRef, -B] extends AnyRef
- extest.Contra[AnyRef, _]
+ extest.Contra[_ >: AnyRef, _]
abstract trait ContraLike[-A >: AnyRef, -B >: List[A]] extends AnyRef
- extest.ContraLike[A,B] forSome { -A >: AnyRef; -B >: List[A] }
+ extest.ContraLike[?0,?1] forSome { type ?0 >: AnyRef; type ?1 >: List[?0] }
abstract trait Cov01[+A <: AnyRef, +B] extends AnyRef
- extest.Cov01[AnyRef,Any]
+ extest.Cov01[_ <: AnyRef, _]
abstract trait Cov02[+A <: AnyRef, B] extends AnyRef
- extest.Cov02[AnyRef, _]
+ extest.Cov02[_ <: AnyRef, _]
abstract trait Cov03[+A <: AnyRef, -B] extends AnyRef
- extest.Cov03[AnyRef, _]
+ extest.Cov03[_ <: AnyRef, _]
abstract trait Cov04[A <: AnyRef, +B] extends AnyRef
- extest.Cov04[_ <: AnyRef, Any]
+ extest.Cov04[_ <: AnyRef, _]
abstract trait Cov05[A <: AnyRef, B] extends AnyRef
extest.Cov05[_ <: AnyRef, _]
@@ -32,7 +32,7 @@ abstract trait Cov06[A <: AnyRef, -B] extends AnyRef
extest.Cov06[_ <: AnyRef, _]
abstract trait Cov07[-A <: AnyRef, +B] extends AnyRef
- extest.Cov07[_ <: AnyRef, Any]
+ extest.Cov07[_ <: AnyRef, _]
abstract trait Cov08[-A <: AnyRef, B] extends AnyRef
extest.Cov08[_ <: AnyRef, _]
@@ -41,16 +41,16 @@ abstract trait Cov09[-A <: AnyRef, -B] extends AnyRef
extest.Cov09[_ <: AnyRef, _]
abstract trait Cov11[+A <: AnyRef, +B <: List[_]] extends AnyRef
- extest.Cov11[AnyRef,List[_]]
+ extest.Cov11[_ <: AnyRef, _ <: List[_]]
abstract trait Cov12[+A <: AnyRef, B <: List[_]] extends AnyRef
- extest.Cov12[AnyRef, _ <: List[_]]
+ extest.Cov12[_ <: AnyRef, _ <: List[_]]
abstract trait Cov13[+A <: AnyRef, -B <: List[_]] extends AnyRef
- extest.Cov13[AnyRef, _ <: List[_]]
+ extest.Cov13[_ <: AnyRef, _ <: List[_]]
abstract trait Cov14[A <: AnyRef, +B <: List[_]] extends AnyRef
- extest.Cov14[_ <: AnyRef, List[_]]
+ extest.Cov14[_ <: AnyRef, _ <: List[_]]
abstract trait Cov15[A <: AnyRef, B <: List[_]] extends AnyRef
extest.Cov15[_ <: AnyRef, _ <: List[_]]
@@ -59,7 +59,7 @@ abstract trait Cov16[A <: AnyRef, -B <: List[_]] extends AnyRef
extest.Cov16[_ <: AnyRef, _ <: List[_]]
abstract trait Cov17[-A <: AnyRef, +B <: List[_]] extends AnyRef
- extest.Cov17[_ <: AnyRef, List[_]]
+ extest.Cov17[_ <: AnyRef, _ <: List[_]]
abstract trait Cov18[-A <: AnyRef, B <: List[_]] extends AnyRef
extest.Cov18[_ <: AnyRef, _ <: List[_]]
@@ -68,16 +68,16 @@ abstract trait Cov19[-A <: AnyRef, -B <: List[_]] extends AnyRef
extest.Cov19[_ <: AnyRef, _ <: List[_]]
abstract trait Cov21[+A, +B] extends AnyRef
- extest.Cov21[Any,Any]
+ extest.Cov21[_, _]
abstract trait Cov22[+A, B] extends AnyRef
- extest.Cov22[Any, _]
+ extest.Cov22[_, _]
abstract trait Cov23[+A, -B] extends AnyRef
- extest.Cov23[Any, _]
+ extest.Cov23[_, _]
abstract trait Cov24[A, +B] extends AnyRef
- extest.Cov24[_, Any]
+ extest.Cov24[_, _]
abstract trait Cov25[A, B] extends AnyRef
extest.Cov25[_, _]
@@ -86,7 +86,7 @@ abstract trait Cov26[A, -B] extends AnyRef
extest.Cov26[_, _]
abstract trait Cov27[-A, +B] extends AnyRef
- extest.Cov27[_, Any]
+ extest.Cov27[_, _]
abstract trait Cov28[-A, B] extends AnyRef
extest.Cov28[_, _]
@@ -95,43 +95,43 @@ abstract trait Cov29[-A, -B] extends AnyRef
extest.Cov29[_, _]
abstract trait Cov31[+A, +B, C <: (A, B)] extends AnyRef
- extest.Cov31[A,B,C] forSome { +A; +B; C <: (A, B) }
+ extest.Cov31[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: (?0, ?1) }
abstract trait Cov32[+A, B, C <: (A, B)] extends AnyRef
- extest.Cov32[A,B,C] forSome { +A; B; C <: (A, B) }
+ extest.Cov32[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: (?0, ?1) }
abstract trait Cov33[+A, -B, C <: Tuple2[A, _]] extends AnyRef
- extest.Cov33[A,B,C] forSome { +A; -B; C <: Tuple2[A, _] }
+ extest.Cov33[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: Tuple2[?0, _] }
abstract trait Cov34[A, +B, C <: (A, B)] extends AnyRef
- extest.Cov34[A,B,C] forSome { A; +B; C <: (A, B) }
+ extest.Cov34[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: (?0, ?1) }
abstract trait Cov35[A, B, C <: (A, B)] extends AnyRef
- extest.Cov35[A,B,C] forSome { A; B; C <: (A, B) }
+ extest.Cov35[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: (?0, ?1) }
abstract trait Cov36[A, -B, C <: Tuple2[A, _]] extends AnyRef
- extest.Cov36[A,B,C] forSome { A; -B; C <: Tuple2[A, _] }
+ extest.Cov36[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: Tuple2[?0, _] }
abstract trait Cov37[-A, +B, C <: Tuple2[_, B]] extends AnyRef
- extest.Cov37[A,B,C] forSome { -A; +B; C <: Tuple2[_, B] }
+ extest.Cov37[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: Tuple2[_, ?1] }
abstract trait Cov38[-A, B, C <: Tuple2[_, B]] extends AnyRef
- extest.Cov38[A,B,C] forSome { -A; B; C <: Tuple2[_, B] }
+ extest.Cov38[?0,?1,?2] forSome { type ?0; type ?1; type ?2 <: Tuple2[_, ?1] }
abstract trait Cov39[-A, -B, C <: Tuple2[_, _]] extends AnyRef
extest.Cov39[_, _, _ <: Tuple2[_, _]]
abstract trait Cov41[+A >: Null, +B] extends AnyRef
- extest.Cov41[Any,Any]
+ extest.Cov41[_ >: Null, _]
abstract trait Cov42[+A >: Null, B] extends AnyRef
- extest.Cov42[Any, _]
+ extest.Cov42[_ >: Null, _]
abstract trait Cov43[+A >: Null, -B] extends AnyRef
- extest.Cov43[Any, _]
+ extest.Cov43[_ >: Null, _]
abstract trait Cov44[A >: Null, +B] extends AnyRef
- extest.Cov44[_ >: Null, Any]
+ extest.Cov44[_ >: Null, _]
abstract trait Cov45[A >: Null, B] extends AnyRef
extest.Cov45[_ >: Null, _]
@@ -140,7 +140,7 @@ abstract trait Cov46[A >: Null, -B] extends AnyRef
extest.Cov46[_ >: Null, _]
abstract trait Cov47[-A >: Null, +B] extends AnyRef
- extest.Cov47[_ >: Null, Any]
+ extest.Cov47[_ >: Null, _]
abstract trait Cov48[-A >: Null, B] extends AnyRef
extest.Cov48[_ >: Null, _]
@@ -149,8 +149,8 @@ abstract trait Cov49[-A >: Null, -B] extends AnyRef
extest.Cov49[_ >: Null, _]
abstract trait Covariant[+A <: AnyRef, +B] extends AnyRef
- extest.Covariant[AnyRef,Any]
+ extest.Covariant[_ <: AnyRef, _]
abstract trait CovariantLike[+A <: AnyRef, +B <: List[A], +This <: extest.CovariantLike[A,B,This] with extest.Covariant[A,B]] extends AnyRef
- extest.CovariantLike[A,B,This] forSome { +A <: AnyRef; +B <: List[A]; +This <: extest.CovariantLike[A,B,This] with extest.Covariant[A,B] }
+ extest.CovariantLike[?0,?1,?2] forSome { type ?0 <: AnyRef; type ?1 <: List[?0]; type ?2 <: extest.CovariantLike[?0,?1,?2] with extest.Covariant[?0,?1] }
diff --git a/test/files/run/existentials-in-compiler.scala b/test/files/run/existentials-in-compiler.scala
index e516eddf95..e35b7231c2 100644
--- a/test/files/run/existentials-in-compiler.scala
+++ b/test/files/run/existentials-in-compiler.scala
@@ -79,7 +79,7 @@ package extest {
exitingTyper {
clazz.info
println(clazz.defString)
- println(" " + classExistentialType(clazz) + "\n")
+ println(" " + classExistentialType(clazz.owner.typeOfThis, clazz) + "\n")
}
}
}
diff --git a/test/files/run/hash-hash-hash-hash.scala b/test/files/run/hash-hash-hash-hash.scala
new file mode 100644
index 0000000000..08793871a7
--- /dev/null
+++ b/test/files/run/hash-hash-hash-hash.scala
@@ -0,0 +1,5 @@
+object Test {
+ def main(args: Array[String]): Unit = {
+ assert(1.##.## == 1) // was java.lang.NoSuchMethodError: java.lang.Object.$hash$hash()I
+ }
+}
diff --git a/test/files/run/iq.scala b/test/files/run/iq.scala
index 0ccf67a2e9..9929f0e1a0 100644
--- a/test/files/run/iq.scala
+++ b/test/files/run/iq.scala
@@ -25,12 +25,18 @@ object iq {
assert(q2 == qb)
val qc = 42 +: q :+ 0
assert(q2 == qc)
+ assert(q ++ qa == qa)
+ val qdr = 1 +: 2 +: 3 +: 4 +: q
+ val qcon1 = 1 +: 2 +: q
+ val qcon2 = q :+ 3 :+ 4
+ val qd = qcon1 ++ qcon2
+ assert(qd == qdr)
Console.println("q2: " + q2)
Console.println("qa: " + qa)
Console.println("qb: " + qb)
Console.println("qc: " + qc)
-
+
/* Test is empty and dequeue.
* Expected: Head: 42
*/
diff --git a/test/files/run/literals.scala b/test/files/run/literals.scala
index 13fda05876..a7962e5cd9 100644
--- a/test/files/run/literals.scala
+++ b/test/files/run/literals.scala
@@ -6,7 +6,7 @@
object Test {
- /* I add a couple of Unicode identifier tests here temporarily */
+ /* I add a couple of Unicode identifier tests here "temporarily" */
def \u03b1\u03c1\u03b5\u03c4\u03b7 = "alpha rho epsilon tau eta"
@@ -80,10 +80,17 @@ object Test {
check_success("1e1f == 10.0f", 1e1f, 10.0f)
check_success(".3f == 0.3f", .3f, 0.3f)
check_success("0f == 0.0f", 0f, 0.0f)
+ check_success("0f == -0.000000000000000000e+00f", 0f, -0.000000000000000000e+00f)
+ check_success("0f == -0.000000000000000000e+00F", 0f, -0.000000000000000000e+00F)
+ check_success("0f == -0.0000000000000000e14f", 0f, -0.0000000000000000e14f)
check_success("01.23f == 1.23f", 01.23f, 1.23f)
check_success("3.14f == 3.14f", 3.14f, 3.14f)
check_success("6.022e23f == 6.022e23f", 6.022e23f, 6.022e23f)
check_success("09f == 9.0f", 09f, 9.0f)
+ check_success("1.00000017881393421514957253748434595763683319091796875001f == 1.0000001f",
+ 1.00000017881393421514957253748434595763683319091796875001f,
+ 1.0000001f)
+ check_success("3.4028235E38f == Float.MaxValue", 3.4028235E38f, Float.MaxValue)
check_success("1.asInstanceOf[Float] == 1.0", 1.asInstanceOf[Float], 1.0f)
check_success("1l.asInstanceOf[Float] == 1.0", 1l.asInstanceOf[Float], 1.0f)
@@ -92,11 +99,17 @@ object Test {
check_success(".3 == 0.3", .3, 0.3)
check_success("0.0 == 0.0", 0.0, 0.0)
check_success("0d == 0.0", 0d, 0.0)
+ check_success("0d == 0.000000000000000000e+00d", 0d, 0.000000000000000000e+00d)
+ check_success("0d == -0.000000000000000000e+00d", 0d, -0.000000000000000000e+00d)
+ check_success("0d == -0.000000000000000000e+00D", 0d, -0.000000000000000000e+00D)
+ check_success("0.0 == 0.000000000000000000e+00", 0.0, 0.000000000000000000e+00)
+ check_success("0.0 == -0.000000000000000000e+00", 0.0, -0.000000000000000000e+00)
check_success("01.23 == 1.23", 01.23, 1.23)
check_success("01.23d == 1.23d", 01.23d, 1.23d)
check_success("3.14 == 3.14", 3.14, 3.14)
check_success("1e-9d == 1.0e-9", 1e-9d, 1.0e-9)
check_success("1e137 == 1.0e137", 1e137, 1.0e137)
+ check_success("1.7976931348623157e308d == Double.MaxValue", 1.7976931348623157e308d, Double.MaxValue)
check_success("1.asInstanceOf[Double] == 1.0", 1.asInstanceOf[Double], 1.0)
check_success("1l.asInstanceOf[Double] == 1.0", 1l.asInstanceOf[Double], 1.0)
diff --git a/test/files/run/patmat-exprs.scala b/test/files/run/patmat-exprs.scala
index 7ca5fd3063..d18df9c714 100644
--- a/test/files/run/patmat-exprs.scala
+++ b/test/files/run/patmat-exprs.scala
@@ -344,13 +344,13 @@ trait Pattern {
}
- case class Zero[T] (implicit num: NumericOps[T]) extends Leaf[T] {
+ case class Zero[T]()(implicit num: NumericOps[T]) extends Leaf[T] {
def derivative(variable: Var[T]) = Zero[T]
def eval(f: Any => Any) = num.zero
override def toString = "0"
}
- case class One[T] (implicit num: NumericOps[T]) extends Leaf[T] {
+ case class One[T]()(implicit num: NumericOps[T]) extends Leaf[T] {
def derivative(variable: Var[T]) = Zero[T]
def eval(f: Any => Any) = num.one
override def toString = "1"
diff --git a/test/files/run/repl-colon-type.check b/test/files/run/repl-colon-type.check
index 1217e8d8c2..5b7a3c7506 100644
--- a/test/files/run/repl-colon-type.check
+++ b/test/files/run/repl-colon-type.check
@@ -75,7 +75,7 @@ TypeRef(
)
TypeRef(
TypeSymbol(
- sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with Serializable
+ sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with FilteredTraversableInternal[A,List[A]] with Serializable
)
args = List(
@@ -142,7 +142,7 @@ TypeRef(
args = List(
TypeRef(
TypeSymbol(
- sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with Serializable
+ sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with FilteredTraversableInternal[A,List[A]] with Serializable
)
args = List(
@@ -175,7 +175,7 @@ PolyType(
args = List(
TypeRef(
TypeSymbol(
- sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with Serializable
+ sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with FilteredTraversableInternal[A,List[A]] with Serializable
)
args = List(TypeParamTypeRef(TypeParam(T <: AnyVal)))
@@ -198,7 +198,7 @@ PolyType(
params = List(TermSymbol(x: T), TermSymbol(y: List[U]))
resultType = TypeRef(
TypeSymbol(
- sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with Serializable
+ sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with Product with GenericTraversableTemplate[A,List] with LinearSeqOptimized[A,List[A]] with FilteredTraversableInternal[A,List[A]] with Serializable
)
args = List(TypeParamTypeRef(TypeParam(U >: T)))
diff --git a/test/files/run/t10026.check b/test/files/run/t10026.check
new file mode 100644
index 0000000000..15a62794a9
--- /dev/null
+++ b/test/files/run/t10026.check
@@ -0,0 +1 @@
+List(1, 2, 3)
diff --git a/test/files/run/t10026.scala b/test/files/run/t10026.scala
new file mode 100644
index 0000000000..a56840c8c2
--- /dev/null
+++ b/test/files/run/t10026.scala
@@ -0,0 +1,11 @@
+import scala.reflect.runtime.universe
+import scala.tools.reflect.ToolBox
+
+object Test {
+ def main(args: Array[String]): Unit = {
+ val classloader = getClass.getClassLoader
+ val toolbox = universe.runtimeMirror(classloader).mkToolBox()
+ println(toolbox.compile(toolbox.parse("Array(1, 2, 3).toList")).apply())
+ }
+}
+
diff --git a/test/files/run/t10072.scala b/test/files/run/t10072.scala
new file mode 100644
index 0000000000..0f1dca1838
--- /dev/null
+++ b/test/files/run/t10072.scala
@@ -0,0 +1,18 @@
+trait T[A] {
+ def a: A
+ def foldLeft[B](zero: B, op: (B, A) => B): B = op(zero, a)
+ def sum[B >: A](zero: B): B
+}
+
+class C[@specialized(Int) A](val a: A) extends T[A] {
+ override def sum[@specialized(Int) B >: A](zero: B): B = foldLeft(zero, (x: B, y: B) => x)
+}
+
+object Test extends App {
+ def factory[T](a: T): C[T] = new C[T](a)
+
+ assert(new C[Int](1).sum(2) == 2)
+ assert(new C[String]("ho").sum("hu") == "hu")
+ assert(factory[Int](1).sum(2) == 2)
+ assert(factory[String]("ho").sum("hu") == "hu")
+}
diff --git a/test/files/run/t10097.check b/test/files/run/t10097.check
new file mode 100644
index 0000000000..0e8b96061c
--- /dev/null
+++ b/test/files/run/t10097.check
@@ -0,0 +1,3 @@
+t10097.scala:2: warning: case classes should have a non-implicit parameter list; adapting to 'case class C()(...)'
+case class C(implicit c: Int)
+ ^
diff --git a/test/files/run/t10097.flags b/test/files/run/t10097.flags
new file mode 100644
index 0000000000..dcc59ebe32
--- /dev/null
+++ b/test/files/run/t10097.flags
@@ -0,0 +1 @@
+-deprecation
diff --git a/test/files/run/t10097.scala b/test/files/run/t10097.scala
new file mode 100644
index 0000000000..a16be897cc
--- /dev/null
+++ b/test/files/run/t10097.scala
@@ -0,0 +1,6 @@
+
+case class C(implicit c: Int)
+
+object Test extends App {
+ assert(C()(42).productArity == 0)
+}
diff --git a/test/files/run/t1459.check b/test/files/run/t1459.check
new file mode 100644
index 0000000000..93b4c5a810
--- /dev/null
+++ b/test/files/run/t1459.check
@@ -0,0 +1,3 @@
+JavaPrinter: one two three
+InheritingPrinter extends JavaPrinter: one two three
+ScalaPrinter: onetwothree
diff --git a/test/files/run/t1459/InheritingPrinter.scala b/test/files/run/t1459/InheritingPrinter.scala
new file mode 100644
index 0000000000..70301307f5
--- /dev/null
+++ b/test/files/run/t1459/InheritingPrinter.scala
@@ -0,0 +1,6 @@
+class InheritingPrinter extends JavaPrinter {
+ override def doit(s: String*) {
+ print("InheritingPrinter extends ")
+ super.doit(s: _*);
+ }
+} \ No newline at end of file
diff --git a/test/files/run/t1459/JavaPrinter.java b/test/files/run/t1459/JavaPrinter.java
new file mode 100644
index 0000000000..3912ea613a
--- /dev/null
+++ b/test/files/run/t1459/JavaPrinter.java
@@ -0,0 +1,7 @@
+public class JavaPrinter implements VarArg {
+ public void doit(String... s) {
+ System.out.print("JavaPrinter: ");
+ for(String str : s)
+ System.out.print(str + " ");
+ }
+}
diff --git a/test/files/run/t1459/ScalaPrinter.scala b/test/files/run/t1459/ScalaPrinter.scala
new file mode 100644
index 0000000000..46305804c2
--- /dev/null
+++ b/test/files/run/t1459/ScalaPrinter.scala
@@ -0,0 +1,6 @@
+class ScalaPrinter extends VarArg {
+ override def doit(s: String*) = {
+ print("ScalaPrinter: ")
+ s.foreach(print _)
+ }
+} \ No newline at end of file
diff --git a/test/files/run/t1459/Test.java b/test/files/run/t1459/Test.java
new file mode 100644
index 0000000000..3cf91e2e8b
--- /dev/null
+++ b/test/files/run/t1459/Test.java
@@ -0,0 +1,15 @@
+public class Test {
+ public static void main(String[] args) {
+ VarArg jp = new JavaPrinter();
+ VarArg ip = new InheritingPrinter();
+ VarArg sp = new ScalaPrinter();
+ doYourThing(jp);
+ doYourThing(ip);
+ doYourThing(sp);
+ }
+
+ public static void doYourThing(VarArg va) {
+ va.doit("one", "two", "three");
+ System.out.println();
+ }
+}
diff --git a/test/files/run/t1459/VarArg.java b/test/files/run/t1459/VarArg.java
new file mode 100644
index 0000000000..7039f99e7b
--- /dev/null
+++ b/test/files/run/t1459/VarArg.java
@@ -0,0 +1,3 @@
+public interface VarArg {
+ void doit(String... s);
+}
diff --git a/test/files/run/t1459generic.check b/test/files/run/t1459generic.check
new file mode 100644
index 0000000000..346fadbc0d
--- /dev/null
+++ b/test/files/run/t1459generic.check
@@ -0,0 +1,4 @@
+Note: t1459generic/Test.java uses unchecked or unsafe operations.
+Note: Recompile with -Xlint:unchecked for details.
+ab
+ab
diff --git a/test/files/run/t1459generic/Impl.scala b/test/files/run/t1459generic/Impl.scala
new file mode 100644
index 0000000000..9234e70456
--- /dev/null
+++ b/test/files/run/t1459generic/Impl.scala
@@ -0,0 +1,4 @@
+class Impl extends VarargGeneric[String] {
+ def genericOne(x: String, arg: String): String = x + arg
+ def genericVar(x: String, args: String*): String = x + args.head
+}
diff --git a/test/files/run/t1459generic/Test.java b/test/files/run/t1459generic/Test.java
new file mode 100644
index 0000000000..a97158796b
--- /dev/null
+++ b/test/files/run/t1459generic/Test.java
@@ -0,0 +1,10 @@
+public class Test {
+ public static void main(String[] args) throws Exception {
+ VarargGeneric vg = new Impl();
+ System.out.println(vg.genericOne("a", "b"));
+ System.out.println(vg.genericVar("a", "b"));
+ // should not result in java.lang.AbstractMethodError: Impl.genericVar(Ljava/lang/Object;[Ljava/lang/String;)Ljava/lang/String;
+ // --> genericVar needs a varargs bridge (scala -> java varargs) and a standard generics bridge
+ // (for comparison, including genericOne, which needs only a generics bridge)
+ }
+}
diff --git a/test/files/run/t1459generic/VarargGeneric.java b/test/files/run/t1459generic/VarargGeneric.java
new file mode 100644
index 0000000000..9b37a0fe3f
--- /dev/null
+++ b/test/files/run/t1459generic/VarargGeneric.java
@@ -0,0 +1,7 @@
+public interface VarargGeneric<T> {
+ String genericOne(T x, String args);
+ // we cannot annotate this with @SafeVarargs, because
+ // it's in an interface. so that's why a warning from
+ // javac appears in the checkfile.
+ String genericVar(T x, String... args);
+}
diff --git a/test/files/run/t4700.check b/test/files/run/t4700.check
new file mode 100644
index 0000000000..ae854b959d
--- /dev/null
+++ b/test/files/run/t4700.check
@@ -0,0 +1,44 @@
+
+scala> import scala.annotation.showAsInfix
+import scala.annotation.showAsInfix
+
+scala> class &&[T,U]
+defined class $amp$amp
+
+scala> def foo: Int && Boolean = ???
+foo: Int && Boolean
+
+scala> def foo: Int && Boolean && String = ???
+foo: Int && Boolean && String
+
+scala> def foo: Int && (Boolean && String) = ???
+foo: Int && (Boolean && String)
+
+scala> @showAsInfix type Mappy[T, U] = Map[T, U]
+defined type alias Mappy
+
+scala> def foo: Int Mappy (Boolean && String) = ???
+foo: Int Mappy (Boolean && String)
+
+scala> @showAsInfix(false) class ||[T,U]
+defined class $bar$bar
+
+scala> def foo: Int || Boolean = ???
+foo: ||[Int,Boolean]
+
+scala> class &:[L, R]
+defined class $amp$colon
+
+scala> def foo: Int &: String = ???
+foo: Int &: String
+
+scala> def foo: Int &: Boolean &: String = ???
+foo: Int &: Boolean &: String
+
+scala> def foo: (Int && String) &: Boolean = ???
+foo: (Int && String) &: Boolean
+
+scala> def foo: Int && (Boolean &: String) = ???
+foo: Int && (Boolean &: String)
+
+scala> :quit
diff --git a/test/files/run/t4700.scala b/test/files/run/t4700.scala
new file mode 100644
index 0000000000..7c02676e89
--- /dev/null
+++ b/test/files/run/t4700.scala
@@ -0,0 +1,22 @@
+import scala.tools.nsc.interpreter._
+import scala.tools.partest.ReplTest
+
+object Test extends ReplTest {
+ def code = """
+ |import scala.annotation.showAsInfix
+ |class &&[T,U]
+ |def foo: Int && Boolean = ???
+ |def foo: Int && Boolean && String = ???
+ |def foo: Int && (Boolean && String) = ???
+ |@showAsInfix type Mappy[T, U] = Map[T, U]
+ |def foo: Int Mappy (Boolean && String) = ???
+ |@showAsInfix(false) class ||[T,U]
+ |def foo: Int || Boolean = ???
+ |class &:[L, R]
+ |def foo: Int &: String = ???
+ |def foo: Int &: Boolean &: String = ???
+ |def foo: (Int && String) &: Boolean = ???
+ |def foo: Int && (Boolean &: String) = ???
+ |""".stripMargin
+}
+
diff --git a/test/files/run/t5907.scala b/test/files/run/t5907.scala
index a005e9fbd3..81fc43e3f5 100644
--- a/test/files/run/t5907.scala
+++ b/test/files/run/t5907.scala
@@ -86,7 +86,7 @@ object Test extends App {
}
}
-case class C1(implicit x: Int) {
+case class C1()(implicit x: Int) {
override def toString = s"c1: $x"
}
case class C2()(y: Int) {
diff --git a/test/files/run/t9013/Test.java b/test/files/run/t9013/Test.java
new file mode 100644
index 0000000000..14152b16ac
--- /dev/null
+++ b/test/files/run/t9013/Test.java
@@ -0,0 +1,20 @@
+import java.util.Comparator;
+
+public class Test {
+ public static void main(String[] args) {
+ ClassImplementsClass c = new ClassImplementsClass();
+
+ c.x("a", "b", "c");
+ c.y("a", "b", "c");
+ c.z("a", "b", "c");
+
+ VarargAbstractClass i = new ClassImplementsClass();
+
+ i.x("a", "b", "c");
+ i.y("a", "b", "c");
+ // System.out.println(i.z("a", "b", "c")); // still incurs a LinkageError.
+ // Perhaps due to Uncurry:
+ // > for every repeated Java parameter `x: T...' --> x: Array[T], except:
+ // > if T is an unbounded abstract type, replace --> x: Array[Object]
+ }
+}
diff --git a/test/files/run/t9013/test.scala b/test/files/run/t9013/test.scala
new file mode 100644
index 0000000000..073f8d086f
--- /dev/null
+++ b/test/files/run/t9013/test.scala
@@ -0,0 +1,18 @@
+import scala.annotation.varargs
+
+abstract class VarargAbstractClass[T] {
+ @varargs
+ def x(els: String*): Int
+
+ @varargs
+ def y(els: String*): Int
+
+ @varargs
+ def z(els: T*): Int
+}
+class ClassImplementsClass extends VarargAbstractClass[String] {
+
+ override def x(els: String*): Int = els.length
+ override def y(els: String*): Int = els.length
+ override def z(els: String*): Int = els.length
+}
diff --git a/test/files/run/t9114.scala b/test/files/run/t9114.scala
new file mode 100644
index 0000000000..656a5c7d8d
--- /dev/null
+++ b/test/files/run/t9114.scala
@@ -0,0 +1,31 @@
+import annotation.unchecked
+
+class Test {
+ trait Two[A, B]
+ type One[A] = Two[A,A]
+ class View extends One[Any]
+
+ def checkAny(x: Some[One[Any]]) = x match { // okay
+ case Some(_: View) => true
+ case _ => false
+ }
+ def checkAbstract[A](x: Some[One[A]]) = x match { // okay
+ case Some(_: View) => true
+ case _ => false
+ }
+
+ def checkExistential(x: Some[One[_]]) = x match {
+ case Some(_: View) => true // compiler crash
+ case _ => false
+ }
+}
+
+object Test {
+ def main(args: Array[String]): Unit = {
+ val t1 = new Test
+ val t2 = new Test
+ assert(t1.checkAny(Some(new t1.View)))
+ assert(t1.checkAbstract(Some(new t1.View)))
+ assert(t1.checkExistential(Some(new t1.View)))
+ }
+}
diff --git a/test/files/run/t9880-9881.check b/test/files/run/t9880-9881.check
new file mode 100644
index 0000000000..36513e249a
--- /dev/null
+++ b/test/files/run/t9880-9881.check
@@ -0,0 +1,36 @@
+
+scala> // import in various ways
+
+scala> import java.util.Date
+import java.util.Date
+
+scala> import scala.util._
+import scala.util._
+
+scala> import scala.reflect.runtime.{universe => ru}
+import scala.reflect.runtime.{universe=>ru}
+
+scala> import ru.TypeTag
+import ru.TypeTag
+
+scala>
+
+scala> // show the imports
+
+scala> :imports
+ 1) import java.lang._ (...)
+ 2) import scala._ (...)
+ 3) import scala.Predef._ (...)
+ 4) import java.util.Date (...)
+ 5) import scala.util._ (...)
+ 6) import scala.reflect.runtime.{universe=>ru} (...)
+ 7) import ru.TypeTag (...)
+
+scala>
+
+scala> // should be able to define this class with the imports above
+
+scala> class C[T](date: Date, rand: Random, typeTag: TypeTag[T])
+defined class C
+
+scala> :quit
diff --git a/test/files/run/t9880-9881.scala b/test/files/run/t9880-9881.scala
new file mode 100644
index 0000000000..0268c8c32c
--- /dev/null
+++ b/test/files/run/t9880-9881.scala
@@ -0,0 +1,29 @@
+import scala.tools.partest.ReplTest
+import scala.tools.nsc.Settings
+
+object Test extends ReplTest {
+
+ override def transformSettings(s: Settings): Settings = {
+ s.Yreplclassbased.value = true
+ s
+ }
+
+ lazy val normalizeRegex = """(import\s.*)\(.*\)""".r
+
+ override def normalize(s: String): String = normalizeRegex.replaceFirstIn(s, "$1(...)")
+
+ def code =
+ """
+ |// import in various ways
+ |import java.util.Date
+ |import scala.util._
+ |import scala.reflect.runtime.{universe => ru}
+ |import ru.TypeTag
+ |
+ |// show the imports
+ |:imports
+ |
+ |// should be able to define this class with the imports above
+ |class C[T](date: Date, rand: Random, typeTag: TypeTag[T])
+ """.stripMargin
+}
diff --git a/test/files/run/trailing-commas.check b/test/files/run/trailing-commas.check
new file mode 100644
index 0000000000..0dc4335ccd
--- /dev/null
+++ b/test/files/run/trailing-commas.check
@@ -0,0 +1,9 @@
+
+scala> // test varargs in patterns
+
+scala> val List(x, y, _*,
+) = 42 :: 17 :: Nil
+x: Int = 42
+y: Int = 17
+
+scala> :quit
diff --git a/test/files/run/trailing-commas.scala b/test/files/run/trailing-commas.scala
new file mode 100644
index 0000000000..6a7f1bb55f
--- /dev/null
+++ b/test/files/run/trailing-commas.scala
@@ -0,0 +1,7 @@
+object Test extends scala.tools.partest.ReplTest {
+ def code = """
+// test varargs in patterns
+val List(x, y, _*,
+) = 42 :: 17 :: Nil
+"""
+}
diff --git a/test/files/run/unit-block-hash-hash.scala b/test/files/run/unit-block-hash-hash.scala
new file mode 100644
index 0000000000..2708810a71
--- /dev/null
+++ b/test/files/run/unit-block-hash-hash.scala
@@ -0,0 +1,12 @@
+object Ex extends Exception
+object Test {
+ def ex: Any = throw Ex
+ def main(args: Array[String]): Unit = {
+ try {
+ { ex; () }.##
+ sys.error("no exception was thrown")
+ } catch {
+ case `Ex` =>
+ }
+ }
+} \ No newline at end of file
diff --git a/test/junit/scala/collection/IndexedSeqTest.scala b/test/junit/scala/collection/IndexedSeqTest.scala
new file mode 100644
index 0000000000..a33849e60b
--- /dev/null
+++ b/test/junit/scala/collection/IndexedSeqTest.scala
@@ -0,0 +1,578 @@
+package scala.collection
+
+import org.junit.Test
+import org.junit.Ignore
+import org.junit.Assert.{assertEquals, _}
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+// with the Ant JUnit runner, it's necessary to @Ignore the abstract
+// classes here, or JUnit tries to instantiate them. the annotations
+// can be removed when this is merged forward (TODO 2.12.x)
+
+/**
+ * base class for testing common methods on a various implementations
+ *
+ * @tparam T the collection type
+ * @tparam E the element type
+ */
+@RunWith(classOf[JUnit4])
+@Ignore
+abstract class IndexedTest[T, E] {
+
+ protected def size = 10
+
+ /**
+ * create a new instance of the test data with known values
+ */
+ protected def underTest(size: Int): T
+
+ /**
+ * returns the value of the data that is expected to be present int the original data at index {{{index}}}
+ * This is conceptully the same as the normal apply operation but unavaialbe due to the base types of T not supporting apply
+ *
+ * @param index the index to use for the returned value
+ * @return the value at the specified index
+ */
+ protected def expectedValueAtIndex(index: Int): E
+ /**
+ * check some simple indexed access
+ */
+ @Test def checkIndexedAccess: Unit = {
+ val test = underTest(size)
+ for (i <- 0 until size) {
+ assertEquals(s" at index $i", expectedValueAtIndex(i), get(test, i))
+ }
+ }
+
+ /**
+ * check simple equallity of the initial data.
+ * More a test of the infra that we use in this est than a full test of equallity
+ */
+ @Test def checkEquals: Unit = {
+ val test1 = underTest(size)
+ val test2 = underTest(size)
+ doAssertEquals("", test1, test2)
+ assertNotSame(test1, test2)
+ expectSameContent("basic equallity", false, test1, test2, 0, size)
+ }
+
+ protected def expectSameContent(txt: String, canBeSame:Boolean, orig: T, test: T, offset: Int, len: Int): Unit = {
+ val txtAndState = s"$txt canBeSame $canBeSame isMutableContent $isMutableContent isTakeAllSame $isTakeAllSame offset $offset len $len length(test) ${length(test)}"
+ val isValidSame = canBeSame && !isMutableContent && offset == 0 && len == size
+ if (isValidSame && isTakeAllSame)
+ assertSame(txtAndState, orig, test)
+ else
+ assertNotSame(txtAndState, orig, test)
+ assertSame(txtAndState, len, length(test))
+ for (i <- 0 until len) {
+ assertEquals(s" $txtAndState $i $offset $len", expectedValueAtIndex(i + offset), get(test, i))
+ }
+ }
+
+ /**
+ * check the operation of {{{take}}} when the parameter is less than the size of the test data
+ */
+ @Test def checkTakeNormal: Unit = {
+ val orig = underTest(size)
+ for (len <- 0 until size) {
+ val taken = take(orig, len)
+ expectSameContent(s" len $len", true, orig, taken, 0, len)
+ }
+ }
+
+ /**
+ * check the operation of {{{slice}}} within the bounds of the source
+ */
+ @Test def checkSliceNormal: Unit = {
+ val orig = underTest(size)
+ for (
+ from <- 0 until size;
+ to <- from until size) {
+
+ val sliced = slice(orig, from, to)
+ expectSameContent(s"from $from, to $to", true, orig, sliced, from, to - from)
+ }
+ }
+
+ /**
+ * check the operation of {{{take}}} works for size of 0
+ * There is a special case tha for some implementations empty will be a singleton
+ */
+ @Test def checkTakeEmpty: Unit = {
+ val orig = underTest(size)
+ val empty1 = take(orig, 0)
+ val empty2 = take(orig, 0)
+ assertEquals(0, length(empty1))
+ if (isEmptyConstant) assertSame(empty1, empty2)
+ }
+
+ /**
+ * check the operation of {{{slice}}} works for size of 0
+ * There is a special case tha for some implementations empty will be a singleton
+ */
+ @Test def checkSliceEmpty: Unit = {
+ val orig = underTest(size)
+ for (start <- 0 until size) {
+ val empty1 = slice(orig, start, start)
+ val empty2 = slice(orig, start, start)
+ assertEquals(s"start $start", 0, length(empty1))
+ if (isEmptyConstant) assertSame(s"start $start", empty1, empty2)
+ }
+ }
+
+ /**
+ * check the operation of {{{take}}} works for the entire content
+ * There is a special case that for some immutable implementations they can share the result
+ */
+ @Test def checkTakeAll: Unit = {
+ val orig = underTest(size)
+ val all = take(orig, size)
+ assertEquals(size, length(all))
+ expectSameContent("take all", true, orig, all, 0, size)
+ if (isMutableContent)
+ assertNotSame(orig, all)
+ else if (isTakeAllSame)
+ assertSame(orig, all)
+ }
+
+ /**
+ * check the operation of {{{slice}}} works for the entire content
+ * There is a special case that for some immutable implementations they can share the result
+ */
+ @Test def checkSliceAll: Unit = {
+ val orig = underTest(size)
+ val all = slice(orig, 0, size)
+ assertEquals(size, length(all))
+ expectSameContent("", true, orig, all, 0, size)
+ if (isMutableContent)
+ assertNotSame(orig, all)
+ else if (isTakeAllSame)
+ assertSame(orig, all)
+ }
+
+ /**
+ * check that take operates appropriately for negative values
+ * take and slice should be lenient and silently ignore any data outside valid ranges
+ */
+ @Test def checkTakeNeg: Unit = {
+ val orig = underTest(size)
+ val e = take(orig, 0)
+ for (len <- List(-1, -10, -99, Int.MinValue)) {
+ val empty = take(orig, len)
+ assertEquals(s"len $len", 0, length(empty))
+ if (isEmptyConstant) assertSame(s"len $len", e, empty)
+ }
+ }
+
+ /**
+ * check that take operates appropriately for lengths that exceed the input size
+ * take and slice should be lenient and silently ignore any data outside valid ranges
+ */
+ @Test def checkTakeTooBig: Unit = {
+ val orig = underTest(size)
+ val e = take(orig, 0)
+ for (len <- List(size + 1, size + 10, Int.MaxValue)) {
+ val all = take(orig, len)
+ assertEquals(s"len $len", size, length(all))
+ expectSameContent("", true, orig, all, 0, size)
+ }
+ }
+
+ /**
+ * check that slice operates appropriately for negative start point
+ * take and slice should be lenient and silently ignore any data outside valid ranges
+ */
+ @Test def checkSliceFromNeg: Unit = {
+ val orig = underTest(size)
+ for (
+ from <- List(-1, -10, -99, Int.MinValue);
+ to <- List(-1, 0, 1, 5)) {
+ val start = slice(orig, from, to)
+ expectSameContent(s"from $from, to $to", true, orig, start, 0, Math.max(0, to))
+ }
+ }
+
+ /**
+ * check that slice operates appropriately for out of range end values
+ * take and slice should be lenient and silently ignore any data outside valid ranges
+ */
+ @Test def checkSliceToTooBig: Unit = {
+ val orig = underTest(size)
+ for (
+ from <- List(-1, -10, -99, Int.MinValue, 0, 1, 5);
+ to <- List(size + 1, size + 10, Int.MaxValue)) {
+ val start = slice(orig, from, to)
+ val realStart = Math.max(0, from)
+ val realLen = size - realStart
+ expectSameContent(s"from $from, to $to", true, orig, start, realStart, realLen)
+ }
+ }
+
+ /**
+ * check that slice operates appropriately for negative values start and ends too large
+ * take and slice should be lenient and silently ignore any data outside valid ranges
+ */
+ @Test def checkSliceFromNegAndToTooBig: Unit = {
+ val orig = underTest(size)
+ for (
+ from <- List(-1, -10, -99, Int.MinValue);
+ to <- List(size + 1, size + 10, Int.MaxValue)) {
+ val all = slice(orig, from, to)
+ expectSameContent(s"from $from, to $to", true, orig, all, 0, size)
+ }
+ }
+
+ protected def intercept[EX <: Exception : Manifest](fn: => Any) {
+ try {
+ val res = fn
+ fail(s"expected exception was not thrown: $res")
+ } catch {
+ case failed: AssertionError => throw failed
+ case e: Exception if manifest[EX].runtimeClass.isAssignableFrom(e.getClass) =>
+ }
+ }
+
+ //accessors
+ //the length of underTest
+ def length(underTest: T): Int
+
+ //the value at index i of underTest
+ def get(underTest: T, i: Int): E
+
+ def slice(underTest: T, from: Int, to: Int): T
+
+ def take(underTest: T, size: Int): T
+
+ //behaviour
+ /** is an empty value the same JVM instance */
+ def isEmptyConstant: Boolean
+
+ /** is a take / slice that results in all the data returned return this
+ * This is only relevant if !isMutableContent
+ */
+ def isTakeAllSame: Boolean
+
+ /** is the content of the collection mutable.
+ * If mutable there is not data sharing allowed by take/slice, if immutable then data sharing is possible
+ * and tested based on isTakeAllSame
+ */
+ def isMutableContent: Boolean
+
+ //helpers
+ //delegate equals check for support arrays
+ def doAssertEquals(txt: String, expected: T, actual: T)
+
+}
+package IndexedTestImpl {
+ import java.lang.reflect.{Array => jlArray}
+ import java.lang.{Boolean => jlBoolean}
+ import java.lang.{Byte => jlByte}
+ import java.lang.{Short => jlShort}
+ import java.lang.{Integer => jlInt}
+ import java.lang.{Long => jlLong}
+ import java.lang.{Float => jlFloat}
+ import java.lang.{Double => jlDouble}
+ import java.lang.{Character => jlChar}
+
+ import scala.collection.immutable.{StringLike, StringOps, WrappedString}
+ import scala.collection.mutable
+ import scala.runtime.BoxedUnit
+ trait DataProvider[E] {
+ protected def expectedValueAtIndex(index: Int): E = {
+ val someNumber = index + jlInt.bitCount(index)
+ toType(someNumber)
+ }
+
+ protected def toType(n: Int): E
+ }
+ trait StringTestData extends DataProvider [String] {
+ def toType(n: Int) = n.toString
+ }
+ trait ByteTestData extends DataProvider [Byte] {
+ def toType(n: Int) = n.toByte
+ }
+ trait ShortTestData extends DataProvider [Short] {
+ def toType(n: Int) = n.toShort
+ }
+ trait IntTestData extends DataProvider [Int] {
+ def toType(n: Int) = n
+ }
+ trait LongTestData extends DataProvider [Long] {
+ def toType(n: Int) = n
+ }
+ trait FloatTestData extends DataProvider [Float] {
+ def toType(n: Int) = n
+ }
+ trait DoubleTestData extends DataProvider [Double] {
+ def toType(n: Int) = n
+ }
+ trait CharTestData extends DataProvider [Char] {
+ def toType(n: Int)= (n+64).toChar
+ }
+ trait BooleanTestData extends DataProvider [Boolean] {
+ def toType(n: Int)= (n & 0) == 0
+ }
+ trait UnitTestData extends DataProvider [BoxedUnit] {
+ def toType(n: Int)= if ((n & 0) == 0) null else BoxedUnit.UNIT
+ }
+
+ @Ignore
+ abstract class ArrayTest[E] (
+ //the object or primitive type of the array
+ val TYPE: Class[_]) extends IndexedTest[Array[E], E]{
+ override final def length(underTest: Array[E]) = underTest.length
+
+ override def get(underTest: Array[E], i: Int) = underTest(i)
+
+ override def slice(underTest: Array[E], from: Int, to: Int) = underTest.slice(from, to)
+
+ override def take(underTest: Array[E], size: Int) = underTest.take(size)
+
+ override def isEmptyConstant = false
+
+ override def isMutableContent = true
+
+ override def isTakeAllSame = false
+
+ override def doAssertEquals(txt: String, expected: Array[E], actual: Array[E]): Unit = {
+ assertEquals(txt, expected.mkString("'"), actual.mkString("'"))
+ }
+
+ override def underTest(size: Int): Array[E] = {
+ val res = jlArray.newInstance(TYPE, size)
+ for (i <- 0 until size) {
+ jlArray.set(res, i, expectedValueAtIndex(i))
+ }
+ res.asInstanceOf[Array[E]]
+ }
+ }
+
+
+ @Ignore
+ abstract class WrappedArrayTest[E](
+ //the object or primitive type of the array
+ val TYPE: Class[_]) extends IndexedTest[mutable.WrappedArray[E], E] with DataProvider[E]{
+ import mutable.WrappedArray
+ override final def length(underTest: WrappedArray[E]) = underTest.length
+
+ override def get(underTest: WrappedArray[E], i: Int) = underTest(i)
+
+ override def slice(underTest: WrappedArray[E], from: Int, to: Int) = underTest.slice(from, to)
+
+ override def take(underTest: WrappedArray[E], size: Int) = underTest.take(size)
+
+ override def isEmptyConstant = false
+
+ override def isMutableContent = true
+
+ override def isTakeAllSame = false
+
+ override def doAssertEquals(txt: String, expected: WrappedArray[E], actual: WrappedArray[E]): Unit = {
+ assertEquals(txt, expected.mkString("'"), actual.mkString("'"))
+ }
+
+ override def underTest(size: Int): WrappedArray[E] = {
+ val res = jlArray.newInstance(TYPE, size)
+ for (i <- 0 until size) {
+ jlArray.set(res, i, expectedValueAtIndex(i))
+ }
+ WrappedArray.make(res.asInstanceOf[Array[E]])
+ }
+ }
+
+ //construct the data using java as much as possible to avoid invalidating the test
+
+ @Ignore
+ abstract class MutableIndexedSeqTest[T <: mutable.Seq[E], E] extends IndexedTest[T, E] with DataProvider[E]{
+ override final def length(underTest: T) = underTest.length
+
+ override def get(underTest: T, i: Int) = underTest(i)
+
+ override def slice(underTest: T, from: Int, to: Int) = underTest.slice(from, to).asInstanceOf[T]
+
+ override def take(underTest: T, size: Int) = underTest.take(size).asInstanceOf[T]
+
+ override def isEmptyConstant = false
+
+ override def isMutableContent = true
+
+ override def isTakeAllSame = true
+
+ override def doAssertEquals(txt: String, expected: T, actual: T): Unit = {
+ assertEquals(txt, expected, actual)
+ }
+
+ def createEmpty(size: Int) : T
+
+ override protected def underTest(size: Int): T = {
+ val res:T = createEmpty(size)
+ for (i <- 0 until size)
+ res(i) = expectedValueAtIndex(i)
+ res
+ }
+
+ }
+ @Ignore
+ abstract class ImmutableIndexedSeqTest[T <: SeqLike[E, T], E] extends IndexedTest[T, E] with DataProvider[E] {
+ override final def length(underTest: T) = underTest.length
+
+ override def get(underTest: T, i: Int) = underTest(i)
+
+ override def slice(underTest: T, from: Int, to: Int) = underTest.slice(from, to)
+
+ override def take(underTest: T, size: Int) = underTest.take(size)
+
+ override def isEmptyConstant = false
+
+ override def isMutableContent = false
+
+ override def isTakeAllSame = true
+
+ override def doAssertEquals(txt: String, expected: T, actual: T): Unit = {
+ assertEquals(txt, expected, actual)
+ }
+
+ }
+ @Ignore
+ abstract class StringOpsBaseTest extends IndexedTest[StringOps, Char] with DataProvider[Char] {
+ override final def length(underTest: StringOps) = underTest.length
+
+ override def get(underTest: StringOps, i: Int) = underTest(i)
+
+ override def slice(underTest: StringOps, from: Int, to: Int) = underTest.slice(from, to)
+
+ override def take(underTest: StringOps, size: Int) = underTest.take(size)
+
+ override def isEmptyConstant = false
+
+ override def isMutableContent = false
+
+ override def isTakeAllSame = false
+
+ override def doAssertEquals(txt: String, expected: StringOps, actual: StringOps): Unit = {
+ assertEquals(txt, expected, actual)
+ }
+
+ }
+
+ class BooleanArrayTest extends ArrayTest[Boolean](jlBoolean.TYPE) with BooleanTestData
+ class ByteArrayTest extends ArrayTest[Byte](jlByte.TYPE) with ByteTestData
+ class ShortArrayTest extends ArrayTest[Short](jlShort.TYPE) with ShortTestData
+ class IntArrayTest extends ArrayTest[Int](jlInt.TYPE) with IntTestData
+ class LongArrayTest extends ArrayTest[Long](jlLong.TYPE) with LongTestData
+ class DoubleArrayTest extends ArrayTest[Double](jlDouble.TYPE) with DoubleTestData
+ class FloatArrayTest extends ArrayTest[Float](jlFloat.TYPE) with FloatTestData
+ class CharArrayTest extends ArrayTest[Char](jlChar.TYPE) with CharTestData
+ class UnitArrayTest extends ArrayTest[BoxedUnit](null) with UnitTestData {
+ override def underTest(size: Int): Array[BoxedUnit] = {
+ val res = new Array[Unit](size)
+ for (i <- 0 until size) {
+ jlArray.set(res, i, expectedValueAtIndex(i))
+ }
+ res.asInstanceOf[Array[BoxedUnit]]
+ }
+ }
+ class RefArrayTest extends ArrayTest[String](classOf[String]) with StringTestData
+
+ class BooleanWrappedArrayTest extends WrappedArrayTest[Boolean](jlBoolean.TYPE) with BooleanTestData
+ class ByteWrappedArrayTest extends WrappedArrayTest[Byte](jlByte.TYPE) with ByteTestData
+ class ShortWrappedArrayTest extends WrappedArrayTest[Short](jlShort.TYPE) with ShortTestData
+ class IntWrappedArrayTest extends WrappedArrayTest[Int](jlInt.TYPE) with IntTestData
+ class LongWrappedArrayTest extends WrappedArrayTest[Long](jlLong.TYPE) with LongTestData
+ class DoubleWrappedArrayTest extends WrappedArrayTest[Double](jlDouble.TYPE) with DoubleTestData
+ class FloatWrappedArrayTest extends WrappedArrayTest[Float](jlFloat.TYPE) with FloatTestData
+ class CharWrappedArrayTest extends WrappedArrayTest[Char](jlChar.TYPE) with CharTestData
+ class UnitWrappedArrayTest extends WrappedArrayTest[BoxedUnit](null) with UnitTestData {
+ import mutable.WrappedArray
+ override def underTest(size: Int): WrappedArray[BoxedUnit] = {
+ val res = new Array[Unit](size)
+ for (i <- 0 until size) {
+ jlArray.set(res, i, expectedValueAtIndex(i))
+ }
+ WrappedArray.make(res.asInstanceOf[Array[Unit]])
+ }
+ }
+ class RefWrappedArrayTest extends WrappedArrayTest[String](classOf[String]) with StringTestData
+
+ class ListBufferTest extends MutableIndexedSeqTest[mutable.ListBuffer[String], String] with StringTestData {
+ import mutable.ListBuffer
+ override def createEmpty(size: Int): ListBuffer[String] = {
+ val res = new ListBuffer[String]
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ res
+ }
+ }
+ class ArraySeqTest extends MutableIndexedSeqTest[mutable.ArraySeq[String], String] with StringTestData {
+ import mutable.ArraySeq
+ override def createEmpty(size: Int): ArraySeq[String] = {
+ val res = new ArraySeq[String](size)
+ for (i <- 0 until size)
+ res (i) = expectedValueAtIndex(i)
+ res
+ }
+ }
+ class ArrayBufferTest extends MutableIndexedSeqTest[mutable.ArrayBuffer[String], String] with StringTestData {
+ import mutable.ArrayBuffer
+ override def createEmpty(size: Int): ArrayBuffer[String] = {
+ val res = new ArrayBuffer[String](size)
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ res
+ }
+ }
+ class ListTest extends ImmutableIndexedSeqTest[List[String], String] with StringTestData {
+
+ override protected def underTest(size: Int): List[String] = {
+ var res:List[String] = Nil
+ var index = size-1
+ while (index >= 0) {
+ res = expectedValueAtIndex(index) :: res
+ index -= 1
+ }
+ res
+ }
+ }
+ class StringBuilderTest extends MutableIndexedSeqTest[StringBuilder, Char] with CharTestData {
+
+ override def createEmpty(size: Int): StringBuilder = new StringBuilder(size)
+
+ override protected def underTest(size: Int): StringBuilder = {
+ var res = createEmpty(size)
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ res
+ }
+ }
+ class StringOpsTest extends StringOpsBaseTest with CharTestData {
+
+ override protected def underTest(size: Int): StringOps = {
+ var res = new StringBuilder(size)
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ res.toString
+ }
+ }
+ class WrappedStringTest extends ImmutableIndexedSeqTest[WrappedString, Char] with CharTestData {
+
+ override def isTakeAllSame: Boolean = false
+
+ override protected def underTest(size: Int): WrappedString = {
+ var res = new StringBuilder(size)
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ new WrappedString(res.toString)
+ }
+ }
+ class VectorTest extends ImmutableIndexedSeqTest[Vector[String], String] with StringTestData {
+
+ override protected def underTest(size: Int): Vector[String] = {
+ var res = Vector.newBuilder[String]
+ for (i <- 0 until size)
+ res += expectedValueAtIndex(i)
+ res.result()
+ }
+ }
+
+}
diff --git a/test/junit/scala/collection/concurrent/TrieMapTest.scala b/test/junit/scala/collection/concurrent/TrieMapTest.scala
new file mode 100644
index 0000000000..ed67f3e9a9
--- /dev/null
+++ b/test/junit/scala/collection/concurrent/TrieMapTest.scala
@@ -0,0 +1,54 @@
+package scala.collection.concurrent
+
+import org.junit.{Assert, Test}
+
+class TrieMapTest {
+
+ private def check[T](result2: List[Any])(f: TrieMap[String, String] => TraversableOnce[Any]) = {
+ val m = TrieMap[String, String]()
+ val values = f(m)
+ m.put("k", "v")
+ Assert.assertEquals(Nil, values.toList)
+ Assert.assertEquals(result2, f(m).toList)
+ }
+
+ @Test
+ def iterator(): Unit = {
+ check(List(("k", "v")))(_.iterator)
+ }
+
+ @Test
+ def values(): Unit = {
+ check(List("v"))(_.values)
+ }
+
+ @Test
+ def valuesIterator(): Unit = {
+ check(List("v"))(_.valuesIterator)
+ }
+
+ @Test
+ def keySet(): Unit = {
+ check(List("k"))(_.keySet)
+ }
+
+ @Test
+ def keysIterator(): Unit = {
+ check(List("k"))(_.keysIterator)
+ }
+
+ @Test
+ def keys(): Unit = {
+ check(List("k"))(_.keys)
+ }
+
+ @Test
+ def filterKeys(): Unit = {
+ check(List(("k", "v")))(_.filterKeys(_ => true))
+ }
+
+ @Test
+ def mapValues(): Unit = {
+ check(List(("k", "v")))(_.mapValues(x => x))
+ }
+}
diff --git a/test/junit/scala/collection/immutable/StreamTest.scala b/test/junit/scala/collection/immutable/StreamTest.scala
index 7046525f37..61f7b792e8 100644
--- a/test/junit/scala/collection/immutable/StreamTest.scala
+++ b/test/junit/scala/collection/immutable/StreamTest.scala
@@ -117,4 +117,10 @@ class StreamTest {
assert((0 #:: 1 #:: s) == (0 #:: 1 #:: s), "Cons of referentially identical streams should be equal (==)")
assert((0 #:: 1 #:: s) equals (0 #:: 1 #:: s), "Cons of referentially identical streams should be equal (equals)")
}
+
+ @Test
+ def t9886: Unit = {
+ assertEquals(Stream(None, Some(1)), None #:: Stream(Some(1)))
+ assertEquals(Stream(None, Some(1)), Stream(None) #::: Stream(Some(1)))
+ }
}
diff --git a/test/junit/scala/collection/mutable/BitSetTest.scala b/test/junit/scala/collection/mutable/BitSetTest.scala
index 84b906e8d5..f0a0ef5d75 100644
--- a/test/junit/scala/collection/mutable/BitSetTest.scala
+++ b/test/junit/scala/collection/mutable/BitSetTest.scala
@@ -7,7 +7,7 @@ import org.junit.runners.JUnit4
@RunWith(classOf[JUnit4])
class BitSetTest {
// Test for SI-8910
- @Test def capacityExpansionTest() {
+ @Test def capacityExpansionTest(): Unit = {
val bitSet = BitSet.empty
val size = bitSet.toBitMask.length
bitSet ^= bitSet
@@ -20,7 +20,7 @@ class BitSetTest {
assert(bitSet.toBitMask.length == size, "Capacity of bitset changed after &~=")
}
- @Test def test_SI8917() {
+ @Test def test_SI8917(): Unit = {
val bigBitSet = BitSet(1, 100, 10000)
val littleBitSet = BitSet(100)
bigBitSet &= littleBitSet
@@ -29,10 +29,16 @@ class BitSetTest {
assert(littleBitSet.toBitMask.length < bigBitSet.toBitMask.length, "Needlessly extended the size of bitset on &=")
}
- @Test def test_SI8647() {
+ @Test def test_SI8647(): Unit = {
val bs = BitSet()
bs.map(_ + 1) // Just needs to compile
val xs = bs: SortedSet[Int]
xs.map(_ + 1) // Also should compile (did before)
}
+
+ @Test def t10164(): Unit = {
+ val bs = BitSet()
+ val last = (bs ++ (0 to 128)).last // Just needs not to throw
+ assert(last == 128)
+ }
}
diff --git a/test/junit/scala/reflect/internal/NamesTest.scala b/test/junit/scala/reflect/internal/NamesTest.scala
index 549c10abed..d6182e7cca 100644
--- a/test/junit/scala/reflect/internal/NamesTest.scala
+++ b/test/junit/scala/reflect/internal/NamesTest.scala
@@ -92,4 +92,29 @@ class NamesTest {
assert(h1 string_== h2)
assert(h1 string_== h1y)
}
+
+ @Test
+ def pos(): Unit = {
+ def check(nameString: String, sub: String) = {
+ val name = TermName(nameString)
+ val javaResult = name.toString.indexOf(sub) match { case -1 => name.length case x => x }
+ val nameResult = name.pos(sub)
+ assertEquals(javaResult, nameResult)
+ if (sub.length == 1) {
+ val nameResultChar = name.pos(sub.head)
+ assertEquals(javaResult, nameResultChar)
+ }
+ }
+
+ check("a", "a") // was "String index out of range: 1
+ check("a", "b")
+ check("a", "ab")
+ check("a", "ba")
+ check("ab", "a")
+ check("ab", "b")
+ check("ab", "ab")
+ check("ab", "ba")
+ check("", "x")
+ check("", "xy")
+ }
}
diff --git a/test/junit/scala/reflect/internal/PrintersTest.scala b/test/junit/scala/reflect/internal/PrintersTest.scala
index 722062ba21..c7cfe0dfbb 100644
--- a/test/junit/scala/reflect/internal/PrintersTest.scala
+++ b/test/junit/scala/reflect/internal/PrintersTest.scala
@@ -556,7 +556,7 @@ class ClassPrintTest {
@Test def testCaseClassWithParams3 = assertPrintedCode(sm"""
|{
- | case class X(implicit x: scala.Int, s: scala.Predef.String);
+ | case class X()(implicit x: scala.Int, s: scala.Predef.String);
| ()
|}""")
diff --git a/test/junit/scala/tools/nsc/classpath/JrtClassPathTest.scala b/test/junit/scala/tools/nsc/classpath/JrtClassPathTest.scala
new file mode 100644
index 0000000000..2c3c5134da
--- /dev/null
+++ b/test/junit/scala/tools/nsc/classpath/JrtClassPathTest.scala
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014 Contributor. All rights reserved.
+ */
+package scala.tools.nsc.classpath
+
+import org.junit.Assert._
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+import scala.tools.nsc.Settings
+import scala.tools.nsc.backend.jvm.AsmUtils
+import scala.tools.nsc.util.ClassPath
+import scala.tools.util.PathResolver
+
+@RunWith(classOf[JUnit4])
+class JrtClassPathTest {
+
+ @Test def lookupJavaClasses(): Unit = {
+ val specVersion = scala.util.Properties.javaSpecVersion
+ // Run the test using the JDK8 or 9 provider for rt.jar depending on the platform the test is running on.
+ val cp: ClassPath =
+ if (specVersion == "" || specVersion == "1.8") {
+ val settings = new Settings()
+ val resolver = new PathResolver(settings)
+ val elements = new ClassPathFactory(settings).classesInPath(resolver.Calculated.javaBootClassPath)
+ AggregateClassPath(elements)
+ }
+ else JrtClassPath().get
+
+ assertEquals(Nil, cp.classes(""))
+ assertTrue(cp.packages("java").toString, cp.packages("java").exists(_.name == "java.lang"))
+ assertTrue(cp.classes("java.lang").exists(_.name == "Object"))
+ val jl_Object = cp.classes("java.lang").find(_.name == "Object").get
+ assertEquals("java/lang/Object", AsmUtils.classFromBytes(jl_Object.file.toByteArray).name)
+ assertTrue(cp.list("java.lang").packages.exists(_.name == "java.lang.annotation"))
+ assertTrue(cp.list("java.lang").classesAndSources.exists(_.name == "Object"))
+ assertTrue(cp.findClass("java.lang.Object").isDefined)
+ assertTrue(cp.findClassFile("java.lang.Object").isDefined)
+ }
+}
diff --git a/test/partest b/test/partest
deleted file mode 100755
index d74176aa8a..0000000000
--- a/test/partest
+++ /dev/null
@@ -1,152 +0,0 @@
-#!/usr/bin/env bash
-#
-##############################################################################
-# Scala test runner 2.10.0
-##############################################################################
-# (c) 2002-2013 LAMP/EPFL
-#
-# This is free software; see the distribution for copying conditions.
-# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-##############################################################################
-
-findScalaHome () {
- # see SI-2092 and SI-5792
- local source="${BASH_SOURCE[0]}"
- while [ -h "$source" ] ; do
- local linked="$(readlink "$source")"
- local dir="$( cd -P $(dirname "$source") && cd -P $(dirname "$linked") && pwd )"
- source="$dir/$(basename "$linked")"
- done
- ( ( cd -P "$(dirname "$source")/.." > /dev/null ) && pwd )
-}
-
-# Use tput to detect color-capable terminal.
-# (note: I have found that on Cygwin, the script sometimes dies here.
-# it doesn't happen from the Cygwin prompt when ssh'ing in to
-# jenkins-worker-windows-publish, only when I make a Jenkins job
-# that runs this script. I don't know why. it may have to do with
-# which bash flags are set (-e? -x?) and with bash flags propagating
-# from one script to another? not sure. anyway, normally in a CI
-# context we run partest through sbt, not through this script, so I'm
-# not investigating further for now.)
-term_colors=$(tput colors 2>/dev/null)
-if [[ $? == 0 ]] && [[ $term_colors -gt 2 ]]; then
- git_diff_options="--color=always --word-diff"
- color_opts="-Dpartest.colors=$term_colors"
-else
- unset color_opts
- git_diff_options="--nocolor"
-fi
-
-cygwin=false;
-darwin=false;
-case "`uname`" in
- CYGWIN*) cygwin=true ;;
- Darwin*) darwin=true ;;
-esac
-
-# Finding the root folder for this Scala distribution
-SCALA_HOME="$(findScalaHome)"
-
-if $cygwin; then
- SCALA_HOME=`cygpath --windows --short-name "$SCALA_HOME"`
- SCALA_HOME=`cygpath --unix "$SCALA_HOME"`
-fi
-
-# Let sbt construct the classpath used to run partest (downloading partest from maven if necessary)
-# PARTEST_CLASSPATH=""
-if [ -z "$PARTEST_CLASSPATH" ] ; then
- if [ ! -f "$SCALA_HOME/build/quick/partest.properties" ] ; then
- (cd "$SCALA_HOME" && sbt dist/mkQuick) # builds quick, downloads partest and writes classpath to build/quick/partest.properties
- fi
-
- PARTEST_CLASSPATH=$( cat "$SCALA_HOME/build/quick/partest.properties" | grep partest.classpath | sed -e 's/\\:/:/g' | cut -f2- -d= )
-
- # sanity check, disabled to save time
- # $( javap -classpath $PARTEST_CLASSPATH scala.tools.partest.nest.NestRunner &> /dev/null ) || unset PARTEST_CLASSPATH
-fi
-
-# if [ -z "$PARTEST_CLASSPATH" ] ; then
-# if [ -f "$SCALA_HOME/lib/scala-partest.jar" ] ; then
-# for ext in "$SCALA_HOME"/lib/* ; do
-# if [ -z "$PARTEST_CLASSPATH" ] ; then
-# PARTEST_CLASSPATH="$ext"
-# else
-# PARTEST_CLASSPATH="$PARTEST_CLASSPATH:$ext"
-# fi
-# done
-# elif [ -f "$SCALA_HOME/build/pack/lib/scala-partest.jar" ] ; then
-# for lib in `echo "scala-partest scala-library scala-parser-combinators scala-xml scala-reflect scala-compiler diffutils"`; do
-# ext="$SCALA_HOME/build/pack/lib/$lib.jar"
-# if [ -z "$PARTEST_CLASSPATH" ] ; then
-# PARTEST_CLASSPATH="$ext"
-# else
-# PARTEST_CLASSPATH="$PARTEST_CLASSPATH:$ext"
-# fi
-# done
-# fi
-# fi
-
-# Locate a javac command
-# Try: JAVA_HOME, sibling to specific JAVACMD, or PATH
-# Don't fail if there is no javac, since not all tests require it.
-if [ -z "$JAVAC_CMD" ] ; then
- if [ -n "${JAVA_HOME}" ] && [ -f "${JAVA_HOME}/bin/javac" ] ; then
- JAVAC_CMD="${JAVA_HOME}/bin/javac"
- fi
- if [ -z "$JAVAC_CMD" ] && [ -n "$JAVACMD" ] ; then
- JDIR=`dirname "${JAVACMD}"`
- JAVAC_CMD="${JDIR}/javac"
- fi
- if [ -z "$JAVAC_CMD" ] ; then
- JAVAC_CMD=`type -p javac`
- fi
-fi
-
-if $cygwin; then
- if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; then
- format=mixed
- else
- format=windows
- fi
- if [ -n "${JAVA_HOME}" ] ; then
- JAVA_HOME=`cygpath --$format "$JAVA_HOME"`
- fi
- if [ -n "${JAVACMD}" ] ; then
- JAVACMD=`cygpath --$format "$JAVACMD"`
- fi
- if [ -n "${JAVAC_CMD}" ] ; then
- JAVAC_CMD=`cygpath --$format "$JAVAC_CMD"`
- fi
- SCALA_HOME=`cygpath --$format "$SCALA_HOME"`
-fi
-
-# last arg wins, so if JAVA_OPTS already contains -Xmx or -Xms the
-# supplied argument will be used.
-JAVA_OPTS="-Xmx1024M -Xms64M $JAVA_OPTS"
-
-# the sbt task doesn't supply any options by default,
-# so don't do that here either -- note that you may want to pass -optimise
-# to mimic what happens during nightlies.
-# [ -n "$SCALAC_OPTS" ] || SCALAC_OPTS="-deprecation"
-
-partestDebugStr=""
-if [ ! -z "${PARTEST_DEBUG}" ] ; then
- partestDebugStr="-Dpartest.debug=${PARTEST_DEBUG}"
-fi
-
-# note that variables which may intentionally be empty must not
-# be quoted: otherwise an empty string will appear as a command line
-# argument, and java will think that is the program to run.
-"${JAVACMD:=java}" \
- $JAVA_OPTS -cp "$PARTEST_CLASSPATH" \
- ${partestDebugStr} \
- ${color_opts} \
- -Dfile.encoding=UTF-8 \
- -Dscala.home="${SCALA_HOME}" \
- -Dpartest.javacmd="${JAVACMD}" \
- -Dpartest.java_opts="${JAVA_OPTS}" \
- -Dpartest.scalac_opts="${SCALAC_OPTS}" \
- -Dpartest.javac_cmd="${JAVAC_CMD}" \
- scala.tools.partest.nest.ConsoleRunner "$@"
diff --git a/test/scalacheck/duration.scala b/test/scalacheck/duration.scala
index 89cb9ff955..fc861b886a 100644
--- a/test/scalacheck/duration.scala
+++ b/test/scalacheck/duration.scala
@@ -32,7 +32,10 @@ object DurationTest extends Properties("Division of Duration by Long") {
val genClose = for {
a <- weightedLong
if a != 0
- b <- choose(Long.MaxValue / a - 10, Long.MaxValue / a + 10)
+ val center = Long.MaxValue / a
+ b <-
+ if (center - 10 < center + 10) choose(center - 10, center + 10)
+ else choose(center + 10, center - 10) // deal with overflow if abs(a) == 1
} yield (a, b)
val genBorderline =
diff --git a/test/simplejson/__init__.py b/test/simplejson/__init__.py
deleted file mode 100644
index d5b4d39913..0000000000
--- a/test/simplejson/__init__.py
+++ /dev/null
@@ -1,318 +0,0 @@
-r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
-JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
-interchange format.
-
-:mod:`simplejson` exposes an API familiar to users of the standard library
-:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
-version of the :mod:`json` library contained in Python 2.6, but maintains
-compatibility with Python 2.4 and Python 2.5 and (currently) has
-significant performance advantages, even without using the optional C
-extension for speedups.
-
-Encoding basic Python object hierarchies::
-
- >>> import simplejson as json
- >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
- '["foo", {"bar": ["baz", null, 1.0, 2]}]'
- >>> print json.dumps("\"foo\bar")
- "\"foo\bar"
- >>> print json.dumps(u'\u1234')
- "\u1234"
- >>> print json.dumps('\\')
- "\\"
- >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
- {"a": 0, "b": 0, "c": 0}
- >>> from StringIO import StringIO
- >>> io = StringIO()
- >>> json.dump(['streaming API'], io)
- >>> io.getvalue()
- '["streaming API"]'
-
-Compact encoding::
-
- >>> import simplejson as json
- >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
- '[1,2,3,{"4":5,"6":7}]'
-
-Pretty printing::
-
- >>> import simplejson as json
- >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
- >>> print '\n'.join([l.rstrip() for l in s.splitlines()])
- {
- "4": 5,
- "6": 7
- }
-
-Decoding JSON::
-
- >>> import simplejson as json
- >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
- >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
- True
- >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
- True
- >>> from StringIO import StringIO
- >>> io = StringIO('["streaming API"]')
- >>> json.load(io)[0] == 'streaming API'
- True
-
-Specializing JSON object decoding::
-
- >>> import simplejson as json
- >>> def as_complex(dct):
- ... if '__complex__' in dct:
- ... return complex(dct['real'], dct['imag'])
- ... return dct
- ...
- >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
- ... object_hook=as_complex)
- (1+2j)
- >>> import decimal
- >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
- True
-
-Specializing JSON object encoding::
-
- >>> import simplejson as json
- >>> def encode_complex(obj):
- ... if isinstance(obj, complex):
- ... return [obj.real, obj.imag]
- ... raise TypeError(repr(o) + " is not JSON serializable")
- ...
- >>> json.dumps(2 + 1j, default=encode_complex)
- '[2.0, 1.0]'
- >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
- '[2.0, 1.0]'
- >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
- '[2.0, 1.0]'
-
-
-Using simplejson.tool from the shell to validate and pretty-print::
-
- $ echo '{"json":"obj"}' | python -m simplejson.tool
- {
- "json": "obj"
- }
- $ echo '{ 1.2:3.4}' | python -m simplejson.tool
- Expecting property name: line 1 column 2 (char 2)
-"""
-__version__ = '2.0.9'
-__all__ = [
- 'dump', 'dumps', 'load', 'loads',
- 'JSONDecoder', 'JSONEncoder',
-]
-
-__author__ = 'Bob Ippolito <bob@redivi.com>'
-
-from decoder import JSONDecoder
-from encoder import JSONEncoder
-
-_default_encoder = JSONEncoder(
- skipkeys=False,
- ensure_ascii=True,
- check_circular=True,
- allow_nan=True,
- indent=None,
- separators=None,
- encoding='utf-8',
- default=None,
-)
-
-def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
- allow_nan=True, cls=None, indent=None, separators=None,
- encoding='utf-8', default=None, **kw):
- """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
- ``.write()``-supporting file-like object).
-
- If ``skipkeys`` is true then ``dict`` keys that are not basic types
- (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
- will be skipped instead of raising a ``TypeError``.
-
- If ``ensure_ascii`` is false, then the some chunks written to ``fp``
- may be ``unicode`` instances, subject to normal Python ``str`` to
- ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
- understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
- to cause an error.
-
- If ``check_circular`` is false, then the circular reference check
- for container types will be skipped and a circular reference will
- result in an ``OverflowError`` (or worse).
-
- If ``allow_nan`` is false, then it will be a ``ValueError`` to
- serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
- in strict compliance of the JSON specification, instead of using the
- JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
-
- If ``indent`` is a non-negative integer, then JSON array elements and object
- members will be pretty-printed with that indent level. An indent level
- of 0 will only insert newlines. ``None`` is the most compact representation.
-
- If ``separators`` is an ``(item_separator, dict_separator)`` tuple
- then it will be used instead of the default ``(', ', ': ')`` separators.
- ``(',', ':')`` is the most compact JSON representation.
-
- ``encoding`` is the character encoding for str instances, default is UTF-8.
-
- ``default(obj)`` is a function that should return a serializable version
- of obj or raise TypeError. The default simply raises TypeError.
-
- To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
- ``.default()`` method to serialize additional types), specify it with
- the ``cls`` kwarg.
-
- """
- # cached encoder
- if (not skipkeys and ensure_ascii and
- check_circular and allow_nan and
- cls is None and indent is None and separators is None and
- encoding == 'utf-8' and default is None and not kw):
- iterable = _default_encoder.iterencode(obj)
- else:
- if cls is None:
- cls = JSONEncoder
- iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
- check_circular=check_circular, allow_nan=allow_nan, indent=indent,
- separators=separators, encoding=encoding,
- default=default, **kw).iterencode(obj)
- # could accelerate with writelines in some versions of Python, at
- # a debuggability cost
- for chunk in iterable:
- fp.write(chunk)
-
-
-def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
- allow_nan=True, cls=None, indent=None, separators=None,
- encoding='utf-8', default=None, **kw):
- """Serialize ``obj`` to a JSON formatted ``str``.
-
- If ``skipkeys`` is false then ``dict`` keys that are not basic types
- (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
- will be skipped instead of raising a ``TypeError``.
-
- If ``ensure_ascii`` is false, then the return value will be a
- ``unicode`` instance subject to normal Python ``str`` to ``unicode``
- coercion rules instead of being escaped to an ASCII ``str``.
-
- If ``check_circular`` is false, then the circular reference check
- for container types will be skipped and a circular reference will
- result in an ``OverflowError`` (or worse).
-
- If ``allow_nan`` is false, then it will be a ``ValueError`` to
- serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
- strict compliance of the JSON specification, instead of using the
- JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
-
- If ``indent`` is a non-negative integer, then JSON array elements and
- object members will be pretty-printed with that indent level. An indent
- level of 0 will only insert newlines. ``None`` is the most compact
- representation.
-
- If ``separators`` is an ``(item_separator, dict_separator)`` tuple
- then it will be used instead of the default ``(', ', ': ')`` separators.
- ``(',', ':')`` is the most compact JSON representation.
-
- ``encoding`` is the character encoding for str instances, default is UTF-8.
-
- ``default(obj)`` is a function that should return a serializable version
- of obj or raise TypeError. The default simply raises TypeError.
-
- To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
- ``.default()`` method to serialize additional types), specify it with
- the ``cls`` kwarg.
-
- """
- # cached encoder
- if (not skipkeys and ensure_ascii and
- check_circular and allow_nan and
- cls is None and indent is None and separators is None and
- encoding == 'utf-8' and default is None and not kw):
- return _default_encoder.encode(obj)
- if cls is None:
- cls = JSONEncoder
- return cls(
- skipkeys=skipkeys, ensure_ascii=ensure_ascii,
- check_circular=check_circular, allow_nan=allow_nan, indent=indent,
- separators=separators, encoding=encoding, default=default,
- **kw).encode(obj)
-
-
-_default_decoder = JSONDecoder(encoding=None, object_hook=None)
-
-
-def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
- parse_int=None, parse_constant=None, **kw):
- """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
- a JSON document) to a Python object.
-
- If the contents of ``fp`` is encoded with an ASCII based encoding other
- than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
- be specified. Encodings that are not ASCII based (such as UCS-2) are
- not allowed, and should be wrapped with
- ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
- object and passed to ``loads()``
-
- ``object_hook`` is an optional function that will be called with the
- result of any object literal decode (a ``dict``). The return value of
- ``object_hook`` will be used instead of the ``dict``. This feature
- can be used to implement custom decoders (e.g. JSON-RPC class hinting).
-
- To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
- kwarg.
-
- """
- return loads(fp.read(),
- encoding=encoding, cls=cls, object_hook=object_hook,
- parse_float=parse_float, parse_int=parse_int,
- parse_constant=parse_constant, **kw)
-
-
-def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
- parse_int=None, parse_constant=None, **kw):
- """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
- document) to a Python object.
-
- If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
- other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
- must be specified. Encodings that are not ASCII based (such as UCS-2)
- are not allowed and should be decoded to ``unicode`` first.
-
- ``object_hook`` is an optional function that will be called with the
- result of any object literal decode (a ``dict``). The return value of
- ``object_hook`` will be used instead of the ``dict``. This feature
- can be used to implement custom decoders (e.g. JSON-RPC class hinting).
-
- ``parse_float``, if specified, will be called with the string
- of every JSON float to be decoded. By default this is equivalent to
- float(num_str). This can be used to use another datatype or parser
- for JSON floats (e.g. decimal.Decimal).
-
- ``parse_int``, if specified, will be called with the string
- of every JSON int to be decoded. By default this is equivalent to
- int(num_str). This can be used to use another datatype or parser
- for JSON integers (e.g. float).
-
- ``parse_constant``, if specified, will be called with one of the
- following strings: -Infinity, Infinity, NaN, null, true, false.
- This can be used to raise an exception if invalid JSON numbers
- are encountered.
-
- To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
- kwarg.
-
- """
- if (cls is None and encoding is None and object_hook is None and
- parse_int is None and parse_float is None and
- parse_constant is None and not kw):
- return _default_decoder.decode(s)
- if cls is None:
- cls = JSONDecoder
- if object_hook is not None:
- kw['object_hook'] = object_hook
- if parse_float is not None:
- kw['parse_float'] = parse_float
- if parse_int is not None:
- kw['parse_int'] = parse_int
- if parse_constant is not None:
- kw['parse_constant'] = parse_constant
- return cls(encoding=encoding, **kw).decode(s)
diff --git a/test/simplejson/decoder.py b/test/simplejson/decoder.py
deleted file mode 100644
index b769ea486c..0000000000
--- a/test/simplejson/decoder.py
+++ /dev/null
@@ -1,354 +0,0 @@
-"""Implementation of JSONDecoder
-"""
-import re
-import sys
-import struct
-
-from simplejson.scanner import make_scanner
-try:
- from simplejson._speedups import scanstring as c_scanstring
-except ImportError:
- c_scanstring = None
-
-__all__ = ['JSONDecoder']
-
-FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
-
-def _floatconstants():
- _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
- if sys.byteorder != 'big':
- _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
- nan, inf = struct.unpack('dd', _BYTES)
- return nan, inf, -inf
-
-NaN, PosInf, NegInf = _floatconstants()
-
-
-def linecol(doc, pos):
- lineno = doc.count('\n', 0, pos) + 1
- if lineno == 1:
- colno = pos
- else:
- colno = pos - doc.rindex('\n', 0, pos)
- return lineno, colno
-
-
-def errmsg(msg, doc, pos, end=None):
- # Note that this function is called from _speedups
- lineno, colno = linecol(doc, pos)
- if end is None:
- #fmt = '{0}: line {1} column {2} (char {3})'
- #return fmt.format(msg, lineno, colno, pos)
- fmt = '%s: line %d column %d (char %d)'
- return fmt % (msg, lineno, colno, pos)
- endlineno, endcolno = linecol(doc, end)
- #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
- #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
- fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
- return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
-
-
-_CONSTANTS = {
- '-Infinity': NegInf,
- 'Infinity': PosInf,
- 'NaN': NaN,
-}
-
-STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
-BACKSLASH = {
- '"': u'"', '\\': u'\\', '/': u'/',
- 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
-}
-
-DEFAULT_ENCODING = "utf-8"
-
-def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
- """Scan the string s for a JSON string. End is the index of the
- character in s after the quote that started the JSON string.
- Unescapes all valid JSON string escape sequences and raises ValueError
- on attempt to decode an invalid string. If strict is False then literal
- control characters are allowed in the string.
-
- Returns a tuple of the decoded string and the index of the character in s
- after the end quote."""
- if encoding is None:
- encoding = DEFAULT_ENCODING
- chunks = []
- _append = chunks.append
- begin = end - 1
- while 1:
- chunk = _m(s, end)
- if chunk is None:
- raise ValueError(
- errmsg("Unterminated string starting at", s, begin))
- end = chunk.end()
- content, terminator = chunk.groups()
- # Content is contains zero or more unescaped string characters
- if content:
- if not isinstance(content, unicode):
- content = unicode(content, encoding)
- _append(content)
- # Terminator is the end of string, a literal control character,
- # or a backslash denoting that an escape sequence follows
- if terminator == '"':
- break
- elif terminator != '\\':
- if strict:
- msg = "Invalid control character %r at" % (terminator,)
- #msg = "Invalid control character {0!r} at".format(terminator)
- raise ValueError(errmsg(msg, s, end))
- else:
- _append(terminator)
- continue
- try:
- esc = s[end]
- except IndexError:
- raise ValueError(
- errmsg("Unterminated string starting at", s, begin))
- # If not a unicode escape sequence, must be in the lookup table
- if esc != 'u':
- try:
- char = _b[esc]
- except KeyError:
- msg = "Invalid \\escape: " + repr(esc)
- raise ValueError(errmsg(msg, s, end))
- end += 1
- else:
- # Unicode escape sequence
- esc = s[end + 1:end + 5]
- next_end = end + 5
- if len(esc) != 4:
- msg = "Invalid \\uXXXX escape"
- raise ValueError(errmsg(msg, s, end))
- uni = int(esc, 16)
- # Check for surrogate pair on UCS-4 systems
- if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
- msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
- if not s[end + 5:end + 7] == '\\u':
- raise ValueError(errmsg(msg, s, end))
- esc2 = s[end + 7:end + 11]
- if len(esc2) != 4:
- raise ValueError(errmsg(msg, s, end))
- uni2 = int(esc2, 16)
- uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
- next_end += 6
- char = unichr(uni)
- end = next_end
- # Append the unescaped character
- _append(char)
- return u''.join(chunks), end
-
-
-# Use speedup if available
-scanstring = c_scanstring or py_scanstring
-
-WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
-WHITESPACE_STR = ' \t\n\r'
-
-def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
- pairs = {}
- # Use a slice to prevent IndexError from being raised, the following
- # check will raise a more specific ValueError if the string is empty
- nextchar = s[end:end + 1]
- # Normally we expect nextchar == '"'
- if nextchar != '"':
- if nextchar in _ws:
- end = _w(s, end).end()
- nextchar = s[end:end + 1]
- # Trivial empty object
- if nextchar == '}':
- return pairs, end + 1
- elif nextchar != '"':
- raise ValueError(errmsg("Expecting property name", s, end))
- end += 1
- while True:
- key, end = scanstring(s, end, encoding, strict)
-
- # To skip some function call overhead we optimize the fast paths where
- # the JSON key separator is ": " or just ":".
- if s[end:end + 1] != ':':
- end = _w(s, end).end()
- if s[end:end + 1] != ':':
- raise ValueError(errmsg("Expecting : delimiter", s, end))
-
- end += 1
-
- try:
- if s[end] in _ws:
- end += 1
- if s[end] in _ws:
- end = _w(s, end + 1).end()
- except IndexError:
- pass
-
- try:
- value, end = scan_once(s, end)
- except StopIteration:
- raise ValueError(errmsg("Expecting object", s, end))
- pairs[key] = value
-
- try:
- nextchar = s[end]
- if nextchar in _ws:
- end = _w(s, end + 1).end()
- nextchar = s[end]
- except IndexError:
- nextchar = ''
- end += 1
-
- if nextchar == '}':
- break
- elif nextchar != ',':
- raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
-
- try:
- nextchar = s[end]
- if nextchar in _ws:
- end += 1
- nextchar = s[end]
- if nextchar in _ws:
- end = _w(s, end + 1).end()
- nextchar = s[end]
- except IndexError:
- nextchar = ''
-
- end += 1
- if nextchar != '"':
- raise ValueError(errmsg("Expecting property name", s, end - 1))
-
- if object_hook is not None:
- pairs = object_hook(pairs)
- return pairs, end
-
-def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
- values = []
- nextchar = s[end:end + 1]
- if nextchar in _ws:
- end = _w(s, end + 1).end()
- nextchar = s[end:end + 1]
- # Look-ahead for trivial empty array
- if nextchar == ']':
- return values, end + 1
- _append = values.append
- while True:
- try:
- value, end = scan_once(s, end)
- except StopIteration:
- raise ValueError(errmsg("Expecting object", s, end))
- _append(value)
- nextchar = s[end:end + 1]
- if nextchar in _ws:
- end = _w(s, end + 1).end()
- nextchar = s[end:end + 1]
- end += 1
- if nextchar == ']':
- break
- elif nextchar != ',':
- raise ValueError(errmsg("Expecting , delimiter", s, end))
-
- try:
- if s[end] in _ws:
- end += 1
- if s[end] in _ws:
- end = _w(s, end + 1).end()
- except IndexError:
- pass
-
- return values, end
-
-class JSONDecoder(object):
- """Simple JSON <http://json.org> decoder
-
- Performs the following translations in decoding by default:
-
- +---------------+-------------------+
- | JSON | Python |
- +===============+===================+
- | object | dict |
- +---------------+-------------------+
- | array | list |
- +---------------+-------------------+
- | string | unicode |
- +---------------+-------------------+
- | number (int) | int, long |
- +---------------+-------------------+
- | number (real) | float |
- +---------------+-------------------+
- | true | True |
- +---------------+-------------------+
- | false | False |
- +---------------+-------------------+
- | null | None |
- +---------------+-------------------+
-
- It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
- their corresponding ``float`` values, which is outside the JSON spec.
-
- """
-
- def __init__(self, encoding=None, object_hook=None, parse_float=None,
- parse_int=None, parse_constant=None, strict=True):
- """``encoding`` determines the encoding used to interpret any ``str``
- objects decoded by this instance (utf-8 by default). It has no
- effect when decoding ``unicode`` objects.
-
- Note that currently only encodings that are a superset of ASCII work,
- strings of other encodings should be passed in as ``unicode``.
-
- ``object_hook``, if specified, will be called with the result
- of every JSON object decoded and its return value will be used in
- place of the given ``dict``. This can be used to provide custom
- deserializations (e.g. to support JSON-RPC class hinting).
-
- ``parse_float``, if specified, will be called with the string
- of every JSON float to be decoded. By default this is equivalent to
- float(num_str). This can be used to use another datatype or parser
- for JSON floats (e.g. decimal.Decimal).
-
- ``parse_int``, if specified, will be called with the string
- of every JSON int to be decoded. By default this is equivalent to
- int(num_str). This can be used to use another datatype or parser
- for JSON integers (e.g. float).
-
- ``parse_constant``, if specified, will be called with one of the
- following strings: -Infinity, Infinity, NaN.
- This can be used to raise an exception if invalid JSON numbers
- are encountered.
-
- """
- self.encoding = encoding
- self.object_hook = object_hook
- self.parse_float = parse_float or float
- self.parse_int = parse_int or int
- self.parse_constant = parse_constant or _CONSTANTS.__getitem__
- self.strict = strict
- self.parse_object = JSONObject
- self.parse_array = JSONArray
- self.parse_string = scanstring
- self.scan_once = make_scanner(self)
-
- def decode(self, s, _w=WHITESPACE.match):
- """Return the Python representation of ``s`` (a ``str`` or ``unicode``
- instance containing a JSON document)
-
- """
- obj, end = self.raw_decode(s, idx=_w(s, 0).end())
- end = _w(s, end).end()
- if end != len(s):
- raise ValueError(errmsg("Extra data", s, end, len(s)))
- return obj
-
- def raw_decode(self, s, idx=0):
- """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
- with a JSON document) and return a 2-tuple of the Python
- representation and the index in ``s`` where the document ended.
-
- This can be used to decode a JSON document from a string that may
- have extraneous data at the end.
-
- """
- try:
- obj, end = self.scan_once(s, idx)
- except StopIteration:
- raise ValueError("No JSON object could be decoded")
- return obj, end
diff --git a/test/simplejson/encoder.py b/test/simplejson/encoder.py
deleted file mode 100644
index cf58290366..0000000000
--- a/test/simplejson/encoder.py
+++ /dev/null
@@ -1,440 +0,0 @@
-"""Implementation of JSONEncoder
-"""
-import re
-
-try:
- from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
-except ImportError:
- c_encode_basestring_ascii = None
-try:
- from simplejson._speedups import make_encoder as c_make_encoder
-except ImportError:
- c_make_encoder = None
-
-ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
-ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
-HAS_UTF8 = re.compile(r'[\x80-\xff]')
-ESCAPE_DCT = {
- '\\': '\\\\',
- '"': '\\"',
- '\b': '\\b',
- '\f': '\\f',
- '\n': '\\n',
- '\r': '\\r',
- '\t': '\\t',
-}
-for i in range(0x20):
- #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
- ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
-
-# Assume this produces an infinity on all machines (probably not guaranteed)
-INFINITY = float('1e66666')
-FLOAT_REPR = repr
-
-def encode_basestring(s):
- """Return a JSON representation of a Python string
-
- """
- def replace(match):
- return ESCAPE_DCT[match.group(0)]
- return '"' + ESCAPE.sub(replace, s) + '"'
-
-
-def py_encode_basestring_ascii(s):
- """Return an ASCII-only JSON representation of a Python string
-
- """
- if isinstance(s, str) and HAS_UTF8.search(s) is not None:
- s = s.decode('utf-8')
- def replace(match):
- s = match.group(0)
- try:
- return ESCAPE_DCT[s]
- except KeyError:
- n = ord(s)
- if n < 0x10000:
- #return '\\u{0:04x}'.format(n)
- return '\\u%04x' % (n,)
- else:
- # surrogate pair
- n -= 0x10000
- s1 = 0xd800 | ((n >> 10) & 0x3ff)
- s2 = 0xdc00 | (n & 0x3ff)
- #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
- return '\\u%04x\\u%04x' % (s1, s2)
- return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
-
-
-encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
-
-class JSONEncoder(object):
- """Extensible JSON <http://json.org> encoder for Python data structures.
-
- Supports the following objects and types by default:
-
- +-------------------+---------------+
- | Python | JSON |
- +===================+===============+
- | dict | object |
- +-------------------+---------------+
- | list, tuple | array |
- +-------------------+---------------+
- | str, unicode | string |
- +-------------------+---------------+
- | int, long, float | number |
- +-------------------+---------------+
- | True | true |
- +-------------------+---------------+
- | False | false |
- +-------------------+---------------+
- | None | null |
- +-------------------+---------------+
-
- To extend this to recognize other objects, subclass and implement a
- ``.default()`` method with another method that returns a serializable
- object for ``o`` if possible, otherwise it should call the superclass
- implementation (to raise ``TypeError``).
-
- """
- item_separator = ', '
- key_separator = ': '
- def __init__(self, skipkeys=False, ensure_ascii=True,
- check_circular=True, allow_nan=True, sort_keys=False,
- indent=None, separators=None, encoding='utf-8', default=None):
- """Constructor for JSONEncoder, with sensible defaults.
-
- If skipkeys is false, then it is a TypeError to attempt
- encoding of keys that are not str, int, long, float or None. If
- skipkeys is True, such items are simply skipped.
-
- If ensure_ascii is true, the output is guaranteed to be str
- objects with all incoming unicode characters escaped. If
- ensure_ascii is false, the output will be unicode object.
-
- If check_circular is true, then lists, dicts, and custom encoded
- objects will be checked for circular references during encoding to
- prevent an infinite recursion (which would cause an OverflowError).
- Otherwise, no such check takes place.
-
- If allow_nan is true, then NaN, Infinity, and -Infinity will be
- encoded as such. This behavior is not JSON specification compliant,
- but is consistent with most JavaScript based encoders and decoders.
- Otherwise, it will be a ValueError to encode such floats.
-
- If sort_keys is true, then the output of dictionaries will be
- sorted by key; this is useful for regression tests to ensure
- that JSON serializations can be compared on a day-to-day basis.
-
- If indent is a non-negative integer, then JSON array
- elements and object members will be pretty-printed with that
- indent level. An indent level of 0 will only insert newlines.
- None is the most compact representation.
-
- If specified, separators should be a (item_separator, key_separator)
- tuple. The default is (', ', ': '). To get the most compact JSON
- representation you should specify (',', ':') to eliminate whitespace.
-
- If specified, default is a function that gets called for objects
- that can't otherwise be serialized. It should return a JSON encodable
- version of the object or raise a ``TypeError``.
-
- If encoding is not None, then all input strings will be
- transformed into unicode using that encoding prior to JSON-encoding.
- The default is UTF-8.
-
- """
-
- self.skipkeys = skipkeys
- self.ensure_ascii = ensure_ascii
- self.check_circular = check_circular
- self.allow_nan = allow_nan
- self.sort_keys = sort_keys
- self.indent = indent
- if separators is not None:
- self.item_separator, self.key_separator = separators
- if default is not None:
- self.default = default
- self.encoding = encoding
-
- def default(self, o):
- """Implement this method in a subclass such that it returns
- a serializable object for ``o``, or calls the base implementation
- (to raise a ``TypeError``).
-
- For example, to support arbitrary iterators, you could
- implement default like this::
-
- def default(self, o):
- try:
- iterable = iter(o)
- except TypeError:
- pass
- else:
- return list(iterable)
- return JSONEncoder.default(self, o)
-
- """
- raise TypeError(repr(o) + " is not JSON serializable")
-
- def encode(self, o):
- """Return a JSON string representation of a Python data structure.
-
- >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
- '{"foo": ["bar", "baz"]}'
-
- """
- # This is for extremely simple cases and benchmarks.
- if isinstance(o, basestring):
- if isinstance(o, str):
- _encoding = self.encoding
- if (_encoding is not None
- and not (_encoding == 'utf-8')):
- o = o.decode(_encoding)
- if self.ensure_ascii:
- return encode_basestring_ascii(o)
- else:
- return encode_basestring(o)
- # This doesn't pass the iterator directly to ''.join() because the
- # exceptions aren't as detailed. The list call should be roughly
- # equivalent to the PySequence_Fast that ''.join() would do.
- chunks = self.iterencode(o, _one_shot=True)
- if not isinstance(chunks, (list, tuple)):
- chunks = list(chunks)
- return ''.join(chunks)
-
- def iterencode(self, o, _one_shot=False):
- """Encode the given object and yield each string
- representation as available.
-
- For example::
-
- for chunk in JSONEncoder().iterencode(bigobject):
- mysocket.write(chunk)
-
- """
- if self.check_circular:
- markers = {}
- else:
- markers = None
- if self.ensure_ascii:
- _encoder = encode_basestring_ascii
- else:
- _encoder = encode_basestring
- if self.encoding != 'utf-8':
- def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
- if isinstance(o, str):
- o = o.decode(_encoding)
- return _orig_encoder(o)
-
- def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
- # Check for specials. Note that this type of test is processor- and/or
- # platform-specific, so do tests which don't depend on the internals.
-
- if o != o:
- text = 'NaN'
- elif o == _inf:
- text = 'Infinity'
- elif o == _neginf:
- text = '-Infinity'
- else:
- return _repr(o)
-
- if not allow_nan:
- raise ValueError(
- "Out of range float values are not JSON compliant: " +
- repr(o))
-
- return text
-
-
- if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
- _iterencode = c_make_encoder(
- markers, self.default, _encoder, self.indent,
- self.key_separator, self.item_separator, self.sort_keys,
- self.skipkeys, self.allow_nan)
- else:
- _iterencode = _make_iterencode(
- markers, self.default, _encoder, self.indent, floatstr,
- self.key_separator, self.item_separator, self.sort_keys,
- self.skipkeys, _one_shot)
- return _iterencode(o, 0)
-
-def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
- ## HACK: hand-optimized bytecode; turn globals into locals
- False=False,
- True=True,
- ValueError=ValueError,
- basestring=basestring,
- dict=dict,
- float=float,
- id=id,
- int=int,
- isinstance=isinstance,
- list=list,
- long=long,
- str=str,
- tuple=tuple,
- ):
-
- def _iterencode_list(lst, _current_indent_level):
- if not lst:
- yield '[]'
- return
- if markers is not None:
- markerid = id(lst)
- if markerid in markers:
- raise ValueError("Circular reference detected")
- markers[markerid] = lst
- buf = '['
- if _indent is not None:
- _current_indent_level += 1
- newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
- separator = _item_separator + newline_indent
- buf += newline_indent
- else:
- newline_indent = None
- separator = _item_separator
- first = True
- for value in lst:
- if first:
- first = False
- else:
- buf = separator
- if isinstance(value, basestring):
- yield buf + _encoder(value)
- elif value is None:
- yield buf + 'null'
- elif value is True:
- yield buf + 'true'
- elif value is False:
- yield buf + 'false'
- elif isinstance(value, (int, long)):
- yield buf + str(value)
- elif isinstance(value, float):
- yield buf + _floatstr(value)
- else:
- yield buf
- if isinstance(value, (list, tuple)):
- chunks = _iterencode_list(value, _current_indent_level)
- elif isinstance(value, dict):
- chunks = _iterencode_dict(value, _current_indent_level)
- else:
- chunks = _iterencode(value, _current_indent_level)
- for chunk in chunks:
- yield chunk
- if newline_indent is not None:
- _current_indent_level -= 1
- yield '\n' + (' ' * (_indent * _current_indent_level))
- yield ']'
- if markers is not None:
- del markers[markerid]
-
- def _iterencode_dict(dct, _current_indent_level):
- if not dct:
- yield '{}'
- return
- if markers is not None:
- markerid = id(dct)
- if markerid in markers:
- raise ValueError("Circular reference detected")
- markers[markerid] = dct
- yield '{'
- if _indent is not None:
- _current_indent_level += 1
- newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
- item_separator = _item_separator + newline_indent
- yield newline_indent
- else:
- newline_indent = None
- item_separator = _item_separator
- first = True
- if _sort_keys:
- items = dct.items()
- items.sort(key=lambda kv: kv[0])
- else:
- items = dct.iteritems()
- for key, value in items:
- if isinstance(key, basestring):
- pass
- # JavaScript is weakly typed for these, so it makes sense to
- # also allow them. Many encoders seem to do something like this.
- elif isinstance(key, float):
- key = _floatstr(key)
- elif key is True:
- key = 'true'
- elif key is False:
- key = 'false'
- elif key is None:
- key = 'null'
- elif isinstance(key, (int, long)):
- key = str(key)
- elif _skipkeys:
- continue
- else:
- raise TypeError("key " + repr(key) + " is not a string")
- if first:
- first = False
- else:
- yield item_separator
- yield _encoder(key)
- yield _key_separator
- if isinstance(value, basestring):
- yield _encoder(value)
- elif value is None:
- yield 'null'
- elif value is True:
- yield 'true'
- elif value is False:
- yield 'false'
- elif isinstance(value, (int, long)):
- yield str(value)
- elif isinstance(value, float):
- yield _floatstr(value)
- else:
- if isinstance(value, (list, tuple)):
- chunks = _iterencode_list(value, _current_indent_level)
- elif isinstance(value, dict):
- chunks = _iterencode_dict(value, _current_indent_level)
- else:
- chunks = _iterencode(value, _current_indent_level)
- for chunk in chunks:
- yield chunk
- if newline_indent is not None:
- _current_indent_level -= 1
- yield '\n' + (' ' * (_indent * _current_indent_level))
- yield '}'
- if markers is not None:
- del markers[markerid]
-
- def _iterencode(o, _current_indent_level):
- if isinstance(o, basestring):
- yield _encoder(o)
- elif o is None:
- yield 'null'
- elif o is True:
- yield 'true'
- elif o is False:
- yield 'false'
- elif isinstance(o, (int, long)):
- yield str(o)
- elif isinstance(o, float):
- yield _floatstr(o)
- elif isinstance(o, (list, tuple)):
- for chunk in _iterencode_list(o, _current_indent_level):
- yield chunk
- elif isinstance(o, dict):
- for chunk in _iterencode_dict(o, _current_indent_level):
- yield chunk
- else:
- if markers is not None:
- markerid = id(o)
- if markerid in markers:
- raise ValueError("Circular reference detected")
- markers[markerid] = o
- o = _default(o)
- for chunk in _iterencode(o, _current_indent_level):
- yield chunk
- if markers is not None:
- del markers[markerid]
-
- return _iterencode
diff --git a/test/simplejson/scanner.py b/test/simplejson/scanner.py
deleted file mode 100644
index adbc6ec979..0000000000
--- a/test/simplejson/scanner.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""JSON token scanner
-"""
-import re
-try:
- from simplejson._speedups import make_scanner as c_make_scanner
-except ImportError:
- c_make_scanner = None
-
-__all__ = ['make_scanner']
-
-NUMBER_RE = re.compile(
- r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
- (re.VERBOSE | re.MULTILINE | re.DOTALL))
-
-def py_make_scanner(context):
- parse_object = context.parse_object
- parse_array = context.parse_array
- parse_string = context.parse_string
- match_number = NUMBER_RE.match
- encoding = context.encoding
- strict = context.strict
- parse_float = context.parse_float
- parse_int = context.parse_int
- parse_constant = context.parse_constant
- object_hook = context.object_hook
-
- def _scan_once(string, idx):
- try:
- nextchar = string[idx]
- except IndexError:
- raise StopIteration
-
- if nextchar == '"':
- return parse_string(string, idx + 1, encoding, strict)
- elif nextchar == '{':
- return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook)
- elif nextchar == '[':
- return parse_array((string, idx + 1), _scan_once)
- elif nextchar == 'n' and string[idx:idx + 4] == 'null':
- return None, idx + 4
- elif nextchar == 't' and string[idx:idx + 4] == 'true':
- return True, idx + 4
- elif nextchar == 'f' and string[idx:idx + 5] == 'false':
- return False, idx + 5
-
- m = match_number(string, idx)
- if m is not None:
- integer, frac, exp = m.groups()
- if frac or exp:
- res = parse_float(integer + (frac or '') + (exp or ''))
- else:
- res = parse_int(integer)
- return res, m.end()
- elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
- return parse_constant('NaN'), idx + 3
- elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
- return parse_constant('Infinity'), idx + 8
- elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
- return parse_constant('-Infinity'), idx + 9
- else:
- raise StopIteration
-
- return _scan_once
-
-make_scanner = c_make_scanner or py_make_scanner
diff --git a/test/simplejson/tool.py b/test/simplejson/tool.py
deleted file mode 100644
index 90443317b2..0000000000
--- a/test/simplejson/tool.py
+++ /dev/null
@@ -1,37 +0,0 @@
-r"""Command-line tool to validate and pretty-print JSON
-
-Usage::
-
- $ echo '{"json":"obj"}' | python -m simplejson.tool
- {
- "json": "obj"
- }
- $ echo '{ 1.2:3.4}' | python -m simplejson.tool
- Expecting property name: line 1 column 2 (char 2)
-
-"""
-import sys
-import simplejson
-
-def main():
- if len(sys.argv) == 1:
- infile = sys.stdin
- outfile = sys.stdout
- elif len(sys.argv) == 2:
- infile = open(sys.argv[1], 'rb')
- outfile = sys.stdout
- elif len(sys.argv) == 3:
- infile = open(sys.argv[1], 'rb')
- outfile = open(sys.argv[2], 'wb')
- else:
- raise SystemExit(sys.argv[0] + " [infile [outfile]]")
- try:
- obj = simplejson.load(infile)
- except ValueError, e:
- raise SystemExit(e)
- simplejson.dump(obj, outfile, sort_keys=True, indent=4)
- outfile.write('\n')
-
-
-if __name__ == '__main__':
- main()