Beispiel #1
0
    def __iter__(self):
        return iter(self.scope)

    def __getitem__(self, name):
        return self.get(name)


def namespaceWrapper(pth, scope):
    pth = reversed(pth[1:])
    for name in pth:
        scope = ScopeWrapper({name: scope})
    return scope


module = Module("builtins")


@module.register("show")
def show(env) -> "(a -- )":
    "Shows the top of the stack"
    thing = env.stack.pop()
    if type(thing) != Token:
        print(thing)
    elif thing.type == "lit_bool":
        print("#t" if thing.val else "#f")
    elif thing.type in ("lit_list", "lit_symbol"):
        print(repr(thing))
    else:
        print(thing.val)
Beispiel #2
0
from nustack.extensionbase import Module, Token

module = Module()

shouldbreak = False

@module.register("forever")
def forever(env):
    global shouldbreak
    code = env.stack.pop().val
    while True:
        if shouldbreak:
            shouldbreak = False
            break
        env.eval(code)

@module.register("break")
def break_(env):
    global shouldbreak
    shouldbreak = True

@module.register("while")
def while_(env):
    global shouldbreak
    cond, code = env.stack.popN(2)
    while True:
        env.eval(cond.val)
        if not env.stack.pop().val or shouldbreak:
            shouldbreak = False
            break
        env.eval(code.val)
Beispiel #3
0
#!python3
"Time - time wrapper for Nustack\nImport with`std::Time import"
import time
from nustack.extensionbase import Module, Token

module = Module("std::Time")


@module.register("time")
def time_(env) -> "( -- f)":
    "Returns the seconds since the epoch"
    env.stack.push(Token("lit_float", time.time()))


@module.register("sleep")
def sleep(env) -> "(n -- )":
    "Sleeps for n seconds"
    n = env.stack.pop().val
    time.sleep(n)


@module.register("ctime")
def ctime(env) -> "(n -- s)":
    "Converts n, the number of seconds since the epoch to a human readable time string"
    n = env.stack.pop().val
    env.stack.push(Token("lit_string", time.ctime(n)))


@module.register("timestr")
def timestr(env) -> "( -- s)":
    "Returns a human readable time string"
Beispiel #4
0
#!python3
"IO - basic file IO\nImport with `std::IO import"
import os.path
from nustack.extensionbase import Module, Token

module = Module("std::IO")


@module.register("open")
def open_(env) -> "(s s -- file)":
    "Pops a string naming a file path and a string used as open flags, returns a file object"
    name, flags = env.stack.popN(2)
    path = env.getDir()
    path = os.path.join(path, name.val)
    f = open(path, flags.val)
    t = Token("file", f)
    env.stack.push(t)


@module.register("readall")
def readall(env) -> "(file -- s file)":
    "Takes a file object, reads everything from it as a string, and returns that string and the original file object"
    f = env.stack.pop()
    cont = f.val.read()
    env.stack.push(Token("lit_string", cont), f)


@module.register("read.n")
def readn(env) -> "(file i -- s file)":
    "Takes a file object and an integer i, reads i charactors or bytes from it as a string, and returns that string and the original file object"
    f, n = env.stack.popN(2)
Beispiel #5
0
#!python3
"Hash - Hash table creation and operations\nImport with `std::Hash import"

from nustack.extensionbase import Module, Token
module = Module("std::Hash")


@module.register("empty")
def empty_hash(env) -> "( -- hash)":
    "Creates an empty hash table"
    env.stack.push(Token("lit_hash", dict()))


@module.register("from.list")
def from_list(env) -> "(list -- hash)":
    "Creates a hash from a list of [key value] lists"
    l = env.stack.pop().val
    env.stack.push(Token("lit_hash", {k: v for (k, v) in l}))


@module.register("get")
def get(env) -> "(hash key -- value)":
    "Retrieves the value asociated with the key in the hash"
    hash, key = env.stack.popN(2)
    env.stack.push(hash.val[key])


