text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/rem
 */
public class rem extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/rem";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return a.remainder(b);
  }
}


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/neg
 */
public class neg extends UnaryOperator<BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/neg";

  public BigDecimal execute(BigDecimal n) {
    return n.negate();
  }
}

repo_name: trith/trith

repo_language: Ruby

mime_type: text/plain


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/min
 */
public class min extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/min";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return a.min(b);
  }
}


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/pow
 */
public class pow extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/pow";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return a.pow(b.intValue()); // FIXME
  }
}


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/add
 */
public class add extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/add";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return a.add(b);
  }
}


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/mul
 */
public class mul extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/mul";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return a.multiply(b);
  }
}


text:
package trith.math;
import  trith.lang.*;
import  trith.lang.Number;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/dec
 */
public class dec extends UnaryOperator<BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/dec";

  public BigDecimal execute(BigDecimal n) {
    return n.subtract(Number.ONE);
  }
}


text:
package trith.math;
import  trith.lang.*;
import  java.math.BigDecimal;
import  java.math.BigInteger;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/math/mod
 */
public class mod extends BinaryOperator<BigDecimal, BigDecimal, BigDecimal> {
  public static final String URL = "http://trith.org/math/mod";

  public BigDecimal execute(BigDecimal a, BigDecimal b) {
    return new BigDecimal(a.toBigIntegerExact().mod(b.toBigIntegerExact()));
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;
import  java.util.concurrent.ExecutionException;
import  java.util.concurrent.TimeUnit;
import  java.util.concurrent.TimeoutException;

/**
 * @author Arto Bendiken
 * @see    http://en.wikipedia.org/wiki/Futures_and_promises
 */
public class Promise<V> implements Future {
  protected boolean isForced = false;
  protected V result;
  protected Callable<V> callable;

  public Promise() {}

  public Promise(Callable<V> callable) {
    this.callable = callable;
  }

  public boolean cancel(boolean mayInterruptIfRunning) {
    return false;
  }

  public boolean isCancelled() {
    return false;
  }

  public boolean isDone() {
    return true;
  }

  public V get() throws InterruptedException, ExecutionException {
    try {
      return force();
    }
    catch (Exception e) {
      throw new ExecutionException(e);
    }
  }

  public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    return get(); // FIXME
  }

  public V force() throws Exception {
    if (!isForced) { // TODO: make this atomic
      isForced = true;
      result   = call();
    }
    return result;
  }

  public V call() throws Exception {
    return callable.call();
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.TimeUnit;
import  java.util.concurrent.ExecutionException;
import  java.util.concurrent.TimeoutException;

/**
 * @author Arto Bendiken
 */
public class Value implements Future<Object> {
  protected Object value;

  public Value(Object value) {
    this.value = value;
  }

  public boolean cancel(boolean mayInterruptIfRunning) {
    return false;
  }

  public boolean isCancelled() {
    return false;
  }

  public boolean isDone() {
    return true;
  }

  public Object get() throws InterruptedException, ExecutionException {
    return value;
  }

  public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    return value;
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;
import  java.util.concurrent.ExecutionException;

/**
 * @author Arto Bendiken
 * @see    http://en.wikipedia.org/wiki/Arity#Nullary
 */
public abstract class NullaryOperator<T> implements Operator {
  public void execute(Machine machine) {
    machine.push(new Callable<T>() {
      public T call() {
        return execute();
      }
    });
  }

  public abstract T execute();
}


text:
package trith.lang;

/**
 * @author Arto Bendiken
 */
public interface Operator {
  public void execute(Machine machine);
}


text:
package trith.lang;
import  java.math.BigDecimal;
import  java.math.BigInteger;

public class Number {
  public static final BigDecimal ZERO  = BigDecimal.ZERO;
  public static final BigDecimal ONE   = BigDecimal.ONE;
  public static final BigDecimal TWO   = BigDecimal.valueOf(2);
  public static final BigDecimal THREE = BigDecimal.valueOf(3);
  public static final BigDecimal FOUR  = BigDecimal.valueOf(4);
  public static final BigDecimal FIVE  = BigDecimal.valueOf(5);
  public static final BigDecimal SIX   = BigDecimal.valueOf(6);
  public static final BigDecimal SEVEN = BigDecimal.valueOf(7);
  public static final BigDecimal EIGHT = BigDecimal.valueOf(8);
  public static final BigDecimal NINE  = BigDecimal.valueOf(9);
  public static final BigDecimal TEN   = BigDecimal.TEN;

  public static BigDecimal valueOf(BigDecimal value) {
    return value;
  }

  public static BigDecimal valueOf(BigInteger value) {
    return new BigDecimal(value);
  }

  public static BigDecimal valueOf(String value) {
    return new BigDecimal(value);
  }

  public static BigDecimal valueOf(byte value) {
    return BigDecimal.valueOf(value);
  }

  public static BigDecimal valueOf(short value) {
    return BigDecimal.valueOf(value);
  }

  public static BigDecimal valueOf(int value) {
    return BigDecimal.valueOf(value);
  }

  public static BigDecimal valueOf(long value) {
    return BigDecimal.valueOf(value);
  }

  public static BigDecimal valueOf(float value) {
    return BigDecimal.valueOf(value);
  }

  public static BigDecimal valueOf(double value) {
    return BigDecimal.valueOf(value);
  }
}


text:
package trith.lang;
import  java.util.concurrent.ExecutorService;
import  java.util.concurrent.Future;

/**
 * @author Arto Bendiken
 */
public class StandardMachine extends AbstractMachine {
  protected final AbstractMachine machine;

  protected ExecutorService getExecutor() {
    return machine.getExecutor();
  }

  public StandardMachine() {
    this(new SequentialMachine());
  }

  public StandardMachine(int concurrencyLevel) {
    this(new ParallelMachine(concurrencyLevel));
  }

  public StandardMachine(AbstractMachine machine) {
    this.machine = machine;
  }

  public Object shift() {
    return machine.shift();
  }

  public void unshift(Operator op) {
    machine.unshift(op);
  }

  public <T> Future<T> peek() {
    return machine.peek();
  }

  public <T> Future<T> pop() {
    return machine.pop();
  }

  public void push(Future<?> value) {
    machine.push(value);
  }

  /**
   * @see trith.core.dup
   */
  public void dup() {
    execute(new trith.core.dup());
  }

  /**
   * @see trith.core.nilp
   */
  public void nilp() {
    execute(new trith.core.nilp());
  }

  /**
   * @see trith.core.nil
   */
  public void nil() {
    execute(new trith.core.nil());
  }

  /**
   * @see trith.core.booleanp
   */
  public void booleanp() {
    execute(new trith.core.booleanp());
  }

  /**
   * @see trith.core.falsep
   */
  public void falsep() {
    execute(new trith.core.falsep());
  }

  /**
   * @see trith.core.truep
   */
  public void truep() {
    execute(new trith.core.truep());
  }

  /**
   * @see trith.core.stringp
   */
  public void stringp() {
    execute(new trith.core.stringp());
  }

  /**
   * @see trith.core.nump
   */
  public void nump() {
    execute(new trith.core.nump());
  }

  /**
   * @see trith.core.zerop
   */
  public void zerop() {
    execute(new trith.core.zerop());
  }

  /*
   * @see trith.math.abs
   */
  public void abs() {
    execute(new trith.math.abs());
  }

  /*
   * @see trith.math.min
   */
  public void min() {
    execute(new trith.math.min());
  }

  /*
   * @see trith.math.max
   */
  public void max() {
    execute(new trith.math.max());
  }

  /*
   * @see trith.math.neg
   */
  public void neg() {
    execute(new trith.math.neg());
  }

  /*
   * @see trith.math.inc
   */
  public void inc() {
    execute(new trith.math.inc());
  }

  /*
   * @see trith.math.dec
   */
  public void dec() {
    execute(new trith.math.dec());
  }

  /*
   * @see trith.math.add
   */
  public void add() {
    execute(new trith.math.add());
  }

  /*
   * @see trith.math.sub
   */
  public void sub() {
    execute(new trith.math.sub());
  }

  /*
   * @see trith.math.mul
   */
  public void mul() {
    execute(new trith.math.mul());
  }

  /*
   * @see trith.math.div
   */
  public void div() {
    execute(new trith.math.div());
  }

  /*
   * @see trith.math.rem
   */
  public void rem() {
    execute(new trith.math.rem());
  }

  /*
   * @see trith.math.mod
   */
  public void mod() {
    execute(new trith.math.mod());
  }

  /*
   * @see trith.math.pow
   */
  public void pow() {
    execute(new trith.math.pow());
  }

  /*
   * @see trith.stream.emptyp
   */
  public void emptyp() {
    execute(new trith.stream.emptyp());
  }

  /*
   * @see trith.stream.length
   */
  public void length() {
    execute(new trith.stream.length());
  }

  /*
   * @see trith.stream.rest
   */
  public void rest() {
    execute(new trith.stream.rest());
  }

  /*
   * @see trith.stream.first
   */
  public void first() {
    execute(new trith.stream.first());
  }

  /*
   * @see trith.stream.nth
   */
  public void nth() {
    execute(new trith.stream.nth());
  }

  /*
   * @see trith.stream.last
   */
  public void last() {
    execute(new trith.stream.last());
  }

  /*
   * @see trith.stream.cons
   */
  public void cons() {
    execute(new trith.stream.cons());
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;
import  java.util.concurrent.ExecutionException;

/**
 * @author Arto Bendiken
 * @see    http://en.wikipedia.org/wiki/Unary_operation
 */
public abstract class UnaryOperator<T, A> implements Operator {
  public void execute(Machine machine) {
    final Future<A> a = machine.pop();

    machine.push(new Callable<T>() {
      public T call() {
        try {
          return execute(a.get());
        }
        catch (InterruptedException e) {
          e.printStackTrace(); // FIXME
        }
        catch (ExecutionException e) {
          e.printStackTrace(); // FIXME
        }
        return null;
      }
    });
  }

  public abstract T execute(A a);
}


text:
package trith.lang;
import  java.util.concurrent.ExecutorService;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;
import  java.util.concurrent.ExecutionException;
import  java.util.Stack;
import  java.util.EmptyStackException;

/**
 * @author Arto Bendiken
 */
public abstract class AbstractMachine implements Machine {
  public final Stack<Future> stack = new Stack<Future>();
  public final Stack<Future> queue = new Stack<Future>();

  protected ExecutorService executor;

  protected ExecutorService getExecutor() {
    return executor;
  }

  protected AbstractMachine() {}

  protected AbstractMachine(ExecutorService executor) {
    this.executor = executor;
  }

  public void execute() {
    Object op;
    while ((op = shift()) != null) {
      if (op instanceof Future) {
        try {
          op = ((Future)op).get();
        }
        catch (InterruptedException e) {
          e.printStackTrace(); // FIXME
        }
        catch (ExecutionException e) {
          e.printStackTrace(); // FIXME
        }
      }
      if (op instanceof Operator) {
        ((Operator)op).execute(this);
      }
      else {
        push(op);
      }
    }
  }

  public void execute(Operator operator) {
    unshift(operator);
    execute();
  }

  public Future<?> submit(Callable<?> callable) {
    return getExecutor().submit(callable);
  }

  public void halt() {
    getExecutor().shutdown();
  }

  public Object shift() {
    if (!queue.empty()) {
      return queue.pop();
    }
    else {
      return null;
    }
  }

  public void unshift(Operator op) {
    queue.push(new Value(op));
  }

  public boolean empty() {
    return stack.empty();
  }

  public <T> T get() {
    try {
      return this.<T>pop().get();
    }
    catch (InterruptedException e) {
      e.printStackTrace(); // FIXME
    }
    catch (ExecutionException e) {
      e.printStackTrace(); // FIXME
    }
    return null;
  }

  public <T> Future<T> peek() {
    try {
      return stack.peek();
    }
    catch (EmptyStackException e) {
      return null;
    }
  }

  public <T> Future<T> pop() {
    try {
      return stack.pop();
    }
    catch (EmptyStackException e) {
      throw new StackUnderflowError();
    }
  }

  public void push(Future<?> value) {
    stack.push(value);
  }

  public void push(Callable<?> callable) {
    push(submit(callable));
  }

  public void push(Object value) {
    push(new Value(value));
  }

  public void push(boolean value) {
    push(Boolean.valueOf(value));
  }

  public void push(char value) {
    push(Character.valueOf(value));
  }

  public void push(byte value) {
    push(Number.valueOf(value));
  }

  public void push(short value) {
    push(Number.valueOf(value));
  }

  public void push(int value) {
    push(Number.valueOf(value));
  }

  public void push(long value) {
    push(Number.valueOf(value));
  }

  public void push(float value) {
    push(Number.valueOf(value));
  }

  public void push(double value) {
    push(Number.valueOf(value));
  }
}


text:
package trith.lang;
import  java.util.Iterator;
import  java.util.Collection;
import  java.util.List;

/**
 * @author Arto Bendiken
 */
public abstract class UnaryStreamOperator<T, A> extends UnaryOperator<T, A> {
  public T execute(A a) {
    if (a instanceof String) {
      return execute((String)a);
    }
    if (a instanceof List) {
      return execute((List)a);
    }
    if (a instanceof Collection) {
      return execute((Collection)a);
    }
    if (a instanceof Iterator) {
      return execute((Iterator)a);
    }
    if (a instanceof Iterable) {
      return execute((Iterable)a);
    }
    return null; // FIXME
  }

  public abstract T execute(String a);
  public abstract T execute(Iterator a);

  public T execute(List a) {
    return execute((Collection)a);
  }

  public T execute(Collection a) {
    return execute(a.iterator());
  }

  public T execute(Iterable a) {
    return execute(a.iterator());
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;
import  java.util.concurrent.ExecutionException;

/**
 * @author Arto Bendiken
 * @see    http://en.wikipedia.org/wiki/Binary_operation
 */
public abstract class BinaryOperator<T, A, B> implements Operator {
  public void execute(Machine machine) {
    final Future<B> b = machine.pop();
    final Future<A> a = machine.pop();

    machine.push(new Callable<T>() {
      public T call() {
        try {
          return execute(a.get(), b.get());
        }
        catch (InterruptedException e) {
          e.printStackTrace(); // FIXME
        }
        catch (ExecutionException e) {
          e.printStackTrace(); // FIXME
        }
        return null;
      }
    });
  }

  public abstract T execute(A a, B b);
}


text:
package trith.lang;
import  java.util.concurrent.Executors;

/**
 * @author Arto Bendiken
 */
public class ParallelMachine extends AbstractMachine {
  public ParallelMachine() {
    this(4); // TODO: figure out how many CPUs are available
  }

  public ParallelMachine(int threads) {
    super(Executors.newFixedThreadPool(threads));
  }
}


text:
package trith.lang;

class Symbol {
  public final String name;

  public static Symbol intern(String name) {
    return new Symbol(name);
  }

  public static Symbol valueOf(String name) {
    return new Symbol(name);
  }

  public static Symbol valueOf(char name) {
    return new Symbol(name);
  }

  public Symbol(String name) {
    this.name = name.intern();
  }

  public Symbol(char name) {
    this.name = String.valueOf(name).intern();
  }

  public String toString() {
    return name;
  }
}


text:
package trith.lang;
import  java.util.concurrent.Future;
import  java.util.concurrent.Callable;

/**
 * @author Arto Bendiken
 */
public interface Machine {
  public void execute();
  public void execute(Operator operator);
  public Future<?> submit(Callable<?> callable);
  public void halt();

  public Object shift();
  public void unshift(Operator op);

  public boolean empty();
  public <T> T get();
  public <T> Future<T> peek();
  public <T> Future<T> pop();
  public void push(Future<?> value);
  public void push(Callable<?> callable);
  public void push(Object value);
}


text:
package trith.lang;
import  java.util.EmptyStackException;

class StackUnderflowError extends EmptyStackException {}


text:
package trith.lang;

public class Reference {}


text:
package trith.lang;
import  java.util.concurrent.Executors;

/**
 * @author Arto Bendiken
 */
public class SequentialMachine extends AbstractMachine {
  public SequentialMachine() {
    super(Executors.newSingleThreadExecutor());
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.concurrent.Future;
import  java.util.concurrent.ExecutionException;
import  java.util.Iterator;
import  java.util.Collection;
import  java.util.List;
import  java.math.BigDecimal;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/nth
 */
public class nth implements Operator {
  public static final String URL = "http://trith.org/stream/nth";

  public void execute(final Machine machine) {
    final Future<BigDecimal> a = machine.pop();

    machine.unshift(new UnaryStreamOperator<Object, Object>() {
      public int getIndex() {
        try {
          return a.get().intValue();
        }
        catch (InterruptedException e) {
          e.printStackTrace(); // FIXME
        }
        catch (ExecutionException e) {
          e.printStackTrace(); // FIXME
        }
        return -1; // FIXME
      }

      public Object execute(String str) {
        return str.charAt(getIndex());
      }

      public Object execute(List list) {
        return list.get(getIndex());
      }

      public Object execute(Iterator iter) {
        int index      = getIndex();
        int position   = 0;
        while (iter.hasNext()) {
          Object element = iter.next();
          if (index == position++) {
            return element;
          }
        }
        throw new ArrayIndexOutOfBoundsException(index);
      }
    });
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.Iterator;
import  java.util.List;
import  java.util.Collections;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/rest
 */
public class rest extends UnaryStreamOperator<Object, Object> {
  public static final String URL = "http://trith.org/stream/rest";

  public Object execute(String str) {
    if (str.isEmpty()) {
      return Collections.EMPTY_LIST;
    }
    else {
      return str.substring(1);
    }
  }

  public Object execute(List list) {
    if (list.isEmpty()) {
      return Collections.EMPTY_LIST;
    }
    else {
      //return list.listIterator(1);
      return list.subList(1, list.size());
    }
  }

  public Object execute(Iterator iter) {
    if (!iter.hasNext()) {
      return Collections.EMPTY_LIST;
    }
    else {
      iter.next();
      return iter;
    }
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.Iterator;
import  java.util.List;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/last
 */
public class last extends UnaryStreamOperator<Object, Object> {
  public static final String URL = "http://trith.org/stream/last";

  public Object execute(String str) {
    if (str.isEmpty()) {
      return null;
    }
    else {
      //return Character.valueOf(str.codePointBefore(str.length()));
      return Character.valueOf(str.charAt(str.length() - 1));
    }
  }

  public Object execute(List list) {
    if (list.isEmpty()) {
      return null;
    }
    else {
      return list.get(list.size() - 1);
    }
  }

  public Object execute(Iterator iter) {
    if (!iter.hasNext()) {
      return null;
    }
    else {
      Object element = null;
      while (iter.hasNext()) {
        element = iter.next();
      }
      return element;
    }
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.Iterator;
import  java.util.Collection;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/emptyp
 */
public class emptyp extends UnaryStreamOperator<Boolean, Object> {
  public static final String URL = "http://trith.org/stream/emptyp";

  public Boolean execute(String str) {
    return Boolean.valueOf(str.isEmpty());
  }

  public Boolean execute(Collection coll) {
    return Boolean.valueOf(coll.isEmpty());
  }

  public Boolean execute(Iterator iter) {
    return Boolean.valueOf(!iter.hasNext());
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  trith.lang.Number;
import  java.math.BigDecimal;
import  java.util.Iterator;
import  java.util.Collection;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/length
 */
public class length extends UnaryStreamOperator<BigDecimal, Object> {
  public static final String URL = "http://trith.org/stream/length";

  /**
   * @see http://java.sun.com/javase/6/docs/api/java/lang/Character.html#unicode
   */
  public BigDecimal execute(String str) {
    //return Number.valueOf(str.codePointCount(0, str.length())); // TODO
    return Number.valueOf(str.length());
  }

  public BigDecimal execute(Collection coll) {
    return Number.valueOf(coll.size());
  }

  public BigDecimal execute(Iterator iter) {
    long length = 0;
    while (iter.hasNext()) {
      length++;
      iter.next();
    }
    return Number.valueOf(length);
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.Iterator;
import  java.util.Collection;
import  java.util.List;
import  java.util.LinkedList;
import  java.util.ArrayList;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/cons
 */
public class cons extends BinaryOperator<Object, Object, Object> {
  public static final String URL = "http://trith.org/stream/cons";

  public Object execute(Object a, Object b) {
    if (b instanceof String) {
      return execute(a, (String)b);
    }
    if (b instanceof List) {
      return execute(a, (List)b);
    }
    if (b instanceof Collection) {
      return execute(a, (Collection)b);
    }
    if (b instanceof Iterator) {
      return execute(a, (Iterator)b);
    }
    if (b instanceof Iterable) {
      return execute(a, (Iterable)b);
    }
    return null; // FIXME
  }

  public Object execute(Object first, String rest) {
    if (!(first instanceof Character)) {
      // TODO: should we throw an error?
    }
    return first.toString().concat(rest);
  }

  public Object execute(Object first, List rest) {
    if (rest instanceof LinkedList) {
      LinkedList result = (LinkedList)((LinkedList)rest).clone();
      result.addFirst(first);
      return result;
    }
    if (rest instanceof ArrayList) {
      ArrayList result = (ArrayList)((ArrayList)rest).clone();
      result.add(0, first);
      return result;
    }
    else {
      // Object#clone is protected in classes we don't explicitly know
      // about, so we'll have to fall back to the Collection interface:
      return execute(first, (Collection)rest);
    }
  }

  public Object execute(Object first, Collection rest) {
    // TODO: this should work lazily
    LinkedList result = new LinkedList(rest);
    result.addFirst(first);
    return result;
  }

  public Object execute(Object first, Iterator rest) {
    // FIXME: this should work lazily
    LinkedList result = new LinkedList();
    result.addFirst(first);
    while (rest.hasNext()) {
      result.addLast(rest.next());
    }
    return result;
  }

  public Object execute(Object first, Iterable rest) {
    return execute(first, rest.iterator());
  }
}


text:
package trith.stream;
import  trith.lang.*;
import  java.util.Iterator;
import  java.util.List;

/**
 * @author Arto Bendiken
 * @see    http://trith.org/stream/first
 */
public class first extends UnaryStreamOperator<Object, Object> {
  public static final String URL = "http://trith.org/stream/first";

  public Object execute(String str) {
    if (str.isEmpty()) {
      return null;
    }
    else {
      return Character.valueOf(str.charAt(0));
    }
  }

  public Object execute(List list) {
    if (list.isEmpty()) {
      return null;
    }
    else {
      return list.get(0);
    }
  }

  public Object execute(Iterator iter) {
    if (!iter.hasNext()) {
      return null;
    }
    else {
      return iter.next();
    }
  }
}


text:
#!/usr/bin/env ruby1.9 -rubygems
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'trith'

BANNER = "Usage: #{File.basename($0)} [options] file [args...]"

case
  when %w(-V -v --version).any? { |opt| ARGV.include?(opt) }
    $stdout.puts Trith::VERSION.to_s
    exit
  when %w(-? -h --help).any? { |opt| ARGV.include?(opt) }
    $stdout.puts BANNER
    exit
  when ARGV.empty?
    abort BANNER
end

begin
  $machine = Trith::Machine.new
  $cache   = Trith::Cache.load_core
  $machine.import!(Trith::Core)

  begin
    case
      when split = ARGV.index('--')
        ARGV.delete_at(split)
        $machine.push(*ARGV.slice!(split, ARGV.size - split))
      when ARGV.size > 1
        $machine.push(*ARGV.slice!(1, ARGV.size - 1))
    end
    $machine.execute(Trith::Reader.read_files(*ARGV))
  rescue Trith::Machine::InvalidOperatorError => e
    $stderr.puts Trith::Shell.format_error(e)
  rescue Trith::Machine::InvalidOperandError => e
    $stderr.puts Trith::Shell.format_error(e)
  rescue Trith::Machine::StackUnderflowError => e
    $stderr.puts Trith::Shell.format_error("stack underflow")
  end

  exit([255, $machine.stack.size].min)
rescue Interrupt
  abort '' # abort due to ^C (SIGINT)
end


text:
#!/usr/bin/env ruby1.9 -rubygems
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'trith'

BANNER = "Usage: #{File.basename($0)} [options] [files...]"

case
  when %w(-V -v --version).any? { |opt| ARGV.delete(opt) }
    $stdout.puts Trith::VERSION.to_s
    exit
  when %w(-? -h --help).any? { |opt| ARGV.delete(opt) }
    $stdout.puts BANNER
    exit
end

begin
  $machine = Trith::Machine.new
  $cache   = Trith::Cache.load_core
  Trith::Shell.setup!($cache)
  Trith::Shell::History.load!

  if %w(-d --debug).any? { |opt| ARGV.delete(opt) }
    $machine.execute_hook = proc do
      $stdout.puts Trith::Shell.inspect($machine, :prefix => '.. ', :align => true)
    end
  end

  ARGV.each do |file|
    $machine.execute(Trith::Reader.read_file(file)) unless file =~ /^--/
  end

  while line = Trith::Shell.readline('>> ')
    unless (line = line.strip).empty?
      case line
        # Operator lookup
        when /^\?\s*(\S*)/, 'help'
          filter = ($1.to_s).empty? ? nil : /#{Regexp.quote($1)}/
          $cache.each_function do |function|
            if !filter || filter =~ function.label
              puts "%-24s%s" % [function.label, function.comment]
            end
          end
          next # skip inspecting the stack

        # Operator definition
        when /^:\s*(\S*)\s+(.*)$/
          Trith::Shell::History.push(": #{$1} #{$2}")
          name, code = $1.to_sym, Trith::Reader.read_all($2)
          $machine.define!(name, code, :method => false)
          next # skip inspecting the stack

        # Code execution
        else
          Trith::Shell::History.push(line)
          begin
            $machine.execute(Trith::Reader.read_all(line))
          rescue Trith::Machine::InvalidOperatorError => e
            $stderr.puts Trith::Shell.format_error(e)
          rescue Trith::Machine::InvalidOperandError => e
            $stderr.puts Trith::Shell.format_error(e)
          rescue Trith::Machine::StackUnderflowError => e
            $stderr.puts Trith::Shell.format_error("stack underflow")
          rescue => e
            $stderr.puts Trith::Shell.format_error(e.inspect)
          end
      end
    end
    $stdout.puts Trith::Shell.inspect($machine, :prefix => '=> ', :align => !!$machine.execute_hook)
  end

  $stdout.puts
rescue Interrupt
  abort '' # abort due to ^C (SIGINT)
ensure
  Trith::Shell::History.dump!
end


text:
#!/usr/bin/env ruby1.9 -rubygems
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'trith'

BANNER = "Usage: #{File.basename($0)} [options] files..."

case
  when %w(-V -v --version).any? { |opt| ARGV.include?(opt) }
    $stdout.puts Trith::VERSION.to_s
    exit
  when %w(-? -h --help).any? { |opt| ARGV.include?(opt) }
    $stdout.puts BANNER
    exit
  when ARGV.empty?
    abort BANNER # FIXME: read from stdin
end

begin
  $compiler = Trith::Compiler.for(:ruby).compile_files(*ARGV)
  File.open('a.rb', 'w+', 0755) { |output| output.write($compiler.to_s) }
rescue SystemCallError => e
  abort "#{File.basename($0)}: #{e}" # abort due to e.g. Errno::ENOENT
rescue Interrupt
  abort '' # abort due to ^C (SIGINT)
end


text:
#!/usr/bin/env ruby1.9 -rubygems
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'trith'

BANNER = "Usage: #{File.basename($0)} [options] command [args...]"

case
  when %w(-V -v --version).any? { |opt| ARGV.include?(opt) }
    $stdout.puts Trith::VERSION.to_s
    exit
  when %w(-? -h --help).any? { |opt| ARGV.include?(opt) }
    $stdout.puts BANNER
    exit
  when ARGV.empty?
    abort BANNER
end


text:
require 'bigdecimal'
require 'rational'
require 'digest/sha1'

# @see http://rubygems.org/gems/backports
require 'backports/1.9.1'        if RUBY_VERSION < '1.9.1'
require 'backports/basic_object' if RUBY_VERSION < '1.9.1'

# @see http://rubygems.org/gems/promise
require 'future'

# @see http://rubygems.org/gems/sxp
require 'sxp'

# @see http://rubygems.org/gems/rdf
require 'rdf'
require 'rdf/ntriples'
require 'rdf/nquads'

# @see http://rubygems.org/gems/ffi
require 'ffi'

module Trith
  include RDF

  autoload :VERSION,  'trith/version'

  # Runtime
  autoload :Cache,    'trith/cache'
  autoload :Compiler, 'trith/compiler'
  autoload :Function, 'trith/function'
  autoload :Machine,  'trith/machine'
  autoload :Reader,   'trith/reader'
  autoload :Shell,    'trith/shell'

  # Vocabularies
  autoload :Core,     'trith/vocab/core'
  autoload :Math,     'trith/vocab/math'
end


text:
module Trith
  ##
  # The Trith code parser.
  #
  # @see http://sxp.rubyforge.org/
  class Reader
    ##
    # @param  [String, #to_s]          url
    # @param  [Hash{Symbol => Object}] options
    # @return [Enumerable<Object>]
    def self.read_url(url, options = {})
      SXP.read_url(url, options)
    end

    ##
    # @param  [Enumerable<String>]     filenames
    # @param  [Hash{Symbol => Object}] options
    # @return [Enumerable<Object>]
    def self.read_files(*filenames)
      SXP.read_files(*filenames)
    end

    ##
    # @param  [String, #to_s]          filename
    # @param  [Hash{Symbol => Object}] options
    # @return [Enumerable<Object>]
    def self.read_file(filename, options = {})
      SXP.read_file(filename, options)
    end

    ##
    # @param  [IO, StringIO, String]   input
    # @param  [Hash{Symbol => Object}] options
    # @return [Enumerable<Object>]
    def self.read_all(input, options = {})
      SXP.read_all(input, options)
    end

    ##
    # @param  [IO, StringIO, String]   input
    # @param  [Hash{Symbol => Object}] options
    # @return [Object]
    def self.read(input, options = {})
      SXP.read(input, options)
    end

    # Prevent the instantiation of this class:
    private_class_method :new
  end # class Reader
end # module Trith


text:
module Trith
  module VERSION
    MAJOR = 0
    MINOR = 0
    TINY  = 4
    EXTRA = nil

    STRING = [MAJOR, MINOR, TINY, EXTRA].compact.join('.')

    ##
    # @return [String]
    def self.to_s() STRING end

    ##
    # @return [String]
    def self.to_str() STRING end

    ##
    # @return [Array(Integer, Integer, Integer)]
    def self.to_a() [MAJOR, MINOR, TINY] end
  end
end


text:
module Trith
  ##
  # The Trith code cache.
  class Cache < RDF::Repository
    ##
    # Returns a cache containing all core functions.
    #
    # @return [Trith::Cache]
    def self.load_core
      load(*Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'etc', '*.nt'))))
    end

    ##
    # @param  [Array<String>] filenames
    # @return [Trith::Cache]
    def self.load(*filenames)
      self.new do |repository|
        filenames.each do |filename|
          repository.load(filename)
        end
      end
    end

    ##
    # @param  [Hash{Symbol => Object} options
    def initialize(options = {}, &block)
      extend Implementation
      super(options, &block)
    end

    ##
    # Returns `true` if the given `function` is cached.
    #
    # @param  [Trith::Function, RDF::Resource] function
    # @return [Boolean]
    def has_function?(function)
      id = case function
        when Trith::Function then function.id
        else Trith::Function.new(function).id
      end
      !query(:subject => id, :predicate => RDF.type, :object => Trith::Function::URI).empty?
    end

    ##
    # Returns `true` if a function with the given `label` is cached.
    #
    # @param  [Symbol, #to_s]         label
    # @param  [Hash{Symbol => Object} options
    # @option options [Symbol, #to_s] :language (nil)
    # @return [Boolean]
    def has_label?(label, options = {})
      !query(:predicate => RDF::RDFS.label, :object => RDF::Literal.new(label.to_s, options)).empty?
    end

    ##
    # Enumerates each function in the cache.
    #
    # @return [Enumerator<Trith::Function>]
    def each_function(&block)
      unless block_given?
        Enumerator.new(self, :each_function)
      else
        query(:predicate => RDF.type, :object => Trith::Function::URI) do |statement|
          block.call(Trith::Function.new(statement.subject, :data => self))
        end
      end
    end

    ##
    # Finds functions fulfilling the given criteria.
    #
    # @param  [Hash{Symbol => Object}] options
    # @option options [Symbol, #to_s]  :label
    # @return [Enumerator<Trith::Function>]
    def find_functions(options = {}, &block)
      unless block_given?
        Enumerator.new(self, :find_functions, options)
      else
        # FIXME: would really need BGP query support in RDF.rb...
        each_function do |function|
          if options.empty?
            block.call(function)
          else
            pattern = case
              when options[:label]
                {:predicate => RDF::RDFS.label, :object => options[:label].to_s}
              else {}
            end
            block.call(function) unless query({:subject => function.id}.merge(pattern)).empty?
          end
        end
      end
    end
  end # class Cache
end # module Trith


text:
module Trith
  ##
  # A base class for Trith compiler targets.
  #
  # @abstract
  class Compiler
    autoload :Ruby, 'trith/compiler/ruby'
    autoload :Java, 'trith/compiler/java'

    # @return [Hash{Symbol => Object}]
    attr_reader :options

    ##
    # @param  [Symbol, #to_sym] target
    # @return [Class]
    def self.for(target = nil, &block)
      target = block.call if block_given?
      case target.to_sym
        when :ruby then Ruby
        when :java then Java
        else nil
      end
    end

    ##
    # @param  [Array<String>]          filenames
    # @param  [Hash{Symbol => Object}] options
    # @return [Compiler]
    def self.compile_files(*filenames)
      options = filenames.last.is_a?(Hash) ? filenames.peek : {}
      self.compile(Reader.read_files(*filenames), options)
    end

    ##
    # @param  [Enumerable]             program
    # @param  [Hash{Symbol => Object}] options
    # @return [Compiler]
    def self.compile(program, options = {})
      self.new(options).compile(program, options)
    end

    ##
    # @param  [Hash{Symbol => Object}] options
    def initialize(options = {})
      @options = options.to_hash.dup
    end

    ##
    # @param  [Enumerable]             program
    # @param  [Hash{Symbol => Object}] options
    # @return [Compiler]
    def compile(program, options = {})
      program = program.respond_to?(:each) ? program : [program]
      program.each { |op| compile_operand(op) }
      self
    end

    protected

    ##
    # @param  [Object] operand
    # @return [void]
    def compile_operand(operand)
      case operand
        when Symbol
          compile_operator(operand)
        when NilClass
          compile_nil(operand)
        when TrueClass, FalseClass
          compile_boolean(operand)
        when Numeric
          compile_number(operand)
        when String
          compile_string(operand)
        when URI
          compile_reference(operand)
        when Array, SXP::List
          compile_quotation(operand)
        when Machine, Function
          compile_quotation(operand.to_a)
        else
          raise NotImplementedError.new("#{self.class}#compile_operand(#{operand.inspect})")
      end
    end

    ##
    # @param  [Symbol, #to_sym] operator
    # @return [void]
    # @abstract
    def compile_operator(operator)
      case operator.to_sym
        when :nil   then compile_nil(nil)
        when :false then compile_boolean(false)
        when :true  then compile_boolean(true)
        else raise NotImplementedError.new("#{self.class}#compile_operator(#{operator.inspect})")
      end
    end

    ##
    # @param  [NilClass] operand
    # @return [void]
    # @abstract
    def compile_nil(operand = nil)
      raise NotImplementedError.new("#{self.class}#compile_nil")
    end

    ##
    # @param  [Boolean] operand
    # @return [void]
    # @abstract
    def compile_boolean(operand)
      raise NotImplementedError.new("#{self.class}#compile_boolean(#{operand.inspect})")
    end

    ##
    # @param  [Numeric] operand
    # @return [void]
    # @abstract
    def compile_number(operand)
      case operand
        when Integer
          compile_integer(operand)
        when Float
          compile_float(operand)
        when BigDecimal
          compile_decimal(operand)
        when Rational
          compile_rational(operand)
        else
          raise NotImplementedError.new("#{self.class}#compile_number(#{operand.inspect})")
      end
    end

    ##
    # @param  [Integer] operand
    # @return [void]
    # @abstract
    def compile_integer(operand)
      raise NotImplementedError.new("#{self.class}#compile_integer(#{operand.inspect})")
    end

    ##
    # @param  [Float] operand
    # @return [void]
    # @abstract
    def compile_float(operand)
      raise NotImplementedError.new("#{self.class}#compile_float(#{operand.inspect})")
    end

    ##
    # @param  [BigDecimal] operand
    # @return [void]
    # @abstract
    def compile_decimal(operand)
      raise NotImplementedError.new("#{self.class}#compile_decimal(#{operand.inspect})")
    end

    ##
    # @param  [Rational] operand
    # @return [void]
    # @abstract
    def compile_rational(operand)
      raise NotImplementedError.new("#{self.class}#compile_rational(#{operand.inspect})")
    end

    ##
    # @param  [String] operand
    # @return [void]
    # @abstract
    def compile_string(operand)
      raise NotImplementedError.new("#{self.class}#compile_string(#{operand.inspect})")
    end

    ##
    # @param  [URI]  operand
    # @return [void]
    # @abstract
    def compile_reference(operand)
      raise NotImplementedError.new("#{self.class}#compile_reference(#{operand.inspect})")
    end

    ##
    # @param  [Array] operand
    # @return [void]
    # @abstract
    def compile_quotation(operand)
      raise NotImplementedError.new("#{self.class}#compile_quotation(#{operand.inspect})")
    end

    ##
    # @private
    def self.inherited(subclass)
      subclass.send(:public_class_method, :new)
      super
    end

    # Prevent the instantiation of this class:
    private_class_method :new
  end # class Compiler
end # module Trith


text:
module Trith
  ##
  # Supporting code for the `3sh` shell.
  module Shell
    require 'readline' unless defined?(Readline)

    autoload :History, 'trith/shell/history'
    autoload :Inspect, 'trith/shell/inspect'

    ##
    # Initializes shell functionality and the Readline library.
    #
    # @param  [Trith::Cache] cache
    # @return [void]
    def self.setup!(cache)
      Readline.completion_proc = completion_proc(cache)
    end

    ##
    # Returns a developer-friendly representation of `value`.
    #
    # @param  [Object]                 value
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect(value, options = {})
      Inspect.inspect(value, {:color => has_color?}.merge(options))
    end

    ##
    # Returns a colorized error message string.
    #
    # @param  [Exception]              error
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.format_error(error, options = {})
      Inspect.colorize(error.to_s, has_color? ? :red : nil)
    end

    ##
    # Reads and returns a line of input from the terminal.
    #
    # @param  [String] prompt
    # @return [String]
    # @see    http://bogojoker.com/readline/
    def self.readline(prompt)
      Readline.readline(prompt)
    end

    ##
    # Returns a symbol indicating which Readline library this Ruby
    # implementation uses.
    #
    # The possible return values are `:readline`, `:libedit` and `:jruby`.
    #
    # The default Ruby versions shipped with Mac OS X use `:libedit` as
    # their Readline library and have buggy functionality that needs to be
    # worked around.
    #
    # @return [Symbol]
    # @see    http://bogojoker.com/readline/#libedit_detection
    def self.readline_library
      @readline_library ||= case RUBY_PLATFORM.to_sym
        when :java
          RUBY_ENGINE.to_sym rescue :jruby   # JRuby 1.4.x/1.5.x
        else
          begin                              # Ruby with `readline`
            Readline.emacs_editing_mode
            :readline
          rescue NotImplementedError         # Ruby with `libedit` (Mac OS X)
            :libedit
          rescue
            :libedit                         # just to be on the safe side
          end
      end
    end

    ##
    # Returns an input completion proc for use with Readline.
    #
    # @param  [Trith::Cache] cache
    # @return [Proc]
    # @see    http://bogojoker.com/readline/
    def self.completion_proc(cache)
      Readline.completion_append_character = ' ' unless broken_append_character?
      proc do |prefix|
        candidates = []
        # TODO: optimize this once RDF::Queryable supports #query([s, p, /o/])
        cache.each_function do |function|
          function.labels.each do |label|
            candidates << label.to_s if label.to_s.start_with?(prefix)
          end
        end
        candidates.map! { |candidate| candidate << ' ' } if broken_append_character?
        candidates.uniq
      end
    end

    ##
    # Returns `true` if the shell's terminal supports ANSI color escapes.
    #
    # @return [Boolean]
    def self.has_color?
      @has_color ||= case
        when !$stdout.isatty        then false
        when ENV['TERM'] =~ /color/ then true  # e.g. "xterm-color"
        else
          begin
            # @see http://rubygems.org/gems/ruby-terminfo
            require 'terminfo' unless defined?(TermInfo)
            TermInfo.default_object.tigetnum('colors').to_i > 1
          rescue
            false # the only safe default
          end
      end
    end

    protected

    ##
    # Returns `true` if the first call to `Readline::HISTORY.push` is broken
    # on this Ruby implementation.
    #
    # This is a `libedit`-related bug encountered with the default Ruby
    # versions shipped with Mac OS X.
    #
    # @return [Boolean]
    # @see    http://bogojoker.com/readline/#libedit_history_issue
    def self.broken_initial_history?
      readline_library == :libedit
    end

    ##
    # Returns `true` if `Readline.completion_append_character` is broken on
    # this Ruby implementation.
    #
    # The feature in question is currently broken on Ruby with `libedit` and
    # just unimplemented on JRuby 1.4.x/1.5.x
    #
    # @return [Boolean]
    # @see    http://bogojoker.com/readline/#libedit_completion_append_character_issue
    def self.broken_append_character?
      [:libedit, :jruby].include?(readline_library)
    end
  end # module Shell
end # module Trith


text:
module Trith
  ##
  # A Trith function.
  class Function
    URI = RDF::URI("http://trith.org/lang/Function").freeze

    # @return [RDF::Resource]
    attr_accessor :id

    # @return [Symbol]
    attr_accessor :label

    # @return [String]
    attr_accessor :comment

    ##
    # @param  [RDF::Resource] id
    def initialize(id = nil, options = {}, &block)
      @id = case id
        when nil then RDF::Node.new
        when RDF::Resource then id
        else RDF::Resource.new(id)
      end

      if block_given?
        case block.arity
          when 1 then block.call(self)
          else self.instance_eval(&block)
        end
      end
    end

    ##
    # @return [Symbol]
    def label
      @label ||= id.to_s.sub(/^(.*)\/([^\/]+)$/, '\2').to_sym # FIXME
    end

    ##
    # @return [Enumerable<Symbol>]
    def labels
      [label] # FIXME
    end

    ##
    # Returns `true` if this is a primitive function.
    #
    # Primitive functions are implemented directly in the Trith interpreter
    # or compiler using native code.
    #
    # @return [Boolean]
    def is_primitive?
      false # TODO
    end

    alias_method :is_native?, :is_primitive?

    ##
    # Returns a developer-friendly representation of this function.
    #
    # @return [String]
    def inspect
      sprintf("#<%s:%#0x(%s)>", self.class.name, __id__, id.to_s)
    end

    ##
    # Returns the RDF representation of this function.
    #
    # @return [RDF::Graph]
    def to_rdf
      RDF::Graph.new(id) do |graph|
        graph << [id, RDF.type, Trith::Function::URI]
        graph << [id, RDF::RDFS.label, label]   if label
        graph << [id, RDF::RDFS.comment, label] if comment
      end
    end

    ##
    # @return [Enumerator]
    def each_statement(&block)
      to_rdf.each_statement(&block)
    end
  end # class Function
end # module Trith


text:
module Trith
  ##
  # The Trith virtual machine.
  class Machine
    # @return [Array]
    attr_reader :stack

    # @return [Array]
    attr_reader :queue

    # @return [Proc]
    attr_accessor :execute_hook

    ##
    # Executes `code` in a new virtual machine instance.
    #
    # The machine will halt when the queue is exhausted, when encountering
    # a `halt` operator, or when encountering an error condition.
    #
    # @overload self.run(code)
    #   @param  [Array] code
    #   @return [Object]
    #
    # @overload self.run(code)
    #   @param  [Array] code
    #   @yield  [machine]
    #   @yieldparam [Machine] machine
    #   @return [Object]
    #
    # @return [Object]
    def self.run(code = [], &block)
      self.new([], code).execute(&block).peek
    end

    ##
    # Initializes a new virtual machine with the given initial `stack`,
    # `queue` and environment.
    #
    # @param  [Array] stack
    # @param  [Array] queue
    # @param  [Hash]  env
    # @yield  [machine]
    # @yieldparam [Machine] machine
    def initialize(stack = [], queue = [], env = {}, &block)
      @stack, @queue, @env = stack, queue, {}
      import!(Trith::Core)
      import!(Trith::Math)
      env.each do |name, operator|
        if operator.is_a?(Proc)
          define!(name, &operator)
        else
          define!(name, operator)
        end
      end
      execute(&block) if block_given?
    end

    ##
    # Returns a developer-friendly representation of this machine.
    #
    # @return [String]
    def inspect
      sprintf("#<%s:%#0x(%s : %s)>", self.class.name, __id__, @stack.inspect, @queue.inspect)
    end

    ##
    # Imports operators from the given `module` into the virtual machine's
    # current environment.
    #
    # @param  [Module] module
    # @return [Machine]
    def import!(mod)
      case mod
        when Module   then import_module!(mod)
        when Function then # TODO
        else # TODO: error
      end
      self
    end

    ##
    # Defines a new operator `name` that will execute the given `code`.
    #
    # @param  [Symbol, #to_sym]        name
    # @param  [Array]                  code
    # @param  [Hash{Symbol => Object}] options
    # @return [Machine]
    def define!(name, code = [], options = {}, &block)
      @env[name = name.to_sym] = lambda { execute(code, &block) }
      define_singleton_method(name, &@env[name]) unless options[:method] == false
      self
    end

    ##
    # Returns the concatenation of the stack and queue.
    #
    # @return [Array]
    def to_a
      (@stack + @queue).to_a
    end

    ##
    # Returns the operand at the top of the stack.
    #
    # If the stack is empty, returns `nil`.
    #
    # @return [Object]
    def peek
      @stack.last
    end

    ##
    # Pops and returns one or more operands off the top of the stack.
    #
    # If the stack doesn't have sufficient operands, raises a stack
    # underflow error.
    #
    # @overload pop
    #   @return [Object]
    #
    # @overload pop(n)
    #   @param  [Integer] n
    #   @return [Array]
    #
    # @return [Object]
    # @raise  [StackUnderflowError]
    def pop(n = nil)
      if @stack.size < (n || 1)
        raise StackUnderflowError.new
      else
        n ? @stack.pop(n) : @stack.pop
      end
    end

    ##
    # Pushes the given operands onto the top of the stack.
    #
    # If no operands were given, shifts an operand off the front of the
    # queue.
    #
    # @overload push
    #   @return [Machine]
    #
    # @overload push(*ops)
    #   @param  [Array] ops
    #   @return [Machine]
    #
    # @return [Machine]
    def push(*ops)
      @stack.push(*(ops.empty? ? [shift] : ops))
      self
    end

    ##
    # Shifts and returns one or more operands off the front of the queue.
    #
    # If the queue doesn't have sufficient operands, throws a `:halt`
    # symbol.
    #
    # @overload shift
    #   @return [Object]
    #
    # @overload shift(n)
    #   @param  [Integer] n
    #   @return [Array]
    #
    # @return [Object]
    def shift(n = nil)
      if @queue.size < (n || 1)
        throw(:halt) # caught in `#execute`
      else
        n ? @queue.shift(n) : @queue.shift
      end
    end

    ##
    # Prepends the given operands onto the front of the queue.
    #
    # If no operands were given, pops an operand off the top of the stack.
    #
    # @overload unshift
    #   @return [Machine]
    #
    # @overload unshift(*ops)
    #   @param  [Array] ops
    #   @return [Machine]
    #
    # @return [Machine]
    def unshift(*ops)
      @queue.unshift(*(ops.empty? ? [pop] : ops))
      self
    end

    ##
    # Executes the virtual machine until it halts.
    #
    # The machine will halt when the queue is exhausted, when encountering
    # a `halt` operator, or when encountering an error condition.
    #
    # @overload execute(code)
    #   @param  [Array] code
    #   @return [Machine]
    #
    # @overload execute(code)
    #   @param  [Array] code
    #   @yield  [machine]
    #   @yieldparam [Machine] machine
    #   @return [Machine]
    #
    # @return [Machine]
    def execute(code = [], &block)
      @queue.unshift(*code) unless code.empty?

      catch(:halt) do # thrown in `#shift`
        Kernel.loop do
          execute_hook.call if execute_hook && !@queue.empty?

          op = shift
          case
            when operator?(op)
              if fn = @env[op]
                fn.call
              else
                unshift(op)
                raise InvalidOperatorError.new(op)
              end
            when operand?(op)
              push(op)
            else
              raise InvalidOperandError.new(op)
          end
        end
      end

      if block_given?
        case block.arity
          when 1 then block.call(self)
          else instance_eval(&block)
        end
      end

      return self
    end

    protected

    ##
    # Returns `true` if `op` is an operator.
    #
    # @param  [Object] op
    # @return [Boolean]
    def operator?(op)
      op.is_a?(Symbol)
    end

    ##
    # Returns `true` if `op` is an operand.
    #
    # @param  [Object] op
    # @return [Boolean]
    def operand?(op)
      !operator?(op)
    end

    ##
    # Returns `true` if `op` is a quotation.
    #
    # @param  [Object] op
    # @return [Boolean]
    def quotation?(op)
      op.is_a?(Array)
    end

    ##
    # @private
    def method_missing(operator, *operands, &block)
      begin
        super
      rescue NoMethodError => e
        raise InvalidOperatorError.new(operator)
      end
    end

    ##
    # Imports operators from the given `module` into the virtual machine's
    # current environment.
    #
    # @param  [Module] module
    # @return [void]
    def import_module!(mod)
      # Include all instance methods from the module into `self`:
      this = class << self; self; end
      this.send(:include, mod)

      # Create wrapper methods to support operators that need their
      # arguments and result marshalled from/to the virtual machine stack:
      mod.public_instance_methods(true).map(&:to_sym).each do |method|
        op = mod.instance_method(method).bind(self)
        case method
          when :stack_ # FIXME
            @env[:stack] = op
          else
            @env[method] = this.send(:define_method, method) do |*args|
              result = op.call(*(!args.empty? ? args : (op.arity > 0 ? pop(op.arity) : [])))
              push(result) unless result.equal?(self)
              return self
            end
        end
      end
    end

    ##
    # Invokes the given block with an empty code queue, restoring the
    # queue contents after the block returns.
    #
    # @yield
    # @param  [Symbol] name
    # @return [void]
    def with_saved_continuation(name = nil, &block)
      cc = capture_continuation
      case block.arity
        when 1 then block.call(cc)
        else block.call
      end
      @queue.push(*cc) unless cc.empty?
      self
    end

    ##
    # Invokes the given block with an empty code queue, passing the previous
    # queue contents as an argument.
    #
    # @yield
    # @return [void]
    def with_current_continuation(&block)
      block.call(capture_continuation)
      self
    end

    ##
    # Captures the current contents of the code queue, returning them to the
    # caller after first clearing the queue.
    #
    # @return [Array]
    def capture_continuation(full = false)
      continuation = @queue.dup
      @queue.clear
      continuation
    end

    ###
    # Invalid operator
    class InvalidOperatorError < NoMethodError
      attr_reader :operator

      def initialize(operator)
        @operator = operator
        super("invalid operator: #{operator}")
      end
    end

    ###
    # Invalid operand
    class InvalidOperandError < ArgumentError
      attr_reader :operand
      attr_reader :operator

      def initialize(operand, operator = nil)
        @operand, @operator = operand, operator
        super("invalid operand: #{operand.inspect}")
      end
    end

    ###
    # Stack underflow
    class StackUnderflowError < RuntimeError; end
  end # class Machine
end # module Trith


text:
module Trith; class Compiler
  ##
  # A Trith-to-Java compiler.
  class Java < Compiler
    ##
    # @param  [Hash{Symbol => Object}] options
    def initialize(options = {})
      super(options)
      @options[:class] ||= 'a'
      @output = StringIO.new
    end

    ##
    # @return [String]
    def to_s
      output = StringIO.new
      output.puts "package #{@options[:package]};" if @options[:package]
      output.puts "import trith.lang.*;"
      output.puts "import trith.core.*;"
      output.puts
      output.puts "public class #{@options[:class]} implements Operator {"
      output.puts "  public static void main(String[] args) {"
      output.puts "    Machine machine = new StandardMachine();"
      output.puts "    for (String arg : args) {"
      output.puts "      machine.push(arg);"
      output.puts "    }"
      output.puts "    machine.execute(new #{@options[:class]}());"
      output.puts "  }"
      output.puts
      output.puts "  public void execute(Machine machine) {"
      output.write @output.string
      output.puts "  }"
      output.puts "}"
      output.string
    end

    protected

    ##
    # @see Trith::Compiler#compile_operator
    # @private
    def compile_operator(operator)
      emit("machine.execute(new trith.core.#{operator}());") # FIXME
    end

    ##
    # @see Trith::Compiler#compile_nil
    # @private
    def compile_nil(operand = nil)
      emit("machine.push(null);")
    end

    ##
    # @see Trith::Compiler#compile_boolean
    # @private
    def compile_boolean(operand)
      emit("machine.push(#{operand});")
    end

    ##
    # @see Trith::Compiler#compile_number
    # @private
    def compile_number(operand)
      emit("machine.push(#{operand});") # FIXME
    end

    alias_method :compile_integer,  :compile_number
    alias_method :compile_float,    :compile_number
    alias_method :compile_decimal,  :compile_number
    alias_method :compile_rational, :compile_number

    ##
    # @see Trith::Compiler#compile_string
    # @private
    def compile_string(operand)
      emit("machine.push(#{operand.inspect});") # FIXME
    end

    ##
    # @see Trith::Compiler#compile_reference
    # @private
    def compile_reference(operand)
      emit("machine.push(#{operand.to_s.inspect});") # FIXME
    end

    ##
    # @see Trith::Compiler#compile_quotation
    # @private
    def compile_quotation(operand)
      emit("machine.push(#{operand.inspect});") # FIXME
    end

    ##
    # @param  [String, #to_s] line
    # @return [void]
    def emit(line)
      @output.puts("    " << line.to_s)
    end
  end # class Java
end; end # class Trith::Compiler


text:
module Trith; class Compiler
  ##
  # A Trith-to-Ruby compiler.
  class Ruby < Compiler
    SHEBANG = "#!/usr/bin/env ruby -rubygems"

    ##
    # @param  [Hash{Symbol => Object}] options
    def initialize(options = {})
      super(options)
      @options[:shebang] ||= SHEBANG
      @output = StringIO.new
    end

    ##
    # @return [String]
    def to_s
      output = StringIO.new
      output.puts @options[:shebang]
      output.puts "require 'rubygems'" if @options[:rubygems]
      output.puts "require 'trith'"
      output.puts
      output.puts "Trith::Machine.run(ARGV) do"
      output.write @output.string
      output.puts "end"
      output.string
    end

    protected

    ##
    # @see Trith::Compiler#compile_operator
    # @private
    def compile_operator(operator)
      emit("call(:#{operator}).execute")
    end

    ##
    # @see Trith::Compiler#compile_nil
    # @private
    def compile_nil(operand = nil)
      emit("push(nil)")
    end

    ##
    # @see Trith::Compiler#compile_boolean
    # @private
    def compile_boolean(operand)
      emit("push(#{operand})")
    end

    ##
    # @see Trith::Compiler#compile_number
    # @private
    def compile_number(operand)
      emit("push(#{operand})")
    end

    alias_method :compile_integer,  :compile_number
    alias_method :compile_float,    :compile_number
    alias_method :compile_decimal,  :compile_number
    alias_method :compile_rational, :compile_number

    ##
    # @see Trith::Compiler#compile_string
    # @private
    def compile_string(operand)
      emit("push(#{operand.inspect})")
    end

    ##
    # @see Trith::Compiler#compile_reference
    # @private
    def compile_reference(operand)
      emit("push(Trith::URI.new(#{operand.to_s.inspect}))")
    end

    ##
    # @see Trith::Compiler#compile_quotation
    # @private
    def compile_quotation(operand)
      emit("push(#{operand.inspect})")
    end

    ##
    # @param  [String, #to_s] line
    # @return [void]
    def emit(line)
      @output.puts("  " << line.to_s)
    end
  end # class Ruby
end; end # class Trith::Compiler


text:
module Trith; module Shell
  ##
  module Inspect
    ##
    # Escape codes for colored shell output.
    module Color
      NOTHING      = "\033[0;0m".freeze
      BLACK        = "\033[0;30m".freeze
      RED          = "\033[0;31m".freeze
      GREEN        = "\033[0;32m".freeze
      BROWN        = "\033[0;33m".freeze
      BLUE         = "\033[0;34m".freeze
      PURPLE       = "\033[0;35m".freeze
      CYAN         = "\033[0;36m".freeze
      LIGHT_GRAY   = "\033[0;37m".freeze
      DARK_GRAY    = "\033[1;30m".freeze
      LIGHT_RED    = "\033[1;31m".freeze
      LIGHT_GREEN  = "\033[1;32m".freeze
      YELLOW       = "\033[1;33m".freeze
      LIGHT_BLUE   = "\033[1;34m".freeze
      LIGHT_PURPLE = "\033[1;35m".freeze
      LIGHT_CYAN   = "\033[1;36m".freeze
      WHITE        = "\033[1;37m".freeze

      # Freeze all color escape strings:
      constants.each do |color|
        color.force_encoding(Encoding::ASCII) if color.respond_to?(:force_encoding)
        color.freeze
      end
    end

    ##
    # @param  [String, #to_s] text
    # @param  [Symbol, #to_s] color
    # @return [String]
    def self.colorize(text, color)
      !color ? text.to_s : [(Color.const_get(color.to_s.upcase) rescue nil), text.to_s, Color::NOTHING].join('')
    end

    ##
    # @param  [Object]                 value
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect(value, options = {})
      case value
        when NilClass   then colorize(:nil, options[:color] ? :green : nil)
        when FalseClass then colorize(false, options[:color] ? :green : nil)
        when TrueClass  then colorize(true, options[:color] ? :green : nil)
        when Symbol     then colorize(value.to_s, options[:color] ? :yellow : nil)
        when Numeric    then colorize(value.inspect, options[:color] ? :cyan : nil)
        when String     then inspect_string(value, options)
        when Array      then inspect_array(value, options)
        when RDF::URI   then inspect_reference(value, options)
        when Machine    then inspect_machine(value, options)
        else value.inspect
      end
    end

    ##
    # @param  [Machine]                machine
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect_machine(machine, options = {})
      (options[:prefix].to_s || '') +
        (options[:align] ? ' ' * [20 - inspect(machine.stack, :color => false).size, 0].max : '') +
        inspect(machine.stack, options) + ' : ' +
        inspect(machine.queue, options)
    end

    ##
    # @param  [Array, #to_ary]         array
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect_array(array, options = {})
      colorize('[', options[:color] ? :green : nil) <<
      array.to_ary.map { |element| inspect(element, options) }.join(' ') <<
      colorize(']', options[:color] ? :green : nil)
    end

    ##
    # @param  [String, #to_str]        string
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect_string(string, options = {})
      colorize('"', options[:color] ? :red : nil) <<
      colorize(string.to_str.inspect[1...-1], options[:color] ? :cyan : nil) <<
      colorize('"', options[:color] ? :red : nil)
    end

    ##
    # @param  [RDF::URI, #to_uri]      uri
    # @param  [Hash{Symbol => Object}] options
    # @return [String]
    def self.inspect_reference(uri, options = {})
      colorize('<', options[:color] ? :red : nil) <<
      colorize(uri.to_uri.to_s, options[:color] ? :cyan : nil) <<
      colorize('>', options[:color] ? :red : nil)
    end
  end # module Color
end; end # module Trith::Shell


text:
module Trith; module Shell
  ##
  # Supporting code for the `3sh` shell's input line history.
  module History
    require 'readline' unless defined?(Readline)

    FILE = File.join(ENV['TRITH_HOME'] || '~', '.trith', '3sh.log').freeze unless const_defined?(:FILE)
    MODE = 0640

    ##
    # Loads the shell history from the `~/.trith/3sh.log` file.
    #
    # @return [void]
    def self.load!
      unless (lines = File.readlines(File.expand_path(FILE)) rescue []).empty?
        Readline::HISTORY.push(*lines.map { |line| line.chomp.strip })
        @load_count = Readline::HISTORY.size
      end
    end

    ##
    # Dumps the shell history to the `~/.trith/3sh.log` file.
    #
    # @return [void]
    def self.dump!
      begin
        require 'fileutils' unless defined?(FileUtils)
        FileUtils.mkdir_p(File.expand_path(File.dirname(FILE)), :mode => 0750)
        File.open(File.expand_path(FILE), 'a+', MODE) do |file|
          lines = Readline::HISTORY.to_a
          lines.slice!(0, @load_count) if @load_count
          file.puts(lines)
        end
      rescue Errno::ENOENT # ignore 'No such file or directory' errors
      rescue Errno::EACCES # ignore 'Permission denied' errors
      end
    end

    ##
    # Returns `true` if the shell history is empty.
    #
    # @return [Boolean]
    def self.empty?
      Readline::HISTORY.empty?
    end

    ##
    # Returns the number of lines in the shell history.
    #
    # @return [Integer]
    def self.size
      Readline::HISTORY.size
    end

    ##
    # Returns `true` if the shell history includes `line`.
    #
    # @param  [String] line
    # @return [Boolean]
    def self.include?(line)
      Readline::HISTORY.include?(line)
    end

    ##
    # Appends `line` to the shell history.
    #
    # Does not append empty lines or consecutive duplicates, and works
    # around implementation-specific issues where needed.
    #
    # @param  [String] line
    # @return [void]
    def self.push(line)
      unless line =~ /^\s$/ || line == peek
        Readline::HISTORY.push(line)

        # This is a workaround for a libedit-related bug encountered with
        # the default Ruby versions shipped with Mac OS X.
        # @see http://bogojoker.com/readline/#libedit_history_issue
        unless Readline::HISTORY.include?(line)
          Readline::HISTORY.push(line)
        end
      end
    end

    ##
    # Returns the most recent line from the shell history.
    #
    # @return [String]
    def self.peek
      case
        when Readline::HISTORY.respond_to?(:peek)
          Readline::HISTORY.peek
        when Readline::HISTORY.respond_to?(:last)
          Readline::HISTORY.last
        else
          Readline::HISTORY.to_a.last
      end
    end

    ##
    # Returns an array representation of the shell history.
    #
    # @return [Array<String>]
    def self.to_a
      Readline::HISTORY.to_a
    end
  end # module History
end; end # module Trith::Shell


text:
module Trith
  ##
  # The Trith core operators.
  module Core
    require 'trith/vocab/core/execution'
    require 'trith/vocab/core/stack'
    require 'trith/vocab/core/bitwise'
    require 'trith/vocab/core/boolean'
    require 'trith/vocab/core/comparison'
    require 'trith/vocab/core/numeric'
    require 'trith/vocab/core/sequence'
    require 'trith/vocab/core/textual'
    require 'trith/vocab/core/output'

    # Include all submodule methods directly into Trith::Core:
    constants.each { |mod| include(const_get(mod)) }
  end # module Core
end # module Trith


text:
module Trith
  ##
  # The Trith math operators.
  #
  # @see http://ruby-doc.org/core/classes/Math.html
  module Math
    require 'trith/vocab/math/arithmetic'
    require 'trith/vocab/math/constants'
    require 'trith/vocab/math/operators'
    require 'trith/vocab/math/trigonometry'

    # Include all submodule methods directly into Trith::Math:
    constants.each { |mod| include(const_get(mod)) }
  end # module Math
end # module Trith


text:
module Trith; module Core
  ##
  # Sequence operators.
  #
  # @see http://ruby-doc.org/core-1.9/classes/Enumerable.html
  # @see http://ruby-doc.org/core-1.9/classes/Enumerator.html
  # @see http://en.wikipedia.org/wiki/Sequence
  module Sequence
    ##
    # Sequence predicates.
    module Predicates
      ##
      # @param  [String, #each, #to_enum] obj
      # @return [Boolean]
      def seqp(obj)
        case obj
          when String then true
          when Array  then true
          else case
            when obj.respond_to?(:each)    then true
            when obj.respond_to?(:to_enum) then true
            else false
          end
        end
      end
      alias_method :seq?, :seqp

      ##
      # @param  [#empty?, #size, #each] seq
      # @return [Boolean]
      def emptyp(seq)
        case
          when seq.respond_to?(:empty?)
            seq.empty?
          when seq.respond_to?(:size)
            seq.size.zero?
          when seq.respond_to?(:each)
            seq.each.to_a.empty? # TODO: optimize
          else
            raise Machine::InvalidOperandError.new(seq, :emptyp)
        end
      end
      alias_method :empty?, :emptyp

      ##
      # @param  [Object]          elt
      # @param  [#member?, #each] seq
      # @return [Boolean]
      def memberp(elt, seq)
        case
          when seq.respond_to?(:member?)
            seq.member?(elt)
          when seq.respond_to?(:each)
            seq.each.member?(elt)
          else
            raise Machine::InvalidOperandError.new(seq, :memberp)
        end
      end
      alias_method :member?, :memberp
    end # module Predicates

    ##
    # Sequence constructors.
    module Constructors
      ##
      # @param  [String, #each, #to_enum] obj
      # @return [Enumerator]
      def seq(obj)
        case obj
          when String then obj.each_char
          when Array  then obj.each
          else case
            when obj.respond_to?(:each)
              obj.each
            when obj.respond_to?(:to_enum)
              obj.to_enum
            else
              raise Machine::InvalidOperandError.new(obj, :seq)
          end
        end
      end

      ##
      # @overload cons(obj, seq)
      #   @param  [#to_s]        obj
      #   @param  [String]       seq
      #   @return [String]
      #
      # @overload cons(obj, seq)
      #   @param  [Object]       obj
      #   @param  [Array, #to_a] seq
      #   @return [Array]
      #
      # @return []
      def cons(obj, seq)
        case seq
          when String
            seq.dup.insert(0, obj.to_s.chr)
          when Array
            seq.dup.unshift(obj)
          else case
            when seq.respond_to?(:to_a)
              seq.to_a.unshift(obj)
            else # TODO: support for `#each`
          end
        end
      end

      ##
      # @param  [Array, #[], #each] seq
      # @return [Machine]
      def uncons(seq)
        case
          when seq.respond_to?(:[])
            case
              when seq.empty?
                raise Machine::InvalidOperandError.new(seq, :uncons)
              else
                push(seq[0], seq[1..-1]) # FIXME
            end
          when seq.respond_to?(:each)
            uncons(seq.each.to_a)
          else
            raise Machine::InvalidOperandError.new(seq, :uncons)
        end
      end

      ##
      # @param  [Integer, #to_i] n
      # @return [Enumerable]
      def list(n)
        stack.pop(n.to_i)
      end

      ##
      # @param  [Integer, #to_i] n
      # @return [Enumerable]
      def iota(n)
        # TODO: should support negative ranges as well.
        (0...(n.to_i)).to_a # FIXME
      end

      ##
      # @param  [Integer, #to_i] a
      # @param  [Integer, #to_i] b
      # @return [Enumerable]
      def range(a, b)
        # TODO: should support negative ranges as well.
        ((a.to_i)..(b.to_i)).to_a # FIXME
      end
    end # module Constructors

    ##
    # Sequence accessors.
    module Accessors
      ##
      # @param  [#length, #size, #each] seq
      # @return [Integer]
      def length(seq)
        case
          when seq.respond_to?(:length)
            seq.length
          when seq.respond_to?(:size)
            seq.size
          when seq.respond_to?(:each)
            seq.each.to_a.size # TODO: optimize
          else
            raise Machine::InvalidOperandError.new(seq, :length)
        end
      end

      ##
      # @param  [#rest, #[], #each] seq
      # @return [Enumerable]
      def rest(seq)
        # TODO: check semantics for empty sequences
        case
          when seq.respond_to?(:rest)
            seq.rest
          when seq.respond_to?(:[])
            seq[1..-1]
          when seq.respond_to?(:each)
            seq.each.to_a[1..-1] # TODO: optimize
          else
            raise Machine::InvalidOperandError.new(seq, :rest)
        end
      end

      ##
      # @param  [#first, #[], #each] seq
      # @return [Object]
      def first(seq)
        case seq
          when String
            seq[0].chr rescue nil # Ruby 1.8 compatible
          else case
            when seq.respond_to?(:first) then seq.first
            else nth(seq, 0)
          end
        end
      end

      ##
      # @param  [#second, #[], #each] seq
      # @return [Object]
      def second(seq)
        case
          when seq.respond_to?(:second) then seq.second
          else nth(seq, 1)
        end
      end

      ##
      # @param  [#third, #[], #each] seq
      # @return [Object]
      def third(seq)
        case
          when seq.respond_to?(:third) then seq.third
          else nth(seq, 2)
        end
      end

      ##
      # @param  [#fourth, #[], #each] seq
      # @return [Object]
      def fourth(seq)
        case
          when seq.respond_to?(:fourth) then seq.fourth
          else nth(seq, 3)
        end
      end

      ##
      # @param  [#fifth, #[], #each] seq
      # @return [Object]
      def fifth(seq)
        case
          when seq.respond_to?(:fifth) then seq.fifth
          else nth(seq, 4)
        end
      end

      ##
      # @param  [#sixth, #[], #each] seq
      # @return [Object]
      def sixth(seq)
        case
          when seq.respond_to?(:sixth) then seq.sixth
          else nth(seq, 5)
        end
      end

      ##
      # @param  [#seventh, #[], #each] seq
      # @return [Object]
      def seventh(seq)
        case
          when seq.respond_to?(:seventh) then seq.seventh
          else nth(seq, 6)
        end
      end

      ##
      # @param  [#eighth, #[], #each] seq
      # @return [Object]
      def eighth(seq)
        case
          when seq.respond_to?(:eighth) then seq.eighth
          else nth(seq, 7)
        end
      end

      ##
      # @param  [#ninth, #[], #each] seq
      # @return [Object]
      def ninth(seq)
        case
          when seq.respond_to?(:ninth) then seq.ninth
          else nth(seq, 8)
        end
      end

      ##
      # @param  [#tenth, #[], #each] seq
      # @return [Object]
      def tenth(seq)
        case
          when seq.respond_to?(:tenth) then seq.tenth
          else nth(seq, 9)
        end
      end

      ##
      # @param  [#nth, #[], #each] seq
      # @param  [Integer, #to_i]   n
      # @return [Object]
      def nth(seq, n)
        case seq
          when String
            seq[n.to_i].chr rescue nil # Ruby 1.8 compatible
          else case
            when seq.respond_to?(:nth)
              seq.nth(n)
            when seq.respond_to?(:[])
              seq[n.to_i]
            when seq.respond_to?(:each)
              seq.each.to_a[n.to_i] # TODO: optimize
            else
              raise Machine::InvalidOperandError.new(seq, :nth)
          end
        end
      end

      ##
      # @param  [#last, #[], #each] seq
      # @return [Object]
      def last(seq)
        case seq
          when String
            seq[-1].chr rescue nil # Ruby 1.8 compatible
          else case
            when seq.respond_to?(:last)
              seq.last
            when seq.respond_to?(:[])
              seq[-1]
            when seq.respond_to?(:each)
              seq.each.to_a.last # TODO: optimize
            else
              raise Machine::InvalidOperandError.new(seq, :last)
          end
        end
      end
    end # module Accessors

    ##
    # Sequence operators.
    module Operators
      ##
      # @param  [#concat, #each] seq1
      # @param  [#each]          seq2
      # @return [Enumerable]
      def concat(seq1, seq2)
        case
          when seq1.respond_to?(:concat)
            seq1.dup.concat(seq2)
          when seq1.respond_to?(:each)
            seq1.each.to_a.concat(seq2.each.to_a) # TODO: optimize
          else
            raise Machine::InvalidOperandError.new(seq1, :concat)
        end
      end

      ##
      # @param  [#reverse, #each] seq
      # @return [Enumerable]
      def reverse(seq)
        case seq
          when String then seq.reverse
          when Array  then seq.reverse
          else case
            when seq.respond_to?(:reverse)
              seq.reverse
            when seq.respond_to?(:each)
              seq.each.to_a.reverse # TODO: optimize
            else
              raise Machine::InvalidOperandError.new(seq, :reverse)
          end
        end
      end

      ##
      # @param  [#flatten, #each] seq
      # @return [Enumerable]
      def flatten(seq)
        case seq
          when String then seq
          when Array  then seq.flatten
          else case
            when seq.respond_to?(:flatten)
              seq.flatten
            when seq.respond_to?(:each)
              seq.each.to_a.flatten # TODO: optimize
            else
              raise Machine::InvalidOperandError.new(seq, :flatten)
          end
        end
      end
    end # module Operators

    ##
    # Sequence combinators.
    module Combinators
      ##
      # @param  [#each] seq
      # @param  [Array] quot
      # @return [Machine]
      def each(seq, quot)
        seq = case seq
          when String then seq.each_char
          else case
            when seq.respond_to?(:each) then seq.each
            else raise Machine::InvalidOperandError.new(seq, :each)
          end
        end
        with_saved_continuation(:each) do
          seq.each { |elem| push(elem).execute(quot) }
        end
      end

      ##
      # @param  [#map, #each] seq
      # @param  [Array]       quot
      # @return [Machine]
      def map(seq, quot)
        seq = case seq
          when String then seq.each_char
          else case
            when seq.respond_to?(:map)  then seq
            when seq.respond_to?(:each) then seq.each
            else raise Machine::InvalidOperandError.new(seq, :map)
          end
        end
        with_saved_continuation(:map) do
          push(seq.map { |elem| push(elem).execute(quot).pop })
        end
      end

      ##
      # @param  [#reduce, #each] seq
      # @param  [Object]         identity
      # @param  [Array]          quot
      # @return [Machine]
      def foldl(seq, identity, quot)
        seq = case seq
          when String then seq.each_char
          else case
            when seq.respond_to?(:reduce) then seq
            when seq.respond_to?(:each)   then seq.each
            else raise Machine::InvalidOperandError.new(seq, :foldl)
          end
        end
        with_saved_continuation(:foldl) do
          push(seq.reduce(identity) { |prev, elem| push(prev, elem).execute(quot).pop })
        end
      end
      alias_method :fold,   :foldl
      alias_method :reduce, :foldl

      ##
      # @param  [#reduce, #each] seq
      # @param  [Array]          quot
      # @return [Machine]
      def foldl1(seq, quot)
        raise Machine::InvalidOperandError.new(seq, :foldl1) if seq.empty?
        seq = case seq
          when String then seq.each_char.to_a
          else case
            when seq.respond_to?(:reduce) then seq.dup
            when seq.respond_to?(:each)   then seq.each.to_a
            else raise Machine::InvalidOperandError.new(seq, :foldl1)
          end
        end
        with_saved_continuation(:foldl1) do
          push(seq.reduce(seq.pop) { |prev, elem| push(prev, elem).execute(quot).pop })
        end
      end
    end # module Combinators

    # Include all submodule methods directly into Trith::Core::Sequence:
    constants.each { |mod| include(const_get(mod)) }
  end # module Sequence
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Boolean operators.
  #
  # @see http://ruby-doc.org/core-1.9/classes/NilClass.html
  # @see http://ruby-doc.org/core-1.9/classes/FalseClass.html
  # @see http://ruby-doc.org/core-1.9/classes/TrueClass.html
  # @see http://en.wikipedia.org/wiki/Nil#Computer_programming
  # @see http://en.wikipedia.org/wiki/Boolean_data_type
  module Boolean
    ##
    # Boolean predicates.
    module Predicates
      ##
      # @param  [Object, #nil?] obj
      # @return [Boolean]
      def nilp(obj)
        obj.nil?
      end
      alias_method :nil?, :nilp

      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def boolp(obj)
        obj.equal?(false) || obj.equal?(true)
      end
      alias_method :bool?, :boolp

      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def falsep(obj)
        obj.equal?(false)
      end
      alias_method :false?, :falsep

      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def truep(obj)
        obj.equal?(true)
      end
      alias_method :true?, :truep

      ##
      # @param  [Object] a
      # @return [Object]
      def notp(a)
        !a
      end
      alias_method :not?, :notp

      ##
      # @param  [Object] a
      # @param  [Object] b
      # @return [Object]
      def andp(a, b)
        a && b
      end
      alias_method :and?, :andp

      ##
      # @param  [Object] a
      # @param  [Object] b
      # @return [Object]
      def orp(a, b)
        a || b
      end
      alias_method :or?, :orp

      ##
      # @param  [Object] a
      # @param  [Object] b
      # @return [Object]
      def xorp(a, b)
        a ^ b
      end
      alias_method :xor?, :xorp
    end # module Predicates

    ##
    # Boolean constructors.
    module Constructors
      ##
      # @return [NilClass]
      def nil
        nil
      end

      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def bool(obj)
        !!obj
      end

      ##
      # @return [FalseClass]
      def false
        false
      end

      ##
      # @return [TrueClass]
      def true
        true
      end
    end # module Constructors

    # Include all submodule methods directly into Trith::Core::Boolean:
    constants.each { |mod| include(const_get(mod)) }
  end # module Boolean
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Execution control operators.
  module Execution
    ##
    # @return [Machine]
    def reset
      @stack.clear
      @queue.clear
      self
    end

    ##
    # @return [Machine]
    def halt
      @queue.clear
      self
    end

    ##
    # @return [Machine]
    def nop
      self # do nothing
    end
    alias_method :',', :nop
    alias_method :';', :nop

    ##
    # @return [Machine]
    def quote
      push([shift])
    end
    alias_method :'\\', :quote
    alias_method :"'", :quote

    ##
    # @return [Machine]
    def call(quot)
      case quot
        when Array
          unshift(*quot)
        when Symbol
          unshift(quot) # FIXME
        else # TODO: error
      end
      self
    end

    ##
    # @return [Machine]
    def times(quot, count)
      with_saved_continuation(:times) do
        case quot
          when Array
            count.to_i.times { unshift(quot, :call) }
          when Symbol
            count.to_i.times { unshift([quot], :call) } # FIXME
          else # TODO: error
        end
      end
    end

    ##
    # @return [Machine]
    def twice(quot)
      with_saved_continuation(:twice) do
        case quot
          when Array
            2.times { unshift(quot, :call) }
          when Symbol
            2.times { unshift([quot], :call) } # FIXME
          else # TODO: error
        end
      end
    end
    alias_method :'2x', :twice

    ##
    # @return [Machine]
    def thrice(quot)
      with_saved_continuation(:thrice) do
        case quot
          when Array
            3.times { unshift(quot, :call) }
          when Symbol
            3.times { unshift([quot], :call) } # FIXME
          else # TODO: error
        end
      end
    end
    alias_method :'3x', :thrice

    ##
    # @return [Machine]
    def loop(quot)
      case quot
        when Array
          unshift(quot, :call, quot, :loop)
        when Symbol
          unshift(quot, [quot], :loop) # FIXME
        else # TODO: error
      end
      self
    end

    ##
    # @return [Machine]
    def while(quot, cond)
      with_saved_continuation(:while) do
        Kernel.loop do # FIXME
          execute(cond)
          case pop
            when false, nil then break
            else execute(quot)
          end
        end
      end
    end

    ##
    # @return [Machine]
    def until(quot, cond)
      with_saved_continuation(:until) do
        Kernel.loop do # FIXME
          execute(cond)
          case pop
            when false, nil then execute(quot)
            else break
          end
        end
      end
    end

    ##
    # @return [Machine]
    def branch(cond, thenop, elseop)
      case cond
        when false, nil then unshift(elseop, :call)
        else unshift(thenop, :call)
      end
      self
    end
    alias_method :if, :branch

    ##
    # @return [Machine]
    def when(cond, quot)
      case cond
        when false, nil then # nop
        else unshift(quot, :call)
      end
      self
    end

    ##
    # @return [Machine]
    def unless(cond, quot)
      case cond
        when false, nil then unshift(quot, :call)
        else # nop
      end
      self
    end
  end # module Execution
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Output operators.
  module Output
    ##
    # @return [Machine]
    def print(obj)
      $stdout.puts(obj) # FIXME
      self
    end
    alias_method :print!, :print
    alias_method :'.',    :print
  end # module Output
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Textual operators.
  #
  # @see http://ruby-doc.org/core-1.9/classes/String.html
  module Textual
    ##
    # Textual predicates.
    module Predicates
      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def chrp(obj)
        case obj
          when String then obj.size == 1
          else false
        end
      end
      alias_method :chr?, :chrp

      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def textp(obj)
        case obj
          when String then true
          else false
        end
      end
      alias_method :text?, :textp
    end

    ##
    # Textual constructors.
    module Constructors
      ##
      # @param  [Integer, String] obj
      # @return [String]
      def chr(obj)
        case obj
          when Integer then obj.chr(Encoding::UTF_8)
          when String  then obj.chr
          else raise Machine::InvalidOperandError.new(obj, :chr)
        end
      end

      ##
      # @param  [Object]  obj
      # @return [String]
      def text(obj)
        case obj
          when String then obj
          else obj.to_s # FIXME
        end
      end
    end # module Constructors

    ##
    # Textual operators.
    module Operators
      ##
      # @param  [Integer, String] obj
      # @return [Integer]
      def ord(obj)
        case obj
          when Integer then obj
          when String  then obj.ord
          else raise Machine::InvalidOperandError.new(obj, :ord)
        end
      end

      ##
      # @param  [String]  str
      # @return [Integer]
      def size(str)
        case str
          when String then str.bytesize
          else -1 # TODO: error
        end
      end
    end # module Operators

    # Include all submodule methods directly into Trith::Core::Textual:
    constants.each { |mod| include(const_get(mod)) }
  end # module Textual
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Numerical operators.
  #
  # @see http://ruby-doc.org/core-1.9/classes/Numeric.html
  # @see http://ruby-doc.org/core-1.9/classes/Integer.html
  # @see http://ruby-doc.org/core-1.9/classes/Rational.html
  # @see http://ruby-doc.org/core-1.9/classes/Float.html
  module Numeric
    ##
    # Numeric constants.
    module Constants
      INF = (1.0 / 0.0).freeze
    end # module Constants

    ##
    # Numeric predicates.
    module Predicates
      ##
      # @param  [Object]  obj
      # @return [Boolean]
      def nump(obj)
        obj.is_a?(Numeric)
      end
      alias_method :num?, :nump

      ##
      # @param  [Object, #integer?] obj
      # @return [Boolean]
      def intp(obj)
        obj.respond_to?(:integer?) && obj.integer?
      end
      alias_method :int?, :intp

      ##
      # @param  [Numeric, #infinite?] n
      # @return [Boolean]
      def infp(n)
        case
          when n.respond_to?(:infinite?)
            !!n.infinite?
          else false
        end
      end
      alias_method :inf?, :infp

      ##
      # @param  [Numeric, #zero?] n
      # @return [Boolean]
      def zerop(n)
        n.zero?
      end
      alias_method :zero?, :zerop

      ##
      # @param  [Numeric, #<=>] n
      # @return [Boolean]
      def onep(n)
        n == 1
      end
      alias_method :one?, :onep

      ##
      # @param  [Numeric, #<=>] n
      # @return [Boolean]
      def negp(n)
        n < 0
      end
      alias_method :neg?, :negp

      ##
      # @param  [Numeric, #<=>] n
      # @return [Boolean]
      def posp(n)
        n > 0
      end
      alias_method :pos?, :posp

      ##
      # @param  [Numeric, #odd?] n
      # @return [Boolean]
      def oddp(n)
        n.odd?
      end
      alias_method :odd?, :oddp

      ##
      # @param  [Numeric, #even?] n
      # @return [Boolean]
      def evenp(n)
        n.even?
      end
      alias_method :even?, :evenp
    end # module Predicates

    ##
    # Numeric constructors.
    module Constructors
      ##
      # @param  [Object]  obj
      # @return [Numeric]
      def num(obj)
        case obj
          when Numeric then obj
          else obj.to_i # FIXME
        end
      end

      ##
      # @return [Numeric]
      def inf
        Constants::INF
      end
    end # module Constructors

    ##
    # @private
    module Experimental
      ##
      # @param  [Numeric, #exact?] n
      # @return [Boolean]
      def exactp(n)
        case n
          when Integer  then true
          when Rational then true
          when Float    then false
          else case
            when n.respond_to?(:exact?)
              n.exact?
            else nil
          end
        end
      end
      alias_method :exact?, :exactp

      ##
      # @param  [Numeric, #inexact?] n
      # @return [Boolean]
      def inexactp(n)
        case n
          when Integer  then false
          when Rational then false
          when Float    then true
          else case
            when n.respond_to?(:inexact?)
              n.inexact?
            else nil
          end
        end
      end
      alias_method :inexact?, :inexactp
    end # module Experimental

    # Include all submodule methods directly into Trith::Core::Numeric:
    constants.each { |mod| include(const_get(mod)) }
  end # module Numeric
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Bitwise operators.
  #
  # @see http://en.wikipedia.org/wiki/Bitwise_operation
  module Bitwise
    ##
    # @param  [Integer] a
    # @return [Integer]
    def not(a)
      ~a
    end

    ##
    # @param  [Integer] a
    # @param  [Integer] b
    # @return [Integer]
    def and(a, b)
      a & b
    end

    ##
    # @param  [Integer] a
    # @param  [Integer] b
    # @return [Integer]
    def or(a, b)
      a | b
    end

    ##
    # @param  [Integer] a
    # @param  [Integer] b
    # @return [Integer]
    def xor(a, b)
      a ^ b
    end

    ##
    # @param  [Integer] a
    # @param  [Integer] b
    # @return [Integer]
    def shl(a, b)
      a << b
    end

    ##
    # @param  [Integer] a
    # @param  [Integer] b
    # @return [Integer]
    def shr(a, b)
      a >> b
    end
  end # module Bitwise
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Stack operators.
  module Stack
    ##
    # Stack shufflers.
    module Shufflers
      ##
      # @return [Machine]
      def clear
        @stack.clear
        self
      end

      ##
      # @return [Machine]
      def depth
        push(@stack.size)
      end

      ##
      # @return [Machine]
      def stack_
        @stack = [@stack]
        self
      end

      ##
      # @param  [#to_a, #each]
      # @return [Machine]
      def unstack(seq)
        @stack = case seq
          when String then seq.each_char.to_a
          when Array  then seq
          else case
            when seq.respond_to?(:to_a) then seq.to_a
            when seq.respond_to?(:each) then seq.each.to_a
            else raise Machine::InvalidOperandError.new(seq, :unstack)
          end
        end
        self
      end

      ##
      # @return [Machine]
      def drop
        pop
        self
      end

      ##
      # @return [Machine]
      def drop2
        pop(2)
        self
      end
      alias_method :'2drop', :drop2

      ##
      # @return [Machine]
      def drop3
        pop(3)
        self
      end
      alias_method :'3drop', :drop3

      ##
      # @return [Machine]
      def dup
        push(*(pop(1) * 2))
      end

      ##
      # @return [Machine]
      def dup2
        push(*(pop(2) * 2))
      end
      alias_method :'2dup', :dup2

      ##
      # @return [Machine]
      def dup3
        push(*(pop(3) * 2))
      end
      alias_method :'3dup', :dup3

      ##
      # @return [Machine]
      def swap
        push(*pop(2).reverse)
      end

      ##
      # @return [Machine]
      def nip
        push(pop(2).last)
      end

      ##
      # @return [Machine]
      def nip2
        push(pop(3).last)
      end
      alias_method :'2nip', :nip2

      ##
      # @return [Machine]
      def over
        push(*((ops = pop(2)) + [ops.first]))
      end

      ##
      # @return [Machine]
      def pick
        push(*((ops = pop(3)) + [ops.first]))
      end

      ##
      # @return [Machine]
      def rot(a, b, c)
        push(b, c, a)
      end
    end # module Shufflers

    ##
    # Stack combinators.
    module Combinators
      ##
      # @return [Machine]
      def dip
        # TODO
      end
    end # module Combinators

    # Include all submodule methods directly into Trith::Core::Stack:
    constants.each { |mod| include(const_get(mod)) }
  end # module Stack
end; end # module Trith::Core


text:
module Trith; module Core
  ##
  # Comparison operators.
  #
  # @see http://ruby-doc.org/core-1.9/classes/Comparable.html
  # @see http://en.wikipedia.org/wiki/Comparison_(computer_programming)
  # @see http://en.wikipedia.org/wiki/Relational_operator
  module Comparison
    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Integer]
    def cmp(a, b)
      a <=> b
    end
    alias_method :<=>, :cmp

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def eq(a, b)
      a == b
    end
    alias_method :'=', :eq

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def ne(a, b)
      a != b
    end
    alias_method :'!=', :ne

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def lt(a, b)
      a < b
    end
    alias_method :<, :lt

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def le(a, b)
      a <= b
    end
    alias_method :<=, :le

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def gt(a, b)
      a > b
    end
    alias_method :>, :gt

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Boolean]
    def ge(a, b)
      a >= b
    end
    alias_method :>=, :ge

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Object]
    def min(a, b)
      [a, b].min
    end

    ##
    # @param  [Object] a
    # @param  [Object] b
    # @return [Object]
    def max(a, b)
      [a, b].max
    end
  end # module Comparison
end; end # module Trith::Core


text:
module Trith; module Math
  ##
  # Trigonometric operators.
  #
  # @see http://en.wikipedia.org/wiki/Trigonometric_functions
  # @see http://en.wikipedia.org/wiki/Inverse_trigonometric_functions
  module Trigonometry
    # TODO
  end # module Trigonometry
end; end # module Trith::Math