Esempio n. 1
0
 def __init__(self):
     self.recurPoint = RT.list()
     self.names = None
     self.ns = clojure_core = Namespace("clojure.core")
     self.lastlineno = -1
     self.aliases = {}
     self.filename = "<unknown>"
     self._NS_ = findItem(clojure_core, _NS_)
Esempio n. 2
0
def registerFns(ns, fns):
    ns = Namespace(ns)
    protofns = {}
    for fn in fns:
        fname = ns.__name__ + fn
        if hasattr(ns, fn):
            proto = getattr(ns, fn)
        else:
            proto = ProtocolFn(fname)
            setattr(ns, fn, proto)
        proto.__name__ = fn
        protofns[fn] = proto

    return protofns
Esempio n. 3
0
def protocolFromType(ns, tp):
    """Considers the input type to be a prototype for a protocol. Useful for
    turning abstract classes into protocols"""
    fns = []
    for x in dir(tp):
        if not x.startswith("_"):
            fns.append(x)

    thens = Namespace(ns)
    proto = Protocol(ns, tp.__name__, fns)

    tp.__exactprotocol__ = proto
    tp.__exactprotocolclass__ = tp

    if not hasattr(tp, "__protocols__"):
        tp.__protocols__ = []
    tp.__protocols__.append(proto)

    if not hasattr(thens, tp.__name__):
        setattr(thens, tp.__name__, proto)
    return proto
Esempio n. 4
0
 def setNS(self, ns):
     self.ns = Namespace(ns)
Esempio n. 5
0
import os.path
import sys
import unittest
sys.path = [os.path.dirname(__file__) + "../"] + sys.path

from clojure.lang.cljkeyword import Keyword
from clojure.lang.namespace import Namespace, findItem
from clojure.lang.var import Var, threadBindings
from clojure.lang.symbol import Symbol
from clojure.main import requireClj

_NS_ = findItem(Namespace("clojure.core"), Symbol("*ns*"))


def mapTest(ns, var):
    class Test(unittest.TestCase):
        def testVar(self):
            with threadBindings({_NS_: var.ns}):
                var()

    name = ns + str(var)
    tst = Test
    tst.__name__ = name
    globals()[name] = tst


for x in os.listdir(os.path.dirname(__file__)):
    if x.endswith(".clj") and x.find("test") >= 0:
        print "Reading tests from", x
        requireClj(os.path.join(os.path.dirname(__file__), x))
        folder, file = os.path.split(x)
Esempio n. 6
0
def run_repl(opts, comp=None):
    """Initializes and runs the REPL. Assumes that RT.init has been called.

    Repeatedly reads well-formed forms from stdin (with an interactive prompt
    if a tty) and evaluates them (and prints the result if a tty). Exits on
    EOF.
    """
    if not opts.quiet and os.isatty(0):
        print VERSION_MSG

    if comp is None:
        curr = currentCompiler.get(lambda: None)
        if curr == None:
            comp = Compiler()
            currentCompiler.set(comp)
        else:
            comp = curr
    comp.setNS(Symbol("user"))
    core = sys.modules["clojure.core"]
    for i in dir(core):
        if not i.startswith("_"):
            setattr(comp.getNS(), i, getattr(core, i))

    line = opts.cmd
    last3 = [None, None, None]

    def firstLinePrompt():
        return comp.getNS().__name__ + "=> " if os.isatty(0) else ""

    def continuationLinePrompt():
        return "." * len(comp.getNS().__name__) + ".. " if os.isatty(0) else ""

    while True:
        # Evaluating before prompting caters for initially given forms.
        r = StringReader(line)
        while True:
            try:
                s = read(r, False, None, True)
                if s is None:
                    break
                res = comp.compile(s)
                out = comp.executeCode(res)
            except Exception:
                traceback.print_exc()
            else:
                if os.isatty(0):
                    RT.printTo(out)
                last3.pop()
                last3.insert(0, out)
                for i, value in enumerate(last3, 1):
                    v = findItem(Namespace("clojure.core"),
                                 Symbol("*{0}".format(i)))
                    if isinstance(value, Var):
                        v.bindRoot(value.deref())
                        v.setMeta(value.meta())
                    else:
                        v.bindRoot(value)
        try:
            line = raw_input(firstLinePrompt())
            while unbalanced(line):
                line += "\n" + raw_input(continuationLinePrompt())
        except BracketsException as exc:
            print exc
            continue
        except EOFError:
            print
            break
Esempio n. 7
0
def main():
    """Main entry point to clojure-py.
    """
    def gobble(option, opt_str, value, parser):
        """Interprets all the remaining arguments as a single argument.
        """
        setattr(parser.values, option.dest, " ".join(parser.rargs))
        del parser.rargs[:]

    parser = OptionParser(
        usage="%prog [options] ... [-c cmd | file | -] [arg] ...",
        version=VERSION_MSG)
    parser.add_option(
        "-c",
        action="callback",
        dest="cmd",
        default="",
        callback=gobble,
        help="program passed in as a string (terminates option list)")
    parser.add_option("-i",
                      action="store_true",
                      dest="interactive",
                      help="inspect interactively after running script")
    parser.add_option(
        "-q",
        action="store_true",
        dest="quiet",
        help="don't print version message on interactive startup")
    # fooling OptionParser
    parser.add_option("--\b\bfile",
                      action="store_true",
                      help="    program read from script file")
    parser.add_option(
        "--\b\b-",
        action="store_true",
        help="    program read from stdin (default; interactive mode if a tty)"
    )
    parser.add_option(
        "--\b\barg ...",
        action="store_true",
        help="    arguments passed to program in *command-line-args*")
    args = sys.argv[1:]
    try:
        i = args.index("-")
    except ValueError:
        i = len(args)
    dash_and_post = args[i:]
    opts, command_line_args = parser.parse_args(args[:i])
    source = command_line_args.pop(0) if command_line_args else None
    command_line_args.extend(dash_and_post)
    opts.command_line_args = command_line_args

    RT.init()
    comp = Compiler()

    command_line_args_sym = findItem(Namespace("clojure.core"),
                                     Symbol("*command-line-args*"))
    with threadBindings({
            currentCompiler: comp,
            command_line_args_sym: command_line_args
    }):
        if source:
            requireClj(source)
        if opts.interactive or not source and not opts.cmd:
            import clojure.repl
            clojure.repl.enable_readline()
            clojure.repl.run_repl(opts, comp)