@module.register("set")
def set(env) -> "(hash key value -- hash)":
    "Sets the value asociated with the key in the hash"
    hash, key, val, = env.stack.popN(3)
Beispiel #6
0
#!python3
"""Requests - A nustack wrapper for the python requests module

Makes heavy use of the new (v0.10) attribute access. For example, to get the text of the webpage "http://example.com"
just run
```
`Requests import
"http://example.com" Requests::get
/* We now get the text attribute of the response object on top of the stack */
::text show
```
You can access every attribute and method of the [python requests Response object](http://docs.python-requests.org/en/master/api/#lower-level-classes) this way.
"""

from nustack.extensionbase import Module, Token
module = Module("std::Requests")

import requests
import urllib.parse

def wrap_req(req):
    return Token("request_obj", req)

@module.register("get")
def get(env) -> "(url -- response_object)":
    "Returns a request object that represents a GET request to the given url"
    url = env.stack.pop().val
    req = wrap_req(requests.get(url))
    env.stack.push(req)

@module.register("head")
Beispiel #7
0
#!python3
"String - String utils and constants\nImport with `std::String import"
import string
from nustack.extensionbase import Module, Token
module = Module("std::Seq")


def strtok(val):
    return Token("lit_string", val)


module.registerValue("ascii_letters", strtok(string.ascii_letters))
module.registerValue("ascii_lowercase", strtok(string.ascii_lowercase))
module.registerValue("ascii_uppercase", strtok(string.ascii_uppercase))
module.registerValue("digits", strtok(string.digits))
module.registerValue("hexdigits", strtok(string.hexdigits))
module.registerValue("octdigits", strtok(string.octdigits))
module.registerValue("punctuation", strtok(string.punctuation))
module.registerValue("printable", strtok(string.printable))
module.registerValue("whitespace", strtok(string.whitespace))


@module.register("split")
def split(env) -> "(s1 s2 -- l)":
    "Splits s1 by s2"
    s1, s2 = env.stack.popN(2)
    res = list(map(strtok, s1.val.split(s2.val)))
    env.stack.push(Token("lit_list", res))


@module.register("join")
Beispiel #8
0
#!python3
"String - String utils and constants\nImport with `std::String import"
import string
from nustack.extensionbase import Module, Token
module = Module("std::Seq")

def strtok(val):
    return Token("lit_string", val)


module.registerValue("ascii_letters", strtok(string.ascii_letters))
module.registerValue("ascii_lowercase", strtok(string.ascii_lowercase))
module.registerValue("ascii_uppercase", strtok(string.ascii_uppercase))
module.registerValue("digits", strtok(string.digits))
module.registerValue("hexdigits", strtok(string.hexdigits))
module.registerValue("octdigits", strtok(string.octdigits))
module.registerValue("punctuation", strtok(string.punctuation))
module.registerValue("printable", strtok(string.printable))
module.registerValue("whitespace", strtok(string.whitespace))

@module.register("split")
def split(env) -> "(s1 s2 -- l)":
    "Splits s1 by s2"
    s1, s2 = env.stack.popN(2)
    res = list(map(strtok, s1.val.split(s2.val)))
    env.stack.push(Token("lit_list", res))

@module.register("join")
def join(env) -> "(sequence s1 -- s2)":
    "Returns a new string formed by inserting s1 between every member of sequence."
    seq, s1 = env.stack.popN(2)
Beispiel #9
0
#!python3
"Shell support."
from nustack.extensionbase import Module, Token
module = Module("std::Shell")

import subprocess, shlex, sys

if sys.platform == "win32":
    out = subprocess.check_output("chcp", shell=True)
    enc = "cp" + out.split()[-1].decode()
else:
    # UNTESTED. Untill I can check this works, assume utf8
    #enc = subprocess.check_output("locale charmap", shell=True).decode()
    enc = "utf8"


