Esempio n. 1
0
    def hIMPORT(self, path, fname="", vars=[]):

        #Step 1: Get module
        try:
            if path[0] == "py":
                path = path[1:]
                raise ImportError # Skip to except clause
            
            loc = self.__get_import_loc(path)
        except ImportError:
            try:
                v, pathp = self.__get_py_import(path)
            except ImportError:
                raise ImportError("Module %s not found" % ".".join(path))
            else:
                name = path[pathp - 1]
                mod = Module.from_py(v)
        else:
            pathp = 0
            while pathp < len(path) and (loc + path[pathp]).exists():
                loc += path[pathp]
                pathp += 1

            if pathp < len(path) and (loc + (path[pathp] + ".or")).exists():
                loc += path[pathp] + ".or"
                pathp += 1

            if "file" in loc.type():
                f = loc.get().open().read()
            elif "$$init.or" in loc:
                f = (loc+"$$init.or").get().open()
            else:
                f = ""
                
            intp2 = Interpreter()
            
            for i in vars:
                intp2.curr[i[2]] = self.curr[i[2]]
                
            run(f, intp2)
            name = path[pathp - 1]
            mod = Module(intp2.curr.dict, name, str(loc))

        # OK, done. mod is now a module object
        for i in path[pathp:]:
            if i != "*":
                try:
                    mod = mod.get(i)
                    name = i
                except KeyError:
                    raise ImportError("Module %s not found" % ".".join(path))
            else:
                for i in mod.dict:
                    self.curr[i] = OrObject.from_py(mod.dict.get(i))
                return

        fname = fname if fname else name

        self.curr[name] = OrObject.from_py(mod)
        return self.curr[name]
Esempio n. 2
0
 def hPRIMITIVE(self, val, *others):
     if val[0] in ("DEC", "INT"):
         return objects.number.Number(*val[1:])
     elif val[0] == "BOOL":
         return OrObject.from_py(val[1])
     elif val[0] == "NIL":
         return OrObject.from_py(None)
     elif val[0] == "INF":
         return objects.constants.inf
Esempio n. 3
0
def call(obj, *args, **kwargs):
    try:
        return OrObject.from_py(obj.get("$$call")(*args, **kwargs))
    except (AttributeError, TypeError, NotImplementedError):
        if all(not hasattr(i, "ispy") or i.ispy() for i in args) and all(not hasattr(i, "ispy") or i.ispy() for k, i in kwargs.items()):
            args = [i.topy() if i.ispy() else i for i in args]
            for i in kwargs:
                kwargs[i] = kwargs[i].topy() if kwargs[i].ispy() else kwargs[i]
            obj = obj.topy() if obj.ispy() else obj

            return OrObject.from_py(obj(*args, **kwargs))
        else:
            raise TypeError(str(obj) + " is not callable")
Esempio n. 4
0
def evalval(type, val):
    if type == "int":
        return Number(val, intonlystr=True)
    elif type == "num":
        return Number(val)
    elif type == "list":
        return OrObject.from_py(val.split(","))
    elif type == "bool":
        return constants.true
    elif type == "str":
        return OrObject.from_py(val)
    else:
        raise TypeError, "`%s` type not supported for command-line \
arguments" % type
Esempio n. 5
0
    def hCALL(self, val, *args):
        func = self.run(val)
      
        if func.tagged("FullMacro") or func.tagged("Macro"):
            # Eh, don't shoot yourself in the foot
            a = map(OrObject.from_py, args)
            kw = {}
        else:
            a = []
            kw = {}

            for i in args:
                if i[0] == "UNWRAPKW":
                    kw.update(self.run(i[1]))
                elif i[0] == "KW":
                    kw[i[1]] = self.run(i[2])
                elif i[0] == "UNWRAP":
                    a.extend(self.run(i[1]).topy())
                else:
                    a.append(self.run(i))
        
        try:
            r = operators.call(func, *a, **kw)
        finally:
            if self.level > len(self.stmtstack):
                self.stmtstack = self.stmtstack[:self.level]
        
        if func.tagged("FullMacro"):
            r = self.run(r)

        if not isinstance(r, OrObject):
            return OrObject.from_py(r)
        else:
            return r
Esempio n. 6
0
 def t(*args):
     try:
         try:
             return OrObject.from_py(args[0].get("$$" + name)(*args[1:]))
         except AttributeError:
             args2 = [args[0]] + list(args[2:])
             return OrObject.from_py(args[1].get("$$r_" + name)(*args2))
     except (AttributeError, IndexError, TypeError, NotImplementedError):
         try:
             return OrObject.from_py(f(*args))
         except TypeError:
             if all(not hasattr(i, "ispy") or i.ispy() for i in args):
                 args = [i.topy() if hasattr(i, "ispy") else i for i in args]
                 return OrObject.from_py(f(*args))
             else:
                 raise NotImplementedError
