Example #1
0
def fnReader(rdr, lparen):
    """Read an anonymous function #() from reader

    rdr -- a read/unread-able object
    lparen -- ignored

    Return an IPersistentList"""
    if ARG_ENV.deref() is not None:
        raise IllegalStateException("Nested #()s are not allowed")
    with threadBindings(RT.map(ARG_ENV, EMPTY_MAP)):
        rdr.back()
        form = read(rdr, True, None, True)
        drefed = ARG_ENV.deref()
        sargs = sorted(list(filter(lambda x: x != -1, drefed)))
        args = []
        if len(sargs):
            for x in range(1, int(str(sargs[-1])) + 1):
                if x in drefed:
                    args.append(drefed[x])
                else:
                    args.append(garg(x))
            retsym = drefed[-1]
            if retsym is not None:
                args.append(_AMP_)
                args.append(retsym)
        vargs = RT.vector(*args)
    return RT.list(_FN_, vargs, form)
Example #2
0
def requireClj(filename, stopafter=None):
    """Compiles and executes the code in a clj file.
    
    If `stopafter` is given, then stop execution as soon as the `stopafter`
    name is defined in the current namespace of the compiler.
    """
    with open(filename) as fl:
        r = StringReader(fl.read())

    RT.init()
    comp = Compiler()
    comp.setFile(filename)

    with threadBindings({currentCompiler:
                         comp}):  #, open(filename + ".cljc", "w") as o:
        try:
            while True:
                EOF = object()
                s = read(r, False, EOF, True)
                if s is EOF:
                    break
                #cPickle.dump(s, o)
                try:
                    res = comp.compile(s)
                    comp.executeCode(res)
                    if stopafter is not None and hasattr(
                            comp.getNS(), stopafter):
                        break
                except Exception as exp:
                    print s, filename
                    raise
        except IOError as e:
            pass
Example #3
0
def requireClj(filename, stopafter=None):
    """Compiles and executes the code in a clj file.
    
    If `stopafter` is given, then stop execution as soon as the `stopafter`
    name is defined in the current namespace of the compiler.
    """
    with open(filename) as fl:
        r = StringReader(fl.read())

    RT.init()
    comp = Compiler()
    comp.setFile(filename)

    with threadBindings({currentCompiler: comp}): #, open(filename + ".cljc", "w") as o:
        try:
            while True:
                EOF = object()
                s = read(r, False, EOF, True)
                if s is EOF:
                    break
                #cPickle.dump(s, o)
                try:
                    res = comp.compile(s)
                    comp.executeCode(res)
                    if stopafter is not None and hasattr(comp.getNS(), stopafter):
                        break
                except Exception as exp:
                    print s, filename
                    raise
        except IOError as e:
            pass
Example #4
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)
Example #5
0
    def executeCode(self, code, ns=None):
        ns = ns or self.getNS()
        if code == []:
            return None
        newcode = expandMetas(code, self)
        newcode.append((RETURN_VALUE, None))
        c = Code(newcode, [], [], False, False, False,
                 str(Symbol(ns.__name__, "<string>")), self.filename, 0, None)
        try:
            c = c.to_code()
        except:
            for x in newcode:
                print x
            raise

        # work on .cljs
        #from clojure.util.freeze import write, read
        #with open("foo.cljs", "wb") as fl:
        #    f = write(c, fl)

        with threadBindings({self._NS_: ns}):
            retval = eval(c, ns.__dict__)
        return retval
Example #6
0
    def executeCode(self, code, ns=None):
        ns = ns or self.getNS()
        if code == []:
            return None
        newcode = expandMetas(code, self)
        newcode.append((RETURN_VALUE, None))
        c = Code(newcode, [], [], False, False, False,
                 str(Symbol(ns.__name__, "<string>")), self.filename, 0, None)
        try:
            c = c.to_code()
        except:
            for x in newcode:
                print x
            raise

        # work on .cljs
        #from clojure.util.freeze import write, read
        #with open("foo.cljs", "wb") as fl:
        #    f = write(c, fl)

        with threadBindings({self._NS_: ns}):
            retval = eval(c, ns.__dict__)
        return retval
Example #7
0
 def __call__(self, r, backquote):
     with threadBindings(RT.map(GENSYM_ENV, EMPTY_MAP)):
         self.rdr = r
         form = read(r, True, None, True)
         return self.syntaxQuote(form)
 def testVar(self):
     with threadBindings({_NS_: var.ns}):
         var()
Example #9
0
 def testVar(self):
     with threadBindings({_NS_: var.ns}):
         var()
Example #10
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)