Exemplo n.º 1
0
def matchSymbol(s):
    """Return a symbol or keyword.

    Return None if the string s does not define a legal symbol or keyword."""
    m = symbolPat.match(s)
    if m is not None:
        ns = m.group(1)
        name = m.group(2)

        if name.endswith(".") and not name.startswith("."):
            name = name[:-1]
        if ns is not None and (ns.endswith(":/") or name.endswith(":")\
            or s.find("::") != -1):
                return None
        ns = ns if ns is None else ns[:-1]
        
        if s.startswith("::"):
            return Keyword(currentNSName(), s[2:])


        iskeyword = s.startswith(':')
        if iskeyword:
            return Keyword(s[1:])
        else:
            return Symbol(ns, name)
    return None
Exemplo n.º 2
0
def compileDef(comp, form):
    if len(form) not in [2, 3]:
        raise CompilerException("Only 2 or 3 arguments allowed to def", form)
    sym = form.next().first()
    value = None
    if len(form) == 3:
        value = form.next().next().first()
    if sym.ns is None:
        ns = comp.getNS()
    else:
        ns = sym.ns

    comp.pushName(RT.name(sym))
    code = []
    v = intern(comp.getNS(), sym)

    v.setDynamic(True)
    if len(form) == 3:
        code.append((LOAD_CONST, v))
        code.append((LOAD_ATTR, "bindRoot"))
        compiledValue = comp.compile(value)
        if isinstance(value, ISeq) \
           and value.first().getName() == 'fn' \
           and sym.meta() is not None:
            try:
                compiledValue[0][1].__doc__ = sym.meta()[Keyword('doc')]
            except AttributeError:
                pass
        code.extend(compiledValue)
        code.append((CALL_FUNCTION, 1))
    else:
        code.append((LOAD_CONST, v))
    v.setMeta(sym.meta())
    comp.popName()
    return code
Exemplo n.º 3
0
from clojure.lang.ipersistentset import IPersistentSet
from clojure.lang.ipersistentlist import IPersistentList
from clojure.lang.iseq import ISeq
from clojure.lang.lispreader import _AMP_, LINE_KEY, garg
from clojure.lang.namespace import Namespace, findNS, findItem, intern
from clojure.lang.persistentlist import PersistentList, EmptyList
from clojure.lang.persistentvector import PersistentVector
import clojure.lang.rt as RT
from clojure.lang.symbol import Symbol
from clojure.lang.var import Var, threadBindings
from clojure.util.byteplay import *
import clojure.util.byteplay as byteplay
import marshal
import types

_MACRO_ = Keyword("macro")
_NS_ = Symbol("*ns*")
version = (sys.version_info[0] * 10) + sys.version_info[1]

PTR_MODE_GLOBAL = "PTR_MODE_GLOBAL"
PTR_MODE_DEREF = "PTR_MODE_DEREF"

AUDIT_CONSTS = False


class MetaBytecode(object):
    pass


class GlobalPtr(MetaBytecode):
    def __init__(self, ns, name):
Exemplo n.º 4
0
import contextlib

from clojure.lang.aref import ARef
from clojure.lang.atomicreference import AtomicReference
from clojure.lang.cljexceptions import (ArityException, IllegalStateException)
from clojure.lang.cljkeyword import Keyword
from clojure.lang.ifn import IFn
from clojure.lang.iprintable import IPrintable
from clojure.lang.persistenthashmap import EMPTY
from clojure.lang.persistentarraymap import create
from clojure.lang.settable import Settable
from clojure.lang.symbol import Symbol
from clojure.lang.threadutil import ThreadLocal, currentThread

privateKey = Keyword("private")
macrokey = Keyword("macro")
STATIC_KEY = Keyword("static")
dvals = ThreadLocal()
privateMeta = create([privateKey, True])
UNKNOWN = Symbol("UNKNOWN")


class Var(ARef, Settable, IFn, IPrintable):
    def __init__(self, *args):
        """Var initializer

        Valid calls:
        - Var(namespace, symbol, root)
        - Var(namespace, symbol) -- unbound Var
        - Var(root) -- anonymous Var
        - Var() -- anonymous, unbound Var
Exemplo n.º 5
0
_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)
        ns, ext = os.path.splitext(x)
        module = sys.modules["tests." + ns]

        for idx in dir(module):
            var = getattr(module, idx)
            if isinstance(var, Var) and str(var).endswith("tests"):
                meta = var.meta()
                if meta and meta[Keyword("test")]:
                    mapTest(ns, var)
Exemplo n.º 6
0
from clojure.lang.cljkeyword import Keyword

default = Keyword("default")


class MultiMethodException(Exception):
    def __init__(self, reason):
        Exception.__init__(self, reason)


class MultiMethod(object):
    def __init__(self, selector):
        self.selector = selector
        self.fns = {}
        self.default = None

    def addMethod(self, value, fn):
        if value in self.fns:
            raise MultiMethodException(
                "Method already exists for value {0}".format(value))
        if value == default and self.default is not none:
            raise MultiMethodException(
                "Method already exists for value {0}".format(value))

        if value == default:
            self.default = fn
        else:
            self.fns[value]

    def __call__(self, *args):
        dval = self.selector(*args)