|
| 1 | +from pixie.vm.code import as_var |
| 2 | +from pixie.vm.object import Object, Type, runtime_error |
| 3 | +from pixie.vm.primitives import nil |
| 4 | +from pixie.vm.string import String |
| 5 | +import pixie.vm.stdlib as proto |
| 6 | +from pixie.vm.code import extend, as_var |
| 7 | +import pixie.vm.rt as rt |
| 8 | +import os |
| 9 | + |
| 10 | +class Environment(Object): |
| 11 | + _type = Type(u"pixie.stdlib.Environment") |
| 12 | + |
| 13 | + def type(self): |
| 14 | + return Environment._type |
| 15 | + |
| 16 | + def val_at(self, key, not_found): |
| 17 | + if not isinstance(key, String): |
| 18 | + runtime_error(u"Environment variables are strings ") |
| 19 | + key_str = str(rt.name(key)) |
| 20 | + try: |
| 21 | + var = os.environ[key_str] |
| 22 | + return rt.wrap(var) |
| 23 | + except KeyError: |
| 24 | + return not_found |
| 25 | + |
| 26 | + # TODO: Implement me. |
| 27 | + # def dissoc(self): |
| 28 | + # def asssoc(self): |
| 29 | + |
| 30 | + def reduce_vars(self, f, init): |
| 31 | + for k, v in os.environ.items(): |
| 32 | + init = f.invoke([init, rt.map_entry(rt.wrap(k), rt.wrap(v))]) |
| 33 | + if rt.reduced_QMARK_(init): |
| 34 | + return init |
| 35 | + return init |
| 36 | + |
| 37 | + |
| 38 | +@extend(proto._val_at, Environment) |
| 39 | +def _val_at(self, key, not_found): |
| 40 | + assert isinstance(self, Environment) |
| 41 | + v = self.val_at(key, not_found) |
| 42 | + return v |
| 43 | + |
| 44 | +@extend(proto._reduce, Environment) |
| 45 | +def _reduce(self, f, init): |
| 46 | + assert isinstance(self, Environment) |
| 47 | + val = self.reduce_vars(f, init) |
| 48 | + if rt.reduced_QMARK_(val): |
| 49 | + return rt.deref(val) |
| 50 | + |
| 51 | + return val |
| 52 | + |
| 53 | +@as_var("pixie.stdlib", "env") |
| 54 | +def _env(): |
| 55 | + return Environment() |
0 commit comments