@module.register("encoding")
def encoding(env) -> "( -- s)":
    "Returns the character encoding of the shell"
    env.stack.push(Token("lit_string", enc))


@module.register("run")
def run(env) -> "(s1 -- l)":
    """Runs s1 as a shell command string and returns a two item list [return-code output]
    Note that this run using the subprocess module with shell=False,
    so if you need to use a built in shell command use run.shell"""
    args = env.stack.pop().val
    args = shlex.split(args)
    try:
        out = subprocess.check_output(
Beispiel #10
0
#!python3
"""Path - Path, file, and directory operations
Import with `std::Path import

In this module, `path` always refers to a string that is a pathname."""

import os, os.path, glob
from nustack.extensionbase import Module, Token

module = Module("std::Path")


@module.register("change.dir")
def change_dir(env) -> "(path -- )":
    "Changes the current working directory to path"
    os.chdir(env.stack.pop().val)


@module.register("get.cwd")
def get_cwd(env) -> "( -- path)":
    "Returns the path of the current working directory"
    env.stack.push(Token("lit_string", os.getcwd()))


@module.register("list.dir")
def list_dir(env) -> "(path -- list)":
    "Lists all the directories and files in a directory given by path"
    path = env.stack.pop().val
    listing = os.listdir(path)
    env.stack.push(
        Token("lit_list", [Token("lit_string", item) for item in listing]))
Beispiel #11
0
#!python3
"""Math - Math ops

All of the trigometric words give and take radians. You can use to.degrees to convert to degrees."""
from nustack.extensionbase import Module, Token
import math, fractions

module = Module("std::Math")


@module.register("ceil")
def ceil(env) -> "(n -- n)":
    "Returns the ceiling of n"
    n = env.stack.pop()
    env.stack.push(Token(n.type, math.ceil(n.val)))


@module.register("floor")
def cfloor(env) -> "(n -- n)":
    "Returns the floor of n"
    n = env.stack.pop()
    env.stack.push(Token(n.type, math.floor(n.val)))


@module.register("abs")
def abs_(env) -> "(n -- n)":
    "Returns the abs of n"
    n = env.stack.pop()
    env.stack.push(Token(n.type, abs(n.val)))

Beispiel #12
0
#!python3
"Seq - Sequence operations\nImport with `std::Seq import"

from nustack.extensionbase import Module, Token
module = Module("std::Seq")

@module.register("nth")
def nth(env) -> "(sequence n -- a)":
    "Returns the nth item of a sequence (eg. list or string)"
    seq, n = env.stack.popN(2)
    a = seq.val[n.val]
    if isinstance(a, Token):
        env.stack.push(a)
    else:
        env.stack.push(Token("lit_any", a))

@module.register("first")
def first(env) -> "(sequence -- a)":
    seq = env.stack.pop()
    a = seq.val[0]
    if isinstance(a, Token):
        env.stack.push(a)
    else:
        env.stack.push(Token("lit_any", a))

@module.register("butfirst")
def first(env) -> "(sequence -- a)":
    seq = env.stack.pop()
    a = seq.val[1:]
    if isinstance(a, Token):
        env.stack.push(a)
Beispiel #13
0
#!python3
"Turtle - Turtle graphics for Nustack.\nImport with `std::Turtle import"
import turtle
from nustack.extensionbase import Module, Token
module = Module("std::Turtle")


def start():
    if not start.started:
        turtle.Screen().title("Nustack Turtle Graphics")
        start.started = True


start.started = False


@module.register("Turtle")
def Turtle(env) -> "( -- turtle)":
    "Creates a new turtle"
    start()
    t = Token("lit_turtle", turtle.Turtle())
    env.stack.push(t)


@module.register("Screen")
def Screen(env) -> "( -- screen)":
    'Returns the Screen used by the turtles.'
    start()
    "Returns the Screen used by turtles"
    s = Token("lit_screen", turtle.Screen())
    env.stack.push(s)