summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorAdriaan Moors <adriaan.moors@typesafe.com>2013-12-09 11:06:22 -0800
committerAdriaan Moors <adriaan.moors@typesafe.com>2013-12-09 17:11:05 -0800
commite55510607031aaf7b8473453f83c44a26c9b97e0 (patch)
tree987d4aeeef387ed435acc64ffadfdf78e6f65bce /docs
parentdc6dd58d9da441b591580684f3d2f38d7898e7d4 (diff)
downloadscala-e55510607031aaf7b8473453f83c44a26c9b97e0.tar.gz
scala-e55510607031aaf7b8473453f83c44a26c9b97e0.tar.bz2
scala-e55510607031aaf7b8473453f83c44a26c9b97e0.zip
Remove docs/examples; they reside at scala/scala-dist
Diffstat (limited to 'docs')
-rw-r--r--docs/examples/actors/auction.scala131
-rw-r--r--docs/examples/actors/boundedbuffer.scala37
-rw-r--r--docs/examples/actors/channels.scala32
-rw-r--r--docs/examples/actors/fringe.scala82
-rw-r--r--docs/examples/actors/links.scala47
-rw-r--r--docs/examples/actors/looping.scala26
-rw-r--r--docs/examples/actors/message.scala40
-rw-r--r--docs/examples/actors/pingpong.scala61
-rw-r--r--docs/examples/actors/producers.scala114
-rw-r--r--docs/examples/actors/seq.scala15
-rw-r--r--docs/examples/boundedbuffer.scala46
-rw-r--r--docs/examples/computeserver.scala54
-rw-r--r--docs/examples/expressions/expressions-current.scala68
-rw-r--r--docs/examples/fors.scala112
-rw-r--r--docs/examples/futures.scala17
-rw-r--r--docs/examples/gadts.scala22
-rw-r--r--docs/examples/iterators.scala28
-rw-r--r--docs/examples/jolib/Ref.scala55
-rw-r--r--docs/examples/jolib/parallelOr.scala58
-rw-r--r--docs/examples/maps.scala187
-rw-r--r--docs/examples/monads/callccInterpreter.scala86
-rw-r--r--docs/examples/monads/directInterpreter.scala55
-rw-r--r--docs/examples/monads/errorInterpreter.scala86
-rw-r--r--docs/examples/monads/simpleInterpreter.scala75
-rw-r--r--docs/examples/monads/stateInterpreter.scala86
-rw-r--r--docs/examples/oneplacebuffer.scala64
-rw-r--r--docs/examples/parsing/ArithmeticParser.scala57
-rw-r--r--docs/examples/parsing/ArithmeticParsers.scala70
-rw-r--r--docs/examples/parsing/JSON.scala44
-rw-r--r--docs/examples/parsing/ListParser.scala33
-rw-r--r--docs/examples/parsing/ListParsers.scala30
-rw-r--r--docs/examples/parsing/MiniML.scala52
-rw-r--r--docs/examples/parsing/lambda/Main.scala34
-rw-r--r--docs/examples/parsing/lambda/TestParser.scala68
-rw-r--r--docs/examples/parsing/lambda/TestSyntax.scala86
-rw-r--r--docs/examples/parsing/lambda/test/test-01.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-02.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-03.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-04.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-05.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-06.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-07.kwi1
-rw-r--r--docs/examples/parsing/lambda/test/test-08.kwi1
-rw-r--r--docs/examples/patterns.scala36
-rw-r--r--docs/examples/pilib/elasticBuffer.scala77
-rw-r--r--docs/examples/pilib/handover.scala186
-rw-r--r--docs/examples/pilib/mobilePhoneProtocol.scala172
-rw-r--r--docs/examples/pilib/piNat.scala89
-rw-r--r--docs/examples/pilib/rwlock.scala329
-rw-r--r--docs/examples/pilib/scheduler.scala150
-rw-r--r--docs/examples/pilib/semaphore.scala72
-rw-r--r--docs/examples/pilib/twoPlaceBuffer.scala67
-rw-r--r--docs/examples/plugintemplate/.classpath11
-rw-r--r--docs/examples/plugintemplate/.project18
-rw-r--r--docs/examples/plugintemplate/build.xml265
-rw-r--r--docs/examples/plugintemplate/doc/README68
-rw-r--r--docs/examples/plugintemplate/doc/examples/plugintemplate/examples/BasicExample.scala8
-rw-r--r--docs/examples/plugintemplate/lib/scalatest.jar.desired.sha11
-rw-r--r--docs/examples/plugintemplate/misc/scalac-plugin.xml4
-rw-r--r--docs/examples/plugintemplate/plugin.properties10
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala61
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplateAnnotationChecker.scala20
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala35
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala79
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala52
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala58
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala32
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala44
-rw-r--r--docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala36
-rw-r--r--docs/examples/plugintemplate/test/plugintemplate/PluginPropertiesSuite.scala14
-rw-r--r--docs/examples/plugintemplate/test/plugintemplate/TemplatePluginSuite.scala22
-rw-r--r--docs/examples/sort.scala48
-rw-r--r--docs/examples/sort1.scala22
-rw-r--r--docs/examples/sort2.scala25
-rw-r--r--docs/examples/swing/ButtonApp.scala24
-rw-r--r--docs/examples/swing/CelsiusConverter.scala42
-rw-r--r--docs/examples/swing/CelsiusConverter2.scala36
-rw-r--r--docs/examples/swing/ComboBoxes.scala86
-rw-r--r--docs/examples/swing/CountButton.scala30
-rw-r--r--docs/examples/swing/Dialogs.scala176
-rw-r--r--docs/examples/swing/GridBagDemo.scala64
-rw-r--r--docs/examples/swing/HelloWorld.scala13
-rw-r--r--docs/examples/swing/LabelTest.scala19
-rw-r--r--docs/examples/swing/LinePainting.scala53
-rw-r--r--docs/examples/swing/ListViewDemo.scala17
-rw-r--r--docs/examples/swing/SimpleApplet.scala18
-rw-r--r--docs/examples/swing/SwingApp.scala29
-rw-r--r--docs/examples/swing/TableSelection.scala96
-rw-r--r--docs/examples/swing/UIDemo.scala147
-rw-r--r--docs/examples/swing/images/banana.jpgbin6000 -> 0 bytes
-rw-r--r--docs/examples/swing/images/margarita1.jpgbin14770 -> 0 bytes
-rw-r--r--docs/examples/swing/images/margarita2.jpgbin17310 -> 0 bytes
-rw-r--r--docs/examples/swing/images/rose.jpgbin13808 -> 0 bytes
-rw-r--r--docs/examples/tcpoly/collection/HOSeq.scala167
-rw-r--r--docs/examples/tcpoly/monads/Monads.scala69
-rw-r--r--docs/examples/typeinf.scala253
-rw-r--r--docs/examples/xml/phonebook/embeddedBook.scala26
-rw-r--r--docs/examples/xml/phonebook/phonebook.scala38
-rw-r--r--docs/examples/xml/phonebook/phonebook1.scala21
-rw-r--r--docs/examples/xml/phonebook/phonebook2.scala25
-rw-r--r--docs/examples/xml/phonebook/phonebook3.scala81
-rw-r--r--docs/examples/xml/phonebook/verboseBook.scala24
102 files changed, 0 insertions, 5831 deletions
diff --git a/docs/examples/actors/auction.scala b/docs/examples/actors/auction.scala
deleted file mode 100644
index c3124c67a9..0000000000
--- a/docs/examples/actors/auction.scala
+++ /dev/null
@@ -1,131 +0,0 @@
-package examples.actors
-
-import java.util.Date
-
-import scala.actors._
-import scala.actors.Actor._
-
-/** A simple demonstrator program implementing an online auction service
- * The example uses the actor abstraction defined in the API of
- * package scala.actors.
- */
-
-trait AuctionMessage
-case class Offer(bid: Int, client: Actor) extends AuctionMessage // make a bid
-case class Inquire(client: Actor) extends AuctionMessage // inquire status
-
-trait AuctionReply
-case class Status(asked: Int, expiration: Date) // asked sum, expiration date
- extends AuctionReply
-case object BestOffer extends AuctionReply // yours is the best offer
-case class BeatenOffer(maxBid: Int) extends AuctionReply // offer beaten by maxBid
-case class AuctionConcluded(seller: Actor, client: Actor) // auction concluded
- extends AuctionReply
-case object AuctionFailed extends AuctionReply // failed with no bids
-case object AuctionOver extends AuctionReply // bidding is closed
-
-class AuctionActor(seller: Actor, minBid: Int, closing: Date) extends Actor {
- val timeToShutdown = 3000 // msec
- val bidIncrement = 10
-
- def act() {
- var maxBid = minBid - bidIncrement
- var maxBidder: Actor = null
-
- loop {
- reactWithin (closing.getTime() - new Date().getTime()) {
-
- case Offer(bid, client) =>
- if (bid >= maxBid + bidIncrement) {
- if (maxBid >= minBid)
- maxBidder ! BeatenOffer(bid)
- maxBid = bid
- maxBidder = client
- client ! BestOffer
- }
- else
- client ! BeatenOffer(maxBid)
-
- case Inquire(client) =>
- client ! Status(maxBid, closing)
-
- case TIMEOUT =>
- if (maxBid >= minBid) {
- val reply = AuctionConcluded(seller, maxBidder)
- maxBidder ! reply
- seller ! reply
- } else {
- seller ! AuctionFailed
- }
- reactWithin(timeToShutdown) {
- case Offer(_, client) => client ! AuctionOver
- case TIMEOUT => exit()
- }
-
- }
- }
- }
-}
-
-object auction {
-
- val random = new scala.util.Random
-
- val minBid = 100
- val closing = new Date(new Date().getTime() + 4000)
-
- val seller = Actor.actor { }
- val auction = new AuctionActor(seller, minBid, closing)
-
- def client(i: Int, increment: Int, top: Int) = new Actor {
- val name = "Client " + i
- def log(msg: String) = Console.println(name + ": " + msg)
- var max: Int = _
- var current: Int = 0
- def act() {
- log("started")
- auction ! Inquire(this)
- receive {
- case Status(maxBid, _) =>
- log("status(" + maxBid + ")")
- max = maxBid
- }
- loop {
- if (max >= top) {
- log("too high for me")
- }
- else if (current < max) {
- current = max + increment
- Thread.sleep(1 + random.nextInt(1000))
- auction ! Offer(current, this)
- }
-
- reactWithin(3000) {
- case BestOffer =>
- log("bestOffer(" + current + ")")
-
- case BeatenOffer(maxBid) =>
- log("beatenOffer(" + maxBid + ")")
- max = maxBid
-
- case AuctionConcluded(seller, maxBidder) =>
- log("auctionConcluded"); exit()
-
- case AuctionOver =>
- log("auctionOver"); exit()
-
- case TIMEOUT =>
- exit()
- }
- }
- }
- }
-
- def main(args: Array[String]) {
- seller.start()
- auction.start()
- client(1, 20, 200).start()
- client(2, 10, 300).start()
- }
-
-}
diff --git a/docs/examples/actors/boundedbuffer.scala b/docs/examples/actors/boundedbuffer.scala
deleted file mode 100644
index c65bb7719c..0000000000
--- a/docs/examples/actors/boundedbuffer.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-
-object boundedbuffer {
- class BoundedBuffer[T](N: Int)(implicit m: Manifest[T]) {
- private case class Put(x: T)
- private case object Get
- private case object Stop
-
- private val buffer = actor {
- val buf = new Array[T](N)
- var in, out, n = 0
- loop {
- react {
- case Put(x) if n < N =>
- buf(in) = x; in = (in + 1) % N; n += 1; reply()
- case Get if n > 0 =>
- val r = buf(out); out = (out + 1) % N; n -= 1; reply(r)
- case Stop =>
- reply(); exit("stopped")
- }
- }
- }
-
- def put(x: T) { buffer !? Put(x) }
- def get: T = (buffer !? Get).asInstanceOf[T]
- def stop() { buffer !? Stop }
- }
-
- def main(args: Array[String]) {
- val buf = new BoundedBuffer[Int](1)
- buf.put(42)
- println("" + buf.get)
- buf.stop()
- }
-}
diff --git a/docs/examples/actors/channels.scala b/docs/examples/actors/channels.scala
deleted file mode 100644
index 3c0dbf232d..0000000000
--- a/docs/examples/actors/channels.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package examples.actors
-
-import scala.actors._
-import scala.actors.Actor._
-
-object channels extends Application {
- case class Msg(ch1: Channel[Int], ch2: Channel[String])
-
- val a = actor {
- val Ch1 = new Channel[Int]
- val Ch2 = new Channel[String]
-
- b ! Msg(Ch1, Ch2)
-
- val ICh1 = Ch1.asInstanceOf[InputChannel[Int]]
- val ICh2 = Ch2.asInstanceOf[InputChannel[String]]
-
- react {
- case ICh1 ! (x: Int) =>
- val r = x + 21
- println("result: "+r)
- case ICh2 ! y =>
- println("received: "+y)
- }
- }
-
- val b = actor {
- react {
- case Msg(ch1, ch2) => ch1 ! 21
- }
- }
-}
diff --git a/docs/examples/actors/fringe.scala b/docs/examples/actors/fringe.scala
deleted file mode 100644
index 2026628cb3..0000000000
--- a/docs/examples/actors/fringe.scala
+++ /dev/null
@@ -1,82 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-import scala.actors.{Channel, OutputChannel}
-
-/**
- @author Philipp Haller
- @version 1.1, 09/21/2007
- */
-object fringe extends Application {
-
- abstract class Tree
- case class Node(left: Tree, right: Tree) extends Tree
- case class Leaf(v: Int) extends Tree
-
- case class CompareFringe(t1: Tree, t2: Tree)
- case class ComputeFringe(t1: Tree, atoms: OutputChannel[Option[Leaf]])
- case class Equal(atom1: Option[Leaf], atom2: Option[Leaf])
- case class Extract(tree: Tree)
-
- val comparator = actor {
- val extractor1 = actor(extractorBehavior())
- val extractor2 = actor(extractorBehavior())
- val ch1 = new Channel[Option[Leaf]]
- val ch2 = new Channel[Option[Leaf]]
- loop {
- react {
- case CompareFringe(tree1, tree2) =>
- extractor1 ! ComputeFringe(tree1, ch1)
- extractor2 ! ComputeFringe(tree2, ch2)
- self ! Equal(ch1.?, ch2.?)
-
- case Equal(atom1, atom2) =>
- if (atom1 == atom2) atom1 match {
- case None =>
- println("same fringe")
- exit()
- case _ =>
- self ! Equal(ch1.?, ch2.?)
- } else {
- println("fringes differ")
- exit()
- }
- }
- }
- }
-
- val extractorBehavior = () => {
- var output: OutputChannel[Option[Leaf]] = null
- loop {
- react {
- case ComputeFringe(tree, leafSink) =>
- output = leafSink
- self ! Extract(tree)
-
- case Extract(tree) => tree match {
- case atom @ Leaf(_) =>
- output ! Some(atom)
- sender ! 'Continue
-
- case Node(left, right) =>
- val outer = self
- val outerCont = sender
- val cont = actor {
- react {
- case 'Continue =>
- outer.send(Extract(right), outerCont)
- }
- }
- self.send(Extract(left), cont)
- }
-
- case 'Continue =>
- output ! None
- exit()
- }
- }
- }
-
- comparator ! CompareFringe(Node(Leaf(5), Node(Leaf(7), Leaf(3))),
- Node(Leaf(5), Node(Leaf(7), Leaf(3))))
-}
diff --git a/docs/examples/actors/links.scala b/docs/examples/actors/links.scala
deleted file mode 100644
index 373e6b07ce..0000000000
--- a/docs/examples/actors/links.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-package examples.actors
-
-import scala.actors.{Actor, Exit}
-import scala.actors.Actor._
-
-object links extends Application {
-
- case object Stop
-
- actor {
- val start = link(p(2))
- start ! Stop
- }
-
- def p(n: Int): Actor =
- if (n == 0) top1()
- else top(p(n-1), n)
-
- def top(a: Actor, n: Int): Actor = actor {
- println("starting actor " + n + " (" + self + ")")
- self.trapExit = true
- link(a)
- loop {
- receive {
- case ex @ Exit(from, reason) =>
- println("Actor " + n + " received " + ex)
- exit('finished)
- case any => {
- println("Actor " + n + " received " + any)
- a ! any
- }
- }
- }
- }
-
- def top1(): Actor = actor {
- println("starting last actor" + " (" + self + ")")
- receive {
- case Stop =>
- println("Last actor now exiting")
- exit('abnormal)
- case any =>
- println("Last actor received " + any)
- top1()
- }
- }
-}
diff --git a/docs/examples/actors/looping.scala b/docs/examples/actors/looping.scala
deleted file mode 100644
index 1ce2e2e5e8..0000000000
--- a/docs/examples/actors/looping.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-
-object looping extends Application {
- case object A
-
- val a = actor {
- var cnt = 0
- loop {
- react {
- case A =>
- cnt += 1
- if (cnt % 2 != 0) continue
- if (cnt < 10)
- println("received A")
- else {
- println("received last A")
- exit()
- }
- }
- }
- }
-
- for (i <- 0 until 10) a ! A
-}
diff --git a/docs/examples/actors/message.scala b/docs/examples/actors/message.scala
deleted file mode 100644
index d385543470..0000000000
--- a/docs/examples/actors/message.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-package examples.actors
-
-import scala.actors.{Actor, Scheduler}
-import scala.actors.Actor._
-import scala.actors.scheduler.SingleThreadedScheduler
-
-object message {
- def main(args: Array[String]) {
- val n = try { args(0).toInt }
- catch {
- case _ =>
- println("Usage: examples.actors.message <n>")
- Predef.exit
- }
- val nActors = 500
- val finalSum = n * nActors
- Scheduler.impl = new SingleThreadedScheduler
-
- def beh(next: Actor, sum: Int) {
- react {
- case value: Int =>
- val j = value + 1; val nsum = sum + j
- if (next == null && nsum >= n * j)
- println(nsum)
- else {
- if (next != null) next ! j
- if (nsum < n * j) beh(next, nsum)
- }
- }
- }
-
- def actorChain(i: Int, a: Actor): Actor =
- if (i > 0) actorChain(i-1, actor(beh(a, 0))) else a
-
- val firstActor = actorChain(nActors, null)
- var i = n; while (i > 0) { firstActor ! 0; i -= 1 }
-
- Scheduler.shutdown()
- }
-}
diff --git a/docs/examples/actors/pingpong.scala b/docs/examples/actors/pingpong.scala
deleted file mode 100644
index 4ed225c662..0000000000
--- a/docs/examples/actors/pingpong.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor
-import scala.actors.Actor._
-
-case object Ping
-case object Pong
-case object Stop
-
-/**
- * Ping pong example.
- *
- * @author Philipp Haller
- * @version 1.1
- */
-object pingpong extends Application {
- val pong = new Pong
- val ping = new Ping(100000, pong)
- ping.start
- pong.start
-}
-
-class Ping(count: Int, pong: Actor) extends Actor {
- def act() {
- var pingsLeft = count - 1
- pong ! Ping
- loop {
- react {
- case Pong =>
- if (pingsLeft % 1000 == 0)
- println("Ping: pong")
- if (pingsLeft > 0) {
- pong ! Ping
- pingsLeft -= 1
- } else {
- println("Ping: stop")
- pong ! Stop
- exit()
- }
- }
- }
- }
-}
-
-class Pong extends Actor {
- def act() {
- var pongCount = 0
- loop {
- react {
- case Ping =>
- if (pongCount % 1000 == 0)
- println("Pong: ping "+pongCount)
- sender ! Pong
- pongCount += 1
- case Stop =>
- println("Pong: stop")
- exit()
- }
- }
- }
-}
diff --git a/docs/examples/actors/producers.scala b/docs/examples/actors/producers.scala
deleted file mode 100644
index 80e5ae33d3..0000000000
--- a/docs/examples/actors/producers.scala
+++ /dev/null
@@ -1,114 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor
-import scala.actors.Actor._
-
-abstract class Producer[T] {
-
- /** A signal that the next value should be produced. */
- private val Next = new Object
-
- /** A label for an undefined state of the iterators. */
- private val Undefined = new Object
-
- /** A signal to stop the coordinator. */
- private val Stop = new Object
-
- protected def produce(x: T) {
- coordinator ! Some(x)
- receive { case Next => }
- }
-
- protected def produceValues: Unit
-
- def iterator = new Iterator[T] {
- private var current: Any = Undefined
- private def lookAhead = {
- if (current == Undefined) current = coordinator !? Next
- current
- }
-
- def hasNext: Boolean = lookAhead match {
- case Some(x) => true
- case None => { coordinator ! Stop; false }
- }
-
- def next: T = lookAhead match {
- case Some(x) => current = Undefined; x.asInstanceOf[T]
- }
- }
-
- private val coordinator: Actor = actor {
- loop {
- react {
- case Next =>
- producer ! Next
- reply {
- receive { case x: Option[_] => x }
- }
- case Stop =>
- exit('stop)
- }
- }
- }
-
- private val producer: Actor = actor {
- receive {
- case Next =>
- produceValues
- coordinator ! None
- }
- }
-}
-
-object producers extends Application {
-
- class Tree(val left: Tree, val elem: Int, val right: Tree)
- def node(left: Tree, elem: Int, right: Tree): Tree = new Tree(left, elem, right)
- def node(elem: Int): Tree = node(null, elem, null)
-
- def tree = node(node(node(3), 4, node(6)), 8, node(node(9), 10, node(11)))
-
- class PreOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- produce(n.elem)
- traverse(n.left)
- traverse(n.right)
- }
- }
- }
-
- class PostOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- traverse(n.left)
- traverse(n.right)
- produce(n.elem)
- }
- }
- }
-
- class InOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- traverse(n.left)
- produce(n.elem)
- traverse(n.right)
- }
- }
- }
-
- actor {
- print("PreOrder:")
- for (x <- new PreOrder(tree).iterator) print(" "+x)
- print("\nPostOrder:")
- for (x <- new PostOrder(tree).iterator) print(" "+x)
- print("\nInOrder:")
- for (x <- new InOrder(tree).iterator) print(" "+x)
- print("\n")
- }
-}
diff --git a/docs/examples/actors/seq.scala b/docs/examples/actors/seq.scala
deleted file mode 100644
index 816c969cb6..0000000000
--- a/docs/examples/actors/seq.scala
+++ /dev/null
@@ -1,15 +0,0 @@
-package examples.actors
-
-object seq extends Application {
- import scala.actors.Actor._
- val a = actor {
- { react {
- case 'A => println("received 1st message")
- }; ()
- } andThen react {
- case 'A => println("received 2nd message")
- }
- }
- a ! 'A
- a ! 'A
-}
diff --git a/docs/examples/boundedbuffer.scala b/docs/examples/boundedbuffer.scala
deleted file mode 100644
index 359bfd8d06..0000000000
--- a/docs/examples/boundedbuffer.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-package examples
-
-object boundedbuffer {
-
- import concurrent.ops._
-
- class BoundedBuffer[A](N: Int)(implicit m: ClassManifest[A]) {
- var in, out, n = 0
- val elems = new Array[A](N)
-
- def await(cond: => Boolean) = while (!cond) { wait() }
-
- def put(x: A) = synchronized {
- await (n < N)
- elems(in) = x; in = (in + 1) % N; n += 1
- if (n == 1) notifyAll()
- }
-
- def get: A = synchronized {
- await (n != 0)
- val x = elems(out); out = (out + 1) % N ; n -= 1
- if (n == N - 1) notifyAll()
- x
- }
- }
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() = {
- println("[killed]")
- System.exit(0)
- }
- },
- delay) // in milliseconds
-
- def main(args: Array[String]) {
- val buf = new BoundedBuffer[String](10)
- var cnt = 0
- def produceString = { cnt += 1; cnt.toString() }
- def consumeString(ss: String) = println(ss)
- spawn { while (true) { val ssss = produceString; buf.put(ssss) } }
- spawn { while (true) { val s = buf.get; consumeString(s) } }
- kill(1000)
- }
-
-}
diff --git a/docs/examples/computeserver.scala b/docs/examples/computeserver.scala
deleted file mode 100644
index 788be284d1..0000000000
--- a/docs/examples/computeserver.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-package examples
-
-import concurrent._, concurrent.ops._
-
-class ComputeServer(n: Int) {
-
- private trait Job {
- type t
- def task: t
- def ret(x: t): Unit
- }
-
- private val openJobs = new Channel[Job]()
-
- private def processor(i: Int) {
- while (true) {
- val job = openJobs.read
- println("read a job")
- job.ret(job.task)
- }
- }
-
- def future[a](p: => a): () => a = {
- val reply = new SyncVar[a]()
- openJobs.write{
- new Job {
- type t = a
- def task = p
- def ret(x: a) = reply.set(x)
- }
- }
- () => reply.get
- }
-
- //spawn(replicate(0, n) { processor })
- spawn((0 until n).par foreach { processor })
-}
-
-object computeserver extends App {
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() = {
- println("[killed]")
- sys exit 0
- }
- },
- delay) // in milliseconds
-
- val server = new ComputeServer(1)
- val f = server.future(42)
- println(f())
- kill(10000)
-}
diff --git a/docs/examples/expressions/expressions-current.scala b/docs/examples/expressions/expressions-current.scala
deleted file mode 100644
index 660a417c11..0000000000
--- a/docs/examples/expressions/expressions-current.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-package examples.expressions
-
-class Ref[a](var elem:a) {}
-
-abstract class Lang {
- trait Visitor {
- def caseNum(n: int): unit
- }
-
- abstract class Exp {
- def visit(v: visitor): unit
- }
-
- type visitor <: Visitor
-
- class Num(n: int) extends Exp {
- def visit(v: visitor): unit = v.caseNum(n)
- }
-
- class Eval(result: Ref[int]) requires visitor extends Visitor {
- def caseNum(n: int) = result.elem = n
- }
-}
-
-abstract class Lang2 extends Lang {
- trait Visitor2 extends Visitor {
- def casePlus(left: Exp, right: Exp): unit
- }
-
- type visitor <: Visitor2
-
- class Plus(l: Exp, r: Exp) extends Exp {
- def visit(v: visitor): unit = v.casePlus(l, r)
- }
-
- // class Eval2(result: Ref[int]): visitor extends Eval(result) with Visitor2 {
- class Eval2(result: Ref[int]) requires visitor extends Eval(result) with Visitor2 {
- def casePlus(l: Exp, r: Exp) =
- result.elem = { l.visit(this); result.elem } + { r.visit(this); result.elem }
- }
-
- class Show2(result: Ref[String]) requires visitor extends Visitor2 {
- def caseNum(n: int) = result.elem = n.toString()
- def casePlus(l: Exp, r: Exp) =
- result.elem =
- "(" + { l.visit(this); result.elem } +
- "+" + { r.visit(this); result.elem } + ")"
- }
-}
-
-object Main {
- def main(args: Array[String]): unit = {
- //val l1 = new Lang { type visitor = Visitor } // not yet implemented
- object l1 extends Lang { type visitor = Visitor } // workaround
- val e1: l1.Exp = new l1.Num(42)
- val iref = new Ref(0)
- Console.println("eval: " + { e1.visit(new l1.Eval(iref)); iref.elem })
-
- //val l2 = new Lang2 { type visitor = Visitor2 } // not yet implemented
- object l2 extends Lang2 { type visitor = Visitor2 } // workaround
- val e2: l2.Exp = new l2.Plus(new l2.Num(5), new l2.Num(37))
- val sref = new Ref("")
- Console.println("eval: " + { e2.visit(new l2.Eval2(iref)); iref.elem })
- Console.println("show: " + { e2.visit(new l2.Show2(sref)); sref.elem })
- e1.visit(new l1.Eval(iref))
- e2.visit(new l2.Show2(sref))
- }
-}
diff --git a/docs/examples/fors.scala b/docs/examples/fors.scala
deleted file mode 100644
index b937e53fcd..0000000000
--- a/docs/examples/fors.scala
+++ /dev/null
@@ -1,112 +0,0 @@
-package examples
-
-import scala.xml._
-
-
-object fors {
-
- val e = Node.NoAttributes
-
- class Person(_name: String, _age: Int) {
- val name = _name
- val age = _age
- }
-
- def printOlderThan20(xs: Seq[Person]): Iterator[String] =
- printOlderThan20(xs.iterator)
-
- def printOlderThan20(xs: Iterator[Person]): Iterator[String] =
- for (p <- xs if p.age > 20) yield p.name
-
- val persons = List(
- new Person("John", 40),
- new Person("Richard", 68)
- )
-
- def divisors(n: Int): List[Int] =
- for (i <- List.range(1, n+1) if n % i == 0) yield i
-
- def isPrime(n: Int) = divisors(n).length == 2
-
- def findNums(n: Int): Iterable[(Int, Int)] =
- for (i <- 1 until n;
- j <- 1 until (i-1);
- if isPrime(i+j)) yield (i, j)
-
- def sum(xs: List[Double]): Double =
- xs.foldLeft(0.0) { (x, y) => x + y }
-
- def scalProd(xs: List[Double], ys: List[Double]) =
- sum(for((x, y) <- xs zip ys) yield x * y)
-
- type Lst = List[Any]
-
- val prefix = null
- val scope = TopScope
-
- val books = List(
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Structure and Interpretation of Computer Programs")),
- Elem(prefix, "author", e, scope,
- Text("Abelson, Harald")),
- Elem(prefix, "author", e, scope,
- Text("Sussman, Gerald J."))),
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Principles of Compiler Design")),
- Elem(prefix, "author", e, scope,
- Text("Aho, Alfred")),
- Elem(prefix, "author", e, scope,
- Text("Ullman, Jeffrey"))),
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Programming in Modula-2")),
- Elem(prefix, "author", e, scope,
- Text("Wirth, Niklaus")))
- )
-
- def findAuthor(books: Lst) =
- for (Elem(_, "book", _, _, book @ _*) <- books;
- Elem(_, "title", _, _, Text(title)) <- book.toList;
- if (title indexOf "Program") >= 0;
- Elem(_, "author", _, _, Text(author)) <- List(book)) yield author
-
- for (Elem(_, "book", _, _, book @ _*) <- books;
- Elem(_, "author", _, _, Text(author)) <- book.toList;
- if author startsWith "Ullman";
- Elem(_, "title", _, _, Text(title)) <- List(book)) yield title
-
- removeDuplicates(
- for (Elem(_, "book", _, _, b1 @ _* ) <- books;
- Elem(_, "book", _, _, b2 @ _*) <- books;
- if b1 != b2;
- Elem(_, "author", _, _, Text(a1)) <- b1.toList;
- Elem(_, "author", _, _, Text(a2)) <- b2.toList;
- if a1 == a2) yield Pair(a1, a2))
-
- def removeDuplicates[a](xs: List[a]): List[a] =
- if (xs.isEmpty)
- xs
- else
- xs.head :: removeDuplicates(for (x <- xs.tail if x != xs.head) yield x)
-
- def main(args: Array[String]) {
- print("Persons over 20:")
- printOlderThan20(persons) foreach { x => print(" " + x) }
- println
-
- println("divisors(34) = " + divisors(34))
-
- print("findNums(15) =");
- findNums(15) foreach { x => print(" " + x); }
- println
-
- val xs = List(3.5, 5.0, 4.5)
- println("average(" + xs + ") = " + sum(xs) / xs.length)
-
- val ys = List(2.0, 1.0, 3.0)
- println("scalProd(" + xs + ", " + ys +") = " + scalProd(xs, ys))
- }
-
-}
diff --git a/docs/examples/futures.scala b/docs/examples/futures.scala
deleted file mode 100644
index e05b6b330e..0000000000
--- a/docs/examples/futures.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-package examples
-
-import concurrent.ops._
-
-object futures {
- def someLengthyComputation = 1
- def anotherLengthyComputation = 2
- def f(x: Int) = x + x
- def g(x: Int) = x * x
-
- def main(args: Array[String]) {
- val x = future(someLengthyComputation)
- anotherLengthyComputation
- val y = f(x()) + g(x())
- println(y)
- }
-}
diff --git a/docs/examples/gadts.scala b/docs/examples/gadts.scala
deleted file mode 100644
index d2792f4ada..0000000000
--- a/docs/examples/gadts.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-package examples
-
-object gadts extends Application {
-
- abstract class Term[T]
- case class Lit(x: Int) extends Term[Int]
- case class Succ(t: Term[Int]) extends Term[Int]
- case class IsZero(t: Term[Int]) extends Term[Boolean]
- case class If[T](c: Term[Boolean],
- t1: Term[T],
- t2: Term[T]) extends Term[T]
-
- def eval[T](t: Term[T]): T = t match {
- case Lit(n) => n
- case Succ(u) => eval(u) + 1
- case IsZero(u) => eval(u) == 0
- case If(c, u1, u2) => eval(if (eval(c)) u1 else u2)
- }
- println(
- eval(If(IsZero(Lit(1)), Lit(41), Succ(Lit(41)))))
-}
-
diff --git a/docs/examples/iterators.scala b/docs/examples/iterators.scala
deleted file mode 100644
index e2e5e050a0..0000000000
--- a/docs/examples/iterators.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-package examples
-
-object iterators {
-
- def Array(elems: Double*): Array[Double] = {
- val ar = new Array[Double](elems.length)
- for (i <- 0 until elems.length)
- ar(i) = elems(i)
- ar
- }
-
- def printArray(xs: Array[Double]) =
- xs.iterator foreach { x => println(x) }
-
- def findGreater(xs: Array[Double], limit: Double) =
- xs.iterator
- .zip(Iterator.from(0))
- .filter{case Pair(x, i) => x > limit }
- .map{case Pair(x, i) => i}
-
- def main(args: Array[String]) {
- val ar = Array/*[Double]*/(6, 2, 8, 5, 1)
- printArray(ar)
- println("Elements greater than 3.0:")
- findGreater(ar, 3.0) foreach { x => Console.println(ar(x)) }
- }
-
-}
diff --git a/docs/examples/jolib/Ref.scala b/docs/examples/jolib/Ref.scala
deleted file mode 100644
index 5f655f16b1..0000000000
--- a/docs/examples/jolib/Ref.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.jolib;
-/*
-import concurrent.SyncVar;
-import concurrent.jolib._;
-
-class Ref[a](init: a) extends Join {
-
- object get extends Synchr[a](this) { case class C() extends SyncVar[a]; }
- object set extends Synchr[unit](this) { case class C(x: a) extends SyncVar[unit]; }
- object state extends Asynchr(this) { case class C(x: a); }
-
- rules (
- Pair(List(get, state), { case List(g @ get.C(), state.C(x) ) =>
- { g.set(x); state(state.C(x)) } }),
- Pair(List(set, state), { case List(s @ set.C(x), state.C(y) ) =>
- { s.set(()); state(state.C(x)) } })
- );
-
- state(state.C(init));
-
- def Get: a = get(get.C());
- def Set(x: a): unit = set(set.C(x));
-}
-*/
-object RefTest {
-
- def main(args: Array[String]) = {
- System.out.println("Started.");
-/*
- concurrent.ops.spawn({
- val r1 = new Ref(0);
- System.out.println("Reference r1 created.");
- System.out.println("Value r1 (first time) = " + r1.Get);
- r1.Set(42);
- System.out.println("Value r1 (second time) = " + r1.Get);
- });
- concurrent.ops.spawn({
- val r2 = new Ref(100);
- System.out.println("Reference r2 created.");
- System.out.println("Value r2 (first time) = " + r2.Get);
- r2.Set(89);
- System.out.println("Value r2 (second time) = " + r2.Get);
- });
-*/
- }
-
-}
diff --git a/docs/examples/jolib/parallelOr.scala b/docs/examples/jolib/parallelOr.scala
deleted file mode 100644
index 72d282bee3..0000000000
--- a/docs/examples/jolib/parallelOr.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.jolib;
-/*
-import concurrent.jolib._;
-import concurrent.SyncVar;
-
-/** Implementation in the join-calculus of a parallel OR. */
-object or extends Join {
-
- object res extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
- object res1 extends Asynchr(this) { case class C(b: boolean); }
- object res2 extends Asynchr(this) { case class C(b: boolean); }
- object res1False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
- object res2False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
-
- rules(
- Pair(List(res, res1), { case List(r @ res.C(), res1.C(b)) =>
- if (b) r.set(b) else r.set(res1False(res1False.C())) }),
-
- Pair(List(res, res2), { case List(r @ res.C(), res2.C(b)) =>
- if (b) r.set(b) else r.set(res2False(res2False.C())) }),
-
- Pair(List(res1False, res2), { case List(r @ res1False.C(), res2.C(b)) =>
- r.set(b) }),
-
- Pair(List(res2False, res1), { case List(r @ res2False.C(), res1.C(b)) =>
- r.set(b) })
- );
-
- def apply(b1: => boolean, b2: => boolean): boolean = {
- concurrent.ops.spawn(res1(res1.C(b1)));
- concurrent.ops.spawn(res2(res2.C(b2)));
- res(res.C())
- }
-}
-*/
-object parallelOr {
-
- def main(args: Array[String]): unit = {
- def loop: boolean = { while (true) {}; true };
-/*
- System.out.println("true || true = " + or(true, true));
- System.out.println("false || false = " + or(false, false));
- System.out.println("false || true = " + or(false, true));
- System.out.println("true || false = " + or(true, false));
- System.out.println("true || loop = " + or(true, loop));
- System.out.println("loop || true = " + or(loop, true));
-*/
- }
-
-}
diff --git a/docs/examples/maps.scala b/docs/examples/maps.scala
deleted file mode 100644
index d545b50ab9..0000000000
--- a/docs/examples/maps.scala
+++ /dev/null
@@ -1,187 +0,0 @@
-package examples
-
-object maps {
-
- import scala.collection.immutable._
-
- trait MapStruct[kt, vt] {
- trait Map extends Function1[kt, vt] {
- def extend(key: kt, value: vt): Map
- def remove(key: kt): Map
- def domain: Stream[kt]
- def range: Stream[vt]
- }
- type map <: Map
- val empty: map
- }
-
- class AlgBinTree[kt >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- type map = AlgMap
-
- val empty: AlgMap = Empty()
-
- private case class Empty() extends AlgMap {}
- private case class Node(key: kt, value: vt, l: map, r: map) extends AlgMap {}
-
- trait AlgMap extends Map {
- def apply(key: kt): vt = this match {
- case Empty() => null
- case Node(k, v, l, r) =>
- if (key < k) l.apply(key)
- else if (key > k) r.apply(key)
- else v
- }
-
- def extend(key: kt, value: vt): map = this match {
- case Empty()=> Node(key, value, empty, empty)
- case Node(k, v, l, r) =>
- if (key < k) Node(k, v, l.extend(key, value), r)
- else if (key > k) Node(k, v, l, r.extend(key, value))
- else Node(k, value, l, r)
- }
-
- def remove(key: kt): map = this match {
- case Empty()=> empty
- case Node(k, v, l, r) =>
- if (key < k) Node(k, v, l.remove(key), r)
- else if (key > k) Node(k, v, l, r.remove(key))
- else if (l == empty) r
- else if (r == empty) l
- else {
- val midKey = r.domain.head
- Node(midKey, r.apply(midKey), l, r.remove(midKey))
- }
- }
-
- def domain: Stream[kt] = this match {
- case Empty()=> Stream.empty
- case Node(k, v, l, r) => l.domain append Stream.cons(k, r.domain)
- }
-
- def range: Stream[vt] = this match {
- case Empty()=> Stream.empty
- case Node(k, v, l, r) => l.range append Stream.cons(v, r.range)
- }
- }
- }
-
- class OOBinTree[kt >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- type map = OOMap
-
- trait OOMap extends Map {
- def apply(key: kt): vt
- def extend(key: kt, value: vt): map
- def remove(key: kt): map
- def domain: Stream[kt]
- def range: Stream[vt]
- }
- val empty: OOMap = new OOMap {
- def apply(key: kt): vt = null
- def extend(key: kt, value: vt) = new Node(key, value, empty, empty)
- def remove(key: kt) = empty
- def domain: Stream[kt] = Stream.empty
- def range: Stream[vt] = Stream.empty
- }
- private class Node(k: kt, v: vt, l: map, r: map) extends OOMap {
- def apply(key: kt): vt =
- if (key < k) l.apply(key)
- else if (key > k) r.apply(key)
- else v;
- def extend(key: kt, value: vt): map =
- if (key < k) new Node(k, v, l.extend(key, value), r)
- else if (key > k) new Node(k, v, l, r.extend(key, value))
- else new Node(k, value, l, r)
- def remove(key: kt): map =
- if (key < k) new Node(k, v, l.remove(key), r)
- else if (key > k) new Node(k, v, l, r.remove(key))
- else if (l == empty) r
- else if (r == empty) l
- else {
- val midKey = r.domain.head
- new Node(midKey, r(midKey), l, r.remove(midKey))
- }
- def domain: Stream[kt] = l.domain append Stream.cons(k, r.domain)
- def range: Stream[vt] = l.range append Stream.cons(v, r.range)
- }
- }
-
- class MutBinTree[kt >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- type map = MutMap
- class MutMap(key: kt, value: vt) extends Map {
- val k = key
- var v = value
- var l, r = empty
-
- def apply(key: kt): vt =
- if (this == empty) null
- else if (key < k) l.apply(key)
- else if (key > k) r.apply(key)
- else v
-
- def extend(key: kt, value: vt): map =
- if (this == empty) new MutMap(key, value)
- else {
- if (key < k) l = l.extend(key, value)
- else if (key > k) r = r.extend(key, value)
- else v = value
- this
- }
-
- def remove(key: kt): map =
- if (this == empty) this
- else if (key < k) { l = l.remove(key); this }
- else if (key > k) { r = r.remove(key); this }
- else if (l == empty) r
- else if (r == empty) l
- else {
- var mid = r
- while (!(mid.l == empty)) { mid = mid.l }
- mid.r = r.remove(mid.k)
- mid.l = l
- mid
- }
-
- def domain: Stream[kt] =
- if (this == empty) Stream.empty
- else l.domain append Stream.cons(k, r.domain)
-
- def range: Stream[vt] =
- if (this == empty) Stream.empty
- else l.range append Stream.cons(v, r.range)
- }
- val empty = new MutMap(null, null)
- }
-
- class Date(y: Int, m: Int, d: Int) extends Ordered[Date] {
- def year = y
- def month = m
- def day = d
-
- def compare(other: Date): Int =
- if (year == other.year &&
- month == other.month &&
- day == other.day)
- 0
- else if (year < other.year ||
- year == other.year && month < other.month ||
- month == other.month && day < other.day)
- -1
- else
- 1
-
- override def equals(that: Any): Boolean =
- that.isInstanceOf[Date] && {
- val o = that.asInstanceOf[Date];
- day == o.day && month == o.month && year == o.year
- }
- }
-
- def main(args: Array[String]) {
- val t = new OOBinTree[Date, String]()
- ()
- }
-
-}
-
-
-
diff --git a/docs/examples/monads/callccInterpreter.scala b/docs/examples/monads/callccInterpreter.scala
deleted file mode 100644
index 5b556bd8fa..0000000000
--- a/docs/examples/monads/callccInterpreter.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-object callccInterpreter {
-
- def id[a](x: a) = x
-
- type Answer = Value;
-
- case class M[A](in: (A => Answer) => Answer) {
- def bind[B](k: A => M[B]) = M[B](c => in (a => k(a) in c));
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A) = M[A](c => c(a));
-
- def showM(m: M[Value]): String = (m in id).toString();
-
- def callCC[A](h: (A => M[A]) => M[A]) =
- M[A](c => h(a => M[A](d => c(a))) in c);
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
- case class Ccc(x: Name, t: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e))
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
- val term2 = Add(Con(1), Ccc("k", Add(Con(2), App(Var("k"), Con(4)))));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- System.out.println(test(term2));
- }
-}
-
diff --git a/docs/examples/monads/directInterpreter.scala b/docs/examples/monads/directInterpreter.scala
deleted file mode 100644
index 06fffba8e2..0000000000
--- a/docs/examples/monads/directInterpreter.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-object directInterpreter {
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value;
- case class Num(n: Int) extends Value;
- case class Fun(f: Value => Value)extends Value;
-
- def showval(v: Value): String = v match {
- case Wrong => "<wrong>"
- case Num(n) => n.toString()
- case Fun(f) => "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): Value = e match {
- case List() => Wrong
- case Pair(y, b) :: e1 => if (x == y) b else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): Value = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => Num(m + n)
- case _ => Wrong
- }
-
- def apply(a: Value, b: Value) = a match {
- case Fun(k) => k(b)
- case _ => Wrong
- }
-
- def interp(t: Term, e: Environment): Value = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => Num(n)
- case Add(l, r) => add(interp(l, e), interp(r, e))
- case Lam(x, t) => Fun(a => interp(t, Pair(x, a) :: e))
- case App(f, t) => apply(interp(f, e), interp(t, e))
- }
-
- def test(t: Term): String =
- showval(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
-
- def main(args: Array[String]) =
- System.out.println(test(term0));
-}
diff --git a/docs/examples/monads/errorInterpreter.scala b/docs/examples/monads/errorInterpreter.scala
deleted file mode 100644
index d3cc45627d..0000000000
--- a/docs/examples/monads/errorInterpreter.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-object errorInterpreter {
-
- trait M[A] {
- def show: String
- def bind[B](k: A => M[B]): M[B]
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)))
- def flatMap[B](f: A => M[B]): M[B] = bind(f)
- }
-
- def unitM[A](a: A): M[A] = new Suc(a)
- def errorM[A](msg: String): M[A] = new Err(msg)
-
- def showM(m: M[Value]): String = m.show
-
- class Suc[A](x: A) extends M[A] {
- def bind[B](k: A => M[B]): M[B] = k(x)
- def show: String = "Success: " + x
- }
- class Err[A](msg: String) extends M[A] {
- def bind[B](k: A => M[B]): M[B] = new Err(msg)
- def show: String = "Error: " + msg
- }
-
- type Name = String
-
- trait Term
- case class Var(x: Name) extends Term
- case class Con(n: Int) extends Term
- case class Add(l: Term, r: Term) extends Term
- case class Lam(x: Name, body: Term) extends Term
- case class App(fun: Term, arg: Term) extends Term
-
- trait Value
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString()
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]]
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => errorM("unbound variable: " + x);
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => errorM("should be numbers: " + a + "," + b)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => errorM("should be function: " + a)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()))
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)))
- val term1 = App(Con(1), Con(2))
-
- def main(args: Array[String]) = {
- System.out.println(test(term0))
- System.out.println(test(term1))
- }
-}
-
diff --git a/docs/examples/monads/simpleInterpreter.scala b/docs/examples/monads/simpleInterpreter.scala
deleted file mode 100644
index cde3a92dbb..0000000000
--- a/docs/examples/monads/simpleInterpreter.scala
+++ /dev/null
@@ -1,75 +0,0 @@
-object simpleInterpreter {
-
- case class M[A](value: A) {
- def bind[B](k: A => M[B]): M[B] = k(value);
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A): M[A] = M(a);
-
- def showM(m: M[Value]): String = m.value.toString();
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- }
-}
-
diff --git a/docs/examples/monads/stateInterpreter.scala b/docs/examples/monads/stateInterpreter.scala
deleted file mode 100644
index 97f3335dab..0000000000
--- a/docs/examples/monads/stateInterpreter.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-package examples.monads;
-
-object stateInterpreter {
-
- type State = Int;
-
- val tickS = new M(s => Pair((), s + 1));
-
- case class M[A](in: State => Pair[A, State]) {
- def bind[B](k: A => M[B]) = M[B]{ s0 =>
- val Pair(a, s1) = this in s0; k(a) in s1
- }
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A) = M[A](s => Pair(a, s));
-
- def showM(m: M[Value]): String = {
- val Pair(a, s1) = m in 0;
- "Value: " + a + "; Count: " + s1
- }
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => for (_ <- tickS) yield Num(m + n)
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => for (_ <- tickS; c <- k(b)) yield c
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- }
-}
-
diff --git a/docs/examples/oneplacebuffer.scala b/docs/examples/oneplacebuffer.scala
deleted file mode 100644
index f7047a1c92..0000000000
--- a/docs/examples/oneplacebuffer.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-package examples
-
-object oneplacebuffer {
-
- import scala.actors.Actor._
- import scala.concurrent.ops
-
- class OnePlaceBuffer {
- private case class Put(x: Int)
- private case object Get
-
- private val m = actor {
- var buf: Option[Int] = None
- loop {
- react {
- case Put(x) if buf.isEmpty =>
- println("put "+x);
- buf = Some(x); reply()
- case Get if !buf.isEmpty =>
- val x = buf.get
- println("get "+x)
- buf = None; reply(x)
- }
- }
- }
- m.start()
-
- def write(x: Int) { m !? Put(x) }
-
- def read(): Int = (m !? Get).asInstanceOf[Int]
- }
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() {
- println("[killed]")
- sys exit 0
- }
- },
- delay) // in milliseconds
-
- def main(args: Array[String]) {
- val buf = new OnePlaceBuffer
- val random = new java.util.Random()
-
- def producer(n: Int) {
- Thread.sleep(random nextInt 1000)
- buf write n
- producer(n + 1)
- }
-
- def consumer {
- Thread.sleep(random nextInt 1000)
- val n = buf.read()
- consumer
- }
-
- ops spawn producer(0)
- ops spawn consumer
- kill(10000)
- }
-
-}
-
diff --git a/docs/examples/parsing/ArithmeticParser.scala b/docs/examples/parsing/ArithmeticParser.scala
deleted file mode 100644
index 99cf7a5578..0000000000
--- a/docs/examples/parsing/ArithmeticParser.scala
+++ /dev/null
@@ -1,57 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2006-2011, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.parsing
-
-import scala.util.parsing.combinator.lexical.StdLexical
-import scala.util.parsing.combinator.syntactical.StdTokenParsers
-
-/** Parse and evaluate a numeric expression as a sequence of terms, separated by + or -
- * a term is a sequence of factors, separated by * or /
- * a factor is a parenthesized expression or a number
- *
- * @author Adriaan Moors
- */
-object arithmeticParser extends StdTokenParsers {
- type Tokens = StdLexical ; val lexical = new StdLexical
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- lazy val expr = term*("+" ^^^ {(x: int, y: int) => x + y} | "-" ^^^ {(x: int, y: int) => x - y})
- lazy val term = factor*("*" ^^^ {(x: int, y: int) => x * y} | "/" ^^^ {(x: int, y: int) => x / y})
- lazy val factor: Parser[int] = "(" ~> expr <~ ")" | numericLit ^^ (_.toInt)
-
- def main(args: Array[String]) {
- println(
- if (args.length == 1) {
- expr(new lexical.Scanner(args(0)))
- }
- else
- "usage: scala examples.parsing.arithmeticParser <expr-string>"
- )
- }
-}
-
-
-object arithmeticParserDesugared extends StdTokenParsers {
- type Tokens = StdLexical ; val lexical = new StdLexical
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- lazy val expr = chainl1(term, (keyword("+").^^^{(x: int, y: int) => x + y}).|(keyword("-").^^^{(x: int, y: int) => x - y}))
- lazy val term = chainl1(factor, (keyword("*").^^^{(x: int, y: int) => x * y}).|(keyword("/").^^^{(x: int, y: int) => x / y}))
- lazy val factor: Parser[int] = keyword("(").~>(expr.<~(keyword(")"))).|(numericLit.^^(x => x.toInt))
-
- def main(args: Array[String]) {
- println(
- if (args.length == 1) {
- expr(new lexical.Scanner(args(0)))
- }
- else
- "usage: scala examples.parsing.arithmeticParser <expr-string>"
- )
- }
-}
diff --git a/docs/examples/parsing/ArithmeticParsers.scala b/docs/examples/parsing/ArithmeticParsers.scala
deleted file mode 100644
index 62d7a61862..0000000000
--- a/docs/examples/parsing/ArithmeticParsers.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-package examples.parsing
-
-import scala.util.parsing.combinator1.syntactical.StandardTokenParsers
-
-object ArithmeticParsers extends StandardTokenParsers {
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- def expr: Parser[Any] = term ~ rep("+" ~ term | "-" ~ term)
- def term = factor ~ rep("*" ~ factor | "/" ~ factor)
- def factor: Parser[Any] = "(" ~ expr ~ ")" | numericLit
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
-
-object ArithmeticParsers1 extends StandardTokenParsers {
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- val reduceList: Int ~ List[String ~ Int] => Int = {
- case i ~ ps => (i /: ps)(reduce)
- }
-
- def reduce(x: Int, r: String ~ Int) = (r: @unchecked) match {
- case "+" ~ y => x + y
- case "-" ~ y => x - y
- case "*" ~ y => x * y
- case "/" ~ y => x / y
- }
-
- def expr : Parser[Int] = term ~ rep ("+" ~ term | "-" ~ term) ^^ reduceList
- def term : Parser[Int] = factor ~ rep ("*" ~ factor | "/" ~ factor) ^^ reduceList
- def factor: Parser[Int] = "(" ~> expr <~ ")" | numericLit ^^ (_.toInt)
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
-
-class Expr
-case class BinOp(op: String, l: Expr, r: Expr) extends Expr
-case class Num(n: Int) extends Expr
-
-object ArithmeticParsers2 extends StandardTokenParsers {
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- val reduceList: Expr ~ List[String ~ Expr] => Expr = {
- case i ~ ps => (i /: ps)(reduce)
- }
-
- def reduce(l: Expr, r: String ~ Expr) = BinOp(r._1, l, r._2)
- def mkNum(s: String) = Num(s.toInt)
-
- def expr : Parser[Expr] = term ~ rep ("+" ~ term | "-" ~ term) ^^ reduceList
- def term : Parser[Expr] = factor ~ rep ("*" ~ factor | "/" ~ factor) ^^ reduceList
- def factor: Parser[Expr] = "(" ~> expr <~ ")" | numericLit ^^ ((s: String) => Num(s.toInt))
-
- def main(args: Array[String]) {
- val parse = phrase(expr)
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(parse(tokens))
- }
-}
-
-
diff --git a/docs/examples/parsing/JSON.scala b/docs/examples/parsing/JSON.scala
deleted file mode 100644
index abfa242e9f..0000000000
--- a/docs/examples/parsing/JSON.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-package examples.parsing
-
-import scala.util.parsing.combinator1.syntactical.StandardTokenParsers
-
-object JSON extends StandardTokenParsers {
- lexical.delimiters += ("{", "}", "[", "]", ":", ",")
- lexical.reserved += ("null", "true", "false")
-
- def obj : Parser[Any] = "{" ~ repsep(member, ",") ~ "}"
- def arr : Parser[Any] = "[" ~ repsep(value, ",") ~ "]"
- def member: Parser[Any] = ident ~ ":" ~ value
- def value : Parser[Any] = ident | numericLit | obj | arr |
- "null" | "true" | "false"
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(value)(tokens))
- }
-}
-object JSON1 extends StandardTokenParsers {
- lexical.delimiters += ("{", "}", "[", "]", ":", ",")
- lexical.reserved += ("null", "true", "false")
-
- def obj: Parser[Map[String, Any]] =
- "{" ~> repsep(member, ",") <~ "}" ^^ (Map() ++ _)
-
- def arr: Parser[List[Any]] =
- "[" ~> repsep(value, ",") <~ "]"
-
- def member: Parser[(String, Any)] =
- ident ~ ":" ~ value ^^ { case name ~ ":" ~ value => (name -> value) }
-
- def value: Parser[Any] =
- ident | numericLit ^^ (_.toInt) | obj | arr |
- "null" ^^^ null | "true" ^^^ true | "false" ^^^ false
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(value)(tokens))
- }
-}
-
diff --git a/docs/examples/parsing/ListParser.scala b/docs/examples/parsing/ListParser.scala
deleted file mode 100644
index 59fc292c1d..0000000000
--- a/docs/examples/parsing/ListParser.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-package examples.parsing
-
-import scala.util.parsing.combinator.{Parsers, ImplicitConversions, ~, mkTilde}
-import scala.util.parsing.input.CharArrayReader
-
-object listParser {
- abstract class Tree
- case class Id(s: String) extends Tree
- case class Num(n: Int) extends Tree
- case class Lst(elems: List[Tree]) extends Tree
-
- import Character.{isLetter, isLetterOrDigit, isDigit}
- def mkString(cs: List[Any]) = cs.mkString("")
-
- class ListParsers extends Parsers {
- type Elem = Char
-
- lazy val ident = rep1(elem("letter", isLetter), elem("letter or digit", isLetterOrDigit)) ^^ {cs => Id(mkString(cs))}
- lazy val number = chainl1(elem("digit", isDigit) ^^ (_ - '0'), success{(accum: Int, d: Int) => accum * 10 + d}) ^^ Num
- lazy val list = '(' ~> repsep(expr, ',') <~ ')' ^^ Lst
- lazy val expr: Parser[Tree] = list | ident | number
- }
-
- def main(args: Array[String]) {
- println(
- if (args.length == 1) {
- (new ListParsers).expr(new CharArrayReader(args(0).toCharArray()))
- }
- else
- "usage: scala examples.parsing.listParser <list-string>"
- )
- }
-}
diff --git a/docs/examples/parsing/ListParsers.scala b/docs/examples/parsing/ListParsers.scala
deleted file mode 100644
index b449c4a641..0000000000
--- a/docs/examples/parsing/ListParsers.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-package examples.parsing
-
-import scala.util.parsing.combinator1.syntactical.StandardTokenParsers
-
-object ListParsers extends StandardTokenParsers {
- lexical.delimiters ++= List("(", ")", ",")
-
- def expr: Parser[Any] = "(" ~ exprs ~ ")" | ident | numericLit
- def exprs: Parser[Any] = expr ~ rep ("," ~ expr)
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
-
-object ListParsers1 extends StandardTokenParsers {
- lexical.delimiters ++= List("(", ")", ",")
-
- def expr: Parser[Any] = "(" ~> exprs <~ ")" | ident | numericLit
-
- def exprs: Parser[List[Any]] = expr ~ rep ("," ~> expr) ^^ { case x ~ y => x :: y }
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
diff --git a/docs/examples/parsing/MiniML.scala b/docs/examples/parsing/MiniML.scala
deleted file mode 100644
index f7f7172e8d..0000000000
--- a/docs/examples/parsing/MiniML.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-package examples.parsing
-
-import scala.util.parsing.combinator1.syntactical.StandardTokenParsers
-import scala.util.parsing.combinator1.syntactical.StandardTokenParsers
-
-object MiniML extends StandardTokenParsers {
- lexical.delimiters += ("(", ")", ".", "=")
- lexical.reserved += ("lambda", "let", "in")
-
- def expr: Parser[Any] = (
- "let" ~ ident ~ "=" ~ expr ~ "in" ~ expr
- | "lambda" ~ ident ~ "." ~ expr
- | simpleExpr ~ rep(expr)
- )
- def simpleExpr: Parser[Any] = (
- ident
- | "(" ~ expr ~ ")"
- )
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
-
-class Expr
-case class Let(x: String, expr: Expr, body: Expr) extends Expr
-case class Lambda(x: String, expr: Expr) extends Expr
-case class Apply(fun: Expr, arg: Expr) extends Expr
-case class Var(x: String) extends Expr
-
-object MiniML1 extends StandardTokenParsers {
- lexical.delimiters += ("(", ")", ".", "=")
- lexical.reserved += ("lambda", "let", "in")
-
- def expr: Parser[Expr] = (
- "let" ~ ident ~ "=" ~ expr ~ "in" ~ expr ^^ { case "let" ~ x ~ "=" ~ e ~ "in" ~ b => Let(x, e, b) }
- | "lambda" ~ ident ~ "." ~ expr ^^ { case "lambda" ~ x ~ "." ~ e => Lambda(x, e) }
- | simpleExpr ~ rep(expr) ^^ { case f ~ as => (f /: as) (Apply) }
- )
- def simpleExpr: Parser[Expr] = (
- ident ^^ { Var }
- | "(" ~> expr <~ ")"
- )
-
- def main(args: Array[String]) {
- val tokens = new lexical.Scanner(args(0))
- println(args(0))
- println(phrase(expr)(tokens))
- }
-}
diff --git a/docs/examples/parsing/lambda/Main.scala b/docs/examples/parsing/lambda/Main.scala
deleted file mode 100644
index 165e82b670..0000000000
--- a/docs/examples/parsing/lambda/Main.scala
+++ /dev/null
@@ -1,34 +0,0 @@
-package examples.parsing.lambda
-
-import scala.util.parsing.combinator.Parsers
-import scala.util.parsing.input.StreamReader
-
-import java.io.File
-import java.io.FileInputStream
-import java.io.InputStreamReader
-
-/**
- * Parser for an untyped lambda calculus
- *
- * Usage: scala examples.parsing.lambda.Main <file>
- *
- * (example files: see test/ *.kwi)
- *
- * @author Miles Sabin (adapted slightly by Adriaan Moors)
- */
-object Main extends Application with TestParser
-{
- override def main(args: Array[String]) =
- {
- val in = StreamReader(new InputStreamReader(new FileInputStream(new File(args(0))), "ISO-8859-1"))
- parse(in) match
- {
- case Success(term, _) =>
- {
- Console.println("Term: \n"+term)
- }
- case Failure(msg, remainder) => Console.println("Failure: "+msg+"\n"+"Remainder: \n"+remainder.pos.longString)
- case Error(msg, remainder) => Console.println("Error: "+msg+"\n"+"Remainder: \n"+remainder.pos.longString)
- }
- }
-}
diff --git a/docs/examples/parsing/lambda/TestParser.scala b/docs/examples/parsing/lambda/TestParser.scala
deleted file mode 100644
index d26589da1b..0000000000
--- a/docs/examples/parsing/lambda/TestParser.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-package examples.parsing.lambda
-
-import scala.util.parsing.input.Reader
-import scala.util.parsing.combinator.lexical.StdLexical
-import scala.util.parsing.combinator.syntactical.StdTokenParsers
-import scala.util.parsing.combinator.ImplicitConversions
-
-/**
- * Parser for an untyped lambda calculus
- *
- * @author Miles Sabin (adapted slightly by Adriaan Moors)
- */
-trait TestParser extends StdTokenParsers with ImplicitConversions with TestSyntax
-{
- type Tokens = StdLexical
- val lexical = new StdLexical
- lexical.reserved ++= List("unit", "let", "in", "if", "then", "else")
- lexical.delimiters ++= List("=>", "->", "==", "(", ")", "=", "\\", "+", "-", "*", "/")
-
-
- def name : Parser[Name] = ident ^^ Name
-
- // meaning of the arguments to the closure during subsequent iterations
- // (...(expr2 op1 expr1) ... op1 expr1)
- // ^a^^^ ^o^ ^b^^^
- // ^^^^^^^a^^^^^^^ ^o^ ^^b^^
- def expr1 : Parser[Term] =
- chainl1(expr2, expr1, op1 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})
-
- def expr2 : Parser[Term] =
- chainl1(expr3, expr2, op2 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})
-
- def expr3 : Parser[Term] =
- chainl1(expr4, expr3, op3 ^^ {o => (a: Term, b: Term) => App(App(o, a), b)})
-
- def expr4 : Parser[Term] =
- ( "\\" ~> lambdas
- | ("let" ~> name) ~ ("=" ~> expr1) ~ ("in" ~> expr1) ^^ flatten3(Let)
- | ("if" ~> expr1) ~ ("then" ~> expr1) ~ ("else" ~> expr1) ^^ flatten3(If)
- | chainl1(aexpr, success(App(_: Term, _: Term)))
- )
-
- def lambdas : Parser[Term] =
- name ~ ("->" ~> expr1 | lambdas) ^^ flatten2(Lam)
-
- def aexpr : Parser[Term] =
- ( numericLit ^^ (_.toInt) ^^ Lit
- | name ^^ Ref
- | "unit" ^^^ Unit()
- | "(" ~> expr1 <~ ")"
- )
-
- def op1 : Parser[Term] =
- "==" ^^^ Ref(Name("=="))
-
- def op2 : Parser[Term] =
- ( "+" ^^^ Ref(Name("+"))
- | "-" ^^^ Ref(Name("-"))
- )
-
- def op3 : Parser[Term] =
- ( "*" ^^^ Ref(Name("*"))
- | "/" ^^^ Ref(Name("/"))
- )
-
- def parse(r: Reader[char]) : ParseResult[Term] =
- phrase(expr1)(new lexical.Scanner(r))
-}
diff --git a/docs/examples/parsing/lambda/TestSyntax.scala b/docs/examples/parsing/lambda/TestSyntax.scala
deleted file mode 100644
index 7edca6ccdc..0000000000
--- a/docs/examples/parsing/lambda/TestSyntax.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-package examples.parsing.lambda
-
-/**
- * Parser for an untyped lambda calculus: abstract syntax tree
- *
- * @author Miles Sabin (adapted slightly by Adriaan Moors)
- */
-trait TestSyntax
-{
- trait Term
-
- case class Unit extends Term
- {
- override def toString = "unit"
- }
-
- case class Lit(n: int) extends Term
- {
- override def toString = n.toString
- }
-
- case class Bool(b: boolean) extends Term
- {
- override def toString = b.toString
- }
-
- case class Name(name: String) extends Term
- {
- override def toString = name
- }
-
- case class Ref(n: Name) extends Term
- {
- def value = n
- }
-
- case class Lam(n: Name, l: Term) extends Term
- {
- override def toString = "(\\ "+n+" -> "+l+")"
- }
-
- case class App(t1: Term, t2: Term) extends Term
- {
- override def toString = "("+t1+" "+t2+")"
- }
-
- case class Let(n: Name, t1: Term, t2: Term) extends Term
- {
- override def toString = "let "+n+" = "+t1+" in "+t2
- }
-
- case class If(c: Term, t1: Term, t2: Term) extends Term
- {
- override def toString = "if "+c+" then "+t1+" else "+t2
- }
-
- trait PrimTerm extends Term
- {
- def apply(n: Lit) : Term
- }
-
- case class PrimPlus extends PrimTerm
- {
- def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n+y.n) }
- }
-
- case class PrimMinus extends PrimTerm
- {
- def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n-y.n) }
- }
-
- case class PrimMultiply extends PrimTerm
- {
- def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n*y.n) }
- }
-
- case class PrimDivide extends PrimTerm
- {
- def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Lit(x.n/y.n) }
- }
-
- case class PrimEquals extends PrimTerm
- {
- def apply(x: Lit) = new PrimTerm { def apply(y: Lit) = Bool(x.n == y.n) }
- }
-}
diff --git a/docs/examples/parsing/lambda/test/test-01.kwi b/docs/examples/parsing/lambda/test/test-01.kwi
deleted file mode 100644
index 9833d10673..0000000000
--- a/docs/examples/parsing/lambda/test/test-01.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let x = 23 in (\y z -> x+y+z) 1 2
diff --git a/docs/examples/parsing/lambda/test/test-02.kwi b/docs/examples/parsing/lambda/test/test-02.kwi
deleted file mode 100644
index 11198c6fc9..0000000000
--- a/docs/examples/parsing/lambda/test/test-02.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let f = (\x y -> x*y) in f 2 3
diff --git a/docs/examples/parsing/lambda/test/test-03.kwi b/docs/examples/parsing/lambda/test/test-03.kwi
deleted file mode 100644
index d4515d7297..0000000000
--- a/docs/examples/parsing/lambda/test/test-03.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let f = (\x y -> x*y) in f (f 1 2) 3
diff --git a/docs/examples/parsing/lambda/test/test-04.kwi b/docs/examples/parsing/lambda/test/test-04.kwi
deleted file mode 100644
index e54c45457a..0000000000
--- a/docs/examples/parsing/lambda/test/test-04.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let fact = \x -> if x == 0 then 1 else x*(fact (x-1)) in unit
diff --git a/docs/examples/parsing/lambda/test/test-05.kwi b/docs/examples/parsing/lambda/test/test-05.kwi
deleted file mode 100644
index 0b95d67846..0000000000
--- a/docs/examples/parsing/lambda/test/test-05.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let fact = \x -> if x == 0 then 1 else x*(fact (x-1)) in fact 6
diff --git a/docs/examples/parsing/lambda/test/test-06.kwi b/docs/examples/parsing/lambda/test/test-06.kwi
deleted file mode 100644
index 47723dc998..0000000000
--- a/docs/examples/parsing/lambda/test/test-06.kwi
+++ /dev/null
@@ -1 +0,0 @@
-2*3+4*5 == 26
diff --git a/docs/examples/parsing/lambda/test/test-07.kwi b/docs/examples/parsing/lambda/test/test-07.kwi
deleted file mode 100644
index 14fba0d66a..0000000000
--- a/docs/examples/parsing/lambda/test/test-07.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let fix = \f -> f(fix f) in unit
diff --git a/docs/examples/parsing/lambda/test/test-08.kwi b/docs/examples/parsing/lambda/test/test-08.kwi
deleted file mode 100644
index 7166d154f0..0000000000
--- a/docs/examples/parsing/lambda/test/test-08.kwi
+++ /dev/null
@@ -1 +0,0 @@
-let fix = (\f -> f(fix f)) in (fix (\g n -> if n == 0 then 1 else n*(g(n-1)))) 5
diff --git a/docs/examples/patterns.scala b/docs/examples/patterns.scala
deleted file mode 100644
index 738deabc66..0000000000
--- a/docs/examples/patterns.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-package examples
-
-object patterns {
-
- trait Tree
- case class Branch(left: Tree, right: Tree) extends Tree
- case class Leaf(x: Int) extends Tree
-
- val tree1 = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4)))
-
- def sumLeaves(t: Tree): Int = t match {
- case Branch(l, r) => sumLeaves(l) + sumLeaves(r)
- case Leaf(x) => x
- }
-
- def find[a,b](it: Iterator[Pair[a, b]], x: a): Option[b] = {
- var result: Option[b] = None
- var found = false
- while (it.hasNext && !found) {
- val Pair(x1, y) = it.next
- if (x == x1) { found = true; result = Some(y) }
- }
- result
- }
-
- def printFinds[a](xs: List[Pair[a, String]], x: a) =
- find(xs.iterator, x) match {
- case Some(y) => System.out.println(y)
- case None => System.out.println("no match")
- }
-
- def main(args: Array[String]) {
- println("sum of leafs=" + sumLeaves(tree1))
- printFinds(List(Pair(3, "three"), Pair(4, "four")), 4)
- }
-}
diff --git a/docs/examples/pilib/elasticBuffer.scala b/docs/examples/pilib/elasticBuffer.scala
deleted file mode 100644
index 5fec96ab6c..0000000000
--- a/docs/examples/pilib/elasticBuffer.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-package examples.pilib
-
-object elasticBuffer {
-
- import scala.concurrent.pilib._
-
- /**
- * Recursive type for channels that carry a "String" channel and
- * an object of the type we define.
- */
- class MetaChan extends Chan[Pair[Chan[String], MetaChan]]
-
- def Buffer(put: Chan[String], get: Chan[String]): Unit = {
-
- /**
- * An empty buffer cell, ready to pass on (o,r) to the left.
- */
- def Bl(i:Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan): unit =
- choice (
- l(Pair(o,r)) * (System.out.println("Removed one cell.")),
- i * (inp => Cl(i, l, o, r, inp))
- )
-
- /**
- * A buffer cell containing a value, ready to receive (o,r) from the right.
- */
- def Cl(i: Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan, content: String): Unit =
- choice (
- o(content) * (Bl(i,l,o,r)),
- i * (inp => Dl(i,l,o,r,content, inp)),
- r * ( { case Pair(newo, newr) => Cl(i,l,newo,newr,content) })
- )
-
- /**
- * Two joined buffer cells, of type Cl
- */
- def Dl(i: Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan,
- content: String, inp: String): Unit = {
- val newlr = new MetaChan
- val newio = new Chan[String]
- spawn < Cl(i, l, newio, newlr, inp) | Cl(newio, newlr, o, r, content) >
- }
-
- // l and r channels for the leftmost and rightmost cell, respectively.
- val unused1 = new MetaChan
- val unused2 = new MetaChan
-
- Bl(put, unused1, get, unused2)
- }
-
- val random = new java.util.Random()
-
- def Producer(n: int, put: Chan[String]): Unit = {
- Thread.sleep(1 + random.nextInt(1000))
- val msg = "object " + n
- put.write(msg)
- System.out.println("Producer gave " + msg)
- Producer(n + 1, put)
- }
-
- def Consumer(get: Chan[String]): Unit = {
- Thread.sleep(1 + random.nextInt(1000))
- val msg = get.read
- System.out.println("Consumer took " + msg)
- Consumer(get)
- }
-
- def main(args: Array[String]): Unit = {
- val put = new Chan[String]
- val get = new Chan[String]
- spawn < Producer(0, put) | Consumer(get) | Buffer(put, get) >
- }
-
-}
diff --git a/docs/examples/pilib/handover.scala b/docs/examples/pilib/handover.scala
deleted file mode 100644
index c9b6156c2c..0000000000
--- a/docs/examples/pilib/handover.scala
+++ /dev/null
@@ -1,186 +0,0 @@
-package examples.pilib
-
-/**
- * Handover example with recursive types for channels.
- */
-object handoverRecursive {
-
- import concurrent.pilib._
-
- val random = new java.util.Random()
-
- /**
- * Recursive type for channels that carry a channel "unit" and
- * an object of the type we define.
- */
- class Switch extends Chan[Pair[Chan[unit], Switch]]
-
- /**
- * Car.
- */
- def Car(talk: Chan[unit], switch: Switch): unit =
- choice (
- switch * ({ case Pair(t,s) => Car(t, s) }),
- talk(()) * ( {
- Thread.sleep(1 + random.nextInt(1000));
- System.out.println("Car emitted a message.");
- Car(talk, switch)
- })
- );
-
- /**
- * Control center.
- */
- def Control(talk1: Chan[unit], switch1: Switch,
- gain1: Switch, lose1: Switch,
- talk2: Chan[unit], switch2: Switch,
- gain2: Switch, lose2: Switch): unit
- = {
- def Control1: unit= {
- Thread.sleep(1 + random.nextInt(1000));
- lose1.write(Pair(talk2, switch2));
- gain2.write(Pair(talk2, switch2));
- Control2
- }
- def Control2: unit = {
- Thread.sleep(1 + random.nextInt(1000));
- lose2.write(Pair(talk1, switch1));
- gain1.write(Pair(talk1, switch1));
- Control1
- }
- Control1
- }
-
- /**
- * Active transmitter.
- */
- def ActiveTransmitter(id: String, talk: Chan[unit], switch: Switch,
- gain: Switch, lose: Switch): unit
- =
- choice (
- talk * (x => {
- System.out.println(id + " received a message.")
- ActiveTransmitter(id, talk, switch, gain, lose)
- }),
- lose * ({ case Pair(t, s) => {
- switch.write(Pair(t, s))
- IdleTransmitter(id, gain, lose)
- }})
- );
-
- /**
- * Idle transmitter.
- */
- def IdleTransmitter(id: String, gain: Switch, lose: Switch): unit = {
- val Pair(t, s) = gain.read;
- ActiveTransmitter(id, t, s, gain, lose)
- }
-
- def main(args: Array[String]): unit = {
- val talk1 = new Chan[unit]
- val switch1 = new Switch
- val gain1 = new Switch
- val lose1 = new Switch
- val talk2 = new Chan[unit]
- val switch2 = new Switch
- val gain2 = new Switch
- val lose2 = new Switch
- spawn <
- Car(talk1, switch1) |
- ActiveTransmitter("Transmitter 1", talk1, switch1, gain1, lose1) |
- IdleTransmitter("Transmitter 2", gain2, lose2) |
- Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2) >
- }
-}
-
-/**
-* Handover example with type casts.
-*/
-object handoverCast {
-
- import concurrent.pilib._;
-
- val random = new java.util.Random();
-
- /**
- * Car.
- */
- def Car(talk: Chan[Any], switch: Chan[Any]): unit =
- choice (
- switch * (o => {
- val Pair(t,s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]];
- Car(t, s)
- }),
- talk(()) * ( {
- Thread.sleep(1 + random.nextInt(1000));
- System.out.println("Car emitted a message.");
- Car(talk, switch)
- })
- );
-
- /**
- * Control center.
- */
- def Control(talk1: Chan[Any], switch1: Chan[Any],
- gain1: Chan[Any], lose1: Chan[Any],
- talk2: Chan[Any], switch2: Chan[Any],
- gain2: Chan[Any], lose2: Chan[Any]): unit
- = {
- def Control1: unit = {
- Thread.sleep(1 + random.nextInt(1000));
- lose1.write(Pair(talk2, switch2));
- gain2.write(Pair(talk2, switch2));
- Control2
- }
- def Control2: unit = {
- Thread.sleep(1 + random.nextInt(1000));
- lose2.write(Pair(talk1, switch1));
- gain1.write(Pair(talk1, switch1));
- Control1
- }
- Control1
- }
-
- /**
- * Active transmitter.
- */
- def ActiveTransmitter(id: String, talk: Chan[Any], switch: Chan[Any],
- gain: Chan[Any], lose: Chan[Any]): unit
- =
- choice (
- talk * (x => {
- System.out.println(id + " received a message.")
- ActiveTransmitter(id, talk, switch, gain, lose)
- }),
- lose * (o => {
- val Pair(t, s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]]
- switch.write(Pair(t, s))
- IdleTransmitter(id, gain, lose)
- })
- )
-
- /**
- * Idle transmitter.
- */
- def IdleTransmitter(id: String, gain: Chan[Any], lose: Chan[Any]): unit = {
- val Pair(t, s) = gain.read.asInstanceOf[Pair[Chan[Any],Chan[Any]]]
- ActiveTransmitter(id, t, s, gain, lose)
- }
-
- def main(args: Array[String]): unit = {
- val talk1 = new Chan[Any]
- val switch1 = new Chan[Any]
- val gain1 = new Chan[Any]
- val lose1 = new Chan[Any]
- val talk2 = new Chan[Any]
- val switch2 = new Chan[Any]
- val gain2 = new Chan[Any]
- val lose2 = new Chan[Any]
- spawn <
- Car(talk1, switch1) |
- ActiveTransmitter("Transmitter 1", talk1, switch1, gain1, lose1) |
- IdleTransmitter("Transmitter 2", gain2, lose2) |
- Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2) >
- }
-
-}
diff --git a/docs/examples/pilib/mobilePhoneProtocol.scala b/docs/examples/pilib/mobilePhoneProtocol.scala
deleted file mode 100644
index e8c0ac1dc4..0000000000
--- a/docs/examples/pilib/mobilePhoneProtocol.scala
+++ /dev/null
@@ -1,172 +0,0 @@
-package examples.pilib
-
-/**
-* Mobile phone protocol.
-* Equivalent to a three-place buffer.
-* @see Bjoern Victor "A verification tool for the polyadic pi-calculus".
-*/
-object mobilePhoneProtocol {
-
- import concurrent.pilib._
-
- val random = new java.util.Random()
-
- // Internal messages exchanged by the protocol.
- trait Message
-
- // Predefined messages used by the protocol.
- case class Data() extends Message;
- case class HoCmd() extends Message; // handover command
- case class HoAcc() extends Message; // handover access
- case class HoCom() extends Message; // handover complete
- case class HoFail() extends Message; // handover fail
- case class ChRel() extends Message; // release
- case class Voice(s: String) extends Message; // voice
- case class Channel(n: Chan[Message]) extends Message; // channel
-
- def MobileSystem(in: Chan[String], out: Chan[String]): unit = {
-
- def CC(fa: Chan[Message], fp: Chan[Message], l: Chan[Channel]): unit =
- choice (
- in * (v => { fa.write(Data()); fa.write(Voice(v)); CC(fa, fp, l) })
- ,
- l * (m_new => {
- fa.write(HoCmd());
- fa.write(m_new);
- choice (
- fp * ({ case HoCom() => {
- System.out.println("Mobile has moved from one cell to another");
- fa.write(ChRel());
- val Channel(m_old) = fa.read;
- l.write(Channel(m_old));
- CC(fp, fa, l)
- }})
- ,
- fa * ({ case HoFail() => {
- System.out.println("Mobile has failed to move from one cell to another");
- l.write(m_new);
- CC(fa, fp, l)
- }})
- )
- })
- );
-
- /*
- * Continuously orders the MSC to switch the MS to the non-used BS.
- */
- def HC(l: Chan[Channel], m: Chan[Message]): unit = {
- Thread.sleep(1 + random.nextInt(1000));
- l.write(Channel(m));
- val Channel(m_new) = l.read;
- HC(l, m_new)
- }
-
- /**
- * Mobile switching center.
- */
- def MSC(fa: Chan[Message], fp: Chan[Message], m: Chan[Message]): unit = {
- val l = new Chan[Channel];
- spawn < HC(l, m) | CC(fa, fp, l) >
- }
-
- /**
- * Active base station.
- */
- def BSa(f: Chan[Message], m: Chan[Message]): unit =
- (f.read) match {
- case Data() => {
- val v = f.read;
- m.write(Data());
- m.write(v);
- BSa(f, m)
- }
- case HoCmd() => {
- val v = f.read;
- m.write(HoCmd());
- m.write(v);
- choice (
- f * ({ case ChRel() => {
- f.write(Channel(m));
- BSp(f, m)
- }})
- ,
- m * ({ case HoFail() => {
- f.write(HoFail());
- BSa(f, m)
- }})
- )
- }
- };
-
- /**
- * Passive base station.
- */
- def BSp(f: Chan[Message], m: Chan[Message]): unit = {
- val HoAcc = m.read
- f.write(HoCom())
- BSa(f, m)
- }
-
- /**
- * Mobile station.
- */
- def MS(m: Chan[Message]): unit =
- (m.read) match {
- case Data() => {
- val Voice(v) = m.read;
- out.write(v);
- MS(m)
- }
- case HoCmd() =>
- (m.read) match {
- case Channel(m_new) => {
- if (random.nextInt(1) == 0)
- choice ( m_new(HoAcc()) * (MS(m_new)) );
- else
- choice ( m(HoFail()) * (MS(m)) );
- }
- }
- };
-
- def P(fa: Chan[Message], fp: Chan[Message]): unit = {
- val m = new Chan[Message];
- spawn < MSC(fa, fp, m) | BSp(fp, m) >
- }
-
- def Q(fa: Chan[Message]): unit = {
- val m = new Chan[Message];
- spawn < BSa(fa, m) | MS(m) >
- }
-
- val fa = new Chan[Message];
- val fp = new Chan[Message];
- spawn < Q(fa) | P(fa, fp) >;
- }
-
- //***************** Entry function ******************//
-
- def main(args: Array[String]): unit = {
-
- def Producer(n: Int, put: Chan[String]): unit = {
- Thread.sleep(1 + random.nextInt(1000));
- val msg = "object " + n;
- put.write(msg);
- System.out.println("Producer gave " + msg);
- Producer(n + 1, put)
- }
-
- def Consumer(get: Chan[String]): unit = {
- Thread.sleep(1 + random.nextInt(1000));
- val msg = get.read;
- System.out.println("Consumer took " + msg);
- Consumer(get)
- }
-
- val put = new Chan[String];
- val get = new Chan[String];
- spawn < Producer(0, put) | Consumer(get) | MobileSystem(put, get) >
- }
-
-}
-
-
diff --git a/docs/examples/pilib/piNat.scala b/docs/examples/pilib/piNat.scala
deleted file mode 100644
index a1a0e682e1..0000000000
--- a/docs/examples/pilib/piNat.scala
+++ /dev/null
@@ -1,89 +0,0 @@
-package examples.pilib
-
-import scala.concurrent.pilib._
-
-/** Church encoding of naturals in the Pi-calculus */
-object piNat extends Application {
-
- /** Locations of Pi-calculus natural */
- class NatChan extends Chan[Triple[Chan[Unit], Chan[NatChan], Chan[NatChan]]]
-
- /** Zero */
- def Z(l: NatChan): Unit = choice (
- l * { case Triple(z, sd, d) => z.write(()) }
- )
-
- /** Successor of Double */
- def SD(n: NatChan, l: NatChan): Unit = choice (
- l * { case Triple(z, sd, d) => sd.write(n) }
- )
-
- /** Double */
- def D(n: NatChan, l: NatChan): Unit = choice (
- l * { case Triple(z, sd, d) => d.write(n) }
- )
-
- /** Make "l" a location representing the natural "n" */
- def make(n: Int, l: NatChan): Unit =
- if (n == 0) Z(l)
- else if (n % 2 == 0) { val l1 = new NatChan; spawn < D(l1, l) >; make(n/2, l1) }
- else { val l1 = new NatChan; spawn < SD(l1, l) >; make(n/2, l1) }
-
- /** Consume the natural "m" and put it successor at location "n" */
- def Succ(m: NatChan, n: NatChan) {
- val z = new Chan[Unit]
- val sd = new Chan[NatChan]
- val d = new Chan[NatChan]
- spawn < m.write(Triple(z, sd, d)) >;
- choice (
- z * { x => make(1, n) },
- sd * { m1 => { val n1 = new NatChan; spawn < D(n1, n) >; Succ(m1, n1) } },
- d * { m1 => SD(m1, n) }
- )
- }
-
- /** Consume the natural "l" and put two copies at locations "m" and "n" */
- def Copy(l: NatChan, m: NatChan, n: NatChan) {
- val z = new Chan[Unit]
- val sd = new Chan[NatChan]
- val d = new Chan[NatChan]
- spawn < l.write(Triple(z, sd, d)) >;
- choice (
- z * { x => spawn < Z(m) >; Z(n) },
- sd * { l1 => { val m1 = new NatChan; val n1 = new NatChan;
- spawn < SD(m1, m) | SD(n1, n) >;
- Copy(l1, m1, n1) } },
- d * { l1 => { val m1 = new NatChan; val n1 = new NatChan;
- spawn < D(m1, m) | D(n1, n) >;
- Copy(l1, m1, n1) } }
- )
- }
-
- /** Consume the natural at location "n" and return its value */
- def value(n: NatChan): Int = {
- val z = new Chan[Unit]
- val sd = new Chan[NatChan]
- val d = new Chan[NatChan]
- spawn < n.write(Triple(z, sd, d)) >;
- choice (
- z * { x => 0 },
- sd * { n1 => 2 * value(n1) + 1 },
- d * { n1 => 2 * value(n1) }
- )
- }
-
- // Test
- val i = 42
- val l = new NatChan
- val l1 = new NatChan
- val l2 = new NatChan
- val l3 = new NatChan
-
- spawn <
- make(i, l) |
- Copy(l, l1, l2) |
- Succ(l2, l3) |
- println("" + i + " = " + value(l1)) |
- println("succ " + i + " = " + value(l3)) >
-
-}
diff --git a/docs/examples/pilib/rwlock.scala b/docs/examples/pilib/rwlock.scala
deleted file mode 100644
index bb1c26bdf2..0000000000
--- a/docs/examples/pilib/rwlock.scala
+++ /dev/null
@@ -1,329 +0,0 @@
-package examples.pilib
-
-/**
-* From Pi to Scala: Semaphores, monitors, read/write locks.
-* Readers/writers locks.
-*/
-object rwlock {
-
- import scala.concurrent.pilib._
-
- class Signal extends Chan[unit] {
- def send = write(())
- def receive = read
- }
-
- class CountLock {
- private val busy = new Signal
- def get = busy.send
- def release = busy.receive
- spawn < release >
- }
-
- /** A binary semaphore
- */
- class Lock {
- private val busy = new Signal;
- private val free = new Signal;
- def get = busy.send;
- def release = free.send;
- spawn < (while (true) {
- choice (
- busy * (x => free.receive),
- free * (x => ())
- )
- }) >
- }
-
- /** A monitor a la Java
- */
- class JavaMonitor {
-
- private val lock = new Lock
-
- private var waiting: List[Signal] = Nil
-
- def Wait = {
- val s = new Signal
- waiting = s :: waiting
- lock.release
- s.receive
- lock.get
- }
-
- def Notify =
- if (!waiting.isEmpty) {
- waiting.head.send
- waiting = waiting.tail
- }
-
- def NotifyAll =
- while (!waiting.isEmpty) {
- waiting.head.send
- waiting = waiting.tail
- }
-
- def await(cond: => boolean): unit =
- while (false == cond) (Wait)
- }
-
- /*
- class Buffer[a](size: Int) extends JavaMonitor with {
- var in = 0, out = 0, n = 0;
- val elems = new Array[a](size);
- def put(x: a) = synchronized {
- await(n < size);
- elems(out) = x;
- out = (out + 1) % size;
- }
- def get: a = synchronized {
- await(n > 0);
- val x = elems(in);
- in = (in + 1) % size;
- x
- }
- }
- */
-
- /** A readers/writers lock. */
- trait ReadWriteLock {
- def startRead: unit
- def startWrite: unit
- def endRead: unit
- def endWrite: unit
- }
-
- /**
- * A readers/writers lock, using monitor abstractions.
- */
- class ReadWriteLock1 extends JavaMonitor with ReadWriteLock {
-
- private var nactive: int = 0
- private var nwriters: int = 0
-
- def status =
- System.out.println(nactive + " active, " + nwriters + " writers");
-
- def startRead = synchronized {
- await(nwriters == 0)
- nactive = nactive + 1
- status
- }
-
- def startWrite = synchronized {
- nwriters = nwriters + 1
- await(nactive == 0)
- nactive = 1
- status
- }
-
- def endRead = synchronized {
- nactive = nactive - 1
- if (nactive == 0) NotifyAll
- status
- }
-
- def endWrite = synchronized {
- nwriters = nwriters - 1
- nactive = 0
- NotifyAll
- status
- }
- }
-
- /** A readers/writers lock, using semaphores
- */
- class ReadWriteLock2 extends ReadWriteLock {
-
- private var rc: int = 0 // reading readers
- private var wc: int = 0 // writing writers
- private var rwc: int = 0 // waiting readers
- private var wwc: int = 0 // waiting writers
- private val mutex = new Lock
- private val rsem = new Lock
- private val wsem = new Lock
-
- def startRead = {
- mutex.get;
- if (wwc > 0 || wc > 0) {
- rwc = rwc + 1;
- mutex.release;
- rsem.get;
- rwc = rwc - 1
- }
- rc = rc + 1;
- if (rwc > 0) rsem.release;
- mutex.release
- }
-
- def startWrite = {
- mutex.get;
- if (rc > 0 || wc > 0) {
- wwc = wwc + 1;
- mutex.release;
- wsem.get;
- wwc = wwc - 1
- }
- wc = wc + 1;
- mutex.release
- }
-
- def endRead = {
- mutex.get;
- rc = rc - 1;
- if (rc == 0 && wwc > 0) wsem.release;
- mutex.release
- }
-
- def endWrite = {
- mutex.get;
- wc = wc - 1;
- if (rwc > 0)
- rsem.release
- else if (wwc > 0) wsem.release;
- mutex.release
- }
- }
-
- /** A readers/writers lock, using channels, without priortities
- */
- class ReadWriteLock3 extends ReadWriteLock {
-
- private val sr = new Signal
- private val er = new Signal
- private val sw = new Signal
- private val ew = new Signal
-
- def startRead = sr.send
- def startWrite = sw.send
- def endRead = er.send
- def endWrite = ew.send
-
- private def rwlock: unit = choice (
- sr * (x => reading(1)),
- sw * (x => { ew.receive; rwlock })
- )
-
- private def reading(n: int): unit = choice (
- sr * (x => reading(n+1)),
- er * (x => if (n == 1) rwlock else reading(n-1))
- )
-
- spawn < rwlock >
- }
-
- /** Same, with sequencing
- */
- class ReadWriteLock4 extends ReadWriteLock {
-
- private val rwlock = new ReadWriteLock3
-
- private val sr = new Signal
- private val ww = new Signal
- private val sw = new Signal
-
- def startRead = sr.send
- def startWrite = { ww.send; sw.send }
- def endRead = rwlock.endRead
- def endWrite = rwlock.endWrite
-
- private def queue: unit = choice (
- sr * (x => { rwlock.startRead ; queue }),
- ww * (x => { rwlock.startWrite; sw.receive; queue })
- )
-
- spawn < queue >;
- }
-
- /** Readwritelock where writers always have priority over readers
- */
- class ReadWriteLock5 extends ReadWriteLock {
-
- private val sr = new Signal
- private val er = new Signal
- private val ww = new Signal
- private val sw = new Signal
- private val ew = new Signal
-
- def startRead = sr.send
- def startWrite = { ww.send; sw.send }
- def endRead = er.send
- def endWrite = ew.send
-
- private def Reading(nr: int, nw: int): unit =
- if (nr == 0 && nw == 0)
- choice (
- sr * (x => Reading(1, 0)),
- ww * (x => Reading(0, 1))
- )
- else if (nr == 0 && nw != 0) {
- sw.receive;
- Writing(nw);
- }
- else if (nr != 0 && nw == 0)
- choice (
- sr * (x => Reading(nr + 1, 0)),
- er * (x => Reading(nr - 1, 0)),
- ww * (x => Reading(nr, 1))
- )
- else if (nr != 0 && nw != 0)
- choice (
- ww * (x => Reading(nr, nw + 1)),
- er * (x => Reading(nr - 1, nw))
- );
-
- private def Writing(nw: int): unit = choice (
- ew * (x => Reading(0, nw - 1)),
- ww * (x => Writing(nw + 1))
- );
-
- spawn < Reading(0, 0) >;
-
- }
-
- /**
- * Main function.
- */
- def main(args: Array[String]): unit = {
- val random = new java.util.Random()
-
- def reader(i: int, rwlock: ReadWriteLock): unit = {
- Thread.sleep(1 + random.nextInt(100))
- System.err.println("Reader " + i + " wants to read.")
- rwlock.startRead
- System.err.println("Reader " + i + " is reading.")
- Thread.sleep(1 + random.nextInt(100))
- rwlock.endRead
- System.err.println("Reader " + i + " has read.")
- reader(i, rwlock)
- }
-
- def writer(i: int, rwlock: ReadWriteLock): unit = {
- Thread.sleep(1 + random.nextInt(100))
- System.err.println("Writer " + i + " wants to write.")
- rwlock.startWrite
- System.err.println("Writer " + i + " is writing.")
- Thread.sleep(1 + random.nextInt(100))
- rwlock.endWrite
- System.err.println("Writer " + i + " has written.")
- writer(i, rwlock)
- }
-
- val n = try { Integer.parseInt(args(0)) } catch { case _ => 0 }
- if (n < 1 || 5 < n) {
- Console.println("Usage: scala examples.pilib.rwlock <n> (n=1..5)")
- exit
- }
- val rwlock = n match {
- case 1 => new ReadWriteLock1
- case 2 => new ReadWriteLock2
- case 3 => new ReadWriteLock3
- case 4 => new ReadWriteLock4
- case 5 => new ReadWriteLock5
- }
- List.range(0, 5) foreach (i => spawn < reader(i, rwlock) >)
- List.range(0, 5) foreach (i => spawn < writer(i, rwlock) >)
- }
-
-}
-
diff --git a/docs/examples/pilib/scheduler.scala b/docs/examples/pilib/scheduler.scala
deleted file mode 100644
index fd8fd52600..0000000000
--- a/docs/examples/pilib/scheduler.scala
+++ /dev/null
@@ -1,150 +0,0 @@
-package examples.pilib
-
-import scala.concurrent.pilib._
-
-object scheduler {
-
- /**
- * Random number generator.
- */
- val random = new util.Random()
-
- //***************** Scheduler ******************//
-
- /**
- * A cell of the scheduler whose attached agent is allowed to start.
- */
- def A(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
- ///- ... complete here ...
- choice ( a * { x => C(a, b)(d, c) })
- ///+
- }
-
- /**
- * A cell of the scheduler in another intermediate state.
- */
- def C(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
- ///- ... complete here ...
- choice (c * { x => B(a, b)(d, c) })
- ///+
- }
-
- /**
- * A cell of the scheduler whose attached agent is allowed to finish.
- */
- def B(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
- ///- ... complete here ...
- // choice (b * { x => D(a, b)(d, c) }) // incorrect naive solution
- choice (
- b * { x => choice ( d(()) * A(a, b)(d, c) ) }, // b.'d.A
- d(()) * (choice (b * { x => A(a, b)(d, c) })) // 'd.b.A
- )
- ///+
- }
-
- /**
- * A cell of the scheduler whose attached agent is not yet allowed to start.
- */
- def D(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
- ///- ... complete here ...
- choice (d(()) * A(a, b)(d, c))
- ///+
- }
-
- //***************** Agents ******************//
-
- def agent(i: Int)(a: Chan[Unit], b: Chan[Unit]) {
- // 50% chance that we sleep forever
- if (i == 0 && random.nextInt(10) < 5) {
- a.attach(x => println("Start and sleeps ----> " + i))
- Thread.sleep(random.nextInt(1000))
- a.write(())
- }
- else {
- a.attach(x => println("Start ----> " + i))
- b.attach(x => println("Stop -> " + i))
- Thread.sleep(random.nextInt(1000))
- a.write(())
- Thread.sleep(random.nextInt(1000))
- b.write(())
- agent(i)(a, b)
- }
- }
-
- //***************** Entry function ******************//
-
- /**
- * Creates a scheduler for five agents (programs).
- */
-
- def main(args: Array[String]) {
- val agentNb = 5
- val agents = List.range(0, agentNb) map agent
- scheduleAgents(agents)
- }
-
- //***************** Infrastructure *****************//
-
- /**
- * A cell is modelled as a function that takes as parameters
- * input and output channels and which returns nothing.
- */
- type Cell = (Chan[Unit], Chan[Unit]) => Unit
-
- /**
- * Creates a cell composed of two cells linked together.
- */
- def join(cell1: Cell, cell2: Cell): Cell =
- (l: Chan[Unit], r: Chan[Unit]) => {
- val link = new Chan[Unit];
- spawn < cell1(l, link) | cell2(link, r) >
- };
-
- /**
- * Links the output of a cell to its input.
- */
- def close(cell: Cell) {
- val a = new Chan[Unit]
- cell(a, a)
- }
-
- /**
- * Creates a cell consisting of a chain of cells.
- */
- def chain(cells: List[Cell]): Cell =
- cells reduceLeft join
-
- /**
- * Creates a cell consisting of a chain of cells.
- */
- def makeRing(cells: List[Cell]): Unit =
- close(chain(cells))
-
- /**
- * An agent is modelled as a function that takes as parameters channels to
- * signal that it has started or finished.
- */
- type Agent = (Chan[Unit], Chan[Unit]) => Unit
-
- /**
- * Takes a list of agents and schedules them.
- */
- def scheduleAgents(agents: List[Agent]) {
- var firstAgent = true;
- val cells = agents map (ag => {
- val a = new Chan[Unit];
- val b = new Chan[Unit];
- spawn < ag(a, b) >;
- (d: Chan[Unit], c: Chan[Unit]) => if (firstAgent) {
- firstAgent = false;
- A(a, b)(d, c)
- }
- else
- D(a, b)(d, c)
- });
- makeRing(cells)
- }
-
-}
-
-
diff --git a/docs/examples/pilib/semaphore.scala b/docs/examples/pilib/semaphore.scala
deleted file mode 100644
index 951c90e8d4..0000000000
--- a/docs/examples/pilib/semaphore.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-package examples.pilib
-
-import scala.concurrent.pilib._
-
-/** Solution of exercise session 6 (first question). */
-object semaphore {
-
- class Signal extends Chan[Unit] {
- def send = write(())
- def receive = read
- }
-
- /** Interface. */
- trait Semaphore {
- def get: Unit
- def release: Unit
- }
-
- /** First implementation. */
- class Sem1 extends Semaphore {
-
- private val g = new Signal
- private val r = new Signal
-
- def get: Unit = g.send
- def release: Unit = r.send
-
- private def Sched: Unit = choice (
- g * (x => { r.receive; Sched }),
- r * (x => Sched)
- )
- spawn< Sched >
- }
-
- /** Second implementation. */
- class Sem2 extends Semaphore {
-
- private val a = new Signal
- private val na = new Signal
-
- def get { a.receive; spawn< na.send > }
- def release: Unit = choice (
- a * (x => spawn< a.send >),
- na * (x => spawn< a.send >)
- )
- spawn< a.send >
- }
-
- /** Test program. */
- def main(args: Array[String]) {
- val random = new util.Random()
- val sem = new Sem2
- def mutex(p: => Unit) { sem.get; p; sem.release }
-
- spawn< {
- Thread.sleep(1 + random.nextInt(100));
- mutex( {
- println("a1");
- Thread.sleep(1 + random.nextInt(100));
- println("a2")
- } )
- } | {
- Thread.sleep(1 + random.nextInt(100));
- mutex( {
- println("b1");
- Thread.sleep(1 + random.nextInt(100));
- println("b2")
- } )
- } >;
- }
-}
-
diff --git a/docs/examples/pilib/twoPlaceBuffer.scala b/docs/examples/pilib/twoPlaceBuffer.scala
deleted file mode 100644
index 255f70ca06..0000000000
--- a/docs/examples/pilib/twoPlaceBuffer.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-package examples.pilib
-
-import scala.concurrent.pilib._
-
-/** Two-place buffer specification and implementation. */
-object twoPlaceBuffer extends Application {
-
- /**
- * Specification.
- */
- def Spec[A](in: Chan[A], out: Chan[A]) {
-
- def B0: Unit = choice (
- in * (x => B1(x))
- )
-
- def B1(x: A): Unit = choice (
- out(x) * (B0),
- in * (y => B2(x, y))
- )
-
- def B2(x: A, y: A): Unit = choice (
- out(x) * (B1(y))
- )
-
- B0
- }
-
- /**
- * Implementation using two one-place buffers.
- */
- def Impl[A](in: Chan[A], out: Chan[A]) {
- ///- ... complete here ...
- // one-place buffer
- def OnePlaceBuffer[A](in: Chan[A], out: Chan[A]) {
- def B0: Unit = choice ( in * (x => B1(x)) )
- def B1(x: A): Unit = choice ( out(x) * (B0))
- B0
- }
- val hidden = new Chan[A]
- spawn < OnePlaceBuffer(in, hidden) | OnePlaceBuffer(hidden, out) >
- ///+
- }
-
- val random = new util.Random()
-
- def Producer(n: Int, in: Chan[String]) {
- Thread.sleep(random.nextInt(1000))
- val msg = "" + n
- choice (in(msg) * {})
- Producer(n + 1, in)
- }
-
- def Consumer(out: Chan[String]) {
- Thread.sleep(random.nextInt(1000))
- choice (out * { msg => () })
- Consumer(out)
- }
-
- val in = new Chan[String]
- in.attach(s => println("put " + s))
- val out = new Chan[String]
- out.attach(s => println("get " + s))
- //spawn < Producer(0, in) | Consumer(out) | Spec(in, out) >
- spawn < Producer(0, in) | Consumer(out) | Impl(in, out) >
-
-}
diff --git a/docs/examples/plugintemplate/.classpath b/docs/examples/plugintemplate/.classpath
deleted file mode 100644
index e9069639ae..0000000000
--- a/docs/examples/plugintemplate/.classpath
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="doc/examples"/>
- <classpathentry kind="src" path="test"/>
- <classpathentry kind="con" path="ch.epfl.lamp.sdt.launching.SCALA_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="lib" path="/Applications/eclipse-3.4M6a/plugins/ch.epfl.lamp.sdt.core_2.7.1.r14724-b20080421111118/lib/scala-compiler.jar"/>
- <classpathentry kind="lib" path="lib/scalatest.jar"/>
- <classpathentry kind="output" path="build/eclipse"/>
-</classpath>
diff --git a/docs/examples/plugintemplate/.project b/docs/examples/plugintemplate/.project
deleted file mode 100644
index 075b0c580c..0000000000
--- a/docs/examples/plugintemplate/.project
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugintemplate</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>ch.epfl.lamp.sdt.core.scalabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>ch.epfl.lamp.sdt.core.scalanature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/docs/examples/plugintemplate/build.xml b/docs/examples/plugintemplate/build.xml
deleted file mode 100644
index 37c8441ce3..0000000000
--- a/docs/examples/plugintemplate/build.xml
+++ /dev/null
@@ -1,265 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<project name="plugintemplate" default="pack">
- <!-- Edit the file plugin.properties to set
- - scala.home
- - plugin.name
- - plugin.commandname
- - plugin.description
- - plugin.mainclass
- - version numbers
- -->
- <property file="${basedir}/plugin.properties"/>
-
- <property name="version" value="${version.major}.${version.minor}"/>
-
- <taskdef resource="scala/tools/ant/antlib.xml">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-compiler.jar"/>
- <pathelement location="${scala.home}/lib/scala-library.jar"/>
- </classpath>
- </taskdef>
-
-
- <!-- =================================================================
- End-user targets
- ================================================================== -->
-
- <target name="build" depends="build.main"/>
- <target name="build.all" depends="build.done"/>
- <target name="test" depends="test.all"/>
- <target name="guitest" depends="guitest.all"/>
- <target name="doc" depends="doc.done"/>
- <target name="pack" depends="pack.done"/>
- <target name="dist" depends="dist.done"/>
- <target name="clean" depends="clean.all"/>
-
- <!-- =================================================================
- Build targets
- ================================================================== -->
-
- <target name="build.main">
- <mkdir dir="build/build.main"/>
- <scalac srcdir="src"
- destdir="build/build.main"
- includes="**/*.scala">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-library.jar"/>
- <pathelement location="${scala.home}/lib/scala-compiler.jar"/>
- </classpath>
- </scalac>
- </target>
-
- <target name="build.test" depends="build.main">
- <mkdir dir="build/build.test"/>
- <scalac srcdir="test"
- destdir="build/build.test"
- includes="**/*.scala">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-library.jar"/>
- <pathelement location="${scala.home}/lib/scala-compiler.jar"/>
- <pathelement location="lib/scalatest.jar"/>
- <pathelement location="build/build.main"/>
- </classpath>
- </scalac>
- </target>
-
- <target name="build.examples" depends="build.test">
- <mkdir dir="build/build.examples"/>
- <scalac srcdir="doc/examples"
- destdir="build/build.examples"
- includes="**/*.scala">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-library.jar"/>
- <pathelement location="${scala.home}/lib/scala-compiler.jar"/>
- <pathelement location="build/build.main"/>
- </classpath>
- </scalac>
- </target>
-
- <target name="build.done" depends="build.examples"/>
-
- <!-- =================================================================
- Test targets
- ================================================================== -->
-
- <target name="test.all" depends="build.done">
- <!-- fork="true" is good for running the graphical mode -->
- <java classname="org.scalatest.tools.Runner" fork="true">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-compiler.jar" />
- <pathelement location="${scala.home}/lib/scala-library.jar" />
- <pathelement location="lib/scalatest.jar" />
- <pathelement location="build/build.main" />
- <pathelement location="build/build.test" />
- </classpath>
-
- <arg value="-p" />
- <arg value="build/build.test" />
-
- <arg value="-o" />
- </java>
- </target>
-
- <target name="guitest.all" depends="build.done">
- <!-- fork="true" is good for running the graphical mode -->
- <java classname="org.scalatest.tools.Runner" fork="true">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-compiler.jar" />
- <pathelement location="${scala.home}/lib/scala-library.jar" />
- <pathelement location="lib/scalatest.jar" />
- <pathelement location="build/build.main" />
- <pathelement location="build/build.test" />
- </classpath>
-
- <arg value="-p" />
- <arg value="build/build.test" />
-
- <arg value="-g" />
- </java>
- </target>
-
- <!-- =================================================================
- Doc targets
- ================================================================== -->
-
- <target name="doc.main">
- <mkdir dir="doc/api"/>
- <scaladoc srcdir="src"
- destdir="doc/api"
- includes="**/*.scala">
- <classpath>
- <pathelement location="${scala.home}/lib/scala-library.jar"/>
- <pathelement location="${scala.home}/lib/scala-compiler.jar"/>
- </classpath>
- </scaladoc>
- </target>
-
- <target name="doc.done" depends="doc.main"/>
-
- <!-- =================================================================
- Pack targets
- ================================================================== -->
-
- <target name="pack.main" depends="build.done">
- <mkdir dir="build/pack"/>
- <jar destfile="build/pack/${plugin.name}.jar">
- <fileset dir="build/build.main"/>
- <fileset file="plugin.properties"/>
- <fileset file="misc/scalac-plugin.xml"/>
- </jar>
- </target>
-
- <target name="pack.src" depends="pack.main">
- <jar destfile="build/pack/${plugin.name}-src.jar"
- basedir="src"
- includes="**/*.scala"/>
- </target>
-
- <target name="pack.done" depends="pack.src"/>
-
- <!-- =================================================================
- Dist targets
- ================================================================== -->
-
- <target name="dist.bin" depends="test.all,pack.done,doc.done">
- <mkdir dir="build/toolscript"/>
- <scalascript
- file="build/toolscript/${plugin.commandname}"
- class="${plugin.mainclass}"/>
- <chmod dir="build/toolscript" perm="a+rx" excludes="*.bat"/>
- </target>
-
- <target name="dist.archive" depends="dist.bin">
- <mkdir dir="build/dist"/>
- <tar destfile="build/dist/${plugin.name}-${version}.tgz"
- compression="gzip">
- <tarfileset prefix="lib" dir="build/pack"
- includes="${plugin.name}.jar"/>
- <tarfileset prefix="src" dir="build/pack"
- includes="${plugin.name}-src.jar"/>
- <tarfileset prefix="doc/${plugin.name}" dir="doc"
- includes="README"/>
- <tarfileset prefix="doc/${plugin.name}" dir="doc"
- includes="examples/**"/>
- <tarfileset prefix="doc/${plugin.name}" dir="doc"
- includes="api/**"/>
- <tarfileset prefix="bin" dir="build/toolscript"
- includes="${plugin.commandname}" mode="755"/>
- <tarfileset prefix="bin" dir="build/toolscript"
- includes="${plugin.commandname}.bat"/>
- <tarfileset prefix="misc/scala-devel/plugins" dir="build/pack"
- includes="${plugin.name}.jar"/>
- </tar>
- </target>
-
- <target name="dist.sbaz" depends="dist.archive">
- <sbaz file="build/dist/${plugin.name}-${version}.sbp"
- adfile="build/dist/${plugin.name}-${version}.advert"
- name="${plugin.name}"
- version="${version}"
- depends="scala-devel"
- desc="${plugin.description}"
- link="${plugin.sbazbaseurl}/${plugin.name}-${version}.sbp">
- <libset dir="build/pack" includes="${plugin.name}.jar"/>
- <srcset dir="build/pack" includes="${plugin.name}-src.jar"/>
- <docset dir="doc" includes="README"/>
- <docset dir="doc" includes="examples/**"/>
- <docset dir="doc" includes="api/**"/>
- <binset dir="build/toolscript"/>
- <looseset destination="misc/scala-devel/plugins">
- <fileset file="build/pack/${plugin.name}.jar"/>
- </looseset>
- </sbaz>
- </target>
-
- <target name="dist.done" depends="dist.sbaz"/>
-
- <!-- =================================================================
- Local installation
- ================================================================== -->
-
- <target name="install" depends="dist.done">
- <exec executable="sbaz">
- <arg line="-v install -f build/dist/${plugin.name}-${version}.sbp"/>
- </exec>
- </target>
-
- <target name="uninstall">
- <exec executable="sbaz">
- <arg line="remove ${plugin.name}"/>
- </exec>
- </target>
-
- <!-- =================================================================
- Clean targets
- ================================================================== -->
-
- <target name="clean.build">
- <delete dir="build/build.main" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- <delete dir="build/build.test" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- <delete dir="build/build.examples" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- </target>
-
- <target name="clean.pack" depends="clean.build">
- <delete dir="build/pack" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- </target>
-
- <target name="clean.dist" depends="clean.pack">
- <delete dir="build/dist" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- <delete dir="build/toolscript" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- </target>
-
- <target name="clean.doc">
- <delete dir="doc/api" includeemptydirs="yes"
- quiet="yes" failonerror="no"/>
- </target>
-
- <target name="clean.all" depends="clean.dist,clean.doc"/>
-</project>
diff --git a/docs/examples/plugintemplate/doc/README b/docs/examples/plugintemplate/doc/README
deleted file mode 100644
index 958f71282b..0000000000
--- a/docs/examples/plugintemplate/doc/README
+++ /dev/null
@@ -1,68 +0,0 @@
-Scala compiler plugin template
-------------------------------
-
-This project is a template that can be used for creating compiler
-plugins for the Scala compiler.
-
-
-Installation
-------------
-To install the compiler plugin, run "ant install". This will create
-an sbaz package for the template plugin and install it in the scala
-installation available in your PATH.
-The install command will also create a script for running the plugin
-as standalone application. The command is called "runplugintemplate"
-and available in your scala installation as well.
-To uninstall the plugin again, run "and uninstall".
-
-Alternatively, copy the file build/pack/plugintemplate.jar, generated
-by "ant pack", to the directory misc/scala-devel/plugins of your
-scala distribution. The scala compiler will then find and integrate
-the new plugin.
-
-Customization
--------------
-The following files need to be edited when creating a new plugin
-- plugin.properties
-- misc/scalac-plugin.xml
-- src / test / doc/examples: The source files of the template plugin
- are located a package called "plugintemplate". This will most likely
- be changed for new plugins.
-
-When using eclipse for development, make sure "scala-compiler.jar" is
-in the Java Build Path: Right-Click the project and select "Properties".
-Then go to "Java Build Path" -> "Libraries" and add the jar file
-"eclipse/plugins/ch.epfl.lamp.sdt.core[..]/lib/scala-compiler.jar".
-
-Traverse, Transform, Check
---------------------------
-There are several pre-defined components that can be used to code
-the behavior of a plugin:
-- TemplateTraverseComponent: a template for tree traversers. Used
- to analyze and collect data about compiler trees.
- -> implement the "check" method
-
-- TemplateTransformComponent: a template for tree transformers.
- -> implement "preTransform" and / or "postTransform"
-
-- TemplateInfoTransformComponent: also a tree transformer, which
- additionally is an InfoTransformer. Allows changing the type
- of some symbols for later phases.
- -> implement "preTransform" and / or "postTransform", and the
- "apply" method of the "infoTransformer".
-
-- TemplateAnnotationChecker: a plugin for the typechecker, useful
- for pluggable type systems. Computes the subtyping between two
- annotated types, and allows providing inferred type information.
- -> implement "annotationsConform" and optionally "addAnnotations"
-
-- TemplateComponent: the most general component. Can do anything it
- likes with the CompilationUnits.
- -> implement the "run" method
-
-Ant tasks
----------
-"build.xml" defines Ant tasks for building, testing and packing a
-plugin. The tests are written using the ScalaTest framework
-(http://www.artima.com/scalatest/).
-Run the tests using "ant test", or "ant guitest".
diff --git a/docs/examples/plugintemplate/doc/examples/plugintemplate/examples/BasicExample.scala b/docs/examples/plugintemplate/doc/examples/plugintemplate/examples/BasicExample.scala
deleted file mode 100644
index d1f6c91cdc..0000000000
--- a/docs/examples/plugintemplate/doc/examples/plugintemplate/examples/BasicExample.scala
+++ /dev/null
@@ -1,8 +0,0 @@
-package plugintemplate.examples
-
-/** An example demonstrating the fancy features of the new
- * compiler plugin.
- */
-class BasicExample {
- def foo = ()
-}
diff --git a/docs/examples/plugintemplate/lib/scalatest.jar.desired.sha1 b/docs/examples/plugintemplate/lib/scalatest.jar.desired.sha1
deleted file mode 100644
index 14c20f874f..0000000000
--- a/docs/examples/plugintemplate/lib/scalatest.jar.desired.sha1
+++ /dev/null
@@ -1 +0,0 @@
-8b6ba65c8146217333f0762087fe2340d572e832 ?scalatest.jar
diff --git a/docs/examples/plugintemplate/misc/scalac-plugin.xml b/docs/examples/plugintemplate/misc/scalac-plugin.xml
deleted file mode 100644
index bad4e87327..0000000000
--- a/docs/examples/plugintemplate/misc/scalac-plugin.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<plugin>
- <name>plugintemplate</name>
- <classname>plugintemplate.TemplatePlugin</classname>
-</plugin>
diff --git a/docs/examples/plugintemplate/plugin.properties b/docs/examples/plugintemplate/plugin.properties
deleted file mode 100644
index 131f96110f..0000000000
--- a/docs/examples/plugintemplate/plugin.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-scala.home=../../../build/pack
-
-plugin.name=plugintemplate
-plugin.commandname=runplugintemplate
-plugin.description=A template compiler plugin saying hello to the World
-plugin.mainclass=plugintemplate.standalone.Main
-plugin.sbazbaseurl=http://scala.epfl.ch/downloads/packages
-
-version.major=0
-version.minor=1
diff --git a/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala b/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
deleted file mode 100644
index ed078a03d7..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-package plugintemplate
-
-import java.util.Properties
-
-/** A utility to load properties of this plugin via the property
- * file "plugin.properties"
- */
-object PluginProperties {
- private val propFilename = "plugin.properties"
-
- val pluginName = getOrElse("plugin.name", "(name_unknown)")
- val pluginDescription = getOrElse("plugin.description", "(plugin description not found)")
- val pluginCommand = getOrElse("plugin.commandname", "(command_unknown)")
- val versionString = {
- val default = "(version_unknown)"
- props match {
- case Some(p) =>
- val major = p.getProperty("version.major")
- val minor = p.getProperty("version.minor")
- if ((major eq null) || (minor eq null)) default
- else major +"."+ minor
- case None => default
- }
- }
-
- private def getOrElse(property: String, default: String) = {
- props match {
- case Some(p) if (p.getProperty(property) != null) =>
- p.getProperty(property)
- case _ =>
- default
- }
- }
-
- private lazy val props: Option[Properties] = {
- /** Running from JAR file: the properties file should be in the
- * jar as well
- */
- var stream = this.getClass.getResourceAsStream("/"+ propFilename)
- if (stream == null) {
- /** Running from .class files: expect classfiles to be in
- * directory [...]/build/build.main, and [...] to contain
- * the properties file.
- */
- try {
- val current = this.getClass.getClassLoader.getResource(".")
- val dir = new java.io.File(current.toURI)
- // dir will be [...]/build/build.main/
- stream = new java.io.FileInputStream(dir.getParentFile.getParent +"/"+ propFilename)
- } catch {
- case _ => ()
- }
- }
- if (stream == null) None
- else {
- val p = new Properties
- p.load(stream)
- Some(p)
- }
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateAnnotationChecker.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateAnnotationChecker.scala
deleted file mode 100644
index 6cd3472675..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateAnnotationChecker.scala
+++ /dev/null
@@ -1,20 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc.Global
-
-abstract class TemplateAnnotationChecker {
- val global: Global
- import global._
-
- object checker extends AnnotationChecker {
- def annotationsConform(tpe1: Type, tpe2: Type): Boolean = {
- println("checking: "+ tpe1 +" <: "+ tpe2)
- true
- }
-
- override def addAnnotations(tree: Tree, tpe: Type): Type = {
- println("adding annot to "+ tree.symbol)
- tpe
- }
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
deleted file mode 100644
index b63f3203b5..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
+++ /dev/null
@@ -1,35 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc._
-import scala.tools.nsc.plugins.PluginComponent
-
-/** This class shows how to implement a compiler component that
- * can be used in a compiler plugin. If the plugin uses a tree
- * transformer and / or an InfoTransformer, look at the two
- * classes <code>TemplateTransformComponent</code> and
- * <code>TemplateInfoTransformComponent</code>.
- *
- * @todo Adapt the name of this class to the plugin, and implement it.
- */
-class TemplateComponent(val global: Global) extends PluginComponent {
- import global._
-
- val runsAfter = List[String]("refchecks")
-
- /** The name of this plugin phase
- * @todo Adapt to specific plugin.
- */
- val phaseName = "plugintemplate"
-
- def newPhase(prev: Phase) = new Phase(prev) {
- def name = phaseName
-
- /** The implementation of this Phase's behavior
- *
- * @todo Implementation.
- */
- def run {
- println("Hello from phase "+ name)
- }
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
deleted file mode 100644
index 71069aed6f..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc._
-import scala.tools.nsc.plugins.PluginComponent
-import scala.tools.nsc.transform.InfoTransform
-// import scala.tools.nsc.transform.TypingTransformers
-
-/** This class implements a plugin component using tree transformers and
- * InfoTransformer. An InfoTransformer will be automatically created
- * and registered in <code>SymbolTable.infoTransformers</code>. If
- * a <code>Typer</code> is needed during transformation, the component
- * should mix in <code>TypingTransformers</code>. This provides a local
- * variable <code>localTyper: Typer</code> that is always updated to
- * the current context.
- *
- * @todo Adapt the name of this class to the plugin, and implement it.
- */
-class TemplateInfoTransformComponent(val global: Global) extends PluginComponent
- // with TypingTransformers
- with InfoTransform {
-
- import global._
- import global.definitions._
-
- val runsAfter = List[String]("refchecks")
- /** The phase name of the compiler plugin
- * @todo Adapt to specific plugin.
- */
- val phaseName = "plugintemplateinfotransform"
-
- def transformInfo(sym: Symbol, tp: Type): Type = infoTransformer.mapOver(tp)
-
- def newTransformer(unit: CompilationUnit) = new TemplateTransformer
-
- /** The type transformation applied by this component. The trait InfoTransform
- * will create an instance of InfoTransformer applying this TypeMap. The type
- * map will be applied when computing a symbol's type in all phases
- * <em>after</em> "plugintemplateinfotransform".
- *
- * @todo Implement.
- */
- private val infoTransformer = new TypeMap {
- def apply(tp: Type): Type = tp match {
- case MethodType(pts, rt) =>
- println("methodType (_, _, ..) => "+ rt)
- tp
- case _ => mapOver(tp)
- }
- }
-
- /** The tree transformer that implements the behavior of this
- * component. Change the superclass to <code>TypingTransformer</code>
- * to make a local typechecker <code>localTyper</code> available.
- *
- * @todo Implement.
- */
- class TemplateTransformer extends /*Typing*/ Transformer {
- /** When using <code>preTransform</code>, each node is
- * visited before its children.
- */
- def preTransform(tree: Tree): Tree = tree match {
- case ValDef(_, name, _, _) =>
- println("pre-info-transforming valdef "+ name)
- tree
- case _ => tree
- }
-
- /** When using <code>postTransform</code>, each node is
- * visited after its children.
- */
- def postTransform(tree: Tree): Tree = tree match {
- case _ => tree
- }
-
- override def transform(tree: Tree): Tree = {
- postTransform(super.transform(preTransform(tree)))
- }
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
deleted file mode 100644
index 6cda37d4e3..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc.Global
-import scala.tools.nsc.plugins.Plugin
-
-/** A class describing the compiler plugin
- *
- * @todo Adapt the name of this class to the plugin being
- * implemented
- */
-class TemplatePlugin(val global: Global) extends Plugin {
- /** The name of this plugin. Extracted from the properties file. */
- val name = PluginProperties.pluginName
-
- val runsAfter = List[String]("refchecks")
-
- /** A short description of the plugin, read from the properties file */
- val description = PluginProperties.pluginDescription
-
- /** @todo A description of the plugin's options */
- override val optionsHelp = Some(
- " -P:"+ name +":option sets some option for this plugin")
-
- /** @todo Implement parsing of plugin options */
- override def processOptions(options: List[String], error: String => Unit) {
- super.processOptions(options, error)
- }
-
- /** The compiler components that will be applied when running
- * this plugin
- *
- * @todo Adapt to the plugin being implemented
- */
- val components = TemplatePlugin.components(global)
-
- val checker = new TemplateAnnotationChecker {
- val global: TemplatePlugin.this.global.type = TemplatePlugin.this.global
- }
- global.addAnnotationChecker(checker.checker)
-}
-
-object TemplatePlugin {
- /** Yields the list of Components to be executed in this plugin
- *
- * @todo: Adapt to specific implementation.
- */
- def components(global: Global) =
- List(new TemplateComponent(global),
- new TemplateTraverseComponent(global),
- new TemplateTransformComponent(global),
- new TemplateInfoTransformComponent(global))
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
deleted file mode 100644
index 7c2630dc16..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc._
-import scala.tools.nsc.plugins.PluginComponent
-import scala.tools.nsc.transform.Transform
-// import scala.tools.nsc.transform.TypingTransformers
-
-/** This class implements a plugin component using tree transformers. If
- * a <code>Typer</code> is needed during transformation, the component
- * should mix in <code>TypingTransformers</code>. This provides a local
- * variable <code>localTyper: Typer</code> that is always updated to
- * the current context.
- *
- * @todo Adapt the name of this class to the plugin, and implement it.
- */
-class TemplateTransformComponent(val global: Global) extends PluginComponent
- // with TypingTransformers
- with Transform {
- import global._
- import global.definitions._
-
- val runsAfter = List[String]("refchecks")
- /** The phase name of the compiler plugin
- * @todo Adapt to specific plugin.
- */
- val phaseName = "plugintemplatetransform"
-
- def newTransformer(unit: CompilationUnit) = new TemplateTransformer
-
- /** The tree transformer that implements the behavior of this
- * component. Change the superclass to <code>TypingTransformer</code>
- * to make a local typechecker <code>localTyper</code> available.
- *
- * @todo Implement.
- */
- class TemplateTransformer extends /*Typing*/ Transformer {
- /** When using <code>preTransform</code>, each node is
- * visited before its children.
- */
- def preTransform(tree: Tree): Tree = tree match {
- case _ => tree
- }
-
- /** When using <code>postTransform</code>, each node is
- * visited after its children.
- */
- def postTransform(tree: Tree): Tree = tree match {
- case New(tpt) =>
- println("post-transforming new "+ tpt)
- tree
- case _ => tree
- }
-
- override def transform(tree: Tree): Tree = {
- postTransform(super.transform(preTransform(tree)))
- }
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
deleted file mode 100644
index 400daf7437..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package plugintemplate
-
-import scala.tools.nsc._
-import scala.tools.nsc.plugins.PluginComponent
-
-/** This class implements a plugin component using a tree
- * traverser */
-class TemplateTraverseComponent (val global: Global) extends PluginComponent {
- import global._
- import global.definitions._
-
- val runsAfter = List[String]("refchecks")
- /** The phase name of the compiler plugin
- * @todo Adapt to specific plugin.
- */
- val phaseName = "plugintemplatetraverse"
-
- def newPhase(prev: Phase): Phase = new TraverserPhase(prev)
- class TraverserPhase(prev: Phase) extends StdPhase(prev) {
- def apply(unit: CompilationUnit) {
- newTraverser().traverse(unit.body)
- }
- }
-
- def newTraverser(): Traverser = new ForeachTreeTraverser(check)
-
- def check(tree: Tree): Unit = tree match {
- case Apply(fun, args) =>
- println("traversing application of "+ fun)
- case _ => ()
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala b/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
deleted file mode 100644
index 0bfcbf53c7..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-package plugintemplate.standalone
-
-import plugintemplate.PluginProperties
-import scala.tools.nsc.CompilerCommand
-import scala.tools.nsc.Settings
-
-/** An object for running the plugin as standalone application.
- *
- * @todo: print, parse and apply plugin options !!!
- * ideally re-use the TemplatePlugin (-> runsAfter, optionsHelp,
- * processOptions, components, annotationChecker) instead of
- * duplicating it here and in PluginRunner.
- */
-object Main {
- def main(args: Array[String]) {
- val settings = new Settings
-
- val command = new CompilerCommand(args.toList, settings) {
- /** The command name that will be printed in the usage message.
- * This is automatically set to the value of 'plugin.commandname' in the
- * file build.properties.
- */
- override val cmdName = PluginProperties.pluginCommand
- }
-
- if (!command.ok)
- return()
-
- /** The version number of this plugin is read from the properties file
- */
- if (settings.version.value) {
- println(command.cmdName +" version "+ PluginProperties.versionString)
- return()
- }
- if (settings.help.value) {
- println(command.usageMsg)
- return()
- }
-
- val runner = new PluginRunner(settings)
- val run = new runner.Run
- run.compile(command.files)
- }
-}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala b/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
deleted file mode 100644
index 06fe669cbd..0000000000
--- a/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-package plugintemplate.standalone
-
-import plugintemplate.{TemplateAnnotationChecker, TemplatePlugin}
-import scala.tools.nsc.{Global, Settings, SubComponent}
-import scala.tools.nsc.reporters.{ConsoleReporter, Reporter}
-
-/** This class is a compiler that will be used for running
- * the plugin in standalone mode.
- */
-class PluginRunner(settings: Settings, reporter: Reporter)
-extends Global(settings, reporter) {
- def this(settings: Settings) = this(settings, new ConsoleReporter(settings))
-
- val annotChecker = new TemplateAnnotationChecker {
- val global: PluginRunner.this.type = PluginRunner.this
- }
- addAnnotationChecker(annotChecker.checker)
-
- /** The phases to be run.
- *
- * @todo: Adapt to specific plugin implementation
- */
- override protected def computeInternalPhases() {
- phasesSet += syntaxAnalyzer
- phasesSet += analyzer.namerFactory
- phasesSet += analyzer.typerFactory
- phasesSet += superAccessors // add super accessors
- phasesSet += pickler // serialize symbol tables
- phasesSet += refChecks // perform reference and override checking, translate nested objects
-
- for (phase <- TemplatePlugin.components(this)) {
- phasesSet += phase
- }
- }
-
-}
diff --git a/docs/examples/plugintemplate/test/plugintemplate/PluginPropertiesSuite.scala b/docs/examples/plugintemplate/test/plugintemplate/PluginPropertiesSuite.scala
deleted file mode 100644
index a07796a7f2..0000000000
--- a/docs/examples/plugintemplate/test/plugintemplate/PluginPropertiesSuite.scala
+++ /dev/null
@@ -1,14 +0,0 @@
-package plugintemplate
-
-import org.scalatest.Suite
-
-class PluginPropertiesSuite extends Suite {
- def testProperties() {
- expect("A template compiler plugin saying hello to the World") {
- PluginProperties.pluginDescription
- }
- expect("0.1") {
- PluginProperties.versionString
- }
- }
-}
diff --git a/docs/examples/plugintemplate/test/plugintemplate/TemplatePluginSuite.scala b/docs/examples/plugintemplate/test/plugintemplate/TemplatePluginSuite.scala
deleted file mode 100644
index 06916f9dd3..0000000000
--- a/docs/examples/plugintemplate/test/plugintemplate/TemplatePluginSuite.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-package plugintemplate
-
-import org.scalatest.Suite
-import org.scalatest.Ignore
-
-class TemplatePluginSuite extends Suite {
- def testName() {
- import scala.tools.nsc.{Global, Settings}
- import scala.tools.nsc.reporters.ConsoleReporter
- val settings = new Settings
- val compiler = new Global(settings, new ConsoleReporter(settings))
- val plugin = new TemplatePlugin(compiler)
- expect("plugintemplate") {
- plugin.name
- }
- }
-
- @Ignore
- def testFail() {
- expect(1) { 2 }
- }
-}
diff --git a/docs/examples/sort.scala b/docs/examples/sort.scala
deleted file mode 100644
index 9a928f1107..0000000000
--- a/docs/examples/sort.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-package examples
-
-object sort {
-
- def sort(a: Array[Int]) {
-
- def swap(i: Int, j: Int) {
- val t = a(i); a(i) = a(j); a(j) = t
- }
-
- def sort1(l: Int, r: Int) {
- val pivot = a((l + r) / 2)
- var i = l
- var j = r
- while (i <= j) {
- while (a(i) < pivot) { i += 1 }
- while (a(j) > pivot) { j -= 1 }
- if (i <= j) {
- swap(i, j)
- i += 1
- j -= 1
- }
- }
- if (l < j) sort1(l, j)
- if (j < r) sort1(i, r)
- }
-
- if (a.length > 0)
- sort1(0, a.length - 1)
- }
-
- def println(ar: Array[Int]) {
- def print1 = {
- def iter(i: Int): String =
- ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")
- if (ar.length == 0) "" else iter(0)
- }
- Console.println("[" + print1 + "]")
- }
-
- def main(args: Array[String]) {
- val ar = Array(6, 2, 8, 5, 1)
- println(ar)
- sort(ar)
- println(ar)
- }
-
-}
diff --git a/docs/examples/sort1.scala b/docs/examples/sort1.scala
deleted file mode 100644
index 39e5519fe0..0000000000
--- a/docs/examples/sort1.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-package examples
-
-object sort1 {
-
- def sort(a: List[Int]): List[Int] = {
- if (a.length < 2)
- a
- else {
- val pivot = a(a.length / 2)
- sort(a.filter(x => x < pivot)) :::
- a.filter(x => x == pivot) :::
- sort(a.filter(x => x > pivot))
- }
- }
-
- def main(args: Array[String]) {
- val xs = List(6, 2, 8, 5, 1)
- println(xs)
- println(sort(xs))
- }
-
-}
diff --git a/docs/examples/sort2.scala b/docs/examples/sort2.scala
deleted file mode 100644
index e0016088bb..0000000000
--- a/docs/examples/sort2.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-package examples
-
-object sort2 {
-
- def sort(a: List[Int]): List[Int] = {
- if (a.length < 2)
- a
- else {
- val pivot = a(a.length / 2)
- def lePivot(x: Int) = x < pivot
- def gtPivot(x: Int) = x > pivot
- def eqPivot(x: Int) = x == pivot
- sort(a filter lePivot) :::
- (a filter eqPivot) :::
- sort(a filter gtPivot)
- }
- }
-
- def main(args: Array[String]) {
- val xs = List(6, 2, 8, 5, 1, 8)
- println(xs)
- println(sort(xs))
- }
-
-}
diff --git a/docs/examples/swing/ButtonApp.scala b/docs/examples/swing/ButtonApp.scala
deleted file mode 100644
index 96799b24f2..0000000000
--- a/docs/examples/swing/ButtonApp.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-package examples.swing
-
-import java.awt.Dimension
-
-import swing._
-import swing.event._
-
-object ButtonApp extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "My Frame"
- contents = new GridPanel(2, 2) {
- hGap = 3
- vGap = 3
- contents += new Button {
- text = "Press Me!"
- reactions += {
- case ButtonClicked(_) => text = "Hello Scala"
- }
- }
- }
- size = new Dimension(300, 80)
- }
-}
-
diff --git a/docs/examples/swing/CelsiusConverter.scala b/docs/examples/swing/CelsiusConverter.scala
deleted file mode 100644
index b4a62fb366..0000000000
--- a/docs/examples/swing/CelsiusConverter.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-package examples.swing
-
-import swing._
-import event._
-
-/** A GUI app to convert celsius to centigrade
- */
-object CelsiusConverter extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "Convert Celsius to Fahrenheit"
- val tempCelsius = new TextField
- val celsiusLabel = new Label {
- text = "Celsius"
- border = Swing.EmptyBorder(5, 5, 5, 5)
- }
- val convertButton = new Button {
- text = "Convert"//new javax.swing.ImageIcon("c:\\workspace\\gui\\images\\convert.gif")
- //border = Border.Empty(5, 5, 5, 5)
- }
- val fahrenheitLabel = new Label {
- text = "Fahrenheit "
- border = Swing.EmptyBorder(5, 5, 5, 5)
- listenTo(convertButton, tempCelsius)
-
- def convert() {
- val c = Integer.parseInt(tempCelsius.text)
- val f = c * 9 / 5 + 32
- text = "<html><font color = red>"+f+"</font> Fahrenheit</html>"
- }
-
- reactions += {
- case ButtonClicked(_) | EditDone(_) => convert()
- }
- }
- contents = new GridPanel(2,2) {
- contents.append(tempCelsius, celsiusLabel, convertButton, fahrenheitLabel)
- border = Swing.EmptyBorder(10, 10, 10, 10)
- }
- //defaultButton = Some(convertButton)
- }
-}
-
diff --git a/docs/examples/swing/CelsiusConverter2.scala b/docs/examples/swing/CelsiusConverter2.scala
deleted file mode 100644
index 3630d61b61..0000000000
--- a/docs/examples/swing/CelsiusConverter2.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-package examples.swing
-
-import swing._
-import event._
-
-object CelsiusConverter2 extends SimpleSwingApplication {
- def newField = new TextField {
- text = "0"
- columns = 5
- horizontalAlignment = Alignment.Right
- }
- val celsius = newField
- val fahrenheit = newField
-
- listenTo(fahrenheit, celsius)
- reactions += {
- case EditDone(`fahrenheit`) =>
- val f = Integer.parseInt(fahrenheit.text)
- val c = (f - 32) * 5 / 9
- celsius.text = c.toString
- case EditDone(`celsius`) =>
- val c = Integer.parseInt(celsius.text)
- val f = c * 9 / 5 + 32
- fahrenheit.text = f.toString
- }
-
- lazy val ui = new FlowPanel(celsius, new Label(" Celsius = "),
- fahrenheit, new Label(" Fahrenheit")) {
- border = Swing.EmptyBorder(15, 10, 10, 10)
- }
- def top = new MainFrame {
- title = "Convert Celsius / Fahrenheit"
- contents = ui
- }
-}
-
diff --git a/docs/examples/swing/ComboBoxes.scala b/docs/examples/swing/ComboBoxes.scala
deleted file mode 100644
index c6ee19013a..0000000000
--- a/docs/examples/swing/ComboBoxes.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-package examples.swing
-
-import swing._
-import event._
-import java.util.Date
-import java.awt.Color
-import java.text.SimpleDateFormat
-import javax.swing.{Icon, ImageIcon}
-
-/**
- * Demonstrates how to use combo boxes and custom item renderers.
- *
- * TODO: clean up layout
- */
-object ComboBoxes extends SimpleSwingApplication {
- import ComboBox._
- lazy val ui = new FlowPanel {
- contents += new ComboBox(List(1,2,3,4))
-
- val patterns = List("dd MMMMM yyyy",
- "dd.MM.yy",
- "MM/dd/yy",
- "yyyy.MM.dd G 'at' hh:mm:ss z",
- "EEE, MMM d, ''yy",
- "h:mm a",
- "H:mm:ss:SSS",
- "K:mm a,z",
- "yyyy.MMMMM.dd GGG hh:mm aaa")
- val dateBox = new ComboBox(patterns) { makeEditable() }
- contents += dateBox
- val field = new TextField(20) { editable = false }
- contents += field
-
- reactions += {
- case SelectionChanged(`dateBox`) => reformat()
- }
- listenTo(dateBox.selection)
-
- def reformat() {
- try {
- val today = new Date
- val formatter = new SimpleDateFormat(dateBox.selection.item)
- val dateString = formatter.format(today)
- field.foreground = Color.black
- field.text = dateString
- } catch {
- case e: IllegalArgumentException =>
- field.foreground = Color.red
- field.text = "Error: " + e.getMessage
- }
- }
-
-
- val icons = try {
- List(new ImageIcon(resourceFromClassloader("images/margarita1.jpg")),
- new ImageIcon(resourceFromClassloader("images/margarita2.jpg")),
- new ImageIcon(resourceFromClassloader("images/rose.jpg")),
- new ImageIcon(resourceFromClassloader("images/banana.jpg")))
- } catch {
- case _ =>
- println("Couldn't load images for combo box")
- List(Swing.EmptyIcon)
- }
-
- val iconBox = new ComboBox(icons) {
- renderer = new ListView.AbstractRenderer[Icon, Label](new Label) {
- def configure(list: ListView[_], isSelected: Boolean, focused: Boolean, icon: Icon, index: Int) {
- component.icon = icon
- component.xAlignment = Alignment.Center
- if(isSelected) {
- component.border = Swing.LineBorder(list.selectionBackground, 3)
- } else {
- component.border = Swing.EmptyBorder(3)
- }
- }
- }
- }
- contents += iconBox
- }
-
- def top = new MainFrame {
- title = "ComboBoxes Demo"
- contents = ui
- }
-}
-
diff --git a/docs/examples/swing/CountButton.scala b/docs/examples/swing/CountButton.scala
deleted file mode 100644
index 5fb14681d6..0000000000
--- a/docs/examples/swing/CountButton.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-package examples.swing
-
-import scala.swing._
-import scala.swing.event._
-
-object CountButton extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "My Frame"
- contents = new GridPanel(2, 2) {
- hGap = 3
- vGap = 3
- val button = new Button {
- text = "Press Me!"
- }
- contents += button
- val label = new Label {
- text = "No button clicks registered"
- }
- contents += label
-
- listenTo(button)
- var nclicks = 0
- reactions += {
- case ButtonClicked(b) =>
- nclicks += 1
- label.text = "Number of button clicks: "+nclicks
- }
- }
- }
-}
diff --git a/docs/examples/swing/Dialogs.scala b/docs/examples/swing/Dialogs.scala
deleted file mode 100644
index 0b4ac258cf..0000000000
--- a/docs/examples/swing/Dialogs.scala
+++ /dev/null
@@ -1,176 +0,0 @@
-package examples.swing
-
-import swing._
-import swing.event._
-
-object Dialogs extends SimpleSwingApplication {
- import TabbedPane._
-
- lazy val label = new Label("No Result yet")
- lazy val tabs = new TabbedPane {
- pages += new Page("File", new GridBagPanel { grid =>
- import GridBagPanel._
- val buttonText = new TextField("Click Me")
-
- val c = new Constraints
- c.fill = Fill.Horizontal
- c.grid = (1,1)
-
- val chooser = new FileChooser
- layout(new Button(Action("Open") {
- chooser.showOpenDialog(grid)
- })) = c
-
- c.grid = (1,2)
- layout(new Button(Action("Save") {
- chooser.showSaveDialog(grid)
- })) = c
-
- c.grid = (1,3)
- layout(new Button(Action("Custom") {
- chooser.showDialog(grid, buttonText.text)
- })) = c
-
- c.grid = (2,3)
- layout(new Label(" with Text ")) = c
-
- c.grid = (3,3)
- c.ipadx = 50
- layout(buttonText) = c
-
- border = Swing.EmptyBorder(5, 5, 5, 5)
- })
- pages += new Page("Simple Modal Dialogs", new BorderPanel {
- import BorderPanel._
- val mutex = new ButtonGroup
- val ok = new RadioButton("OK (in the L&F's words)")
- val ynlf = new RadioButton("Yes/No (in the L&F's words)")
- val ynp = new RadioButton("Yes/No (in the programmer's words)")
- val yncp = new RadioButton("Yes/No/Cancel (in the programmer's words)")
- val radios = List(ok, ynlf, ynp, yncp)
- mutex.buttons ++= radios
- mutex.select(ok)
- val buttons = new BoxPanel(Orientation.Vertical) {
- contents ++= radios
- }
- layout(buttons) = Position.North
- layout(new Button(Action("Show It!") {
- import Dialog._
- mutex.selected.get match {
- case `ok` =>
- showMessage(buttons, "Eggs aren't supposed to be green.")
- case `ynlf` =>
- label.text = showConfirmation(buttons,
- "Would you like green eggs and ham?",
- "An Inane Question") match {
- case Result.Yes => "Ewww!"
- case Result.No => "Me neither!"
- case _ => "Come on -- tell me!"
- }
- case `ynp` =>
- val options = List("Yes, please",
- "No, thanks",
- "No eggs, no ham!")
- label.text = showOptions(buttons,
- "Would you like some green eggs to go with that ham?",
- "A Silly Question",
- entries = options,
- initial = 2) match {
- case Result.Yes => "You're kidding!"
- case Result.No => "I don't like them, either."
- case _ => "Come on -- 'fess up!"
- }
- case `yncp` =>
- val options = List("Yes, please",
- "No, thanks",
- "No eggs, no ham!")
- label.text = showOptions(buttons,
- message = "Would you like some green eggs to go with that ham?",
- title = "A Silly Question",
- entries = options,
- initial = 2) match {
- case Result.Yes => "Here you go: green eggs and ham!"
- case Result.No => "OK, just the ham, then."
- case Result.Cancel => "Well, I'm certainly not going to eat them!"
- case _ => "Please tell me what you want!"
- }
- }
- })) = Position.South
- })
- pages += new Page("More Dialogs", new BorderPanel {
- import BorderPanel._
- val mutex = new ButtonGroup
- val pick = new RadioButton("Pick one of several choices")
- val enter = new RadioButton("Enter some text")
- val custom = new RadioButton("Custom")
- val customUndec = new RadioButton("Custom undecorated")
- val custom2 = new RadioButton("2 custom dialogs")
- val radios = List(pick, enter, custom, customUndec, custom2)
- mutex.buttons ++= radios
- mutex.select(pick)
- val buttons = new BoxPanel(Orientation.Vertical) {
- contents ++= radios
- }
- layout(buttons) = Position.North
- layout(new Button(Action("Show It!") {
- import Dialog._
- mutex.selected.get match {
- case `pick` =>
- val possibilities = List("ham", "spam", "yam")
- val s = showInput(buttons,
- "Complete the sentence:\n\"Green eggs and...\"",
- "Customized Dialog",
- Message.Plain,
- Swing.EmptyIcon,
- possibilities, "ham")
-
- //If a string was returned, say so.
- label.text = if ((s != None) && (s.get.length > 0))
- "Green eggs and... " + s.get + "!"
- else
- "Come on, finish the sentence!"
- case `enter` =>
- val s = showInput(buttons,
- "Complete the sentence:\n\"Green eggs and...\"",
- "Customized Dialog",
- Message.Plain,
- Swing.EmptyIcon,
- Nil, "ham")
-
- //If a string was returned, say so.
- label.text = if ((s != None) && (s.get.length > 0))
- "Green eggs and... " + s.get + "!"
- else
- "Come on, finish the sentence!"
- case `custom` =>
- val dialog = new Dialog(top)
- dialog.open()
- dialog.contents = Button("Close Me!") { dialog.close() }
- case `customUndec` =>
- val dialog = new Dialog with RichWindow.Undecorated
- dialog.open()
- dialog.contents = Button("Close Me!") { dialog.close() }
- case `custom2` =>
- val d1 = new Dialog
- val d2 = new Dialog(d1)
- d1.open()
- d2.open()
- d1.contents = Button("Close Me! I am the owner and will automatically close the other one") { d1.close() }
- d2.contents = Button("Close Me!") { d2.close() }
- }
- })) = Position.South
- })
- }
-
- lazy val ui: Panel = new BorderPanel {
- layout(tabs) = BorderPanel.Position.Center
- layout(label) = BorderPanel.Position.South
- }
-
-
- lazy val top = new MainFrame {
- title = "Dialog Demo"
- contents = ui
- }
-}
-
diff --git a/docs/examples/swing/GridBagDemo.scala b/docs/examples/swing/GridBagDemo.scala
deleted file mode 100644
index 60cfc13acb..0000000000
--- a/docs/examples/swing/GridBagDemo.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-package examples.swing
-
-import swing._
-import swing.event._
-import GridBagPanel._
-import java.awt.Insets
-
-object GridBagDemo extends SimpleSwingApplication {
- lazy val ui = new GridBagPanel {
- val c = new Constraints
- val shouldFill = true
- if (shouldFill) {
- c.fill = Fill.Horizontal
- }
-
- val button1 = new Button("Button 1")
-
- c.weightx = 0.5
-
- c.fill = Fill.Horizontal
- c.gridx = 0;
- c.gridy = 0;
- layout(button1) = c
-
- val button2 = new Button("Button 2")
- c.fill = Fill.Horizontal
- c.weightx = 0.5;
- c.gridx = 1;
- c.gridy = 0;
- layout(button2) = c
-
- val button3 = new Button("Button 3")
- c.fill = Fill.Horizontal
- c.weightx = 0.5;
- c.gridx = 2;
- c.gridy = 0;
- layout(button3) = c
-
- val button4 = new Button("Long-Named Button 4")
- c.fill = Fill.Horizontal
- c.ipady = 40; //make this component tall
- c.weightx = 0.0;
- c.gridwidth = 3;
- c.gridx = 0;
- c.gridy = 1;
- layout(button4) = c
-
- val button5 = new Button("5")
- c.fill = Fill.Horizontal
- c.ipady = 0; //reset to default
- c.weighty = 1.0; //request any extra vertical space
- c.anchor = Anchor.PageEnd
- c.insets = new Insets(10,0,0,0); //top padding
- c.gridx = 1; //aligned with button 2
- c.gridwidth = 2; //2 columns wide
- c.gridy = 2; //third row
- layout(button5) = c
- }
-
- def top = new MainFrame {
- title = "GridBag Demo"
- contents = ui
- }
-}
diff --git a/docs/examples/swing/HelloWorld.scala b/docs/examples/swing/HelloWorld.scala
deleted file mode 100644
index e89bfedd8a..0000000000
--- a/docs/examples/swing/HelloWorld.scala
+++ /dev/null
@@ -1,13 +0,0 @@
-package examples.swing
-
-import swing._
-
-/**
- * A simple swing demo.
- */
-object HelloWorld extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "Hello, World!"
- contents = new Button("Click Me!")
- }
-}
diff --git a/docs/examples/swing/LabelTest.scala b/docs/examples/swing/LabelTest.scala
deleted file mode 100644
index edd7a14634..0000000000
--- a/docs/examples/swing/LabelTest.scala
+++ /dev/null
@@ -1,19 +0,0 @@
-package examples.swing
-
-import scala.swing._
-import scala.swing.event._
-
-object LabelTest extends SimpleSwingApplication {
- def top = new MainFrame{
- contents = new Label {
- text = "Hello"
- import java.awt.event._
- listenTo(mouse.clicks)
- reactions += {
- case MousePressed(_,_,_,_,_) =>
- println("Mouse pressed2")
- }
- }
- }
-}
-
diff --git a/docs/examples/swing/LinePainting.scala b/docs/examples/swing/LinePainting.scala
deleted file mode 100644
index f72f8701ed..0000000000
--- a/docs/examples/swing/LinePainting.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-package examples.swing
-
-import scala.swing.Swing._
-import scala.swing.{MainFrame, Panel}
-import scala.swing.event._
-import java.awt.{Color, Graphics2D, Point, geom}
-
-/**
- * Dragging the mouse draws a simple graph
- *
- * @author Frank Teubler, Ingo Maier
- */
-object LinePainting extends SimpleSwingApplication {
- lazy val ui = new Panel {
- background = Color.white
- preferredSize = (200,200)
-
- focusable = true
- listenTo(mouse.clicks, mouse.moves, keys)
-
- reactions += {
- case e: MousePressed =>
- moveTo(e.point)
- requestFocusInWindow()
- case e: MouseDragged => lineTo(e.point)
- case e: MouseReleased => lineTo(e.point)
- case KeyTyped(_,'c',_,_) =>
- path = new geom.GeneralPath
- repaint()
- case _: FocusLost => repaint()
- }
-
- /* records the dragging */
- var path = new geom.GeneralPath
-
- def lineTo(p: Point) { path.lineTo(p.x, p.y); repaint() }
- def moveTo(p: Point) { path.moveTo(p.x, p.y); repaint() }
-
- override def paintComponent(g: Graphics2D) = {
- super.paintComponent(g)
- g.setColor(new Color(100,100,100))
- g.drawString("Press left mouse button and drag to paint." +
- (if(hasFocus) " Press 'c' to clear." else ""), 10, size.height-10)
- g.setColor(Color.black)
- g.draw(path)
- }
- }
-
- def top = new MainFrame {
- title = "Simple Line Painting Demo"
- contents = ui
- }
-}
diff --git a/docs/examples/swing/ListViewDemo.scala b/docs/examples/swing/ListViewDemo.scala
deleted file mode 100644
index 5630f2871d..0000000000
--- a/docs/examples/swing/ListViewDemo.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-package examples.swing
-
-object ListViewDemo extends SimpleSwingApplication {
- def top = new MainFrame {
- case class City(name: String, country: String, population: Int, capital: Boolean)
- val items = List(City("Lausanne", "Switzerland", 129273, false),
- City("Paris", "France", 2203817, true),
- City("New York", "USA", 8363710 , false),
- City("Berlin", "Germany", 3416300, true),
- City("Tokio", "Japan", 12787981, true))
- import ListView._
- contents = new FlowPanel(new ScrollPane(new ListView(items) {
- renderer = Renderer(_.name)
- }))
- //new ScrollPane(new Table(items)))
- }
-}
diff --git a/docs/examples/swing/SimpleApplet.scala b/docs/examples/swing/SimpleApplet.scala
deleted file mode 100644
index 502de537a3..0000000000
--- a/docs/examples/swing/SimpleApplet.scala
+++ /dev/null
@@ -1,18 +0,0 @@
-package examples.swing
-
-import event._
-
-class SimpleApplet extends Applet {
- object ui extends UI with Reactor {
- def init() = {
- val button = new Button("Press here!")
- val text = new TextArea("Java Version: " + util.Properties.javaVersion + "\n")
- listenTo(button)
- reactions += {
- case ButtonClicked(_) => text.text += "Button Pressed!\n"
- case _ =>
- }
- contents = new BoxPanel(Orientation.Vertical) { contents.append(button, text) }
- }
- }
-}
diff --git a/docs/examples/swing/SwingApp.scala b/docs/examples/swing/SwingApp.scala
deleted file mode 100644
index b3fe7447ef..0000000000
--- a/docs/examples/swing/SwingApp.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-package examples.swing
-
-import swing._
-import swing.event._
-
-object SwingApp extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "SwingApp"
- var numclicks = 0
- object label extends Label {
- val prefix = "Number of button clicks: "
- text = prefix + "0 "
- listenTo(button)
- reactions += {
- case ButtonClicked(button) =>
- numclicks = numclicks + 1
- text = prefix + numclicks
- }
- }
- object button extends Button {
- text = "I am a button"
- }
- contents = new FlowPanel {
- contents.append(button, label)
- border = Swing.EmptyBorder(5, 5, 5, 5)
- }
- }
-}
-
diff --git a/docs/examples/swing/TableSelection.scala b/docs/examples/swing/TableSelection.scala
deleted file mode 100644
index 8c8ea4ffcc..0000000000
--- a/docs/examples/swing/TableSelection.scala
+++ /dev/null
@@ -1,96 +0,0 @@
-package examples.swing
-
-import java.awt.Dimension
-import swing.event._
-
-object TableSelection extends SimpleSwingApplication {
- val model = Array(List("Mary", "Campione", "Snowboarding", 5, false).toArray,
- List("Alison", "Huml", "Rowing", 5, false).toArray,
- List("Kathy", "Walrath", "Knitting", 5, false).toArray,
- List("Sharon", "Zakhour", "Speed reading", 5, false).toArray,
- List("Philip", "Milne", "Pool", 5, false).toArray)
- /*val model = Array.tabulate(10000) { i =>
- List("Mary", "Campione", "Snowboarding", i, false).toArray
- }*/
-
- lazy val ui = new BoxPanel(Orientation.Vertical) {
- val table = new Table(model, Array("First Name", "Last Name", "Sport", "# of Years", "Vegetarian")) {
- preferredViewportSize = new Dimension(500, 70)
- }
- //1.6:table.fillsViewportHeight = true
- listenTo(table.selection)
-
- contents += new ScrollPane(table)
- contents += new Label("Selection Mode")
-
- def radio(mutex: ButtonGroup, text: String): RadioButton = {
- val b = new RadioButton(text)
- listenTo(b)
- mutex.buttons += b
- contents += b
- b
- }
-
- val intervalMutex = new ButtonGroup
- val multiInterval = radio(intervalMutex, "Multiple Interval Selection")
- val elementInterval = radio(intervalMutex, "Single Selection")
- val singleInterval = radio(intervalMutex, "Single Interval Selection")
- intervalMutex.select(multiInterval)
-
- contents += new Label("Selection Options")
- val elemMutex = new ButtonGroup
- val rowSelection = radio(elemMutex, "Row Selection")
- val columnSelection = radio(elemMutex, "Column Selection")
- val cellSelection = radio(elemMutex, "Cell Selection")
- elemMutex.select(rowSelection)
-
- val output = new TextArea(5, 40) { editable = false }
- contents += new ScrollPane(output)
-
- def outputSelection() {
- output.append("Lead: " + table.selection.rows.leadIndex + "," +
- table.selection.columns.leadIndex + ". ")
- output.append("Rows:")
- for (c <- table.selection.rows) output.append(" " + c)
- output.append(". Columns:")
- for (c <- table.selection.columns) output.append(" " + c)
- output.append(".\n")
- }
-
- reactions += {
- case ButtonClicked(`multiInterval`) =>
- table.selection.intervalMode = Table.IntervalMode.MultiInterval
- if (cellSelection.selected) {
- elemMutex.select(rowSelection)
- table.selection.elementMode = Table.ElementMode.None
- }
- cellSelection.enabled = false
- case ButtonClicked(`elementInterval`) =>
- table.selection.intervalMode = Table.IntervalMode.Single
- cellSelection.enabled = true
- case ButtonClicked(`singleInterval`) =>
- table.selection.intervalMode = Table.IntervalMode.SingleInterval
- cellSelection.enabled = true
- case ButtonClicked(`rowSelection`) =>
- if (rowSelection.selected)
- table.selection.elementMode = Table.ElementMode.Row
- case ButtonClicked(`columnSelection`) =>
- if (columnSelection.selected)
- table.selection.elementMode = Table.ElementMode.Column
- case ButtonClicked(`cellSelection`) =>
- if (cellSelection.selected)
- table.selection.elementMode = Table.ElementMode.Cell
- case TableRowsSelected(_, range, false) =>
- output.append("Rows selected, changes: " + range + "\n")
- outputSelection()
- case TableColumnsSelected(_, range, false) =>
- output.append("Columns selected, changes " + range + "\n")
- outputSelection()
- }
- }
-
- def top = new MainFrame {
- title = "Table Selection"
- contents = ui
- }
-}
diff --git a/docs/examples/swing/UIDemo.scala b/docs/examples/swing/UIDemo.scala
deleted file mode 100644
index 6d77c049e0..0000000000
--- a/docs/examples/swing/UIDemo.scala
+++ /dev/null
@@ -1,147 +0,0 @@
-package examples.swing
-
-import swing._
-import event._
-import Swing._
-import ListView._
-
-object UIDemo extends SimpleSwingApplication {
- def top = new MainFrame {
- title = "Scala Swing Demo"
-
- /*
- * Create a menu bar with a couple of menus and menu items and
- * set the result as this frame's menu bar.
- */
- menuBar = new MenuBar {
- contents += new Menu("A Menu") {
- contents += new MenuItem("An item")
- contents += new MenuItem(Action("An action item") {
- println("Action '"+ title +"' invoked")
- })
- contents += new Separator
- contents += new CheckMenuItem("Check me")
- contents += new CheckMenuItem("Me too!")
- contents += new Separator
- val a = new RadioMenuItem("a")
- val b = new RadioMenuItem("b")
- val c = new RadioMenuItem("c")
- val mutex = new ButtonGroup(a,b,c)
- contents ++= mutex.buttons
- }
- contents += new Menu("Empty Menu")
- }
-
- /*
- * The root component in this frame is a panel with a border layout.
- */
- contents = new BorderPanel {
- import BorderPanel.Position._
-
- var reactLive = false
-
- val tabs = new TabbedPane {
- import TabbedPane._
- val buttons = new FlowPanel {
- border = Swing.EmptyBorder(5,5,5,5)
-
- contents += new BoxPanel(Orientation.Vertical) {
- border = CompoundBorder(TitledBorder(EtchedBorder, "Radio Buttons"), EmptyBorder(5,5,5,10))
- val a = new RadioButton("Green Vegetables")
- val b = new RadioButton("Red Meat")
- val c = new RadioButton("White Tofu")
- val mutex = new ButtonGroup(a,b,c)
- contents ++= mutex.buttons
- }
- contents += new BoxPanel(Orientation.Vertical) {
- border = CompoundBorder(TitledBorder(EtchedBorder, "Check Boxes"), EmptyBorder(5,5,5,10))
- val paintLabels = new CheckBox("Paint Labels")
- val paintTicks = new CheckBox("Paint Ticks")
- val snapTicks = new CheckBox("Snap To Ticks")
- val live = new CheckBox("Live")
- contents.append(paintLabels, paintTicks, snapTicks, live)
- listenTo(paintLabels, paintTicks, snapTicks, live)
- reactions += {
- case ButtonClicked(`paintLabels`) =>
- slider.paintLabels = paintLabels.selected
- case ButtonClicked(`paintTicks`) =>
- slider.paintTicks = paintTicks.selected
- case ButtonClicked(`snapTicks`) =>
- slider.snapToTicks = snapTicks.selected
- case ButtonClicked(`live`) =>
- reactLive = live.selected
- }
- }
- contents += new Button(Action("Center Frame") { centerOnScreen() })
- }
- pages += new Page("Buttons", buttons)
- pages += new Page("GridBag", GridBagDemo.ui)
- pages += new Page("Converter", CelsiusConverter2.ui)
- pages += new Page("Tables", TableSelection.ui)
- pages += new Page("Dialogs", Dialogs.ui)
- pages += new Page("Combo Boxes", ComboBoxes.ui)
- pages += new Page("Split Panes",
- new SplitPane(Orientation.Vertical, new Button("Hello"), new Button("World")) {
- continuousLayout = true
- })
-
- val password = new FlowPanel {
- contents += new Label("Enter your secret password here ")
- val field = new PasswordField(10)
- contents += field
- val label = new Label(field.text)
- contents += label
- listenTo(field)
- reactions += {
- case EditDone(`field`) => label.text = field.password.mkString
- }
- }
-
- pages += new Page("Password", password)
- pages += new Page("Painting", LinePainting.ui)
- //pages += new Page("Text Editor", TextEditor.ui)
- }
-
- val list = new ListView(tabs.pages) {
- selectIndices(0)
- selection.intervalMode = ListView.IntervalMode.Single
- renderer = ListView.Renderer(_.title)
- }
- val center = new SplitPane(Orientation.Vertical, new ScrollPane(list), tabs) {
- oneTouchExpandable = true
- continuousLayout = true
- }
- layout(center) = Center
-
- /*
- * This slider is used above, so we need lazy initialization semantics.
- * Objects or lazy vals are the way to go, but objects give us better
- * type inference at times.
- */
- object slider extends Slider {
- min = 0
- value = tabs.selection.index
- max = tabs.pages.size-1
- majorTickSpacing = 1
- }
- layout(slider) = South
-
- /*
- * Establish connection between the tab pane, slider, and list view.
- */
- listenTo(slider)
- listenTo(tabs.selection)
- listenTo(list.selection)
- reactions += {
- case ValueChanged(`slider`) =>
- if(!slider.adjusting || reactLive) tabs.selection.index = slider.value
- case SelectionChanged(`tabs`) =>
- slider.value = tabs.selection.index
- list.selectIndices(tabs.selection.index)
- case SelectionChanged(`list`) =>
- if (list.selection.items.length == 1)
- tabs.selection.page = list.selection.items(0)
- }
- }
- }
-}
diff --git a/docs/examples/swing/images/banana.jpg b/docs/examples/swing/images/banana.jpg
deleted file mode 100644
index 62267a4325..0000000000
--- a/docs/examples/swing/images/banana.jpg
+++ /dev/null
Binary files differ
diff --git a/docs/examples/swing/images/margarita1.jpg b/docs/examples/swing/images/margarita1.jpg
deleted file mode 100644
index d315f7c79f..0000000000
--- a/docs/examples/swing/images/margarita1.jpg
+++ /dev/null
Binary files differ
diff --git a/docs/examples/swing/images/margarita2.jpg b/docs/examples/swing/images/margarita2.jpg
deleted file mode 100644
index c8b076e5f9..0000000000
--- a/docs/examples/swing/images/margarita2.jpg
+++ /dev/null
Binary files differ
diff --git a/docs/examples/swing/images/rose.jpg b/docs/examples/swing/images/rose.jpg
deleted file mode 100644
index d4a2b58062..0000000000
--- a/docs/examples/swing/images/rose.jpg
+++ /dev/null
Binary files differ
diff --git a/docs/examples/tcpoly/collection/HOSeq.scala b/docs/examples/tcpoly/collection/HOSeq.scala
deleted file mode 100644
index a6757b95ba..0000000000
--- a/docs/examples/tcpoly/collection/HOSeq.scala
+++ /dev/null
@@ -1,167 +0,0 @@
-package examples.tcpoly.collection;
-
-trait HOSeq {
- // an internal interface that encapsulates the accumulation of elements (of type elT) to produce
- // a structure of type coll[elT] -- different kinds of collections should provide different implicit
- // values implementing this interface, in order to provide more performant ways of building that structure
- trait Accumulator[+coll[x], elT] {
- def += (el: elT): Unit
- def result: coll[elT]
- }
-
-
- // Iterable abstracts over the type of its structure as well as its elements (see PolyP's Bifunctor)
- // m[x] is intentionally unbounded: fold can then be defined nicely
- // variance: if we write m[+x] instead of +m[+x], x is an invariant position because its enclosing type
- // is an invariant position -- should probably rule that out?
- trait Iterable[+m[+x], +t] {
- //def unit[a](orig: a): m[a]
- def iterator: Iterator[t]
-
- // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
- def accumulator[t]: Accumulator[m, t]
-
- def filter(p: t => Boolean): m[t] = {
- val buf = accumulator[t]
- val elems = elements
- while (elems.hasNext) { val x = elems.next; if (p(x)) buf += x }
- buf.result
- }
-
- def map[s](f: t => s): m[s] = {
- val buf = accumulator[s]
- val elems = elements
- while (elems.hasNext) buf += f(elems.next)
- buf.result
- }
-
- // flatMap is a more specialized map, it only works if the mapped function produces Iterable values,
- // which are then added to the result one by one
- // the compiler should be able to find the right accumulator (implicit buf) to build the result
- // to get concat, resColl = SingletonIterable, f = unit for SingletonIterable
- def flatMap[resColl[x] <: Iterable[resColl, x], s](f: t => resColl[s])(implicit buf: Accumulator[resColl, s]): resColl[s] = {
- // TODO: would a viewbound for resColl[x] be better?
- // -- 2nd-order type params are not yet in scope in view bound
- val elems = elements
- while (elems.hasNext) {
- val elemss: Iterator[s] = f(elems.next).iterator
- while (elemss.hasNext) buf += elemss.next
- }
- buf.result
- }
- }
-
- final class ListBuffer[A] {
- private var start: List[A] = Nil
- private var last: ::[A] = _
- private var exported: boolean = false
-
- /** Appends a single element to this buffer.
- *
- * @param x the element to append.
- */
- def += (x: A): unit = {
- if (exported) copy
- if (start.isEmpty) {
- last = new HOSeq.this.:: (x, Nil)
- start = last
- } else {
- val last1 = last
- last = new HOSeq.this.:: (x, null) // hack: ::'s tail will actually be last
- //last1.tl = last
- }
- }
-
- /** Converts this buffer to a list
- */
- def toList: List[A] = {
- exported = !start.isEmpty
- start
- }
-
- /** Clears the buffer contents.
- */
- def clear: unit = {
- start = Nil
- exported = false
- }
-
- /** Copy contents of this buffer */
- private def copy = {
- var cursor = start
- val limit = last.tail
- clear
- while (cursor ne limit) {
- this += cursor.head
- cursor = cursor.tail
- }
- }
- }
-
- implicit def listAccumulator[elT]: Accumulator[List, elT] = new Accumulator[List, elT] {
- private[this] val buff = new ListBuffer[elT]
- def += (el: elT): Unit = buff += el
- def result: List[elT] = buff.toList
- }
-
- trait List[+t] extends Iterable[List, t] {
- def head: t
- def tail: List[t]
- def isEmpty: Boolean
- def iterator: Iterator[t] = error("TODO")
-
- // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
- def accumulator[t]: Accumulator[List, t] = error("TODO")
- }
-
- // TODO: the var tl approach does not seem to work because subtyping isn't fully working yet
- final case class ::[+b](hd: b, private val tl: List[b]) extends List[b] {
- def head = hd
- def tail = if(tl==null) this else tl // hack
- override def isEmpty: boolean = false
- }
-
- case object Nil extends List[Nothing] {
- def isEmpty = true
- def head: Nothing =
- throw new NoSuchElementException("head of empty list")
- def tail: List[Nothing] =
- throw new NoSuchElementException("tail of empty list")
- }
-}
-
-
-
-// misc signatures collected from mailing list / library code:
- /*override def flatMap[B](f: A => Iterable[B]): Set[B]
- final override def flatMap[b](f: Any => Iterable[b]): Array[b]
- def flatMap[b](f: a => Parser[b]) = new Parser[b]
- override def flatMap[b](f: a => Iterable[b]): List[b]
-
-
- MapResult[K] <: Seq[K]
- FilterResult <: Seq[T]
- Concat <: Seq[T]
- Subseq <: Seq[T]
-
-
- def map[K](f: T=>K): MapResult[K]
- def filter(f: T=>Boolean): FilterResult
- def subseq(from: int, to: int): Subseq
- def flatMap[S <: Seq[K], K](f: T => S): S#Concat // legal?
- def concat(others: Seq[T]): Concat
- */
-
-/*trait Iterator[t] {
- // @post hasAdvanced implies hasNext
- // model def hasAdvanced: Boolean
-
- def hasNext: Boolean // pure
-
- // @pre hasAdvanced
- def current: t // pure
-
- // @pre hasNext
- // @post hasAdvanced
- def advance: Unit
-}*/
diff --git a/docs/examples/tcpoly/monads/Monads.scala b/docs/examples/tcpoly/monads/Monads.scala
deleted file mode 100644
index b6e3d5b9a8..0000000000
--- a/docs/examples/tcpoly/monads/Monads.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-package examples.tcpoly.monad;
-
-trait Monads {
- /**
- * class Monad m where
- * (>>=) :: m a -> (a -> m b) -> m b
- * return :: a -> m a
- *
- * MonadTC encodes the above Haskell type class,
- * an instance of MonadTC corresponds to a method dictionary.
- * (see http://lampwww.epfl.ch/~odersky/talks/wg2.8-boston06.pdf)
- *
- * Note that the identity (`this') of the method dictionary does not really correspond
- * to the instance of m[x] (`self') that is `wrapped': e.g., unit does not use `self' (which
- * corresponds to the argument of the implicit conversion that encodes an instance of this type class)
- */
- // Option =:= [x] => Option[x] <: [x] => Any
-// trait MonadTC[m <: [x] => Any, a] {
- // MonadTC[m[x], a] x is a type parameter too -- should not write e.g., m[Int] here
- trait MonadTC[m[x], a] {
- def unit[a](orig: a): m[a]
-
- // >>='s first argument comes from the implicit definition constructing this "method dictionary"
- def >>=[b](fun: a => m[b]): m[b]
- }
-}
-
-/**
- * instance Monad Maybe where
- * (Just x) >>= k = k x
- * Nothing >>= _ = Nothing
- */
-trait OptionMonad extends Monads {
- // this implicit method encodes the Monad type class instance for Option
- implicit def OptionInstOfMonad[a](self: Option[a]): MonadTC[Option, a]
- = new MonadTC[Option, a] {
- def unit[a](orig: a) = Some(orig)
- def >>=[b](fun: a => Option[b]): Option[b] = self match {
- case Some(x) => fun(x)
- case None => None
- }
- }
-}
-
-object main extends OptionMonad with Application {
- Console.println(Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") >>= (x => Some(x.length)))
-}
-
-
-/*
-trait MonadTC[m[x], a] requires m[x] {
- def unit[a](orig: a): m[a]
-
- // >>='s first argument comes from the implicit definition constructing this "method dictionary"
- def >>=[b](fun: a => m[b]): m[b]
-}
-
-abstract class OptionIsMonad[t[x] <: Option[x], a] implicit extends MonadTC[t, a] {
- def unit[a](orig: a) = Some(orig) // TODO: problematic.. is a meta-member: not invoked on this
-}
-
-class SomeIsMonad[a] extends OptionIsMonad[Some, a] {
- def >>=[b](fun: a => Option[b]): Option[b] = fun(x)
-}
-
-class NoneIsMonad[a] extends OptionIsMonad[None, a] {
- def >>=[b](fun: a => Option[b]): Option[b] = None
-}
-*/
diff --git a/docs/examples/typeinf.scala b/docs/examples/typeinf.scala
deleted file mode 100644
index d4bc8bf3e1..0000000000
--- a/docs/examples/typeinf.scala
+++ /dev/null
@@ -1,253 +0,0 @@
-package examples
-
-object typeinf {
-
-trait Term {}
-
-case class Var(x: String) extends Term {
- override def toString() = x
-}
-case class Lam(x: String, e: Term) extends Term {
- override def toString() = "(\\" + x + "." + e + ")"
-}
-case class App(f: Term, e: Term) extends Term {
- override def toString() = "(" + f + " " + e + ")"
-}
-case class Let(x: String, e: Term, f: Term) extends Term {
- override def toString() = "let " + x + " = " + e + " in " + f
-}
-
-sealed trait Type {}
-case class Tyvar(a: String) extends Type {
- override def toString() = a
-}
-case class Arrow(t1: Type, t2: Type) extends Type {
- override def toString() = "(" + t1 + "->" + t2 + ")"
-}
-case class Tycon(k: String, ts: List[Type]) extends Type {
- override def toString() =
- k + (if (ts.isEmpty) "" else ts.mkString("[", ",", "]"))
-}
-
-object typeInfer {
-
- private var n: Int = 0
- def newTyvar(): Type = { n += 1; Tyvar("a" + n) }
-
- trait Subst extends Function1[Type, Type] {
- def lookup(x: Tyvar): Type
- def apply(t: Type): Type = t match {
- case tv @ Tyvar(a) => val u = lookup(tv); if (t == u) t else apply(u)
- case Arrow(t1, t2) => Arrow(apply(t1), apply(t2))
- case Tycon(k, ts) => Tycon(k, ts map apply)
- }
- def extend(x: Tyvar, t: Type) = new Subst {
- def lookup(y: Tyvar): Type = if (x == y) t else Subst.this.lookup(y)
- }
- }
-
- val emptySubst = new Subst { def lookup(t: Tyvar): Type = t }
-
- case class TypeScheme(tyvars: List[Tyvar], tpe: Type) {
- def newInstance: Type =
- (emptySubst /: tyvars) ((s, tv) => s.extend(tv, newTyvar())) (tpe)
- }
-
- type Env = List[Pair[String, TypeScheme]]
-
- def lookup(env: Env, x: String): TypeScheme = env match {
- case List() => null
- case Pair(y, t) :: env1 => if (x == y) t else lookup(env1, x)
- }
-
- def gen(env: Env, t: Type): TypeScheme =
- TypeScheme(tyvars(t) diff tyvars(env), t)
-
- def tyvars(t: Type): List[Tyvar] = t match {
- case tv @ Tyvar(a) => List(tv)
- case Arrow(t1, t2) => tyvars(t1) union tyvars(t2)
- case Tycon(k, ts) => (List[Tyvar]() /: ts) ((tvs, t) => tvs union tyvars(t))
- }
-
- def tyvars(ts: TypeScheme): List[Tyvar] =
- tyvars(ts.tpe) diff ts.tyvars;
-
- def tyvars(env: Env): List[Tyvar] =
- (List[Tyvar]() /: env) ((tvs, nt) => tvs union tyvars(nt._2))
-
- def mgu(t: Type, u: Type, s: Subst): Subst = Pair(s(t), s(u)) match {
- case Pair(Tyvar(a), Tyvar(b)) if (a == b) =>
- s
- case Pair(Tyvar(a), _) if !(tyvars(u) contains a) =>
- s.extend(Tyvar(a), u)
- case Pair(_, Tyvar(a)) =>
- mgu(u, t, s)
- case Pair(Arrow(t1, t2), Arrow(u1, u2)) =>
- mgu(t1, u1, mgu(t2, u2, s))
- case Pair(Tycon(k1, ts), Tycon(k2, us)) if (k1 == k2) =>
- (s /: (ts zip us)) ((s, tu) => mgu(tu._1, tu._2, s))
- case _ =>
- throw new TypeError("cannot unify " + s(t) + " with " + s(u))
- }
-
- case class TypeError(s: String) extends Exception(s) {}
-
- def tp(env: Env, e: Term, t: Type, s: Subst): Subst = {
- current = e
- e match {
- case Var(x) =>
- val u = lookup(env, x)
- if (u == null) throw new TypeError("undefined: " + x)
- else mgu(u.newInstance, t, s)
-
- case Lam(x, e1) =>
- val a, b = newTyvar()
- val s1 = mgu(t, Arrow(a, b), s)
- val env1 = Pair(x, TypeScheme(List(), a)) :: env
- tp(env1, e1, b, s1)
-
- case App(e1, e2) =>
- val a = newTyvar()
- val s1 = tp(env, e1, Arrow(a, t), s)
- tp(env, e2, a, s1)
-
- case Let(x, e1, e2) =>
- val a = newTyvar()
- val s1 = tp(env, e1, a, s)
- tp(Pair(x, gen(env, s1(a))) :: env, e2, t, s1)
- }
- }
- var current: Term = null
-
- def typeOf(env: Env, e: Term): Type = {
- val a = newTyvar()
- tp(env, e, a, emptySubst)(a)
- }
-}
-
- object predefined {
- val booleanType = Tycon("Boolean", List())
- val intType = Tycon("Int", List())
- def listType(t: Type) = Tycon("List", List(t))
-
- private def gen(t: Type): typeInfer.TypeScheme = typeInfer.gen(List(), t)
- private val a = typeInfer.newTyvar()
- val env = List(
-/*
- Pair("true", gen(booleanType)),
- Pair("false", gen(booleanType)),
- Pair("if", gen(Arrow(booleanType, Arrow(a, Arrow(a, a))))),
- Pair("zero", gen(intType)),
- Pair("succ", gen(Arrow(intType, intType))),
- Pair("nil", gen(listType(a))),
- Pair("cons", gen(Arrow(a, Arrow(listType(a), listType(a))))),
- Pair("isEmpty", gen(Arrow(listType(a), booleanType))),
- Pair("head", gen(Arrow(listType(a), a))),
- Pair("tail", gen(Arrow(listType(a), listType(a)))),
-*/
- Pair("fix", gen(Arrow(Arrow(a, a), a)))
- )
- }
-
- trait MiniMLParsers extends CharParsers {
-
- /** whitespace */
- def whitespace = rep{chr(' ') ||| chr('\t') ||| chr('\n')}
-
- /** A given character, possible preceded by whitespace */
- def wschr(ch: char) = whitespace &&& chr(ch)
-
- def isLetter = (c: char) => Character.isLetter(c)
- def isLetterOrDigit: char => boolean = Character.isLetterOrDigit
-
- /** identifiers or keywords */
- def id: Parser[String] =
- for (
- c: char <- rep(chr(' ')) &&& chr(isLetter);
- cs: List[char] <- rep(chr(isLetterOrDigit))
- ) yield (c :: cs).mkString("", "", "")
-
- /** Non-keyword identifiers */
- def ident: Parser[String] =
- for (s <- id if s != "let" && s != "in") yield s
-
- /** term = '\' ident '.' term | term1 {term1} | let ident "=" term in term */
- def term: Parser[Term] = (
- ( for (
- _ <- wschr('\\');
- x <- ident;
- _ <- wschr('.');
- t <- term)
- yield Lam(x, t): Term )
- |||
- ( for (
- letid <- id if letid == "let";
- x <- ident;
- _ <- wschr('=');
- t <- term;
- inid <- id; if inid == "in";
- c <- term)
- yield Let(x, t, c) )
- |||
- ( for (
- t <- term1;
- ts <- rep(term1))
- yield (t /: ts)((f, arg) => App(f, arg)) )
- )
-
- /** term1 = ident | '(' term ')' */
- def term1: Parser[Term] = (
- ( for (s <- ident)
- yield Var(s): Term )
- |||
- ( for (
- _ <- wschr('(');
- t <- term;
- _ <- wschr(')'))
- yield t )
- )
-
- /** all = term ';' */
- def all: Parser[Term] =
- for (
- t <- term;
- _ <- wschr(';'))
- yield t
- }
-
- class ParseString(s: String) extends Parsers {
- type inputType = int
- val input = 0
- def any = new Parser[char] {
- def apply(in: int): Parser[char]#Result =
- if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None
- }
- }
-
- def showType(e: Term): String =
- try {
- typeInfer.typeOf(predefined.env, e).toString()
- }
- catch {
- case typeInfer.TypeError(msg) =>
- "\n cannot type: " + typeInfer.current +
- "\n reason: " + msg
- }
-
- def main(args: Array[String]) {
- Console.println(
- if (args.length == 1) {
- val ps = new ParseString(args(0)) with MiniMLParsers
- ps.all(ps.input) match {
- case Some(Pair(term, _)) =>
- "" + term + ": " + showType(term)
- case None =>
- "syntax error"
- }
- }
- else
- "usage: java examples.typeinf <expr-string>"
- )
- }
-
-}
diff --git a/docs/examples/xml/phonebook/embeddedBook.scala b/docs/examples/xml/phonebook/embeddedBook.scala
deleted file mode 100644
index 3286485f0b..0000000000
--- a/docs/examples/xml/phonebook/embeddedBook.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/* examples/phonebook/embeddedBook.scala */
-package phonebook
-
-object embeddedBook {
-
- val company = <a href="http://acme.org">ACME</a>
- val first = "Burak"
- val last = "Emir"
- val location = "work"
-
- val embBook =
- <phonebook>
- <descr>
- This is the <b>phonebook</b> of the
- {company} corporation.
- </descr>
- <entry>
- <name>{ first+" "+last }</name>
- <phone where={ location }>+41 21 693 68 {val x = 60 + 7; x}</phone>
- </entry>
- </phonebook>;
-
- def main(args: Array[String]) =
- Console.println( embBook )
-
-}
diff --git a/docs/examples/xml/phonebook/phonebook.scala b/docs/examples/xml/phonebook/phonebook.scala
deleted file mode 100644
index 3c0dfbd837..0000000000
--- a/docs/examples/xml/phonebook/phonebook.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-package phonebook ;
-
-object phonebook {
-
- val labPhoneBook =
- <phonebook>
- <descr>
- This is the <b>phonebook</b> of the
- <a href="http://acme.org">ACME</a> corporation.
- </descr>
- <entry>
- <name>Burak</name>
- <phone where="work"> +41 21 693 68 67</phone>
- <phone where="mobile">+41 79 602 23 23</phone>
- </entry>
- </phonebook>;
-
- Console.println( labPhoneBook );
-
- // XML is immutable - adding an element
-
- import scala.xml.{ Node, Text };
-
- def add( phonebook:Node, newEntry:Node ):Node = phonebook match {
- case <phonebook>{ ch @ _* }</phonebook> =>
- <phonebook>{ ch }{ newEntry }</phonebook>
- }
-
- val pb2 =
- add( labPhoneBook,
- <entry>
- <name>Kim</name>
- <phone where="work"> +41 21 111 11 11</phone>
- </entry> );
-
- def main(args:Array[String]) = Console.println( pb2 );
-
-}
diff --git a/docs/examples/xml/phonebook/phonebook1.scala b/docs/examples/xml/phonebook/phonebook1.scala
deleted file mode 100644
index 316c6c1995..0000000000
--- a/docs/examples/xml/phonebook/phonebook1.scala
+++ /dev/null
@@ -1,21 +0,0 @@
-/* examples/phonebook/phonebook1.scala */
-package phonebook
-
-object phonebook1 {
-
- val labPhoneBook =
- <phonebook>
- <descr>
- This is the <b>phonebook</b> of the
- <a href="http://acme.org">ACME</a> corporation.
- </descr>
- <entry>
- <name>Burak Emir</name>
- <phone where="work">+41 21 693 68 67</phone>
- </entry>
- </phonebook>;
-
- def main(args: Array[String]) =
- Console.println( labPhoneBook )
-
-}
diff --git a/docs/examples/xml/phonebook/phonebook2.scala b/docs/examples/xml/phonebook/phonebook2.scala
deleted file mode 100644
index 2a708daf7c..0000000000
--- a/docs/examples/xml/phonebook/phonebook2.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/* examples/xml/phonebook/phonebook2.scala */
-package phonebook;
-
-object phonebook2 {
-
- import scala.xml.Node
-
- /** adds an entry to a phonebook */
- def add( p: Node, newEntry: Node ): Node = p match {
-
- case <phonebook>{ ch @ _* }</phonebook> =>
-
- <phonebook>{ ch }{ newEntry }</phonebook>
- }
-
- val pb2 =
- add( phonebook1.labPhoneBook,
- <entry>
- <name>Kim</name>
- <phone where="work">+41 21 111 11 11</phone>
- </entry> );
-
- def main( args: Array[String] ) =
- Console.println( pb2 )
-}
diff --git a/docs/examples/xml/phonebook/phonebook3.scala b/docs/examples/xml/phonebook/phonebook3.scala
deleted file mode 100644
index 12f2deaa79..0000000000
--- a/docs/examples/xml/phonebook/phonebook3.scala
+++ /dev/null
@@ -1,81 +0,0 @@
-package phonebook;
-
-object phonebook3 {
-
- import scala.xml.{Elem, Node, Text} ;
- import scala.xml.PrettyPrinter ;
- import Node.NoAttributes ;
-
- /* this method "changes" (returns an updated copy) of the phonebook when the
- * entry for Name exists. If it has an attribute "where" whose value is equal to the
- * parameter Where, it is changed, otherwise, it is added.
- */
- def change ( phonebook:Node, Name:String, Where:String, newPhone:String ) = {
-
- /** this nested function walks through tree, and returns an updated copy of it */
- def copyOrChange ( ch: Iterator[Node] ) = {
-
- import xml.Utility.{trim,trimProper} //removes whitespace nodes, which are annoying in matches
-
- for( val c <- ch ) yield
- trimProper(c) match {
-
- // if the node is the particular entry we are looking for, return an updated copy
-
- case x @ <entry><name>{ Text(Name) }</name>{ ch1 @ _* }</entry> =>
-
- var updated = false;
- val ch2 = for(c <- ch1) yield c match { // does it have the phone number?
-
- case y @ <phone>{ _* }</phone> if y \ "@where" == Where =>
- updated = true
- <phone where={ Where }>{ newPhone }</phone>
-
- case y => y
-
- }
- if( !updated ) { // no, so we add as first entry
-
- <entry>
- <name>{ Name }</name>
- <phone where={ Where }>{ newPhone }</phone>
- { ch1 }
- </entry>
-
- } else { // yes, and we changed it as we should
-
- <entry>
- { ch2 }
- </entry>
-
- }
- // end case x @ <entry>...
-
- // other entries are copied without changing them
-
- case x =>
- x
-
- }
- } ; // for ... yield ... returns an Iterator[Node]
-
- // decompose phonebook, apply updates
- phonebook match {
- case <phonebook>{ ch @ _* }</phonebook> =>
- <phonebook>{ copyOrChange( ch.iterator ) }</phonebook>
- }
-
- }
-
- val pb2 =
- change( phonebook1.labPhoneBook, "John", "work", "+41 55 555 55 55" );
-
- val pp = new PrettyPrinter( 80, 5 );
-
- def main( args:Array[String] ) = {
- Console.println("---before---");
- Console.println( pp.format( phonebook1.labPhoneBook ));
- Console.println("---after---");
- Console.println( pp.format( pb2 ));
- }
-}
diff --git a/docs/examples/xml/phonebook/verboseBook.scala b/docs/examples/xml/phonebook/verboseBook.scala
deleted file mode 100644
index 2dcb155480..0000000000
--- a/docs/examples/xml/phonebook/verboseBook.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/* examples/xml/phonebook/verboseBook.scala */
-package phonebook
-
-object verboseBook {
-
- import scala.xml.{ UnprefixedAttribute, Elem, Node, Null, Text, TopScope }
-
- val pbookVerbose =
- Elem(null, "phonebook", Null, TopScope,
- Elem(null, "descr", Null, TopScope,
- Text("This is a "),
- Elem(null, "b", Null, TopScope, Text("sample")),
- Text("description")
- ),
- Elem(null, "entry", Null, TopScope,
- Elem(null, "name", Null, TopScope, Text("Burak Emir")),
- Elem(null, "phone", new UnprefixedAttribute("where","work", Null), TopScope,
- Text("+41 21 693 68 67"))
- )
- )
-
- def main(args: Array[String]) =
- Console.println( pbookVerbose )
-}