diff options
Diffstat (limited to 'src')
104 files changed, 953 insertions, 176 deletions
diff --git a/src/actors/scala/actors/Actor.scala b/src/actors/scala/actors/Actor.scala index 0e52e867ca..5062bfa44c 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 d41d2ea9e8..792eae40a4 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 <code>ForkJoinScheduler</code> 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 c31026c3e8..ba0f88c668 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 575a2698e5..a317cf0a86 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 13da20c4d6..9577537f30 100644 --- a/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java +++ b/src/actors/scala/actors/threadpool/helpers/ThreadHelpers.java @@ -45,7 +45,7 @@ public class ThreadHelpers { /** * 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. * <p> diff --git a/src/compiler/scala/tools/ant/Same.scala b/src/compiler/scala/tools/ant/Same.scala index 2c68e12ba8..deaa9135a1 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 5d1f82e77a..e22d804f93 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 31244ea7b4..88b4b371fb 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 f83f476695..5ce42326e2 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 703cf233e1..ed93bcdcce 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 c471c455ae..c01338f916 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 a5cd7c1bc2..089e473546 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 a38239a119..9d687083c7 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 db5dae0cd9..7fca0687fe 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 a1198409dc..108a54ca83 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 56fe04055c..aca34ec3a0 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 9fa77baeac..3425c04277 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 55f361cf1f..aba4d66165 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 7f79c69f52..22d884a04e 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 116c06179a..7fa41a5803 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 33e91759f8..0137b33cd0 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 0549e2c758..6cc30eb8c8 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 a3a04e34b9..e7fd22d00c 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 cdc18ed566..8fa27c04f6 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 70ab35b13c..54e6acb082 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 e38d14c10b..993002dc1d 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, "<no finalizer>", 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 ad85ded12b..9f22a6de90 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 6da0279ffe..3f7383daf9 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 43ab35b83e..49f5cf78c9 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 c45983d5b6..58ca183359 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 03bb2bae3f..acc28bd445 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 66dc3c78b2..aeea6b5452 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 46e45a861b..647a17b66b 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 47807ccdac..4e5d5668cb 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 6e380027b6..36a715ba26 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 4fdcbafa83..5e78cb4ebb 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 440f2933f9..932326ecc7 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 9d131f4786..dcbc84334c 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 01aaa6c007..c2b73b2831 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 { * <p> * 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. * </p> diff --git a/src/compiler/scala/tools/nsc/io/File.scala b/src/compiler/scala/tools/nsc/io/File.scala index 7bf04cbe5c..eddc9c0de6 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 eac7530aa3..8f5ad5c820 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 3131c78bd0..a4699cfd88 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 b5e23d61f0..6ce244b772 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 f944a168e9..5bc10a4fef 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 6e5a8ac817..153aa0faf5 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 758c28a238..0e190a0da1 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 c06d2ce7dc..2f56180c8d 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 95bf16db5b..3e8f7bd2c7 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 019f40d72f..fb03f8d159 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 29ef9f3f03..62fb0dab00 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 a11038104b..dfa9f1c7cf 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 6de2f35796..06e4de80f9 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 56bef2caa4..2b06d808ae 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 f647660193..cc3024d3e4 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 a5e69d5471..9eb8d25b26 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 21afaea22d..9a509251fb 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 0427269ffd..3dab6f4810 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 07d7d26c6f..74b05ed2a1 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 48a675a405..334e6bf1ed 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 2c56bbf36e..2cb791566f 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 ba3f3c31e0..541e45a477 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 baf4249bbe..814d50e910 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) * } <b>catch</b> { * <b>case</b> e: InterruptedException => // do nothing - * <b>case</b> e: Throwable => e.printStackTrace(); system.exit(1) + * <b>case</b> e: Throwable => e.printStackTrace(); sys.exit(1) * } * } while (<b>true</b>) * } @@ -115,14 +115,14 @@ object RMIDelegate { if (args.length > 0) { if (args(0) equals "-help") { println("Usage: rmidelegate <options> <port>") - system.exit(0) + sys.exit(0) } try { port = args(0).toInt } catch { case e: NumberFormatException => println("Usage: rmidelegate <options> <port>") - 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 755d899765..37f18aea4e 100644 --- a/src/jline/src/main/java/jline/UnixTerminal.java +++ b/src/jline/src/main/java/jline/UnixTerminal.java @@ -28,7 +28,7 @@ import static jline.console.Key.*; * <em>/dev/tty</em> file to disable character echoing and enable * character input. All known unix systems (including * Linux and Macintosh OS X) support the <em>stty</em>), so this - * implementation should work for an reasonable POSIX system. + * implementation should work for an reasonable POSIX sys. * * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a> * @author <a href="mailto:dwkemp@gmail.com">Dale Kemp</a> diff --git a/src/jline/src/main/java/jline/WindowsTerminal.java b/src/jline/src/main/java/jline/WindowsTerminal.java index dcaa3a9cde..4304d6d473 100644 --- a/src/jline/src/main/java/jline/WindowsTerminal.java +++ b/src/jline/src/main/java/jline/WindowsTerminal.java @@ -302,7 +302,7 @@ public class WindowsTerminal * 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 e8768fd150..f07582c356 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 26d7ff2eed..2f95c4fb80 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 1bf3b795f2..aa9f99b4cb 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 6baa05c21a..86b3b9f1e4 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 f02c6fce66..0d454a4ba2 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 1c2d4ba362..58a6982615 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 9de466e04c..3a38f831b2 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 29dfc3ad19..5bd220f81f 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 536976f5e3..ccd693a241 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 757f5d2686..acced246da 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 e1d04eafa5..6f96130568 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 index a01eee6931..e840f28467 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 index 17a5e398ef..af79d95a2a 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 index 1e989f86ec..85deba62b6 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 0000000000..505a859377 --- /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 0000000000..6453002ae4 --- /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 0000000000..798796b29c --- /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, "<output stream>")) + 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, "<input stream>")) + 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 0000000000..3e6d41b5b6 --- /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, "<input stream>")) + 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 0000000000..b9ac156044 --- /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 0000000000..aebce5ac94 --- /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 0000000000..107921d66a --- /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 0000000000..659c883d39 --- /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 9e69d73f44..7e1f815bbb 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 d98b031744..b6df4d47e1 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 1ac3c0f24d..9355848e02 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 c1cb5a197a..24f3d39e4c 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 3b31f9976e..49200045d8 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 12d0205469..d63a612017 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 cac2319b50..efac91d3b2 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 @@ public abstract class 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 043c48e968..7b9f5ff457 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 01b4d848f8..e108db0c97 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 df8f1a5f74..38110645ba 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 ea44d30613..888df04dec 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 <root>/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 <root>/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 <root>/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 ef0a1e910c..7aa4ccc546 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 5602eea151..952dd15953 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 5dc02b90ad..a94d32797f 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 6f00df7660..4ef1f46f16 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 cdfee01f82..f910e8fe52 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 13c3aacbd0..4ef930b60e 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 02fd8dc737..6da3ab2053 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() {} } |