Esempio n. 7
0
 def hSTRING(self, vals):
     strs = []
     for val in vals:
         body, flags = val[1:]
         if "r" not in flags:
             body = eval('"""' + body + '"""')
         strs.append(body)
     return OrObject.from_py("".join(strs))
Esempio n. 8
0
    def hPROCDIR(self, cmd):
        args = cmd[1:]
        cmd = cmd[0]
        
        if cmd in self.procdirs:
            return OrObject.from_py(self.procdirs[cmd](args, self, globals()))
        elif cmd == "set":
            if len(args) != 2:
                raise SyntaxError("#!set requires two arguments")

            return self.set_option(args[0], args[1])
        elif cmd == "debug":
            if not self.opts["debugger"]:
                import debugger
                self.opts["debugger"] = debugger.Debugger(self, ":anon:")

            self.opts["debugger"].stepconsole = self.consolelevel
            self.opts["debugger"].steplevel = self.level
            return
        elif cmd == "step":
            self.opts["debugger"].steplevel += 1
            if args[0] == "in":
                self.opts["debugger"].steplevel += 2
            elif args[0] == "out":
                self.opts["debugger"].steplevel -= 2
            elif args[0] == "end":
                self.opts["debugger"].steplevel = -1

            raise DropI("Stepping")
        elif cmd == "ec":
            if not self.opts["logger"]:
                return
            elif not args:
                return OrObject.from_py(self.opts["logger"])
            elif len(args) >= 1 and args[0] == "data":
                type = "data"
                val = " ".join(args[1:])
            else:
                type = "message"
                val = " ".join(args)
            
            return self.opts["logger"].write(val, type)

        # Hmm, we still haven't been run
        raise SyntaxError("Processing directive not available: " + cmd)
Esempio n. 9
0
    def hOP(self, op, *args):
        if op in ("--", "++"):
            v = self.run(args[0])
            self.hASSIGN1(analyze.parser.h_loc(args[0]), ["OP", op[0], args[0], ["PRIMITIVE", ("INT", "1", 10)]])
            return v

        args = map(self.run, args)
        func = operators.op_names[op]

        try:
            r = func(*args)
        except TypeError:
            raise

        return OrObject.from_py(r)
Esempio n. 10
0
    def hTRY(self, block, *catches):
        try:
            self.run(block)
            return objects.constants.true
        except Exception, e:
            for i, v in enumerate(catches[1::4]):
                if any(operators.is_(e, self.run(j)) for j in v) or not v:
                    if catches[3*i+2]:
                        self.curr[catches[3*i+2]] = OrObject.from_py(e)
                    self.run(catches[3*i+3])
                    return objects.constants.false

            if catches[-2] == "FINALLY":
                self.run(catches[-1])

            raise
Esempio n. 11
0
    def __init__(self, g=None):

        # Set up the global contexts
        if not g:
            g = InheritDict(builtin.builtin)
        self.cntx = [g, InheritDict(g)]
        self.bindcntx = self.cntx[-1]
        self.curr["intp"] = OrObject.from_py(self)

        # Set up interpreter options
        self.opts = {"logger": None, "debugger": None}

        # Set up statement stacks and location information
        self.stmtstack = []
        self.cstmt = [(0, 0), (0, 0), ""] # Default
        self.level = 0
        self.consolelevel = 0

        # Set up module search path
        self.searchpath = [files.Path("."), files.Path(objects.about.mainpath) +
            "../stdlib", files.Path(objects.about.mainpath) + "../sitelib"]
        userbase = files.Path("%APPDATA%/oranj/" if os.name == "nt" else
            "~/.local/lib/oranj")
        self.searchpath.append(userbase)
        self.searchpath.append(userbase + objects.about.version)

        # A few convenience methods for dealing with variables
        @OrObject.from_py
        def vars():
            return OrObject.from_py(self.curr.dict)

        @OrObject.from_py
        def globals():
            return OrObject.from_py(self.cntx[1].dict)

        @OrObject.from_py
        def locals():
            return OrObject.from_py(self.curr.dict)

        g["vars"] = vars
        g["globals"] = globals
        g["locals"] = locals

        import libproc
        self.procblocks = libproc.blocks
        self.procdirs = libproc.dirs
Esempio n. 12
0
def expose(r, n=""):
    v = OrObject.from_py(r)
    if n:
        v.name = n
    return v
Esempio n. 13
0
def getattr_(x, y):
    if x.has("$$getattr"):
        return x.get("$$getattr", y)
    else:
        return OrObject.from_py(x.get(y))
