Newer
Older
NewLang / main.py
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright 2021 Jookia <contact@jookia.org>

import parse

def do_system_print(env, args):
    (text_type, text_value) = args[0]
    if text_type == "symbol":
        (text_type, text_value) = env[text_value]
    if text_type != "text":
        print("Invalid print value: %s" % (text_type))
        return None
    else:
        print(text_value)
        return None

def do_system_read(env, args):
    return ('text', input())

base_env = {
    "system": {
        "type": "module",
        "print": do_system_print,
        "read": do_system_read,
    }
}

def run_statement(env, ast):
    command = env[ast[1]][ast[2]]
    return command(env, ast[3])

def run_set(env, ast):
    env[ast[1]] = run_statement(env, ast[2])
    return env[ast[1]]

def run_if(env, ast):
    print("Unimplemented if")
    return None

def run_command(env, ast):
    type = ast[0]
    if type == "statement":
        return run_statement(env, ast)
    elif type == "set":
        return run_set(env, ast)
    elif type == "if":
        return run_if(env, ast)
    else:
        print("Unknown command type %s" % (ast))
        return None

def main(args):
    if len(args) != 2:
        print("Usage: main.py FILENAME")
        return 1
    filename = args[1]
    code = open(filename).read()
    if code[0:2] == '#!':
        next_line = code.find('\n') + 1
        code = code[next_line:]
    tokens = parse.tokenizer(code)
    parse.parser_reset(tokens)
    ast = parse.parse_file()
    if not ast:
        return 1
    for command in ast:
        run_command(base_env, command)
    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))