diff --git a/src/actors/scala/actors/Actor.scala b/src/actors/scala/actors/Actor.scala index 0e52e867cae7..5062bfa44ce5 100644 --- a/src/actors/scala/actors/Actor.scala +++ b/src/actors/scala/actors/Actor.scala @@ -543,7 +543,7 @@ trait Actor extends AbstractActor with ReplyReactor with ActorCanReply with Inpu received = Some(TIMEOUT) senders = this :: senders } else - system.error("unhandled timeout") + sys.error("unhandled timeout") } var done = false diff --git a/src/actors/scala/actors/Scheduler.scala b/src/actors/scala/actors/Scheduler.scala index d41d2ea9e82e..792eae40a4b9 100644 --- a/src/actors/scala/actors/Scheduler.scala +++ b/src/actors/scala/actors/Scheduler.scala @@ -45,7 +45,7 @@ object Scheduler extends DelegatingScheduler { if (sched.isInstanceOf[ForkJoinScheduler]) { sched.asInstanceOf[ForkJoinScheduler].snapshot() } else - system.error("scheduler does not implement snapshot") + sys.error("scheduler does not implement snapshot") } /* Only ForkJoinScheduler implements this method. @@ -55,7 +55,7 @@ object Scheduler extends DelegatingScheduler { if (sched.isInstanceOf[ForkJoinScheduler]) { sched.asInstanceOf[ForkJoinScheduler].restart() } else - system.error("scheduler does not implement restart") + sys.error("scheduler does not implement restart") } } diff --git a/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala b/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala index c31026c3e820..ba0f88c668ca 100644 --- a/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala +++ b/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala @@ -160,9 +160,9 @@ class ForkJoinScheduler(val initCoreSize: Int, val maxSize: Int, daemon: Boolean def restart() { synchronized { if (!snapshoting) - system.error("snapshot has not been invoked") + sys.error("snapshot has not been invoked") else if (isActive) - system.error("scheduler is still active") + sys.error("scheduler is still active") else snapshoting = false diff --git a/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala b/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala index 575a2698e55c..a317cf0a86d7 100644 --- a/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala +++ b/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala @@ -181,9 +181,9 @@ class ResizableThreadPoolScheduler(protected val terminate: Boolean, def restart() { synchronized { if (!suspending) - system.error("snapshot has not been invoked") + sys.error("snapshot has not been invoked") else if (isActive) - system.error("scheduler is still active") + sys.error("scheduler is still active") else suspending = false diff --git a/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java b/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java index 13da20c4d656..9577537f30fd 100644 --- a/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java +++ b/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java @@ -45,7 +45,7 @@ public void run() { /** * Abstraction of the exception handler which receives notifications of - * exceptions occurred possibly in various parts of the system. Exception + * exceptions occurred possibly in various parts of the sys. Exception * handlers present attractive approach to exception handling in multi-threaded * systems, as they can handle exceptions that occurred in different threads. *

diff --git a/src/compiler/scala/tools/ant/Same.scala b/src/compiler/scala/tools/ant/Same.scala index 2c68e12ba824..deaa9135a15b 100644 --- a/src/compiler/scala/tools/ant/Same.scala +++ b/src/compiler/scala/tools/ant/Same.scala @@ -90,8 +90,8 @@ class Same extends ScalaMatchingTask { /** Tests if all mandatory attributes are set and valid. */ private def validateAttributes = { - if (origin.isEmpty) system.error("Mandatory attribute 'dir' is not set.") - if (destination.isEmpty) system.error("Mandatory attribute 'todir' is not set.") + if (origin.isEmpty) sys.error("Mandatory attribute 'dir' is not set.") + if (destination.isEmpty) sys.error("Mandatory attribute 'todir' is not set.") } private def reportDiff(f1: File, f2: File) = { @@ -150,7 +150,7 @@ class Same extends ScalaMatchingTask { } if (!allEqualNow) if (failing) - system.error("There were differences between '" + origin.get + "' and '" + destination.get + "'") + sys.error("There were differences between '" + origin.get + "' and '" + destination.get + "'") else log("There were differences between '" + origin.get + "' and '" + destination.get + "'") else { diff --git a/src/compiler/scala/tools/ant/sabbus/Break.scala b/src/compiler/scala/tools/ant/sabbus/Break.scala index 5d1f82e77a2e..e22d804f9359 100644 --- a/src/compiler/scala/tools/ant/sabbus/Break.scala +++ b/src/compiler/scala/tools/ant/sabbus/Break.scala @@ -20,7 +20,7 @@ class Break extends Task { private var id: Option[String] = None override def execute { - if (id.isEmpty) system.error("Attribute 'id' is not set") + if (id.isEmpty) sys.error("Attribute 'id' is not set") Compilers.break(id.get) } diff --git a/src/compiler/scala/tools/ant/sabbus/Make.scala b/src/compiler/scala/tools/ant/sabbus/Make.scala index 31244ea7b40d..88b4b371fb14 100644 --- a/src/compiler/scala/tools/ant/sabbus/Make.scala +++ b/src/compiler/scala/tools/ant/sabbus/Make.scala @@ -14,8 +14,8 @@ import org.apache.tools.ant.Task class Make extends Task with TaskArgs { override def execute { - if (id.isEmpty) system.error("Mandatory attribute 'id' is not set.") - if (compilerPath.isEmpty) system.error("Mandatory attribute 'compilerpath' is not set.") + if (id.isEmpty) sys.error("Mandatory attribute 'id' is not set.") + if (compilerPath.isEmpty) sys.error("Mandatory attribute 'compilerpath' is not set.") val settings = new Settings if (!destinationDir.isEmpty) settings.d = destinationDir.get if (!compTarget.isEmpty) settings.target = compTarget.get diff --git a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala index f83f476695a2..5ce42326e22f 100644 --- a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala +++ b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala @@ -62,9 +62,9 @@ class ScalacFork extends ScalaMatchingTask with ScalacShared with TaskArgs { log("Executing ant task scalacfork, origin: %s".format(originOfThis), Project.MSG_VERBOSE) - val compilerPath = this.compilerPath getOrElse system.error("Mandatory attribute 'compilerpath' is not set.") - val sourceDir = this.sourceDir getOrElse system.error("Mandatory attribute 'srcdir' is not set.") - val destinationDir = this.destinationDir getOrElse system.error("Mandatory attribute 'destdir' is not set.") + val compilerPath = this.compilerPath getOrElse sys.error("Mandatory attribute 'compilerpath' is not set.") + val sourceDir = this.sourceDir getOrElse sys.error("Mandatory attribute 'srcdir' is not set.") + val destinationDir = this.destinationDir getOrElse sys.error("Mandatory attribute 'destdir' is not set.") val settings = new Settings settings.d = destinationDir @@ -114,7 +114,7 @@ class ScalacFork extends ScalaMatchingTask with ScalacShared with TaskArgs { val res = execWithArgFiles(java, paths) if (failOnError && res != 0) - system.error("Compilation failed because of an internal compiler error;"+ + sys.error("Compilation failed because of an internal compiler error;"+ " see the error output for details.") } } diff --git a/src/compiler/scala/tools/ant/sabbus/Use.scala b/src/compiler/scala/tools/ant/sabbus/Use.scala index 703cf233e1b5..ed93bcdcceb3 100644 --- a/src/compiler/scala/tools/ant/sabbus/Use.scala +++ b/src/compiler/scala/tools/ant/sabbus/Use.scala @@ -39,8 +39,8 @@ class Use extends ScalaMatchingTask { private var failOnError: Boolean = true override def execute() { - if (id.isEmpty) system.error("Mandatory attribute 'id' is not set.") - if (sourceDir.isEmpty) system.error("Mandatory attribute 'srcdir' is not set.") + if (id.isEmpty) sys.error("Mandatory attribute 'id' is not set.") + if (sourceDir.isEmpty) sys.error("Mandatory attribute 'srcdir' is not set.") val compiler = Compilers(id.get) if (!destinationDir.isEmpty) compiler.settings.d = destinationDir.get val mapper = new GlobPatternMapper() @@ -58,7 +58,7 @@ class Use extends ScalaMatchingTask { log("Compiling " + includedFiles.size + " file" + (if (includedFiles.size > 1) "s" else "") + " to " + compiler.settings.d.getAbsolutePath) val (errors, warnings) = compiler.compile(includedFiles) if (errors > 0) - system.error("Compilation failed with " + errors + " error" + (if (errors > 1) "s" else "") + ".") + sys.error("Compilation failed with " + errors + " error" + (if (errors > 1) "s" else "") + ".") else if (warnings > 0) log("Compilation succeeded with " + warnings + " warning" + (if (warnings > 1) "s" else "") + ".") } @@ -67,7 +67,7 @@ class Use extends ScalaMatchingTask { ex.printStackTrace val errorMsg = "Compilation failed because of an internal compiler error (" + msg + "); see the error output for details." - if (failOnError) system.error(errorMsg) else log(errorMsg) + if (failOnError) sys.error(errorMsg) else log(errorMsg) } } diff --git a/src/compiler/scala/tools/cmd/Demo.scala b/src/compiler/scala/tools/cmd/Demo.scala index c471c455aed4..c01338f91669 100644 --- a/src/compiler/scala/tools/cmd/Demo.scala +++ b/src/compiler/scala/tools/cmd/Demo.scala @@ -48,7 +48,7 @@ object DemoSpec extends DemoSpec with Property { type ThisCommandLine = SpecCommandLine def creator(args: List[String]) = new SpecCommandLine(args) { - override def errorFn(msg: String) = { println("Error: " + msg) ; system.exit(0) } + override def errorFn(msg: String) = { println("Error: " + msg) ; sys.exit(0) } } } diff --git a/src/compiler/scala/tools/cmd/package.scala b/src/compiler/scala/tools/cmd/package.scala index a5cd7c1bc2c6..089e473546fa 100644 --- a/src/compiler/scala/tools/cmd/package.scala +++ b/src/compiler/scala/tools/cmd/package.scala @@ -12,7 +12,7 @@ package object cmd { def runAndExit(body: => Unit): Nothing = { body - system.exit(0) + sys.exit(0) } def toOpt(s: String) = if (s startsWith "--") s else "--" + s diff --git a/src/compiler/scala/tools/cmd/program/Simple.scala b/src/compiler/scala/tools/cmd/program/Simple.scala index a38239a11961..9d687083c704 100644 --- a/src/compiler/scala/tools/cmd/program/Simple.scala +++ b/src/compiler/scala/tools/cmd/program/Simple.scala @@ -66,8 +66,8 @@ object Simple { * inaccessible due to the overriding var. */ trait Ticket2338WontFixWorkaround { - def enforceArity_=(x: Boolean): Unit = system.error("unreachable") - def onlyKnownOptions_=(x: Boolean): Unit = system.error("unreachable") + def enforceArity_=(x: Boolean): Unit = sys.error("unreachable") + def onlyKnownOptions_=(x: Boolean): Unit = sys.error("unreachable") } /** Configurability simplicity achieved by turning defs into vars and letting diff --git a/src/compiler/scala/tools/nsc/CompileClient.scala b/src/compiler/scala/tools/nsc/CompileClient.scala index db5dae0cd915..7fca0687feb1 100644 --- a/src/compiler/scala/tools/nsc/CompileClient.scala +++ b/src/compiler/scala/tools/nsc/CompileClient.scala @@ -114,7 +114,7 @@ class StandardCompileClient { } def main(args: Array[String]): Unit = - system.exit(try main0(args) catch { case e: Exception => 1 }) + sys.exit(try main0(args) catch { case e: Exception => 1 }) } diff --git a/src/compiler/scala/tools/nsc/CompileServer.scala b/src/compiler/scala/tools/nsc/CompileServer.scala index a1198409dc6c..108a54ca833e 100644 --- a/src/compiler/scala/tools/nsc/CompileServer.scala +++ b/src/compiler/scala/tools/nsc/CompileServer.scala @@ -36,7 +36,7 @@ class StandardCompileServer extends SocketServer { private def exit(code: Int): Nothing = { System.err.close() System.out.close() - system.exit(code) + sys.exit(code) } private val runtime = Runtime.getRuntime() diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index 56fe04055cbf..aca34ec3a045 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -236,7 +236,7 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable // XXX: short term, but I can't bear to add another option. // scalac -Dscala.timings will make this true. - def timings = system.props contains "scala.timings" + def timings = sys.props contains "scala.timings" def debug = settings.debug.value def deprecation = settings.deprecation.value diff --git a/src/compiler/scala/tools/nsc/Interpreter.scala b/src/compiler/scala/tools/nsc/Interpreter.scala index 9fa77baeacb3..3425c04277e3 100644 --- a/src/compiler/scala/tools/nsc/Interpreter.scala +++ b/src/compiler/scala/tools/nsc/Interpreter.scala @@ -1367,7 +1367,7 @@ object Interpreter { intLoop.createInterpreter intLoop.in = InteractiveReader.createDefault(intLoop.interpreter) - // rebind exit so people don't accidentally call system.exit by way of predef + // rebind exit so people don't accidentally call sys.exit by way of predef intLoop.interpreter.beQuietDuring { intLoop.interpreter.interpret("""def exit = println("Type :quit to resume program execution.")""") for (p <- args) { diff --git a/src/compiler/scala/tools/nsc/InterpreterLoop.scala b/src/compiler/scala/tools/nsc/InterpreterLoop.scala index 55f361cf1f9a..aba4d6616556 100644 --- a/src/compiler/scala/tools/nsc/InterpreterLoop.scala +++ b/src/compiler/scala/tools/nsc/InterpreterLoop.scala @@ -117,7 +117,7 @@ class InterpreterLoop(in0: Option[BufferedReader], protected val out: PrintWrite private def installSigIntHandler() { def onExit() { Console.println("") // avoiding "shell prompt in middle of line" syndrome - system.exit(1) + sys.exit(1) } ignoring(classOf[Exception]) { SignalManager("INT") = { diff --git a/src/compiler/scala/tools/nsc/Main.scala b/src/compiler/scala/tools/nsc/Main.scala index 7f79c69f5275..22d884a04e30 100644 --- a/src/compiler/scala/tools/nsc/Main.scala +++ b/src/compiler/scala/tools/nsc/Main.scala @@ -120,7 +120,7 @@ object Main extends AnyRef with EvalLoop { def main(args: Array[String]) { process(args) - system exit (if (reporter.hasErrors) 1 else 0) + sys.exit(if (reporter.hasErrors) 1 else 0) } } diff --git a/src/compiler/scala/tools/nsc/MainGenericRunner.scala b/src/compiler/scala/tools/nsc/MainGenericRunner.scala index 116c06179abd..7fa41a5803da 100644 --- a/src/compiler/scala/tools/nsc/MainGenericRunner.scala +++ b/src/compiler/scala/tools/nsc/MainGenericRunner.scala @@ -31,7 +31,7 @@ object MainGenericRunner { def main(args: Array[String]) { if (!process(args)) - system.exit(1) + sys.exit(1) } def process(args: Array[String]): Boolean = { diff --git a/src/compiler/scala/tools/nsc/MainTokenMetric.scala b/src/compiler/scala/tools/nsc/MainTokenMetric.scala index 33e91759f82c..0137b33cd018 100644 --- a/src/compiler/scala/tools/nsc/MainTokenMetric.scala +++ b/src/compiler/scala/tools/nsc/MainTokenMetric.scala @@ -34,7 +34,7 @@ object MainTokenMetric { } def process(args: Array[String]) { - val settings = new Settings(system.error) + val settings = new Settings(sys.error) reporter = new ConsoleReporter(settings) val command = new CompilerCommand(args.toList, settings) try { @@ -50,7 +50,7 @@ object MainTokenMetric { def main(args: Array[String]) { process(args) - system.exit(if (reporter.hasErrors) 1 else 0) + sys.exit(if (reporter.hasErrors) 1 else 0) } } diff --git a/src/compiler/scala/tools/nsc/ScalaDoc.scala b/src/compiler/scala/tools/nsc/ScalaDoc.scala index 0549e2c758ed..6cc30eb8c8fa 100644 --- a/src/compiler/scala/tools/nsc/ScalaDoc.scala +++ b/src/compiler/scala/tools/nsc/ScalaDoc.scala @@ -79,6 +79,6 @@ object ScalaDoc { def main(args: Array[String]): Unit = { process(args) - system.exit(if (reporter.hasErrors) 1 else 0) + sys.exit(if (reporter.hasErrors) 1 else 0) } } diff --git a/src/compiler/scala/tools/nsc/ScriptRunner.scala b/src/compiler/scala/tools/nsc/ScriptRunner.scala index a3a04e34b9de..e7fd22d00ca9 100644 --- a/src/compiler/scala/tools/nsc/ScriptRunner.scala +++ b/src/compiler/scala/tools/nsc/ScriptRunner.scala @@ -134,7 +134,7 @@ object ScriptRunner { scriptFileIn: String): Boolean = { val scriptFile = Path(scriptFileIn).toAbsolute.path - val compSettingNames = new Settings(system.error).visibleSettings.toList map (_.name) + val compSettingNames = new Settings(sys.error).visibleSettings.toList map (_.name) val compSettings = settings.visibleSettings.toList filter (compSettingNames contains _.name) val coreCompArgs = compSettings flatMap (_.unparse) val compArgs = coreCompArgs ::: List("-Xscript", scriptMain(settings), scriptFile) @@ -178,7 +178,7 @@ object ScriptRunner { val compiledPath = Directory makeTemp "scalascript" // delete the directory after the user code has finished - system.addShutdownHook(compiledPath.deleteRecursively()) + sys.addShutdownHook(compiledPath.deleteRecursively()) settings.outdir.value = compiledPath.path @@ -198,7 +198,7 @@ object ScriptRunner { else None } - /** The script runner calls system.exit to communicate a return value, but this must + /** The script runner calls sys.exit to communicate a return value, but this must * not take place until there are no non-daemon threads running. Tickets #1955, #2006. */ waitingForThreads { diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala index cdc18ed566ec..8fa27c04f6ae 100644 --- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala +++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala @@ -684,7 +684,7 @@ abstract class TreeBrowsers { toDocument(thistpe) :/: ", " :/: toDocument(supertpe) ::")")) case _ => - system.error("Unknown case: " + t.toString() +", "+ t.getClass) + sys.error("Unknown case: " + t.toString() +", "+ t.getClass) } } diff --git a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala index 70ab35b13ce9..54e6acb082b5 100644 --- a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala +++ b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala @@ -581,7 +581,7 @@ abstract class ScalaPrimitives { val arrayParent = tpe :: tpe.parents collectFirst { case TypeRef(_, ArrayClass, elem :: Nil) => elem } - arrayParent getOrElse system.error(fun.fullName + " : " + (tpe :: tpe.baseTypeSeq.toList).mkString(", ")) + arrayParent getOrElse sys.error(fun.fullName + " : " + (tpe :: tpe.baseTypeSeq.toList).mkString(", ")) } code match { diff --git a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala index e38d14c10b87..993002dc1dcc 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala @@ -75,8 +75,8 @@ trait ExceptionHandlers { } object NoFinalizer extends Finalizer(null, "", NoPosition) { - override def startBlock: BasicBlock = system.error("NoFinalizer cannot have a start block."); - override def setStartBlock(b: BasicBlock): Unit = system.error("NoFinalizer cannot have a start block."); + override def startBlock: BasicBlock = sys.error("NoFinalizer cannot have a start block."); + override def setStartBlock(b: BasicBlock): Unit = sys.error("NoFinalizer cannot have a start block."); override def dup = this } } diff --git a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala index ad85ded12bd8..9f22a6de906f 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala @@ -191,7 +191,7 @@ trait Linearizers { */ class DumpLinearizer extends Linearizer { def linearize(m: IMethod): List[BasicBlock] = m.code.blocks.toList - def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = system.error("not implemented") + def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = sys.error("not implemented") } /** The MSIL linearizer is used only for methods with at least one exception handler. @@ -328,7 +328,7 @@ trait Linearizers { } def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = { - system.error("not implemented") + sys.error("not implemented") } } } diff --git a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala index 6da0279ffe2c..3f7383daf96c 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala @@ -578,7 +578,7 @@ trait Opcodes { self: ICodes => * then pushes one exception instance. */ case class LOAD_EXCEPTION(clasz: Symbol) extends Instruction { - override def consumed = system.error("LOAD_EXCEPTION does clean the whole stack, no idea how many things it consumes!") + override def consumed = sys.error("LOAD_EXCEPTION does clean the whole stack, no idea how many things it consumes!") override def produced = 1 override def producedTypes = REFERENCE(clasz) :: Nil } diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala index 43ab35b83e73..49f5cf78c99a 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala @@ -301,7 +301,7 @@ abstract class CopyPropagation { out.bindings += (LocalVar(local) -> v) } case Nil => - system.error("Incorrect icode in " + method + ". Expecting something on the stack.") + sys.error("Incorrect icode in " + method + ". Expecting something on the stack.") } out.stack = out.stack drop 1; diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala index c45983d5b661..58ca18335900 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala @@ -82,7 +82,7 @@ trait DataFlowAnalysis[L <: SemiLattice] { Console.println("in: " + in.mkString("", "\n", "")) Console.println("out: " + out.mkString("", "\n", "")) e.printStackTrace - system.error("Could not find element " + e.getMessage) + sys.error("Could not find element " + e.getMessage) } /** ... diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala index 03bb2bae3fa5..acc28bd4458c 100644 --- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala +++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala @@ -46,7 +46,7 @@ abstract class TypeFlowAnalysis { def lub2(exceptional: Boolean)(s1: TypeStack, s2: TypeStack) = { if (s1 eq bottom) s2 else if (s2 eq bottom) s1 - else if ((s1 eq exceptionHandlerStack) || (s2 eq exceptionHandlerStack)) system.error("merging with exhan stack") + else if ((s1 eq exceptionHandlerStack) || (s2 eq exceptionHandlerStack)) sys.error("merging with exhan stack") else { // if (s1.length != s2.length) // throw new CheckerException("Incompatible stacks: " + s1 + " and " + s2); diff --git a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala index 66dc3c78b2c2..aeea6b545265 100644 --- a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala +++ b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala @@ -296,7 +296,7 @@ abstract class Inliners extends SubComponent { def isMonadic = isMonadicMethod(sym) def handlers = m.exh - def blocks = if (m.code eq null) system.error("blocks = null + " + m) else m.code.blocks + def blocks = if (m.code eq null) sys.error("blocks = null + " + m) else m.code.blocks def locals = m.locals def length = blocks.length def openBlocks = blocks filterNot (_.closed) diff --git a/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala b/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala index 46e45a861b36..647a17b66bc1 100644 --- a/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala +++ b/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala @@ -214,7 +214,7 @@ abstract class SourcelessComments { /** Class `AnyVal` is the root class of all ''value types''. * * `AnyVal` has a fixed number of subclasses, which describe values which are not implemented as objects in the - * underlying host system. + * underlying host sys. * * Classes [[scala.Double]], [[scala.Float]], [[scala.Long]], [[scala.Int]], [[scala.Char]], [[scala.Short]], * and [[scala.Byte]] are together called ''numeric value types''. Classes [[scala.Byte]], [[scala.Short]], and @@ -235,7 +235,7 @@ abstract class SourcelessComments { val minValue = "MIN_" + sym.name.toString().toUpperCase() comment(sym) = new DocComment(""" /** Class `""" + sym.name + """` belongs to the value classes whose instances are not represented as objects by - * the underlying host system. There is an implicit conversion from instances of `""" + sym.name + """` to + * the underlying host sys. There is an implicit conversion from instances of `""" + sym.name + """` to * instances of [[scala.runtime.Rich""" + sym.name + """]] which provides useful non-primitive operations. * All value classes inherit from class [[scala.AnyVal]]. * diff --git a/src/compiler/scala/tools/nsc/interactive/REPL.scala b/src/compiler/scala/tools/nsc/interactive/REPL.scala index 47807ccdac9e..4e5d5668cb70 100644 --- a/src/compiler/scala/tools/nsc/interactive/REPL.scala +++ b/src/compiler/scala/tools/nsc/interactive/REPL.scala @@ -56,7 +56,7 @@ object REPL { def main(args: Array[String]) { process(args) - system.exit(if (reporter.hasErrors) 1 else 0) + sys.exit(if (reporter.hasErrors) 1 else 0) } def loop(action: (String) => Unit) { @@ -125,7 +125,7 @@ object REPL { doComplete(makePos(file, off1, off1)) case List("quit") => comp.askShutdown() - system.exit(1) + sys.exit(1) case _ => println("unrecongized command") } diff --git a/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala b/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala index 6e380027b6a5..36a715ba26e5 100644 --- a/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala +++ b/src/compiler/scala/tools/nsc/interactive/tests/Tester.scala @@ -199,6 +199,6 @@ object Tester { println("filenames = "+filenames) val files = filenames.toArray map (str => new BatchSourceFile(AbstractFile.getFile(str)): SourceFile) new Tester(args(0).toInt, files, settings).run() - system.exit(0) + sys.exit(0) } } diff --git a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala index 4fdcbafa835b..5e78cb4ebbce 100644 --- a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala @@ -23,7 +23,7 @@ trait InteractiveReader { def readLine(prompt: String): String = { def handler: Catcher[String] = { - case e: ClosedByInterruptException => system.error("Reader closed by interrupt.") + case e: ClosedByInterruptException => sys.error("Reader closed by interrupt.") // Terminal has to be re-initialized after SIGSTP or up arrow etc. stop working. case e: IOException if restartSystemCall(e) => reset() ; readLine(prompt) } diff --git a/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala index 440f2933f9d8..932326ecc7f7 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala @@ -19,12 +19,12 @@ trait ReflectionCompletion extends CompletionAware { def reflectName(m: AccessibleObject) = m match { case x: reflect.Method => x.getName case x: reflect.Field => x.getName - case x => system.error(x.toString) + case x => sys.error(x.toString) } def isPublic(m: AccessibleObject) = m match { case x: reflect.Method => Modifier isPublic x.getModifiers case x: reflect.Field => Modifier isPublic x.getModifiers - case x => system.error(x.toString) + case x => sys.error(x.toString) } lazy val (staticMethods, instanceMethods) = clazz.getMethods.toList partition (x => isStatic(x.getModifiers)) diff --git a/src/compiler/scala/tools/nsc/interpreter/package.scala b/src/compiler/scala/tools/nsc/interpreter/package.scala index 9d131f4786ac..dcbc84334c26 100644 --- a/src/compiler/scala/tools/nsc/interpreter/package.scala +++ b/src/compiler/scala/tools/nsc/interpreter/package.scala @@ -8,7 +8,7 @@ package scala.tools.nsc package object interpreter { private[nsc] val DebugProperty = "scala.repl.debug" private[nsc] var _debug = false - private[nsc] def isReplDebug = _debug || (system.props contains DebugProperty) + private[nsc] def isReplDebug = _debug || (sys.props contains DebugProperty) /** Debug output */ def repldbg(msg: String) = if (isReplDebug) Console println msg diff --git a/src/compiler/scala/tools/nsc/io/AbstractFile.scala b/src/compiler/scala/tools/nsc/io/AbstractFile.scala index 01aaa6c0078e..c2b73b2831f4 100644 --- a/src/compiler/scala/tools/nsc/io/AbstractFile.scala +++ b/src/compiler/scala/tools/nsc/io/AbstractFile.scala @@ -61,7 +61,7 @@ object AbstractFile { *

* This class and its children serve to unify handling of files and * directories. These files and directories may or may not have some - * real counter part within the file system. For example, some file + * real counter part within the file sys. For example, some file * handles reference files within a zip archive or virtual ones * that exist only in memory. *

diff --git a/src/compiler/scala/tools/nsc/io/File.scala b/src/compiler/scala/tools/nsc/io/File.scala index 7bf04cbe5cb6..eddc9c0de68b 100644 --- a/src/compiler/scala/tools/nsc/io/File.scala +++ b/src/compiler/scala/tools/nsc/io/File.scala @@ -112,6 +112,12 @@ class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) w finally out close } + def writeBytes(bytes: Array[Byte]): Unit = { + val out = bufferedOutput() + try out write bytes + finally out close + } + def appendAll(strings: String*): Unit = { val out = bufferedWriter(append = true) try strings foreach (out write _) diff --git a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala index eac7530aa347..8f5ad5c820b4 100644 --- a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala +++ b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala @@ -27,8 +27,8 @@ extends AbstractFile { var lastModified: Long = System.currentTimeMillis override def file = null - override def input = system.error("directories cannot be read") - override def output = system.error("directories cannot be written") + override def input = sys.error("directories cannot be read") + override def output = sys.error("directories cannot be written") /** Does this abstract file denote an existing file? */ def create { unsupported } diff --git a/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala index 3131c78bd0b4..a4699cfd88f6 100644 --- a/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala @@ -32,7 +32,7 @@ trait AbsScalaSettings { /** **/ abstract class SettingGroup(val prefix: String) extends AbsSetting { def name = prefix - def helpDescription: String = system.error("todo") + def helpDescription: String = sys.error("todo") def unparse: List[String] = List(name) } } diff --git a/src/compiler/scala/tools/nsc/symtab/Scopes.scala b/src/compiler/scala/tools/nsc/symtab/Scopes.scala index b5e23d61f055..6ce244b772bf 100644 --- a/src/compiler/scala/tools/nsc/symtab/Scopes.scala +++ b/src/compiler/scala/tools/nsc/symtab/Scopes.scala @@ -227,7 +227,7 @@ trait Scopes { /** lookup a symbol entry matching given name. * @note from Martin: I believe this is a hotspot or will be one - * in future versions of the type system. I have reverted the previous + * in future versions of the type sys. I have reverted the previous * change to use iterators as too costly. */ def lookupEntry(name: Name): ScopeEntry = { @@ -248,7 +248,7 @@ trait Scopes { /** lookup next entry with same name as this one * @note from Martin: I believe this is a hotspot or will be one - * in future versions of the type system. I have reverted the previous + * in future versions of the type sys. I have reverted the previous * change to use iterators as too costly. */ def lookupNextEntry(entry: ScopeEntry): ScopeEntry = { diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala index f944a168e9e8..5bc10a4fef9e 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala @@ -360,12 +360,12 @@ abstract class ICodeReader extends ClassfileParser { case JVM.pop => code.emit(DROP(INT)) // any 1-word type would do case JVM.pop2 => code.emit(DROP(LONG)) // any 2-word type would do case JVM.dup => code.emit(DUP(ObjectReference)) // TODO: Is the kind inside DUP ever needed? - case JVM.dup_x1 => code.emit(DUP_X1) // system.error("Unsupported JVM bytecode: dup_x1") - case JVM.dup_x2 => code.emit(DUP_X2) // system.error("Unsupported JVM bytecode: dup_x2") + case JVM.dup_x1 => code.emit(DUP_X1) // sys.error("Unsupported JVM bytecode: dup_x1") + case JVM.dup_x2 => code.emit(DUP_X2) // sys.error("Unsupported JVM bytecode: dup_x2") case JVM.dup2 => code.emit(DUP(LONG)) // TODO: Is the kind inside DUP ever needed? - case JVM.dup2_x1 => code.emit(DUP2_X1) // system.error("Unsupported JVM bytecode: dup2_x1") - case JVM.dup2_x2 => code.emit(DUP2_X2) // system.error("Unsupported JVM bytecode: dup2_x2") - case JVM.swap => system.error("Unsupported JVM bytecode: swap") + case JVM.dup2_x1 => code.emit(DUP2_X1) // sys.error("Unsupported JVM bytecode: dup2_x1") + case JVM.dup2_x2 => code.emit(DUP2_X2) // sys.error("Unsupported JVM bytecode: dup2_x2") + case JVM.swap => sys.error("Unsupported JVM bytecode: swap") case JVM.iadd => code.emit(CALL_PRIMITIVE(Arithmetic(ADD, INT))) case JVM.ladd => code.emit(CALL_PRIMITIVE(Arithmetic(ADD, LONG))) @@ -452,8 +452,8 @@ abstract class ICodeReader extends ClassfileParser { case JVM.if_acmpne => code.emit(LCJUMP(parseJumpTarget, pc + size, NE, ObjectReference)) case JVM.goto => emit(LJUMP(parseJumpTarget)) - case JVM.jsr => system.error("Cannot handle jsr/ret") - case JVM.ret => system.error("Cannot handle jsr/ret") + case JVM.jsr => sys.error("Cannot handle jsr/ret") + case JVM.ret => sys.error("Cannot handle jsr/ret") case JVM.tableswitch => val padding = if ((pc + size) % 4 != 0) 4 - ((pc + size) % 4) else 0 size += padding @@ -578,14 +578,14 @@ abstract class ICodeReader extends ClassfileParser { case JVM.fstore => code.emit(STORE_LOCAL(code.getLocal(in.nextChar, FLOAT))); size += 2 case JVM.dstore => code.emit(STORE_LOCAL(code.getLocal(in.nextChar, DOUBLE))); size += 2 case JVM.astore => code.emit(STORE_LOCAL(code.getLocal(in.nextChar, ObjectReference))); size += 2 - case JVM.ret => system.error("Cannot handle jsr/ret") + case JVM.ret => sys.error("Cannot handle jsr/ret") case JVM.iinc => size += 4 val local = code.getLocal(in.nextChar, INT) code.emit(CONSTANT(Constant(in.nextChar))) code.emit(CALL_PRIMITIVE(Arithmetic(ADD, INT))) code.emit(STORE_LOCAL(local)) - case _ => system.error("Invalid 'wide' operand") + case _ => sys.error("Invalid 'wide' operand") } case JVM.multianewarray => @@ -598,9 +598,9 @@ abstract class ICodeReader extends ClassfileParser { case JVM.ifnull => code.emit(LCZJUMP(parseJumpTarget, pc + size, EQ, ObjectReference)) case JVM.ifnonnull => code.emit(LCZJUMP(parseJumpTarget, pc + size, NE, ObjectReference)) case JVM.goto_w => code.emit(LJUMP(parseJumpTargetW)) - case JVM.jsr_w => system.error("Cannot handle jsr/ret") + case JVM.jsr_w => sys.error("Cannot handle jsr/ret") -// case _ => system.error("Unknown bytecode") +// case _ => sys.error("Unknown bytecode") } pc += size } diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala index 6e5a8ac817ef..153aa0faf5f3 100644 --- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala +++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala @@ -450,7 +450,7 @@ abstract class ExplicitOuter extends InfoTransform if (sym.isClassConstructor) { rhs match { case Literal(_) => - system.error("unexpected case") //todo: remove + sys.error("unexpected case") //todo: remove case _ => val clazz = sym.owner val vparamss1 = diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala index 758c28a238b8..0e190a0da17f 100644 --- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala +++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala @@ -301,7 +301,7 @@ abstract class TailCalls extends Transform { rewriteApply(fun, fun, Nil, args) case Alternative(_) | Star(_) | Bind(_, _) => - system.error("We should've never gotten inside a pattern") + sys.error("We should've never gotten inside a pattern") case EmptyTree | Super(_, _) | This(_) | Select(_, _) | Ident(_) | Literal(_) | Function(_, _) | TypeTree() => tree case _ => diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala index c06d2ce7dc76..2f56180c8d4b 100644 --- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala +++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala @@ -587,7 +587,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers with ast.Tr val args1 = transformTrees(fn.symbol.name match { case nme.unapply => args case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeListFromReturnTypeSeq(fn.tpe)) - case _ => system.error("internal error: UnApply node has wrong symbol") + case _ => sys.error("internal error: UnApply node has wrong symbol") }) treeCopy.UnApply(tree, fn1, args1) diff --git a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala index 95bf16db5b0e..3e8f7bd2c75e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala @@ -39,7 +39,7 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT private var accDefs: List[(Symbol, ListBuffer[Tree])] = List() private def accDefBuf(clazz: Symbol) = - accDefs collectFirst { case (`clazz`, buf) => buf } getOrElse system.error("no acc def buf for "+clazz) + accDefs collectFirst { case (`clazz`, buf) => buf } getOrElse sys.error("no acc def buf for "+clazz) private def transformArgs(args: List[Tree], params: List[Symbol]) = ((args, params).zipped map { (arg, param) => @@ -406,7 +406,7 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT * self type is a Java class, and a protected accessor is needed, we issue * an error. If the self type is a Scala class, we don't add an accessor. * An accessor is not needed if the access boundary is larger than the - * enclosing package, since that translates to 'public' on the host system. + * enclosing package, since that translates to 'public' on the host sys. * (as Java has no real package nesting). * * If the access happens inside a 'trait', access is more problematic since diff --git a/src/compiler/scala/tools/nsc/util/MsilClassPath.scala b/src/compiler/scala/tools/nsc/util/MsilClassPath.scala index 019f40d72fe4..fb03f8d1594d 100644 --- a/src/compiler/scala/tools/nsc/util/MsilClassPath.scala +++ b/src/compiler/scala/tools/nsc/util/MsilClassPath.scala @@ -112,7 +112,7 @@ class AssemblyClassPath(types: Array[MSILType], namespace: String, val context: else namespace drop (i + 1) } def asURLs = List(new java.net.URL(name)) - def asClasspathString = system.error("Unknown") // I don't know what if anything makes sense here? + def asClasspathString = sys.error("Unknown") // I don't know what if anything makes sense here? private lazy val first: Int = { var m = 0 diff --git a/src/compiler/scala/tools/nsc/util/Origins.scala b/src/compiler/scala/tools/nsc/util/Origins.scala index 29ef9f3f035f..62fb0dab0007 100644 --- a/src/compiler/scala/tools/nsc/util/Origins.scala +++ b/src/compiler/scala/tools/nsc/util/Origins.scala @@ -85,7 +85,7 @@ object Origins { { // Console.println("\nOrigins loaded: registering shutdown hook to display results.") - system.addShutdownHook(counters foreach (_.purge())) + sys.addShutdownHook(counters foreach (_.purge())) } def apply[T: Manifest](tag: String): Origins = apply(tag, manifest[T].erasure) diff --git a/src/compiler/scala/tools/nsc/util/ShowPickled.scala b/src/compiler/scala/tools/nsc/util/ShowPickled.scala index a11038104b62..dfa9f1c7cf13 100644 --- a/src/compiler/scala/tools/nsc/util/ShowPickled.scala +++ b/src/compiler/scala/tools/nsc/util/ShowPickled.scala @@ -28,10 +28,10 @@ object ShowPickled extends Names { } def readName = if (isName) new String(bytes, "UTF-8") - else system.error("%s is no name" format tagName) + else sys.error("%s is no name" format tagName) def nameIndex = if (hasName) readNat(bytes, 0) - else system.error("%s has no name" format tagName) + else sys.error("%s has no name" format tagName) def tagName = tag2string(tag) override def toString = "%d,%d: %s".format(num, startIndex, tagName) diff --git a/src/compiler/scala/tools/nsc/util/package.scala b/src/compiler/scala/tools/nsc/util/package.scala index 6de2f35796f6..06e4de80f9de 100644 --- a/src/compiler/scala/tools/nsc/util/package.scala +++ b/src/compiler/scala/tools/nsc/util/package.scala @@ -22,9 +22,9 @@ package object util { * execution to complete. */ def waitingForThreads[T](body: => T) = { - val ts1 = system.allThreads() + val ts1 = sys.allThreads() val result = body - val ts2 = system.allThreads() + val ts2 = sys.allThreads() val newThreads = ts2.toSet -- ts1 filterNot (_.isDaemon()) newThreads foreach (_.join()) diff --git a/src/compiler/scala/tools/reflect/Mock.scala b/src/compiler/scala/tools/reflect/Mock.scala index 56bef2caa478..2b06d808aeda 100644 --- a/src/compiler/scala/tools/reflect/Mock.scala +++ b/src/compiler/scala/tools/reflect/Mock.scala @@ -53,7 +53,7 @@ object Mock { /** Tries to implement all the class's interfaces. */ def fromClass(clazz: Class[_])(pf: PartialFunction[Invoked, AnyRef]): AnyRef = allInterfaces(clazz) match { - case Nil => system.error(clazz + " implements no interfaces.") + case Nil => sys.error(clazz + " implements no interfaces.") case x :: xs => fromInterfaces(x, xs: _*)(pf) } } diff --git a/src/compiler/scala/tools/util/SocketServer.scala b/src/compiler/scala/tools/util/SocketServer.scala index f64766019397..cc3024d3e473 100644 --- a/src/compiler/scala/tools/util/SocketServer.scala +++ b/src/compiler/scala/tools/util/SocketServer.scala @@ -42,7 +42,7 @@ abstract class SocketServer def fatal(msg: String): Nothing = { System.err.println(msg) - system.exit(1) + sys.exit(1) } private def warn(msg: String) { diff --git a/src/dbc/scala/dbc/datatype/Factory.scala b/src/dbc/scala/dbc/datatype/Factory.scala index a5e69d547157..9eb8d25b26eb 100644 --- a/src/dbc/scala/dbc/datatype/Factory.scala +++ b/src/dbc/scala/dbc/datatype/Factory.scala @@ -234,17 +234,17 @@ object Factory { } /* Unsupported data types. */ case REF | ARRAY | STRUCT => - system.error ("I don't support composite data types yet."); + sys.error ("I don't support composite data types yet."); case DATALINK | DISTINCT | JAVA_OBJECT | NULL => - system.error ("I won't support strange data types."); + sys.error ("I won't support strange data types."); /* Unsupported binary string data types. */ case BINARY | BLOB | LONGVARBINARY | VARBINARY => - system.error ("I don't support binary string data types yet."); + sys.error ("I don't support binary string data types yet."); /* Unsupported date and time data types. */ case DATE | TIME | TIMESTAMP => - system.error ("I don't support date and time data types yet."); + sys.error ("I don't support date and time data types yet."); /* Default case */ - case x => system.error ("I don't know about this ("+metadata.getColumnTypeName(index)+") JDBC type.") + case x => sys.error ("I don't know about this ("+metadata.getColumnTypeName(index)+") JDBC type.") } } } diff --git a/src/dbc/scala/dbc/datatype/Unknown.scala b/src/dbc/scala/dbc/datatype/Unknown.scala index 21afaea22dbd..9a509251fbce 100644 --- a/src/dbc/scala/dbc/datatype/Unknown.scala +++ b/src/dbc/scala/dbc/datatype/Unknown.scala @@ -29,6 +29,6 @@ class Unknown extends DataType { /** A SQL-99 compliant string representation of the type. */ override def sqlString: java.lang.String = - system.error("The 'UNKNOWN' data type cannot be represented."); + sys.error("The 'UNKNOWN' data type cannot be represented."); } diff --git a/src/dbc/scala/dbc/result/Relation.scala b/src/dbc/scala/dbc/result/Relation.scala index 0427269ffd41..3dab6f481002 100644 --- a/src/dbc/scala/dbc/result/Relation.scala +++ b/src/dbc/scala/dbc/result/Relation.scala @@ -75,7 +75,7 @@ abstract class Relation extends AnyRef with Iterable[Tuple] { resultNext = result.next() newTuple } - else system.error("next on empty iterator") + else sys.error("next on empty iterator") } } diff --git a/src/dbc/scala/dbc/statement/Select.scala b/src/dbc/scala/dbc/statement/Select.scala index 07d7d26c6fd1..74b05ed2a1b1 100644 --- a/src/dbc/scala/dbc/statement/Select.scala +++ b/src/dbc/scala/dbc/statement/Select.scala @@ -67,7 +67,7 @@ abstract class Select extends Relation { ((name:String, dc:DerivedColumn) => name + ", " + dc.sqlString)) }) + (fromClause match { - case Nil => system.error("Empty from clause is not allowed") + case Nil => sys.error("Empty from clause is not allowed") case _ => (" FROM " + fromClause.tail.foldLeft(fromClause.head.sqlInnerString) ((name:String, rel:Relation) => name + ", " + rel.sqlInnerString)) }) + @@ -78,7 +78,7 @@ abstract class Select extends Relation { (groupByClause match { case None => "" case Some(gbl) => gbl match { - case Nil => system.error("Empty group by clause is not allowed") + case Nil => sys.error("Empty group by clause is not allowed") case _ => (" GROUP BY " + gbl.tail.foldLeft(gbl.head.sqlInnerString) diff --git a/src/dbc/scala/dbc/statement/expression/SetFunction.scala b/src/dbc/scala/dbc/statement/expression/SetFunction.scala index 48a675a40541..334e6bf1ed10 100644 --- a/src/dbc/scala/dbc/statement/expression/SetFunction.scala +++ b/src/dbc/scala/dbc/statement/expression/SetFunction.scala @@ -35,6 +35,6 @@ object SetFunction { ); } abstract class Binary extends SetFunction { - def sqlString = system.error("Binary set function is not supported yet."); + def sqlString = sys.error("Binary set function is not supported yet."); } } diff --git a/src/dbc/scala/dbc/value/Unknown.scala b/src/dbc/scala/dbc/value/Unknown.scala index 2c56bbf36ed0..2cb791566ff6 100644 --- a/src/dbc/scala/dbc/value/Unknown.scala +++ b/src/dbc/scala/dbc/value/Unknown.scala @@ -16,7 +16,7 @@ abstract class Unknown extends Value { val dataType: datatype.Unknown; - def sqlString = system.error("An 'ANY' value cannot be represented."); + def sqlString = sys.error("An 'ANY' value cannot be represented."); } diff --git a/src/detach/library/scala/remoting/Channel.scala b/src/detach/library/scala/remoting/Channel.scala index ba3f3c31e00d..541e45a47722 100644 --- a/src/detach/library/scala/remoting/Channel.scala +++ b/src/detach/library/scala/remoting/Channel.scala @@ -51,7 +51,7 @@ class Channel protected (socket: Socket) { } catch { case e: Exception => - system.error("Class loader undefined: " + e.getMessage) + sys.error("Class loader undefined: " + e.getMessage) null } def classLoader: ClassLoader = cl @@ -82,7 +82,7 @@ class Channel protected (socket: Socket) { } catch { case e: IOException => - system.error("Input stream undefined: "+e.getMessage+" ("+this+")") + sys.error("Input stream undefined: "+e.getMessage+" ("+this+")") null } private lazy val out = @@ -91,7 +91,7 @@ class Channel protected (socket: Socket) { } catch { case e: IOException => - system.error("Output stream undefined: "+e.getMessage+" ("+this+")") + sys.error("Output stream undefined: "+e.getMessage+" ("+this+")") null } diff --git a/src/detach/library/scala/runtime/remoting/RegistryDelegate.scala b/src/detach/library/scala/runtime/remoting/RegistryDelegate.scala index baf4249bbe10..814d50e91041 100644 --- a/src/detach/library/scala/runtime/remoting/RegistryDelegate.scala +++ b/src/detach/library/scala/runtime/remoting/RegistryDelegate.scala @@ -62,7 +62,7 @@ import java.rmi.server.UnicastRemoteObject * Thread.sleep(Long.MAX_VALUE) * } catch { * case e: InterruptedException => // do nothing - * case e: Throwable => e.printStackTrace(); system.exit(1) + * case e: Throwable => e.printStackTrace(); sys.exit(1) * } * } while (true) * } @@ -115,14 +115,14 @@ object RMIDelegate { if (args.length > 0) { if (args(0) equals "-help") { println("Usage: rmidelegate ") - system.exit(0) + sys.exit(0) } try { port = args(0).toInt } catch { case e: NumberFormatException => println("Usage: rmidelegate ") - system.exit(1) + sys.exit(1) } val opts = args filter (_ startsWith "-J-D") for (opt <- opts) { @@ -149,7 +149,7 @@ object RMIDelegate { // do nothing case e: Throwable => e.printStackTrace() - system.exit(1) + sys.exit(1) } } while (true) } diff --git a/src/jline/src/main/java/jline/UnixTerminal.java b/src/jline/src/main/java/jline/UnixTerminal.java index 755d899765d9..37f18aea4ee9 100644 --- a/src/jline/src/main/java/jline/UnixTerminal.java +++ b/src/jline/src/main/java/jline/UnixTerminal.java @@ -28,7 +28,7 @@ * /dev/tty file to disable character echoing and enable * character input. All known unix systems (including * Linux and Macintosh OS X) support the stty), so this - * implementation should work for an reasonable POSIX system. + * implementation should work for an reasonable POSIX sys. * * @author Marc Prud'hommeaux * @author Dale Kemp diff --git a/src/jline/src/main/java/jline/WindowsTerminal.java b/src/jline/src/main/java/jline/WindowsTerminal.java index dcaa3a9cde92..4304d6d47330 100644 --- a/src/jline/src/main/java/jline/WindowsTerminal.java +++ b/src/jline/src/main/java/jline/WindowsTerminal.java @@ -302,7 +302,7 @@ public static enum ConsoleMode * control keys are processed by the system and are not returned in the * ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also * enabled, backspace, carriage return, and linefeed characters are handled - * by the system. + * by the sys. */ ENABLE_PROCESSED_INPUT(1), diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala index e8768fd1508b..f07582c3561d 100644 --- a/src/library/scala/Predef.scala +++ b/src/library/scala/Predef.scala @@ -58,14 +58,14 @@ object Predef extends LowPriorityImplicits { // Deprecated - @deprecated("Use system.error(message) instead") - def error(message: String): Nothing = system.error(message) + @deprecated("Use sys.error(message) instead") + def error(message: String): Nothing = sys.error(message) - @deprecated("Use system.exit() instead") - def exit(): Nothing = system.exit() + @deprecated("Use sys.exit() instead") + def exit(): Nothing = sys.exit() - @deprecated("Use system.exit(status) instead") - def exit(status: Int): Nothing = system.exit(status) + @deprecated("Use sys.exit(status) instead") + def exit(status: Int): Nothing = sys.exit(status) @deprecated("Use formatString.format(args: _*) or arg.formatted(formatString) instead") def format(text: String, xs: Any*) = augmentString(text).format(xs: _*) diff --git a/src/library/scala/collection/immutable/HashMap.scala b/src/library/scala/collection/immutable/HashMap.scala index 26d7ff2eed94..2f95c4fb8073 100644 --- a/src/library/scala/collection/immutable/HashMap.scala +++ b/src/library/scala/collection/immutable/HashMap.scala @@ -452,7 +452,7 @@ time { mNew.iterator.foreach( p => ()) } new HashTrieMap[A, B1](this.bitmap | that.bitmap, merged, totalelems) case hm: HashMapCollision1[_, _] => that.merge0(this, level, merger) case hm: HashMap[_, _] => this - case _ => system.error("section supposed to be unreachable.") + case _ => sys.error("section supposed to be unreachable.") } } diff --git a/src/library/scala/collection/immutable/HashSet.scala b/src/library/scala/collection/immutable/HashSet.scala index 1bf3b795f231..aa9f99b4cb41 100644 --- a/src/library/scala/collection/immutable/HashSet.scala +++ b/src/library/scala/collection/immutable/HashSet.scala @@ -186,12 +186,12 @@ object HashSet extends ImmutableSetFactory[HashSet] { // hash codes and remove the collision. however this is never called // because no references to this class are ever handed out to client code // and HashTrieSet serialization takes care of the situation - system.error("cannot serialize an immutable.HashSet where all items have the same 32-bit hash code") + sys.error("cannot serialize an immutable.HashSet where all items have the same 32-bit hash code") //out.writeObject(kvs) } private def readObject(in: java.io.ObjectInputStream) { - system.error("cannot deserialize an immutable.HashSet where all items have the same 32-bit hash code") + sys.error("cannot deserialize an immutable.HashSet where all items have the same 32-bit hash code") //kvs = in.readObject().asInstanceOf[ListSet[A]] //hash = computeHash(kvs.) } diff --git a/src/library/scala/collection/immutable/IntMap.scala b/src/library/scala/collection/immutable/IntMap.scala index 6baa05c21afd..86b3b9f1e41d 100644 --- a/src/library/scala/collection/immutable/IntMap.scala +++ b/src/library/scala/collection/immutable/IntMap.scala @@ -118,7 +118,7 @@ private[immutable] abstract class IntMapIterator[V, T](it : IntMap[V]) extends I case t@IntMap.Tip(_, _) => valueOf(t); // This should never happen. We don't allow IntMap.Nil in subtrees of the IntMap // and don't return an IntMapIterator for IntMap.Nil. - case IntMap.Nil => system.error("Empty maps not allowed as subtrees"); + case IntMap.Nil => sys.error("Empty maps not allowed as subtrees"); } } @@ -254,8 +254,8 @@ sealed abstract class IntMap[+T] extends Map[Int, T] with MapLike[Int, T, IntMap final override def apply(key : Int) : T = this match { case IntMap.Bin(prefix, mask, left, right) => if (zero(key, mask)) left(key) else right(key); - case IntMap.Tip(key2, value) => if (key == key2) value else system.error("Key not found"); - case IntMap.Nil => system.error("key not found"); + case IntMap.Tip(key2, value) => if (key == key2) value else sys.error("Key not found"); + case IntMap.Nil => sys.error("key not found"); } def + [S >: T] (kv: (Int, S)): IntMap[S] = updated(kv._1, kv._2) @@ -417,7 +417,7 @@ sealed abstract class IntMap[+T] extends Map[Int, T] with MapLike[Int, T, IntMap final def firstKey : Int = this match { case Bin(_, _, l, r) => l.firstKey; case Tip(k, v) => k; - case IntMap.Nil => system.error("Empty set") + case IntMap.Nil => sys.error("Empty set") } /** @@ -426,6 +426,6 @@ sealed abstract class IntMap[+T] extends Map[Int, T] with MapLike[Int, T, IntMap final def lastKey : Int = this match { case Bin(_, _, l, r) => r.lastKey; case Tip(k, v) => k; - case IntMap.Nil => system.error("Empty set") + case IntMap.Nil => sys.error("Empty set") } } diff --git a/src/library/scala/collection/immutable/LongMap.scala b/src/library/scala/collection/immutable/LongMap.scala index f02c6fce664c..0d454a4ba264 100644 --- a/src/library/scala/collection/immutable/LongMap.scala +++ b/src/library/scala/collection/immutable/LongMap.scala @@ -115,7 +115,7 @@ private[immutable] abstract class LongMapIterator[V, T](it : LongMap[V]) extends case t@LongMap.Tip(_, _) => valueOf(t); // This should never happen. We don't allow LongMap.Nil in subtrees of the LongMap // and don't return an LongMapIterator for LongMap.Nil. - case LongMap.Nil => system.error("Empty maps not allowed as subtrees"); + case LongMap.Nil => sys.error("Empty maps not allowed as subtrees"); } } @@ -252,8 +252,8 @@ sealed abstract class LongMap[+T] extends Map[Long, T] with MapLike[Long, T, Lon final override def apply(key : Long) : T = this match { case LongMap.Bin(prefix, mask, left, right) => if (zero(key, mask)) left(key) else right(key); - case LongMap.Tip(key2, value) => if (key == key2) value else system.error("Key not found"); - case LongMap.Nil => system.error("key not found"); + case LongMap.Tip(key2, value) => if (key == key2) value else sys.error("Key not found"); + case LongMap.Nil => sys.error("key not found"); } def + [S >: T] (kv: (Long, S)): LongMap[S] = updated(kv._1, kv._2) diff --git a/src/library/scala/collection/immutable/RedBlack.scala b/src/library/scala/collection/immutable/RedBlack.scala index 1c2d4ba36280..58a698261530 100644 --- a/src/library/scala/collection/immutable/RedBlack.scala +++ b/src/library/scala/collection/immutable/RedBlack.scala @@ -98,7 +98,7 @@ abstract class RedBlack[A] extends Serializable { } def subl(t: Tree[B]) = t match { case BlackTree(x, xv, a, b) => RedTree(x, xv, a, b) - case _ => system.error("Defect: invariance violation; expected black, got "+t) + case _ => sys.error("Defect: invariance violation; expected black, got "+t) } def balLeft(x: A, xv: B, tl: Tree[B], tr: Tree[B]) = (tl, tr) match { case (RedTree(y, yv, a, b), c) => @@ -107,7 +107,7 @@ abstract class RedBlack[A] extends Serializable { balance(x, xv, bl, RedTree(y, yv, a, b)) case (bl, RedTree(y, yv, BlackTree(z, zv, a, b), c)) => RedTree(z, zv, BlackTree(x, xv, bl, a), balance(y, yv, b, subl(c))) - case _ => system.error("Defect: invariance violation at "+right) + case _ => sys.error("Defect: invariance violation at "+right) } def balRight(x: A, xv: B, tl: Tree[B], tr: Tree[B]) = (tl, tr) match { case (a, RedTree(y, yv, b, c)) => @@ -116,7 +116,7 @@ abstract class RedBlack[A] extends Serializable { balance(x, xv, RedTree(y, yv, a, b), bl) case (RedTree(y, yv, a, BlackTree(z, zv, b, c)), bl) => RedTree(z, zv, balance(y, yv, subl(a), b), BlackTree(x, xv, c, bl)) - case _ => system.error("Defect: invariance violation at "+left) + case _ => sys.error("Defect: invariance violation at "+left) } def delLeft = left match { case _: BlackTree[_] => balLeft(key, value, left.del(k), right) @@ -237,7 +237,7 @@ abstract class RedBlack[A] extends Serializable { case BlackTree(_, _, _, _) :: tail => if (depth == 1) zipper else findDepth(tail, depth - 1) case _ :: tail => findDepth(tail, depth) - case Nil => system.error("Defect: unexpected empty zipper while computing range") + case Nil => sys.error("Defect: unexpected empty zipper while computing range") } // Blackening the smaller tree avoids balancing problems on union; diff --git a/src/library/scala/collection/mutable/ArrayStack.scala b/src/library/scala/collection/mutable/ArrayStack.scala index 9de466e04c3a..3a38f831b222 100644 --- a/src/library/scala/collection/mutable/ArrayStack.scala +++ b/src/library/scala/collection/mutable/ArrayStack.scala @@ -114,7 +114,7 @@ extends Seq[T] * @return the element on top of the stack */ def pop: T = { - if (index == 0) system.error("Stack empty") + if (index == 0) sys.error("Stack empty") index -= 1 val x = table(index).asInstanceOf[T] table(index) = null diff --git a/src/library/scala/collection/mutable/OpenHashMap.scala b/src/library/scala/collection/mutable/OpenHashMap.scala index 29dfc3ad19ed..5bd220f81fac 100644 --- a/src/library/scala/collection/mutable/OpenHashMap.scala +++ b/src/library/scala/collection/mutable/OpenHashMap.scala @@ -180,7 +180,7 @@ extends Map[Key, Value] val initialModCount = modCount; private[this] def advance { - if (initialModCount != modCount) system.error("Concurrent modification"); + if (initialModCount != modCount) sys.error("Concurrent modification"); while((index <= mask) && (table(index) == null || table(index).value == None)) index+=1; } @@ -217,7 +217,7 @@ extends Map[Key, Value] override def foreach[U](f : ((Key, Value)) => U) { val startModCount = modCount; foreachUndeletedEntry(entry => { - if (modCount != startModCount) system.error("Concurrent Modification") + if (modCount != startModCount) sys.error("Concurrent Modification") f((entry.key, entry.value.get))} ); } diff --git a/src/library/scala/collection/parallel/mutable/ParArray.scala b/src/library/scala/collection/parallel/mutable/ParArray.scala index 536976f5e3b3..ccd693a2415d 100644 --- a/src/library/scala/collection/parallel/mutable/ParArray.scala +++ b/src/library/scala/collection/parallel/mutable/ParArray.scala @@ -630,7 +630,7 @@ self => new ScanToArray(left, z, op, targetarr), new ScanToArray(right, z, op, targetarr) ) - case _ => system.error("Can only split scan tree internal nodes.") + case _ => sys.error("Can only split scan tree internal nodes.") } def shouldSplitFurther = tree match { case ScanNode(_, _) => true diff --git a/src/library/scala/collection/parallel/package.scala b/src/library/scala/collection/parallel/package.scala index 757f5d2686db..acced246da49 100644 --- a/src/library/scala/collection/parallel/package.scala +++ b/src/library/scala/collection/parallel/package.scala @@ -210,7 +210,7 @@ package object parallel { afterCombine(other) this - } else system.error("Unexpected combiner type.") + } else sys.error("Unexpected combiner type.") } else this } diff --git a/src/library/scala/mobile/Code.scala b/src/library/scala/mobile/Code.scala index e1d04eafa5a0..6f96130568bb 100644 --- a/src/library/scala/mobile/Code.scala +++ b/src/library/scala/mobile/Code.scala @@ -196,7 +196,7 @@ class Code(clazz: java.lang.Class[_]) { if (cs.length > 0) { cs(0).newInstance("").asInstanceOf[AnyRef] } else { - system.error("class " + clazz.getName() + " has no public constructor") + sys.error("class " + clazz.getName() + " has no public constructor") } } } diff --git a/src/library/scala/system/PropertiesMap.scala b/src/library/scala/sys/PropertiesMap.scala similarity index 98% rename from src/library/scala/system/PropertiesMap.scala rename to src/library/scala/sys/PropertiesMap.scala index a01eee693193..e840f2846773 100644 --- a/src/library/scala/system/PropertiesMap.scala +++ b/src/library/scala/sys/PropertiesMap.scala @@ -6,7 +6,7 @@ ** |/ ** \* */ -package scala.system +package scala.sys import scala.collection.mutable import scala.collection.JavaConverters._ diff --git a/src/library/scala/system/ShutdownHookThread.scala b/src/library/scala/sys/ShutdownHookThread.scala similarity index 98% rename from src/library/scala/system/ShutdownHookThread.scala rename to src/library/scala/sys/ShutdownHookThread.scala index 17a5e398efb7..af79d95a2aab 100644 --- a/src/library/scala/system/ShutdownHookThread.scala +++ b/src/library/scala/sys/ShutdownHookThread.scala @@ -6,7 +6,7 @@ ** |/ ** \* */ -package scala.system +package scala.sys /** A minimal Thread wrapper to enhance shutdown hooks. It knows * how to unregister itself. diff --git a/src/library/scala/system/package.scala b/src/library/scala/sys/package.scala similarity index 95% rename from src/library/scala/system/package.scala rename to src/library/scala/sys/package.scala index 1e989f86ec93..85deba62b686 100644 --- a/src/library/scala/system/package.scala +++ b/src/library/scala/sys/package.scala @@ -11,7 +11,7 @@ package scala import scala.collection.immutable import collection.JavaConverters._ -/** The package object `scala.system` contains methods for reading +/** The package object `scala.sys` contains methods for reading * and altering core aspects of the virtual machine as well as the * world outside of it. * @@ -19,7 +19,7 @@ import collection.JavaConverters._ * @version 2.9 * @since 2.9 */ -package object system { +package object sys { /** Throw a new RuntimeException with the supplied message. * * @return Nothing. @@ -50,7 +50,7 @@ package object system { /** A bidirectional, mutable Map representing the current system Properties. * * @return a PropertiesMap. - * @see `scala.system.PropertiesMap` + * @see `scala.sys.PropertiesMap` */ def props: PropertiesMap = new PropertiesMap diff --git a/src/library/scala/sys/process/BasicIO.scala b/src/library/scala/sys/process/BasicIO.scala new file mode 100644 index 000000000000..505a859377f9 --- /dev/null +++ b/src/library/scala/sys/process/BasicIO.scala @@ -0,0 +1,81 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ +import java.io.{ BufferedReader, InputStreamReader } + +object BasicIO { + final val BufferSize = 8192 + final val Newline = props("line.separator") + + def apply(buffer: StringBuffer, log: Option[ProcessLogger], withIn: Boolean) = + new ProcessIO(input(withIn), processFully(buffer), getErr(log)) + def apply(log: ProcessLogger, withIn: Boolean) = + new ProcessIO(input(withIn), processInfoFully(log), processErrFully(log)) + + def getErr(log: Option[ProcessLogger]) = log match { + case Some(lg) => processErrFully(lg) + case None => toStdErr + } + + private def processErrFully(log: ProcessLogger) = processFully(log error _) + private def processInfoFully(log: ProcessLogger) = processFully(log info _) + + def ignoreOut = (i: OutputStream) => () + + def close(c: Closeable) = try c.close() catch { case _: IOException => () } + def processFully(buffer: Appendable): InputStream => Unit = processFully(appendLine(buffer)) + def processFully(processLine: String => Unit): InputStream => Unit = in => { + val reader = new BufferedReader(new InputStreamReader(in)) + processLinesFully(processLine)(reader.readLine) + } + + def processLinesFully(processLine: String => Unit)(readLine: () => String) { + def readFully() { + val line = readLine() + if (line != null) { + processLine(line) + readFully() + } + } + readFully() + } + def connectToIn(o: OutputStream): Unit = transferFully(System.in, o) + def input(connect: Boolean): OutputStream => Unit = if (connect) connectToIn else ignoreOut + def standard(connectInput: Boolean): ProcessIO = standard(input(connectInput)) + def standard(in: OutputStream => Unit): ProcessIO = new ProcessIO(in, toStdOut, toStdErr) + + def toStdErr = (in: InputStream) => transferFully(in, System.err) + def toStdOut = (in: InputStream) => transferFully(in, System.out) + + def transferFully(in: InputStream, out: OutputStream): Unit = + try transferFullyImpl(in, out) + catch { case _: InterruptedException => () } + + private[this] def appendLine(buffer: Appendable): String => Unit = line => { + buffer.append(line) + buffer.append(Newline) + } + + private[this] def transferFullyImpl(in: InputStream, out: OutputStream) { + val buffer = new Array[Byte](BufferSize) + def loop() { + val byteCount = in.read(buffer) + if (byteCount > 0) { + out.write(buffer, 0, byteCount) + out.flush() + loop() + } + } + loop() + } +} + diff --git a/src/library/scala/sys/process/Process.scala b/src/library/scala/sys/process/Process.scala new file mode 100644 index 000000000000..6453002ae44d --- /dev/null +++ b/src/library/scala/sys/process/Process.scala @@ -0,0 +1,85 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ +import ProcessBuilder._ + +/** Represents a process that is running or has finished running. + * It may be a compound process with several underlying native processes (such as 'a #&& b`). + */ +trait Process { + /** Blocks until this process exits and returns the exit code.*/ + def exitValue(): Int + /** Destroys this process. */ + def destroy(): Unit +} + +/** Methods for constructing simple commands that can then be combined. */ +object Process extends ProcessCreation { } + +trait ProcessCreation { + def apply(command: String): ProcessBuilder = apply(command, None) + def apply(command: Seq[String]): ProcessBuilder = apply(command, None) + def apply(command: String, arguments: Seq[String]): ProcessBuilder = apply(command +: arguments, None) + + /** create ProcessBuilder with working dir set to File and extra environment variables */ + def apply(command: String, cwd: File, extraEnv: (String, String)*): ProcessBuilder = + apply(command, Some(cwd), extraEnv: _*) + + /** create ProcessBuilder with working dir set to File and extra environment variables */ + def apply(command: Seq[String], cwd: File, extraEnv: (String, String)*): ProcessBuilder = + apply(command, Some(cwd), extraEnv: _*) + + /** create ProcessBuilder with working dir optionaly set to File and extra environment variables */ + def apply(command: String, cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = { + apply(command.split("""\s+"""), cwd, extraEnv : _*) + // not smart to use this on windows, because CommandParser uses \ to escape ". + /*CommandParser.parse(command) match { + case Left(errorMsg) => error(errorMsg) + case Right((cmd, args)) => apply(cmd :: args, cwd, extraEnv : _*) + }*/ + } + + /** create ProcessBuilder with working dir optionaly set to File and extra environment variables */ + def apply(command: Seq[String], cwd: Option[File], extraEnv: (String, String)*): ProcessBuilder = { + val jpb = new JProcessBuilder(command.toArray : _*) + cwd foreach (jpb directory _) + extraEnv foreach { case (k, v) => jpb.environment.put(k, v) } + apply(jpb) + } + + def apply(builder: JProcessBuilder): ProcessBuilder = new Simple(builder) + def apply(file: File): FileBuilder = new FileImpl(file) + def apply(url: URL): URLBuilder = new URLImpl(url) + def apply(command: scala.xml.Elem): ProcessBuilder = apply(command.text.trim) + def apply(value: Boolean): ProcessBuilder = apply(value.toString, if (value) 0 else 1) + + def apply(name: String, exitValue: => Int): ProcessBuilder = new Dummy(name, exitValue) + def applySeq[T](builders: Seq[T])(implicit convert: T => Source): Seq[Source] = builders.map(convert) + + def cat(file: Source, files: Source*): ProcessBuilder = cat(file +: files) + def cat(files: Seq[Source]): ProcessBuilder = { + require(files.nonEmpty) + files map (_.cat) reduceLeft (_ #&& _) + } +} + +trait ProcessImplicits { + import Process._ + + implicit def buildersToProcess[T](builders: Seq[T])(implicit convert: T => Source): Seq[Source] = applySeq(builders) + implicit def builderToProcess(builder: JProcessBuilder): ProcessBuilder = apply(builder) + implicit def fileToProcess(file: File): FileBuilder = apply(file) + implicit def urlToProcess(url: URL): URLBuilder = apply(url) + implicit def xmlToProcess(command: scala.xml.Elem): ProcessBuilder = apply(command) + implicit def stringToProcess(command: String): ProcessBuilder = apply(command) + implicit def stringSeqToProcess(command: Seq[String]): ProcessBuilder = apply(command) +} diff --git a/src/library/scala/sys/process/ProcessBuilder.scala b/src/library/scala/sys/process/ProcessBuilder.scala new file mode 100644 index 000000000000..798796b29cdf --- /dev/null +++ b/src/library/scala/sys/process/ProcessBuilder.scala @@ -0,0 +1,113 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ +import ProcessBuilder._ + +/** Represents a runnable process. */ +trait ProcessBuilder extends Source with Sink { + /** Starts the process represented by this builder, blocks until it exits, and returns the output as a String. Standard error is + * sent to the console. If the exit code is non-zero, an exception is thrown.*/ + def !! : String + /** Starts the process represented by this builder, blocks until it exits, and returns the output as a String. Standard error is + * sent to the provided ProcessLogger. If the exit code is non-zero, an exception is thrown.*/ + def !!(log: ProcessLogger): String + /** Starts the process represented by this builder. The output is returned as a Stream that blocks when lines are not available + * but the process has not completed. Standard error is sent to the console. If the process exits with a non-zero value, + * the Stream will provide all lines up to termination and then throw an exception. */ + def lines: Stream[String] + /** Starts the process represented by this builder. The output is returned as a Stream that blocks when lines are not available + * but the process has not completed. Standard error is sent to the provided ProcessLogger. If the process exits with a non-zero value, + * the Stream will provide all lines up to termination but will not throw an exception. */ + def lines(log: ProcessLogger): Stream[String] + /** Starts the process represented by this builder. The output is returned as a Stream that blocks when lines are not available + * but the process has not completed. Standard error is sent to the console. If the process exits with a non-zero value, + * the Stream will provide all lines up to termination but will not throw an exception. */ + def lines_! : Stream[String] + /** Starts the process represented by this builder. The output is returned as a Stream that blocks when lines are not available + * but the process has not completed. Standard error is sent to the provided ProcessLogger. If the process exits with a non-zero value, + * the Stream will provide all lines up to termination but will not throw an exception. */ + def lines_!(log: ProcessLogger): Stream[String] + /** Starts the process represented by this builder, blocks until it exits, and returns the exit code. Standard output and error are + * sent to the console.*/ + def ! : Int + /** Starts the process represented by this builder, blocks until it exits, and returns the exit code. Standard output and error are + * sent to the given ProcessLogger.*/ + def !(log: ProcessLogger): Int + /** Starts the process represented by this builder, blocks until it exits, and returns the exit code. Standard output and error are + * sent to the console. The newly started process reads from standard input of the current process.*/ + def !< : Int + /** Starts the process represented by this builder, blocks until it exits, and returns the exit code. Standard output and error are + * sent to the given ProcessLogger. The newly started process reads from standard input of the current process.*/ + def !<(log: ProcessLogger): Int + /** Starts the process represented by this builder. Standard output and error are sent to the console.*/ + def run(): Process + /** Starts the process represented by this builder. Standard output and error are sent to the given ProcessLogger.*/ + def run(log: ProcessLogger): Process + /** Starts the process represented by this builder. I/O is handled by the given ProcessIO instance.*/ + def run(io: ProcessIO): Process + /** Starts the process represented by this builder. Standard output and error are sent to the console. + * The newly started process reads from standard input of the current process if `connectInput` is true.*/ + def run(connectInput: Boolean): Process + /** Starts the process represented by this builder, blocks until it exits, and returns the exit code. Standard output and error are + * sent to the given ProcessLogger. + * The newly started process reads from standard input of the current process if `connectInput` is true.*/ + def run(log: ProcessLogger, connectInput: Boolean): Process + + /** Constructs a command that runs this command first and then `other` if this command succeeds.*/ + def #&& (other: ProcessBuilder): ProcessBuilder + /** Constructs a command that runs this command first and then `other` if this command does not succeed.*/ + def #|| (other: ProcessBuilder): ProcessBuilder + /** Constructs a command that will run this command and pipes the output to `other`. `other` must be a simple command.*/ + def #| (other: ProcessBuilder): ProcessBuilder + /** Constructs a command that will run this command and then `other`. The exit code will be the exit code of `other`.*/ + def ### (other: ProcessBuilder): ProcessBuilder + + def canPipeTo: Boolean +} + +object ProcessBuilder extends ProcessBuilderImpl { + trait URLBuilder extends Source { + + } + trait FileBuilder extends Sink with Source { + def #<<(f: File): ProcessBuilder + def #<<(u: URL): ProcessBuilder + def #<<(i: => InputStream): ProcessBuilder + def #<<(p: ProcessBuilder): ProcessBuilder + } + trait Source { + protected def toSource: ProcessBuilder + /** Writes the output stream of this process to the given file. */ + def #> (f: File): ProcessBuilder = toFile(f, false) + /** Appends the output stream of this process to the given file. */ + def #>> (f: File): ProcessBuilder = toFile(f, true) + /** Writes the output stream of this process to the given OutputStream. The + * argument is call-by-name, so the stream is recreated, written, and closed each + * time this process is executed. */ + def #>(out: => OutputStream): ProcessBuilder = #> (new OStreamBuilder(out, "")) + def #>(b: ProcessBuilder): ProcessBuilder = new PipedBuilder(toSource, b, false) + def cat = toSource + private def toFile(f: File, append: Boolean) = #> (new FileOutput(f, append)) + } + trait Sink { + protected def toSink: ProcessBuilder + /** Reads the given file into the input stream of this process. */ + def #< (f: File): ProcessBuilder = #< (new FileInput(f)) + /** Reads the given URL into the input stream of this process. */ + def #< (f: URL): ProcessBuilder = #< (new URLInput(f)) + /** Reads the given InputStream into the input stream of this process. The + * argument is call-by-name, so the stream is recreated, read, and closed each + * time this process is executed. */ + def #<(in: => InputStream): ProcessBuilder = #< (new IStreamBuilder(in, "")) + def #<(b: ProcessBuilder): ProcessBuilder = new PipedBuilder(b, toSink, false) + } +} diff --git a/src/library/scala/sys/process/ProcessBuilderImpl.scala b/src/library/scala/sys/process/ProcessBuilderImpl.scala new file mode 100644 index 000000000000..3e6d41b5b68f --- /dev/null +++ b/src/library/scala/sys/process/ProcessBuilderImpl.scala @@ -0,0 +1,196 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ +import java.io.{ FileInputStream, FileOutputStream } +import Uncloseable.protect + +private[process] trait ProcessBuilderImpl { + self: ProcessBuilder.type => + + class Dummy(override val toString: String, exitValue: => Int) extends AbstractBuilder { + override def run(io: ProcessIO): Process = new DummyProcess(exitValue) + override def canPipeTo = true + } + + private[process] class URLInput(url: URL) extends IStreamBuilder(url.openStream, url.toString) + private[process] class FileInput(file: File) extends IStreamBuilder(new FileInputStream(file), file.getAbsolutePath) + private[process] class FileOutput(file: File, append: Boolean) extends OStreamBuilder(new FileOutputStream(file, append), file.getAbsolutePath) + + private[process] class OStreamBuilder( + stream: => OutputStream, + label: String + ) extends ThreadBuilder(label, _ writeInput protect(stream)) { } + + private[process] class IStreamBuilder( + stream: => InputStream, + label: String + ) extends ThreadBuilder(label, _ processOutput protect(stream)) { } + + private[process] abstract class ThreadBuilder( + override val toString: String, + runImpl: ProcessIO => Unit + ) extends AbstractBuilder { + + override def run(io: ProcessIO): Process = { + val success = new SyncVar[Boolean] + success put false + val t = Spawn { + runImpl(io) + success set true + } + + new ThreadProcess(t, success) + } + } + + /** Represents a simple command without any redirection or combination. */ + private[process] class Simple(p: JProcessBuilder) extends AbstractBuilder { + override def run(io: ProcessIO): Process = { + val process = p.start() // start the external process + import io._ + + // spawn threads that process the input, output, and error streams using the functions defined in `io` + val inThread = Spawn(writeInput(process.getOutputStream), true) + val outThread = Spawn(processOutput(process.getInputStream)) + val errorThread = + if (p.redirectErrorStream) Nil + else List(Spawn(processError(process.getErrorStream))) + + new SimpleProcess(process, inThread, outThread :: errorThread) + } + override def toString = p.command.toString + override def canPipeTo = true + } + + private[process] abstract class AbstractBuilder extends ProcessBuilder with Sink with Source { + protected def toSource = this + protected def toSink = this + + def #|(other: ProcessBuilder): ProcessBuilder = { + require(other.canPipeTo, "Piping to multiple processes is not supported.") + new PipedBuilder(this, other, false) + } + def #||(other: ProcessBuilder): ProcessBuilder = new OrBuilder(this, other) + def #&&(other: ProcessBuilder): ProcessBuilder = new AndBuilder(this, other) + def ###(other: ProcessBuilder): ProcessBuilder = new SequenceBuilder(this, other) + + def run(): Process = run(false) + def run(connectInput: Boolean): Process = run(BasicIO.standard(connectInput)) + def run(log: ProcessLogger): Process = run(log, false) + def run(log: ProcessLogger, connectInput: Boolean): Process = run(BasicIO(log, connectInput)) + + def !! = slurp(None, false) + def !!(log: ProcessLogger) = slurp(Some(log), false) + def !!< = slurp(None, true) + def !!<(log: ProcessLogger) = slurp(Some(log), true) + + def lines: Stream[String] = lines(false, true, None) + def lines(log: ProcessLogger): Stream[String] = lines(false, true, Some(log)) + def lines_! : Stream[String] = lines(false, false, None) + def lines_!(log: ProcessLogger): Stream[String] = lines(false, false, Some(log)) + + def ! = run(false).exitValue() + def !(io: ProcessIO) = run(io).exitValue() + def !(log: ProcessLogger) = runBuffered(log, false) + def !< = run(true).exitValue() + def !<(log: ProcessLogger) = runBuffered(log, true) + + private[this] def slurp(log: Option[ProcessLogger], withIn: Boolean): String = { + val buffer = new StringBuffer + val code = this ! BasicIO(buffer, log, withIn) + + if (code == 0) buffer.toString + else sys.error("Nonzero exit value: " + code) + } + + private[this] def lines( + withInput: Boolean, + nonZeroException: Boolean, + log: Option[ProcessLogger] + ): Stream[String] = { + val streamed = Streamed[String](nonZeroException) + val process = run(new ProcessIO(BasicIO.input(withInput), BasicIO.processFully(streamed.process), BasicIO.getErr(log))) + + Spawn(streamed done process.exitValue()) + streamed.stream() + } + + private[this] def runBuffered(log: ProcessLogger, connectInput: Boolean) = + log buffer run(log, connectInput).exitValue() + + def canPipeTo = false + } + + class URLImpl(url: URL) extends URLBuilder with Source { + protected def toSource = new URLInput(url) + } + class FileImpl(base: File) extends FileBuilder with Sink with Source { + protected def toSource = new FileInput(base) + protected def toSink = new FileOutput(base, false) + + def #<<(f: File): ProcessBuilder = #<<(new FileInput(f)) + def #<<(u: URL): ProcessBuilder = #<<(new URLInput(u)) + def #<<(s: => InputStream): ProcessBuilder = #<<(new IStreamBuilder(s, "")) + def #<<(b: ProcessBuilder): ProcessBuilder = new PipedBuilder(b, new FileOutput(base, true), false) + } + + private[process] abstract class BasicBuilder extends AbstractBuilder { + protected[this] def checkNotThis(a: ProcessBuilder) = require(a != this, "Compound process '" + a + "' cannot contain itself.") + final def run(io: ProcessIO): Process = { + val p = createProcess(io) + p.start() + p + } + protected[this] def createProcess(io: ProcessIO): BasicProcess + } + + private[process] abstract class SequentialBuilder( + a: ProcessBuilder, + b: ProcessBuilder, + operatorString: String + ) extends BasicBuilder { + + checkNotThis(a) + checkNotThis(b) + override def toString = " ( " + a + " " + operatorString + " " + b + " ) " + } + + private[process] class PipedBuilder( + first: ProcessBuilder, + second: ProcessBuilder, + toError: Boolean + ) extends SequentialBuilder(first, second, if (toError) "#|!" else "#|") { + + override def createProcess(io: ProcessIO) = new PipedProcesses(first, second, io, toError) + } + + private[process] class AndBuilder( + first: ProcessBuilder, + second: ProcessBuilder + ) extends SequentialBuilder(first, second, "#&&") { + override def createProcess(io: ProcessIO) = new AndProcess(first, second, io) + } + + private[process] class OrBuilder( + first: ProcessBuilder, + second: ProcessBuilder + ) extends SequentialBuilder(first, second, "#||") { + override def createProcess(io: ProcessIO) = new OrProcess(first, second, io) + } + + private[process] class SequenceBuilder( + first: ProcessBuilder, + second: ProcessBuilder + ) extends SequentialBuilder(first, second, "###") { + override def createProcess(io: ProcessIO) = new ProcessSequence(first, second, io) + } +} \ No newline at end of file diff --git a/src/library/scala/sys/process/ProcessIO.scala b/src/library/scala/sys/process/ProcessIO.scala new file mode 100644 index 000000000000..b9ac1560447d --- /dev/null +++ b/src/library/scala/sys/process/ProcessIO.scala @@ -0,0 +1,23 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ + +/** Each method will be called in a separate thread.*/ +final class ProcessIO( + val writeInput: OutputStream => Unit, + val processOutput: InputStream => Unit, + val processError: InputStream => Unit +) { + def withOutput(process: InputStream => Unit): ProcessIO = new ProcessIO(writeInput, process, processError) + def withError(process: InputStream => Unit): ProcessIO = new ProcessIO(writeInput, processOutput, process) + def withInput(write: OutputStream => Unit): ProcessIO = new ProcessIO(write, processOutput, processError) +} diff --git a/src/library/scala/sys/process/ProcessImpl.scala b/src/library/scala/sys/process/ProcessImpl.scala new file mode 100644 index 000000000000..aebce5ac94c7 --- /dev/null +++ b/src/library/scala/sys/process/ProcessImpl.scala @@ -0,0 +1,232 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +import processAliases._ +import java.io.{ FilterInputStream, FilterOutputStream, PipedInputStream, PipedOutputStream } +import java.util.concurrent.LinkedBlockingQueue + +/** Runs provided code in a new Thread and returns the Thread instance. */ +private object Spawn { + def apply(f: => Unit): Thread = apply(f, false) + def apply(f: => Unit, daemon: Boolean): Thread = { + val thread = new Thread() { override def run() = { f } } + thread.setDaemon(daemon) + thread.start() + thread + } +} +private object Future { + def apply[T](f: => T): () => T = { + val result = new SyncVar[Either[Throwable, T]] + def run: Unit = + try result.set(Right(f)) + catch { case e: Exception => result set Left(e) } + + Spawn(run) + + () => result.get match { + case Right(value) => value + case Left(exception) => throw exception + } + } +} +object Uncloseable { + def apply(in: InputStream): InputStream = new FilterInputStream(in) { override def close() { } } + def apply(out: OutputStream): OutputStream = new FilterOutputStream(out) { override def close() { } } + def protect(in: InputStream): InputStream = if (in eq System.in) Uncloseable(in) else in + def protect(out: OutputStream): OutputStream = if ((out eq System.out) || (out eq System.err)) Uncloseable(out) else out +} + +private class AndProcess( + a: ProcessBuilder, + b: ProcessBuilder, + io: ProcessIO +) extends SequentialProcess(a, b, io, _ == 0) + +private class OrProcess( + a: ProcessBuilder, + b: ProcessBuilder, + io: ProcessIO +) extends SequentialProcess(a, b, io, _ != 0) + +private class ProcessSequence( + a: ProcessBuilder, + b: ProcessBuilder, + io: ProcessIO +) extends SequentialProcess(a, b, io, _ => true) + +private class SequentialProcess( + a: ProcessBuilder, + b: ProcessBuilder, + io: ProcessIO, + evaluateSecondProcess: Int => Boolean +) extends CompoundProcess { + + protected[this] override def runAndExitValue() = { + val first = a.run(io) + runInterruptible(first.exitValue)(first.destroy()) flatMap { codeA => + if (evaluateSecondProcess(codeA)) { + val second = b.run(io) + runInterruptible(second.exitValue)(second.destroy()) + } + else Some(codeA) + } + } +} + +private abstract class BasicProcess extends Process { + def start(): Unit +} + +private abstract class CompoundProcess extends BasicProcess { + def destroy() = destroyer() + def exitValue() = getExitValue() getOrElse sys.error("No exit code: process destroyed.") + def start() = getExitValue + + protected lazy val (getExitValue, destroyer) = { + val code = new SyncVar[Option[Int]]() + code set None + val thread = Spawn(code.set(runAndExitValue())) + + ( + Future { thread.join(); code.get }, + () => thread.interrupt() + ) + } + + /** Start and block until the exit value is available and then return it in Some. Return None if destroyed (use 'run')*/ + protected[this] def runAndExitValue(): Option[Int] + + protected[this] def runInterruptible[T](action: => T)(destroyImpl: => Unit): Option[T] = { + try Some(action) + catch { case _: InterruptedException => destroyImpl; None } + } +} + +private class PipedProcesses(a: ProcessBuilder, b: ProcessBuilder, defaultIO: ProcessIO, toError: Boolean) extends CompoundProcess { + protected[this] override def runAndExitValue() = { + val currentSource = new SyncVar[Option[InputStream]] + val pipeOut = new PipedOutputStream + val source = new PipeSource(currentSource, pipeOut, a.toString) + source.start() + + val pipeIn = new PipedInputStream(pipeOut) + val currentSink = new SyncVar[Option[OutputStream]] + val sink = new PipeSink(pipeIn, currentSink, b.toString) + sink.start() + + def handleOutOrError(fromOutput: InputStream) = currentSource put Some(fromOutput) + + val firstIO = + if (toError) + defaultIO.withError(handleOutOrError) + else + defaultIO.withOutput(handleOutOrError) + val secondIO = defaultIO.withInput(toInput => currentSink put Some(toInput)) + + val second = b.run(secondIO) + val first = a.run(firstIO) + try { + runInterruptible { + first.exitValue + currentSource put None + currentSink put None + val result = second.exitValue + result + } { + first.destroy() + second.destroy() + } + } + finally { + BasicIO.close(pipeIn) + BasicIO.close(pipeOut) + } + } +} +private class PipeSource(currentSource: SyncVar[Option[InputStream]], pipe: PipedOutputStream, label: => String) extends Thread { + final override def run() { + currentSource.get match { + case Some(source) => + try BasicIO.transferFully(source, pipe) + catch { case e: IOException => println("I/O error " + e.getMessage + " for process: " + label); e.printStackTrace() } + finally { + BasicIO.close(source) + currentSource.unset() + } + run() + case None => + currentSource.unset() + BasicIO.close(pipe) + } + } +} +private class PipeSink(pipe: PipedInputStream, currentSink: SyncVar[Option[OutputStream]], label: => String) extends Thread { + final override def run() { + currentSink.get match { + case Some(sink) => + try BasicIO.transferFully(pipe, sink) + catch { case e: IOException => println("I/O error " + e.getMessage + " for process: " + label); e.printStackTrace() } + finally { + BasicIO.close(sink) + currentSink.unset() + } + run() + case None => + currentSink.unset() + } + } +} +/** A thin wrapper around a java.lang.Process. `ioThreads` are the Threads created to do I/O. +* The implementation of `exitValue` waits until these threads die before returning. */ +private class DummyProcess(action: => Int) extends Process { + private[this] val exitCode = Future(action) + override def exitValue() = exitCode() + override def destroy() { } +} +/** A thin wrapper around a java.lang.Process. `outputThreads` are the Threads created to read from the +* output and error streams of the process. `inputThread` is the Thread created to write to the input stream of +* the process. +* The implementation of `exitValue` interrupts `inputThread` and then waits until all I/O threads die before +* returning. */ +private class SimpleProcess(p: JProcess, inputThread: Thread, outputThreads: List[Thread]) extends Process { + override def exitValue() = { + try p.waitFor() // wait for the process to terminate + finally inputThread.interrupt() // we interrupt the input thread to notify it that it can terminate + + outputThreads.foreach(_.join()) // this ensures that all output is complete before returning (waitFor does not ensure this) + p.exitValue() + } + override def destroy() = { + try p.destroy() + finally { inputThread.interrupt() } + } +} +private final class ThreadProcess(thread: Thread, success: SyncVar[Boolean]) extends Process { + override def exitValue() = { + thread.join() + if (success.get) 0 else 1 + } + override def destroy() { thread.interrupt() } +} + +private object Streamed { + def apply[T](nonzeroException: Boolean): Streamed[T] = { + val q = new LinkedBlockingQueue[Either[Int, T]] + def next(): Stream[T] = q.take match { + case Left(0) => Stream.empty + case Left(code) => if (nonzeroException) error("Nonzero exit code: " + code) else Stream.empty + case Right(s) => Stream.cons(s, next) + } + new Streamed((s: T) => q.put(Right(s)), code => q.put(Left(code)), () => next()) + } +} +private final class Streamed[T](val process: T => Unit, val done: Int => Unit, val stream: () => Stream[T]) extends NotNull \ No newline at end of file diff --git a/src/library/scala/sys/process/ProcessLogger.scala b/src/library/scala/sys/process/ProcessLogger.scala new file mode 100644 index 000000000000..107921d66afa --- /dev/null +++ b/src/library/scala/sys/process/ProcessLogger.scala @@ -0,0 +1,16 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys +package process + +trait ProcessLogger { + def info(s: => String): Unit + def error(s: => String): Unit + def buffer[T](f: => T): T +} diff --git a/src/library/scala/sys/process/package.scala b/src/library/scala/sys/process/package.scala new file mode 100644 index 000000000000..659c883d396e --- /dev/null +++ b/src/library/scala/sys/process/package.scala @@ -0,0 +1,25 @@ +/* __ *\ +** ________ ___ / / ___ Scala API ** +** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL ** +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** +** /____/\___/_/ |_/____/_/ | | ** +** |/ ** +\* */ + +package scala.sys + +package object process extends ProcessImplicits { + // These are in a nested object instead of at the package level + // due to the issues described in tickets #3160 and #3836. + private[process] object processAliases { + type Closeable = java.io.Closeable + type File = java.io.File + type IOException = java.io.IOException + type InputStream = java.io.InputStream + type JProcess = java.lang.Process + type JProcessBuilder = java.lang.ProcessBuilder + type OutputStream = java.io.OutputStream + type SyncVar[T] = scala.concurrent.SyncVar[T] + type URL = java.net.URL + } +} diff --git a/src/library/scala/util/parsing/combinator/Parsers.scala b/src/library/scala/util/parsing/combinator/Parsers.scala index 9e69d73f4409..7e1f815bbbf4 100644 --- a/src/library/scala/util/parsing/combinator/Parsers.scala +++ b/src/library/scala/util/parsing/combinator/Parsers.scala @@ -137,7 +137,7 @@ trait Parsers { def flatMapWithNext[U](f: Nothing => Input => ParseResult[U]): ParseResult[U] = this - def get: Nothing = system.error("No result when parsing failed") + def get: Nothing = sys.error("No result when parsing failed") } /** An extractor so NoSuccess(msg, next) can be used in matches. */ diff --git a/src/library/scala/xml/dtd/ContentModelParser.scala b/src/library/scala/xml/dtd/ContentModelParser.scala index d98b03174453..b6df4d47e1ce 100644 --- a/src/library/scala/xml/dtd/ContentModelParser.scala +++ b/src/library/scala/xml/dtd/ContentModelParser.scala @@ -21,10 +21,10 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning # def accept(tok: Int) = { if (token != tok) { if ((tok == STAR) && (token == END)) // common mistake - system.error("in DTDs, \n"+ + sys.error("in DTDs, \n"+ "mixed content models must be like (#PCDATA|Name|Name|...)*"); else - system.error("expected "+token2string(tok)+ + sys.error("expected "+token2string(tok)+ ", got unexpected token:"+token2string(token)); } nextToken @@ -45,7 +45,7 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning # case NAME => value match { case "ANY" => ANY case "EMPTY" => EMPTY - case _ => system.error("expected ANY, EMPTY or '(' instead of " + value ); + case _ => sys.error("expected ANY, EMPTY or '(' instead of " + value ); } case LPAREN => @@ -65,12 +65,12 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning # accept( STAR ); res case _ => - system.error("unexpected token:" + token2string(token) ); + sys.error("unexpected token:" + token2string(token) ); } } case _ => - system.error("unexpected token:" + token2string(token) ); + sys.error("unexpected token:" + token2string(token) ); } // sopt ::= S? def sOpt = if( token == S ) nextToken; @@ -118,12 +118,12 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning # def particle = token match { case LPAREN => nextToken; sOpt; regexp; case NAME => val a = Letter(ElemName(value)); nextToken; maybeSuffix(a) - case _ => system.error("expected '(' or Name, got:"+token2string(token)); + case _ => sys.error("expected '(' or Name, got:"+token2string(token)); } // atom ::= name def atom = token match { case NAME => val a = Letter(ElemName(value)); nextToken; a - case _ => system.error("expected Name, got:"+token2string(token)); + case _ => sys.error("expected Name, got:"+token2string(token)); } } diff --git a/src/library/scala/xml/dtd/Scanner.scala b/src/library/scala/xml/dtd/Scanner.scala index 1ac3c0f24dd5..9355848e0293 100644 --- a/src/library/scala/xml/dtd/Scanner.scala +++ b/src/library/scala/xml/dtd/Scanner.scala @@ -44,7 +44,7 @@ class Scanner extends Tokens with parsing.TokenTests { final def next = if (it.hasNext) c = it.next else c = ENDCH final def acc(d: Char) { - if (c == d) next else system.error("expected '"+d+"' found '"+c+"' !"); + if (c == d) next else sys.error("expected '"+d+"' found '"+c+"' !"); } final def accS(ds: Seq[Char]) { ds foreach acc } @@ -65,7 +65,7 @@ class Scanner extends Tokens with parsing.TokenTests { case ENDCH => END case _ => if (isNameStart(c)) name; // NAME - else system.error("unexpected character:" + c) + else sys.error("unexpected character:" + c) } final def name = { diff --git a/src/library/scala/xml/parsing/MarkupParser.scala b/src/library/scala/xml/parsing/MarkupParser.scala index c1cb5a197acf..24f3d39e4cd5 100644 --- a/src/library/scala/xml/parsing/MarkupParser.scala +++ b/src/library/scala/xml/parsing/MarkupParser.scala @@ -866,7 +866,7 @@ trait MarkupParser extends MarkupParserCommon with TokenTests new PublicID(pubID, sysID); } else { reportSyntaxError("PUBLIC or SYSTEM expected"); - system.error("died parsing notationdecl") + sys.error("died parsing notationdecl") } xSpaceOpt xToken('>') diff --git a/src/library/scala/xml/parsing/MarkupParserCommon.scala b/src/library/scala/xml/parsing/MarkupParserCommon.scala index 3b31f9976ee5..49200045d8c3 100644 --- a/src/library/scala/xml/parsing/MarkupParserCommon.scala +++ b/src/library/scala/xml/parsing/MarkupParserCommon.scala @@ -24,7 +24,7 @@ import MarkupParserCommon._ * All members should be accessed through those. */ private[scala] trait MarkupParserCommon extends TokenTests { - protected def unreachable = system.error("Cannot be reached.") + protected def unreachable = sys.error("Cannot be reached.") // type HandleType // MarkupHandler, SymbolicXMLBuilder type InputType // Source, CharArrayReader @@ -85,7 +85,7 @@ private[scala] trait MarkupParserCommon extends TokenTests { case `end` => return buf.toString case ch => buf append ch } - system.error("Expected '%s'".format(end)) + sys.error("Expected '%s'".format(end)) } /** [42] '<' xmlEndTag ::= '<' '/' Name S? '>' diff --git a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala index 12d020546937..d63a612017a3 100644 --- a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala +++ b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala @@ -35,7 +35,7 @@ abstract class ValidatingMarkupHandler extends MarkupHandler with Logged { val res = decl.contentModel.validate(ns); Console.println("res = "+res); if(!res) - //system.error("invalid!"); + //sys.error("invalid!"); } */ diff --git a/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java b/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java index cac2319b50b2..efac91d3b283 100644 --- a/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java +++ b/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java @@ -126,7 +126,7 @@ private BindingFlags() {} * throws an exception if the caller supplies a non-null Binder object, * since that implies that the caller is supplying BindToXXX * implementations that will pick the appropriate method. - * Reflection models the accessibility rules of the common type system. + * Reflection models the accessibility rules of the common type sys. * For example, if the caller is in the same assembly, the caller * does not need special permissions for internal members. Otherwise, * the caller needs ReflectionPermission. This is consistent with diff --git a/src/partest/scala/tools/partest/PartestTask.scala b/src/partest/scala/tools/partest/PartestTask.scala index 043c48e968cf..7b9f5ff457f0 100644 --- a/src/partest/scala/tools/partest/PartestTask.scala +++ b/src/partest/scala/tools/partest/PartestTask.scala @@ -192,7 +192,7 @@ class PartestTask extends Task with CompilationPathProperty { srcDir foreach (x => setProp("partest.srcdir", x)) - val classpath = this.compilationPath getOrElse system.error("Mandatory attribute 'compilationPath' is not set.") + val classpath = this.compilationPath getOrElse sys.error("Mandatory attribute 'compilationPath' is not set.") val scalaLibrary = { (classpath.list map { fs => new File(fs) }) find { f => @@ -202,7 +202,7 @@ class PartestTask extends Task with CompilationPathProperty { case _ => false } } - } getOrElse system.error("Provided classpath does not contain a Scala library.") + } getOrElse sys.error("Provided classpath does not contain a Scala library.") val antRunner = new scala.tools.partest.nest.AntRunner val antFileManager = antRunner.fileManager @@ -262,7 +262,7 @@ class PartestTask extends Task with CompilationPathProperty { val allFailures = _results map (_._2) sum val allFailedPaths = _results flatMap (_._3) - def f = if (errorOnFailed && allFailures > 0) (system error _) else log(_: String) + def f = if (errorOnFailed && allFailures > 0) (sys error _) else log(_: String) def s = if (allFailures > 1) "s" else "" val msg = if (allFailures > 0) diff --git a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala index 01b4d848f82b..e108db0c9782 100644 --- a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala +++ b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala @@ -62,7 +62,7 @@ class ConsoleFileManager extends FileManager { if (!srcDir.isDirectory) { NestUI.failure("Source directory \"" + srcDir.path + "\" not found") - system.exit(1) + sys.exit(1) } CLASSPATH = { diff --git a/src/partest/scala/tools/partest/nest/NestUI.scala b/src/partest/scala/tools/partest/nest/NestUI.scala index df8f1a5f747d..38110645baf6 100644 --- a/src/partest/scala/tools/partest/nest/NestUI.scala +++ b/src/partest/scala/tools/partest/nest/NestUI.scala @@ -98,7 +98,7 @@ object NestUI { println println(utils.Properties.versionString) println("maintained by Philipp Haller (EPFL)") - system.exit(1) + sys.exit(1) } var _verbose = false diff --git a/src/partest/scala/tools/partest/nest/PathSettings.scala b/src/partest/scala/tools/partest/nest/PathSettings.scala index ea44d30613df..888df04dec99 100644 --- a/src/partest/scala/tools/partest/nest/PathSettings.scala +++ b/src/partest/scala/tools/partest/nest/PathSettings.scala @@ -15,14 +15,14 @@ import java.net.URLClassLoader object PathSettings { import PartestDefaults.{ testRootDir, srcDirName } - private def cwd = Directory.Current getOrElse system.error("user.dir property not set") + private def cwd = Directory.Current getOrElse sys.error("user.dir property not set") private def isPartestDir(d: Directory) = (d.name == "test") && (d / srcDirName isDirectory) // Directory /test lazy val testRoot: Directory = testRootDir getOrElse { val candidates: List[Directory] = (cwd :: cwd.parents) flatMap (d => List(d, Directory(d / "test"))) - candidates find isPartestDir getOrElse system.error("Directory 'test' not found.") + candidates find isPartestDir getOrElse sys.error("Directory 'test' not found.") } // Directory /test/files @@ -38,7 +38,7 @@ object PathSettings { // but in the postmodern "sbt" build, it is called target. Look for both. val dirs = Path.onlyDirs(bases flatMap (x => List(x / "build", x / "target"))) - dirs.headOption getOrElse system.error("Neither 'build' nor 'target' dir found under test root " + testRoot + ".") + dirs.headOption getOrElse sys.error("Neither 'build' nor 'target' dir found under test root " + testRoot + ".") } // Directory /build/pack/lib @@ -46,7 +46,7 @@ object PathSettings { lazy val scalaCheck: File = buildPackLibDir.files ++ srcLibDir.files find (_.name startsWith "scalacheck") getOrElse { - system.error("No scalacheck jar found in '%s' or '%s'".format(buildPackLibDir, srcLibDir)) + sys.error("No scalacheck jar found in '%s' or '%s'".format(buildPackLibDir, srcLibDir)) } } diff --git a/src/partest/scala/tools/partest/nest/Worker.scala b/src/partest/scala/tools/partest/nest/Worker.scala index ef0a1e910c18..7aa4ccc54631 100644 --- a/src/partest/scala/tools/partest/nest/Worker.scala +++ b/src/partest/scala/tools/partest/nest/Worker.scala @@ -144,7 +144,7 @@ class Worker(val fileManager: FileManager, params: TestRunParams) extends Actor def currentFileElapsed = (System.currentTimeMillis - currentFileStart) / 1000 def forceTimeout() = { println("Let's see what them threads are doing before I kill that test.") - system.allThreads foreach { t => + sys.allThreads foreach { t => println(t) t.getStackTrace foreach println println("") diff --git a/src/scalacheck/org/scalacheck/Commands.scala b/src/scalacheck/org/scalacheck/Commands.scala index 5602eea1518f..952dd15953b3 100644 --- a/src/scalacheck/org/scalacheck/Commands.scala +++ b/src/scalacheck/org/scalacheck/Commands.scala @@ -26,7 +26,7 @@ trait Commands extends Prop { class Binding(private val key: State) { def get: Any = bindings.find(_._1 eq key) match { - case None => system.error("No value bound") + case None => sys.error("No value bound") case Some(x) => x } } @@ -139,7 +139,7 @@ trait Commands extends Prop { case Cmds(Nil, _) => proved case Cmds(c::cs, s::ss) => c.postCondition(s,c.nextState(s),c.run(s)) && runCommands(Cmds(cs,ss)) - case _ => system.error("Should not be here") + case _ => sys.error("Should not be here") } private def commandsProp: Prop = { diff --git a/src/scalacheck/org/scalacheck/ConsoleReporter.scala b/src/scalacheck/org/scalacheck/ConsoleReporter.scala index 5dc02b90ad30..a94d32797f29 100644 --- a/src/scalacheck/org/scalacheck/ConsoleReporter.scala +++ b/src/scalacheck/org/scalacheck/ConsoleReporter.scala @@ -79,10 +79,10 @@ object ConsoleReporter { res.status match { case Test.Proved(_) => {} case Test.Passed => {} - case f @ Test.Failed(_, _) => system.error(m + f) + case f @ Test.Failed(_, _) => sys.error(m + f) case Test.Exhausted => {} - case f @ Test.GenException(_) => system.error(m + f) - case f @ Test.PropException(_, _, _) => system.error(m + f) + case f @ Test.GenException(_) => sys.error(m + f) + case f @ Test.PropException(_, _, _) => sys.error(m + f) } } diff --git a/src/scalap/scala/tools/scalap/CodeWriter.scala b/src/scalap/scala/tools/scalap/CodeWriter.scala index 6f00df7660b0..4ef1f46f161f 100644 --- a/src/scalap/scala/tools/scalap/CodeWriter.scala +++ b/src/scalap/scala/tools/scalap/CodeWriter.scala @@ -58,7 +58,7 @@ class CodeWriter(writer: Writer) { try { writer.write(nl) } catch { - case e => system.error("IO error") + case e => sys.error("IO error") } line = align align = true @@ -127,7 +127,7 @@ class CodeWriter(writer: Writer) { line = false this } catch { - case e => system.error("IO error") + case e => sys.error("IO error") } override def toString(): String = writer.toString() diff --git a/src/swing/doc/README b/src/swing/doc/README index cdfee01f8235..f910e8fe522c 100644 --- a/src/swing/doc/README +++ b/src/swing/doc/README @@ -16,7 +16,7 @@ The widget class hierarchy loosely resembles that of Java Swing. The main differ child component. In the end, it is not more work to move all children to a newly created panel.) - The event system. TODO + The event sys. TODO The library comprises three main packages: diff --git a/src/swing/scala/swing/MainFrame.scala b/src/swing/scala/swing/MainFrame.scala index 13c3aacbd0c9..4ef930b60e0d 100644 --- a/src/swing/scala/swing/MainFrame.scala +++ b/src/swing/scala/swing/MainFrame.scala @@ -17,5 +17,5 @@ import event._ * framework and quits the application when closed. */ class MainFrame extends Frame { - override def closeOperation { system.exit(0) } + override def closeOperation { sys.exit(0) } } diff --git a/src/swing/scala/swing/SwingApplication.scala b/src/swing/scala/swing/SwingApplication.scala index 02fd8dc7376d..6da3ab2053b4 100644 --- a/src/swing/scala/swing/SwingApplication.scala +++ b/src/swing/scala/swing/SwingApplication.scala @@ -4,6 +4,6 @@ abstract class SwingApplication extends Reactor { def main(args: Array[String]) = Swing.onEDT { startup(args) } def startup(args: Array[String]) - def quit() { shutdown(); system.exit(0) } + def quit() { shutdown(); sys.exit(0) } def shutdown() {} } diff --git a/test/files/detach-run/actor/ServerConsole.scala b/test/files/detach-run/actor/ServerConsole.scala index d38725ddeed9..8ebd9d4c2e9d 100644 --- a/test/files/detach-run/actor/ServerConsole.scala +++ b/test/files/detach-run/actor/ServerConsole.scala @@ -48,7 +48,7 @@ trait ServerConsole extends Thread { } terminate() println("Server exited ("+mkTimeString(currentTime - startTime)+")") - system.exit(0) + sys.exit(0) } protected def trace(msg: String) { diff --git a/test/files/detach-run/basic/basic.scala b/test/files/detach-run/basic/basic.scala index c785bd6c7d99..4d0fc2d93365 100644 --- a/test/files/detach-run/basic/basic.scala +++ b/test/files/detach-run/basic/basic.scala @@ -24,7 +24,7 @@ object Test { private var th = new Thread(this) def start() { th.start(); Thread.sleep(1000) } def run() { Server.main(Array(port.toString)) } - def terminate() { Server.terminate(); system.exit(0) } + def terminate() { Server.terminate(); sys.exit(0) } } private class ClientThread(host: String, port: Int) extends Runnable { diff --git a/test/files/neg/found-req-variance.scala b/test/files/neg/found-req-variance.scala index c44d021fac01..024b24c36747 100644 --- a/test/files/neg/found-req-variance.scala +++ b/test/files/neg/found-req-variance.scala @@ -42,7 +42,7 @@ object Test { object Functions { object Set1 { def f[T, R](x: FF1[T, R]) = () - def h[T, R] : FF1[T, R] = system.error("") + def h[T, R] : FF1[T, R] = sys.error("") def ff1 = f[B, B](h[A, A]) // fail def ff2 = f[B, B](h[B, A]) // fail @@ -56,7 +56,7 @@ object Functions { } object Set2 { def f[T, R](x: FF2[T, R]) = () - def h[T, R] : FF2[T, R] = system.error("") + def h[T, R] : FF2[T, R] = sys.error("") def ff1 = f[B, B](h[A, A]) // suggest def ff2 = f[B, B](h[B, A]) // suggest diff --git a/test/files/neg/tailrec-2.scala b/test/files/neg/tailrec-2.scala index 0d446364fd58..342cd85323b5 100644 --- a/test/files/neg/tailrec-2.scala +++ b/test/files/neg/tailrec-2.scala @@ -17,10 +17,10 @@ class Bop4[+A](val element: A) extends Super[A] { } object Other { - def f[T] : Bop4[T] = system.error("") + def f[T] : Bop4[T] = sys.error("") } object Bop { - def m1[A] : Super[A] = system.error("") - def m2[A] : Bop2[A] = system.error("") + def m1[A] : Super[A] = sys.error("") + def m2[A] : Bop2[A] = sys.error("") } \ No newline at end of file diff --git a/test/files/neg/tcpoly_variance.check b/test/files/neg/tcpoly_variance.check index dfe48f9544e9..0695fa09a15d 100644 --- a/test/files/neg/tcpoly_variance.check +++ b/test/files/neg/tcpoly_variance.check @@ -1,5 +1,5 @@ tcpoly_variance.scala:6: error: overriding method str in class A of type => m[java.lang.Object]; method str has incompatible type - override def str: m[String] = system.error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object] + override def str: m[String] = sys.error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object] ^ one error found diff --git a/test/files/neg/tcpoly_variance.scala b/test/files/neg/tcpoly_variance.scala index 04846e81d89b..4b9bd50e0850 100644 --- a/test/files/neg/tcpoly_variance.scala +++ b/test/files/neg/tcpoly_variance.scala @@ -1,7 +1,7 @@ class A[m[x]] { - def str: m[Object] = system.error("foo") + def str: m[Object] = sys.error("foo") } class B[m[x]] extends A[m] { - override def str: m[String] = system.error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object] + override def str: m[String] = sys.error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object] } diff --git a/test/files/neg/tcpoly_variance_enforce.check b/test/files/neg/tcpoly_variance_enforce.check index 48025889fc18..44b5b2c15ce5 100644 --- a/test/files/neg/tcpoly_variance_enforce.check +++ b/test/files/neg/tcpoly_variance_enforce.check @@ -36,10 +36,10 @@ object fcoll4_2 extends coll4[FooString, Any] // error ^ tcpoly_variance_enforce.scala:37: error: kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll. FooInvar's type parameters do not match type m's expected parameters: type x (in class FooInvar) is invariant, but type x is declared covariant - def x: coll[FooInvar] = system.error("foo") // error + def x: coll[FooInvar] = sys.error("foo") // error ^ tcpoly_variance_enforce.scala:38: error: kinds of the type arguments (FooContra) do not conform to the expected kinds of the type parameters (type m) in trait coll. FooContra's type parameters do not match type m's expected parameters: type x (in class FooContra) is contravariant, but type x is declared covariant - def y: coll[FooContra] = system.error("foo") // error + def y: coll[FooContra] = sys.error("foo") // error ^ 11 errors found diff --git a/test/files/neg/tcpoly_variance_enforce.scala b/test/files/neg/tcpoly_variance_enforce.scala index cbc8ad7c66f2..ddff0e9f9438 100644 --- a/test/files/neg/tcpoly_variance_enforce.scala +++ b/test/files/neg/tcpoly_variance_enforce.scala @@ -34,8 +34,8 @@ object fcoll4_2 extends coll4[FooString, Any] // error object test { var ok: coll[FooCov] = _ - def x: coll[FooInvar] = system.error("foo") // error - def y: coll[FooContra] = system.error("foo") // error + def x: coll[FooInvar] = sys.error("foo") // error + def y: coll[FooContra] = sys.error("foo") // error } diff --git a/test/files/run/lisp.scala b/test/files/run/lisp.scala index 3436594deff2..f3687ea1bb37 100644 --- a/test/files/run/lisp.scala +++ b/test/files/run/lisp.scala @@ -20,7 +20,7 @@ class LispTokenizer(s: String) extends Iterator[String] { do i = i + 1 while (!isDelimiter(s charAt i)) s.substring(start, i) - } else system.error("premature end of string") + } else sys.error("premature end of string") } //############################################################################ @@ -102,7 +102,7 @@ object LispCaseClasses extends Lisp { var indent: Int = 0 def lispError[a](msg: String): a = - system.error("error: " + msg + "\n" + curexp); + sys.error("error: " + msg + "\n" + curexp); trait Environment { def lookup(n: String): Data; @@ -201,7 +201,7 @@ object LispCaseClasses extends Lisp { val ps: List[String] = toList(params) map { case SYM(name) => name - case _ => system.error("illegal parameter list"); + case _ => sys.error("illegal parameter list"); } FUN(args => eval(expr, extendEnv(env, ps, args))) @@ -237,7 +237,7 @@ object LispCaseClasses extends Lisp { val it = new LispTokenizer(s); def parseExpr(token: String): Data = { if (token == "(") parseList - else if (token == ")") system.error("unbalanced parentheses") + else if (token == ")") sys.error("unbalanced parentheses") else if ('0' <= token.charAt(0) && token.charAt(0) <= '9') NUM(token.toInt) else if (token.charAt(0) == '\"' && token.charAt(token.length()-1)=='\"') @@ -270,7 +270,7 @@ object LispAny extends Lisp { var indent: Int = 0; def lispError[a](msg: String): a = - system.error("error: " + msg + "\n" + curexp); + sys.error("error: " + msg + "\n" + curexp); trait Environment { def lookup(n: String): Data; @@ -392,7 +392,7 @@ object LispAny extends Lisp { val ps: List[String] = asList(params) map { case Symbol(name) => name - case _ => system.error("illegal parameter list"); + case _ => sys.error("illegal parameter list"); } Lambda(args => eval(expr, extendEnv(env, ps, args))) @@ -428,7 +428,7 @@ object LispAny extends Lisp { val it = new LispTokenizer(s); def parseExpr(token: String): Data = { if (token == "(") parseList - else if (token == ")") system.error("unbalanced parentheses") + else if (token == ")") sys.error("unbalanced parentheses") //else if (Character.isDigit(token.charAt(0))) else if (token.charAt(0).isDigit) token.toInt diff --git a/test/files/scalacheck/process.scala b/test/files/scalacheck/process.scala new file mode 100644 index 000000000000..1e06c4669e7a --- /dev/null +++ b/test/files/scalacheck/process.scala @@ -0,0 +1,160 @@ +/** process tests. + */ + +import java.io.{ File, FileNotFoundException, IOException, InputStream, OutputStream, FileInputStream } +import java.net.{ URI, URISyntaxException, URL } +import org.scalacheck._ +import Prop._ +import sys.process._ +import scala.tools.nsc.io.{ File => SFile } + +/** This has scrounged bits of sbt to flesh it out enough to run. + */ +package processtest { + + object exit + { + def fn(code: Int) = System.exit(code) + def main(args: Array[String]) = exit.fn(java.lang.Integer.parseInt(args(0))) + } + object cat + { + def main(args: Array[String]) + { + try { + if (args.length == 0) + IO.transfer(System.in, System.out) + else + catFiles(args.toList) + exit.fn(0) + } catch { + case e => + e.printStackTrace() + System.err.println("Error: " + e.toString) + exit.fn(1) + } + } + private def catFiles(filenames: List[String]): Option[String] = filenames match { + case head :: tail => + val file = new File(head) + if (file.isDirectory) + throw new IOException("Is directory: " + file) + else if (file.exists) { + IO.transfer(file, System.out) + catFiles(tail) + } + else + throw new FileNotFoundException("No such file or directory: " + file) + case Nil => None + } + } + object echo + { + def main(args: Array[String]) + { + System.out.println(args.mkString(" ")) + } + } +} + +object IO { + def transfer(in: InputStream, out: OutputStream): Unit = BasicIO.transferFully(in, out) + def transfer(in: File, out: OutputStream): Unit = BasicIO.transferFully(new FileInputStream(in), out) + + def classLocation(cl: Class[_]): URL = { + val codeSource = cl.getProtectionDomain.getCodeSource + if(codeSource == null) sys.error("No class location for " + cl) + else codeSource.getLocation + } + def classLocationFile(cl: Class[_]): File = toFile(classLocation(cl)) + def classLocation[T](implicit mf: Manifest[T]): URL = classLocation(mf.erasure) + def classLocationFile[T](implicit mf: Manifest[T]): File = classLocationFile(mf.erasure) + + def toFile(url: URL) = + try { new File(url.toURI) } + catch { case _: URISyntaxException => new File(url.getPath) } +} + +class ProcessSpecification extends Properties("Process I/O") { + implicit val exitCodeArb: Arbitrary[Array[Byte]] = Arbitrary(Gen.choose(0, 10) flatMap { size => + Gen.resize(size, Arbitrary.arbArray[Byte].arbitrary) + }) + + /*property("Correct exit code") = forAll( (exitCode: Byte) => checkExit(exitCode)) + property("#&& correct") = forAll( (exitCodes: Array[Byte]) => checkBinary(exitCodes)(_ #&& _)(_ && _)) + property("#|| correct") = forAll( (exitCodes: Array[Byte]) => checkBinary(exitCodes)(_ #|| _)(_ || _)) + property("### correct") = forAll( (exitCodes: Array[Byte]) => checkBinary(exitCodes)(_ ### _)( (x,latest) => latest))*/ + property("Pipe to output file") = forAll( (data: Array[Byte]) => checkFileOut(data)) + property("Pipe to input file") = forAll( (data: Array[Byte]) => checkFileIn(data)) + property("Pipe to process") = forAll( (data: Array[Byte]) => checkPipe(data)) + + private def checkBinary(codes: Array[Byte])(reduceProcesses: (ProcessBuilder, ProcessBuilder) => ProcessBuilder)(reduceExit: (Boolean, Boolean) => Boolean) = + { + (codes.length > 1) ==> + { + val unsignedCodes = codes.map(unsigned) + val exitCode = unsignedCodes.map(code => Process(process("processtest.exit " + code))).reduceLeft(reduceProcesses) ! + val expectedExitCode = unsignedCodes.map(toBoolean).reduceLeft(reduceExit) + toBoolean(exitCode) == expectedExitCode + } + } + private def toBoolean(exitCode: Int) = exitCode == 0 + private def checkExit(code: Byte) = + { + val exitCode = unsigned(code) + (process("processtest.exit " + exitCode) !) == exitCode + } + private def checkFileOut(data: Array[Byte]) = + { + withData(data) { (temporaryFile, temporaryFile2) => + val catCommand = process("processtest.cat " + temporaryFile.getAbsolutePath) + catCommand #> temporaryFile2 + } + } + private def checkFileIn(data: Array[Byte]) = + { + withData(data) { (temporaryFile, temporaryFile2) => + val catCommand = process("processtest.cat") + temporaryFile #> catCommand #> temporaryFile2 + } + } + private def checkPipe(data: Array[Byte]) = + { + withData(data) { (temporaryFile, temporaryFile2) => + val catCommand = process("processtest.cat") + temporaryFile #> catCommand #| catCommand #> temporaryFile2 + } + } + private def temp() = SFile(File.createTempFile("processtest", "")) + private def withData(data: Array[Byte])(f: (File, File) => ProcessBuilder) = + { + val temporaryFile1 = temp() + val temporaryFile2 = temp() + try { + temporaryFile1 writeBytes data + val process = f(temporaryFile1.jfile, temporaryFile2.jfile) + ( process ! ) == 0 && + { + val b1 = temporaryFile1.slurp() + val b2 = temporaryFile2.slurp() + b1 == b2 + } + } + finally + { + temporaryFile1.delete() + temporaryFile2.delete() + } + } + private def unsigned(b: Byte): Int = ((b: Int) +256) % 256 + private def process(command: String) = { + val thisClasspath = List(getSource[ScalaObject], getSource[IO.type], getSource[SourceTag]).mkString(File.pathSeparator) + "java -cp " + thisClasspath + " " + command + } + private def getSource[T : Manifest]: String = + IO.classLocationFile[T].getAbsolutePath +} +private trait SourceTag + + +object Test extends ProcessSpecification { }