Esempio n. 14
0
            for n, vv in zip(names, flatten_tuples(v)):
                self.curr[n] = OrObject.from_py(vv)
            self.run(block)

        return zip(valpairs)

    @autoblock
    def hFOR2(self, (names, vals), block, *others):
        vals = map(self.run, vals)
        valpairs = zip(*vals)

        try:
            for v in zip(*vals):
                try:
                    for n, vv in zip(names, flatten_tuples(v)):
                        self.curr[n] = OrObject.from_py(vv)
                    self.run(block)
                except ContinueI, e:
                    if e.args != () and e.args[0] > 1:
                        v = e.args[0] - 1
                        raise ContinueI(v)
        except BreakI, e:
            if e.args != () and e.args[0] != 0:
                v = e.args[0] - 1
                raise BreakI(v)
            else:
                if "ELSE" in others:
                    i = others.find("ELSE")
                    self.run(others[i + 1])
        
        return valpairs
Esempio n. 15
0
 def vars():
     return OrObject.from_py(self.curr.dict)
Esempio n. 16
0
 def hOP1(self, op, v1, v2):
     return OrObject.from_py(operators.op_names[op](self.run(v1), self.run(v2)))
Esempio n. 17
0
 def globals():
     return OrObject.from_py(self.cntx[1].dict)
Esempio n. 18
0
 def locals():
     return OrObject.from_py(self.curr.dict)
Esempio n. 19
0
 def hLIST(self, vars):
     return OrObject.from_py(map(self.run, vars))
Esempio n. 20
0
 def hSLICE(self, *stops):
     return OrObject.from_py(slice(*[self.run(i).topy() for i in stops]))
Esempio n. 21
0
 def hDICT(self, vars):
     vars = map(lambda x: (self.run(x[0]), self.run(x[1])), vars)
     return OrObject.from_py(dict(vars))
Esempio n. 22
0
def parseargs(args, schema):
    passargs = {}
    takingopts = True
    errors = False
    setval = ""
    
    if schema.dump:
        passargs[schema.dump] = [] # Not OrObjected yet
    if schema.kwdump:
        passargs[schema.kwdump] = {} # Also not OO'd yet
    
    for i in args:
        if i.startswith("--") and len(i) > 2 and takingopts:
            kw, t, val = i[2:].partition("=")
            
            if kw not in schema.long and not schema.kwdump:
                print "ERROR: Unknown option `%s`" % kw
                errors = True
                continue
            elif schema.kwdump:
                passargs[schema.kwdump][kw] = evalval("str", val)
                continue
            
            if kw in schema.mandatory:
                schema.mandatory.remove(kw)
            
            passargs[kw] = evalval(schema.long[kw], val)
        elif i == "--" and takingopts:
            takingopts = False
        elif i.startswith("-") and takingopts:
            key = i[1:2]
            val = i[2:]
            
            if key not in schema.short:
                print "ERROR: Unknown option `%s`" % key
                errors = True
                continue
            elif schema.kwdump:
                setval = ":kwdump:"
                continue
            
            if schema.short[key] in schema.mandatory:
                schema.mandatory.remove(schema.short[key])
            
            if schema.long[schema.short[key]] == "bool":
                passargs[schema.short[key]] = constants.true
            elif val:
                passargs[schema.short[key]] = evalval(schema.long[schema.short[key]], val)
            else:
                setval = schema.short[key]
        elif setval:
            if setval == ":kwdump:":
                passargs[schema.kwdump][setval] = evalval("str", val)
            else:
                passargs[setval] = evalval(schema.long[setval], i)
                setval = ""
        else:
            try:
                kw = schema.mandatory[0]
            except IndexError:
                print "ERROR: Too many arguments"
                errors = True
                continue
            
            if kw == schema.dump:
                passargs[schema.dump].append(i)
                takingopts = False
                continue
            
            passargs[kw] = evalval(schema.long[kw], i)
            schema.mandatory.pop(0)
    
    if schema.dump:
        passargs[schema.dump] = OrObject.from_py(passargs[schema.dump])
    if schema.kwdump:
        passargs[schema.kwdump] = OrObject.from_py(passargs[schema.kwdump])
    
    if len(schema.mandatory) and schema.mandatory[0] != schema.dump:
        m = len(schema.mandatory) - (1 if schema.dump in schema.mandatory else 0)
        print "Arguments Missing: " + ", ".join(map(lambda x: "`%s`"%x, schema.mandatory))
        print "ERROR: Missing %d arguments; consult --help for command syntax" % m
        errors = True
    if setval:
        print "ERROR: Expecting value for argument `%s`" % setval
        errors = True
    
    if errors:
        sys.exit(1)
    
    return passargs
Esempio n. 23
0
 def hPROCBLOCK(self, type, body):
     if type[0] in self.procblocks:
         fn = self.procblocks[type[0]]
         return OrObject.from_py(fn(type[1:], body, self, globals()))
     else:
         raise SyntaxError("Processing block not available: " + type[0])