Files
kraken/k_prime.krak
2020-06-28 19:17:09 -04:00

753 lines
25 KiB
Plaintext

import mem:*
import io:*
import str:*
import vec:*
import vec_literals:*
import util:*
import map:*
import rc:*
import fungll:*
adt KPValue_int {
True, // 101 1 0
False, // 100 1 0
Env: *KPEnv, // 011 1 0
Combiner: KPCombiner, // 010 1 0
BuiltinCombiner: KPBuiltinCombiner, // ''' ' '
String: str, // 001 1 0
Symbol: str, // 000 1 0
Int: int, // 0 0
Vector: rc<vec<KPValue>>, //<10sizebits> 1
// same encoding, but encodes 0-length null ptr
Nil // 00000000000 1
}
obj KPEnv (Object) {
var data: map<str, KPValue>
var outer: *KPEnv
fun construct(): *KPEnv {
return construct(null<KPEnv>())
}
fun construct(outer: *KPEnv): *KPEnv {
data.construct()
this->outer = outer
return this
}
fun copy_construct(old: *KPEnv): void {
data.copy_construct(&old->data)
outer = old->outer
}
fun destruct(): void {
data.destruct()
outer = null<KPEnv>()
}
fun operator=(other:ref KPEnv):void {
destruct()
copy_construct(&other)
}
fun set(key: str, val: KPValue) {
data.set(key, val)
}
fun remove(key: str) {
data.remove(key)
}
fun find(key: str): *KPEnv {
if (data.contains_key(key)) {
return this
} else if (outer != null<KPEnv>()) {
return outer->find(key)
} else {
return null<KPEnv>()
}
}
fun get(key: str): KPResult {
var env = find(key)
if (env != null<KPEnv>()) {
return KPResult::Ok(env->data.get(key))
} else {
return KPResult::Err(kpString(str("'") + key + "' not found"))
}
}
fun to_string(): str {
var to_ret = str()
to_string(str("\t"), to_ret)
return to_ret
}
fun to_string(tabs: ref str, s: ref str) {
for (var i = 0; i < data.keys.size; i++;) {
/*s += tabs + data.keys[i] + ": " + data.values[i] + "\n"*/
s += tabs + data.keys[i] + "\n"
}
if outer != null<KPEnv>() {
outer->to_string(tabs + "\t", s)
}
}
}
obj KPBuiltinCombiner (Object) {
var name: str
var fp: fun(vec<KPValue>, *KPEnv): KPResult
fun construct(name: ref str, fp: fun(vec<KPValue>, *KPEnv): KPResult): *KPBuiltinCombiner {
this->name.copy_construct(&name)
this->fp = fp
return this
}
fun copy_construct(old: *KPBuiltinCombiner): void {
this->fp = old->fp
this->name.copy_construct(&old->name)
}
fun destruct(): void {
this->name.destruct()
}
fun operator=(other:ref KPBuiltinCombiner):void {
destruct()
copy_construct(&other)
}
fun operator==(other: ref KPBuiltinCombiner):bool {
return false
}
fun call(params: vec<KPValue>, dynamic_env: KPValue): KPResult {
if !dynamic_env.is_env() {
return KPResult::Err(kpString(pr_str(dynamic_env, true) + " is not an env"))
}
return fp(params, dynamic_env.get_env())
}
}
fun make_builtin_combiner(name: str, f: fun(vec<KPValue>, *KPEnv): KPResult): KPValue {
var to_ret.construct(name, f): KPBuiltinCombiner
return nmMV(KPValue_int::BuiltinCombiner(to_ret))
}
obj KPCombiner (Object) {
var env: *KPEnv
var dynamic_env_name: str
var parameters: vec<str>
var is_variadic: bool
var body: *KPValue
fun construct(env: *KPEnv, dynamic_env_name: str, parameters: vec<str>, is_variadic: bool, body: KPValue): *KPCombiner {
this->env = env
this->dynamic_env_name.copy_construct(&dynamic_env_name)
this->parameters.copy_construct(&parameters)
this->is_variadic = is_variadic
this->body = new<KPValue>()
this->body->copy_construct(&body)
return this
}
fun copy_construct(old: *KPCombiner): void {
this->env = old->env
this->dynamic_env_name.copy_construct(&old->dynamic_env_name)
this->parameters.copy_construct(&old->parameters)
this->is_variadic = old->is_variadic
this->body = new<KPValue>()
this->body->copy_construct(old->body)
}
fun destruct(): void {
this->env = null<KPEnv>()
dynamic_env_name.destruct()
parameters.destruct()
delete(body)
body = null<KPValue>()
}
fun operator=(other:ref KPCombiner):void {
destruct()
copy_construct(&other)
}
fun operator==(other: ref KPCombiner):bool {
// not sure about env
return env == other.env && dynamic_env_name == other.dynamic_env_name && parameters == other.parameters && is_variadic == other.is_variadic && body->equals(*other.body)
}
// no call b/c need to do in EVAL for TCO
fun prep_call(params: ref vec<KPValue>, dynamic_env: KPValue): pair<*KPEnv, KPResult> {
// tco
if (!is_variadic && parameters.size != params.size) || (is_variadic && parameters.size > params.size + 1) {
return make_pair(null<KPEnv>(), KPResult::Err(kpString(str("combiner called with the wrong number of parameters: ") + params.size + " but expecting " + parameters.size + ": [ " + str(",").join(parameters) + "], was: " + pr_str(kpVector(params), true) + ", function body is " + pr_str(*body, true))))
}
var new_env = new<KPEnv>()->construct(env)
for (var i = 0; i < parameters.size; i++;) {
if is_variadic && i == parameters.size - 1 {
new_env->set(parameters[i], kpVector(params.slice(i, -1)))
} else {
new_env->set(parameters[i], params[i])
}
}
new_env->set(dynamic_env_name, dynamic_env)
return make_pair(new_env, KPResult::Ok(*body))
}
}
obj KPValue (Object) {
var internal: KPValue_int
var meta: *KPValue
fun construct(): *KPValue {
internal.copy_construct(&KPValue_int::Nil());
meta = null<KPValue>()
}
fun construct(i: ref KPValue_int, m: *KPValue): *KPValue {
internal.copy_construct(&i);
meta = m
}
fun copy_construct(other: *KPValue): void {
internal.copy_construct(&other->internal);
/*meta = other->meta*/
if other->meta != null<KPValue>() {
meta = new<KPValue>()
meta->copy_construct(other->meta)
} else {
meta = null<KPValue>()
}
}
fun operator=(other: ref KPValue): void {
destruct()
copy_construct(&other)
}
fun destruct(): void {
if meta != null<KPValue>()
delete(meta)
internal.destruct()
}
fun equals(other: ref KPValue): bool {
match (internal) {
KPValue_int::Vector(d) { match (other.internal) {
KPValue_int::Vector(db) {
if d.get().size != db.get().size {
return false
}
for (var i = 0; i < d.get().size; i++;) {
if !d.get()[i].equals(db.get()[i]) {
return false
}
}
return true
}
} }
KPValue_int::String(d) { match (other.internal) { KPValue_int::String(db) { return d == db; } } }
KPValue_int::Int(d) { match (other.internal) { KPValue_int::Int(db) { return d == db; } } }
KPValue_int::Symbol(d) { match (other.internal) { KPValue_int::Symbol(db) { return d == db; } } }
KPValue_int::Combiner(d){ match (other.internal) { KPValue_int::Combiner(db) { return d == db; } } }
KPValue_int::BuiltinCombiner(d) { match (other.internal) { KPValue_int::BuiltinCombiner(db) { return d == db; } } }
KPValue_int::Env(e) { match (other.internal) { KPValue_int::Env(eb) { return e == eb; } } }
KPValue_int::True() { match (other.internal) { KPValue_int::True() { return true; } } }
KPValue_int::False() { match (other.internal) { KPValue_int::False() { return true; } } }
KPValue_int::Nil() { match (other.internal) { KPValue_int::Nil() { return true; } } }
}
return false
}
fun deep_clone(): KPValue {
match (internal) {
KPValue_int::Vector(v) {
return kpVector(v.get())
}
KPValue_int::Env(e) {
var newenv = new<KPEnv>()
newenv->copy_construct(e)
return kpEnv(e)
}
}
return *this
}
fun is_combiner(): bool {
match (internal) {
KPValue_int::Combiner(f) {
return true
}
KPValue_int::BuiltinCombiner(f) {
return true
}
}
return false
}
fun is_env(): bool {
match (internal) {
KPValue_int::Env(e) {
return true
}
}
return false
}
fun get_env(): *KPEnv {
match (internal) {
KPValue_int::Env(e) {
return e
}
}
error("Tried to get env on not an env" + pr_str(*this, true))
}
fun is_vector(): bool {
match (internal) {
KPValue_int::Vector(v) {
return true
}
}
return false
}
fun get_vector_rc(): rc<vec<KPValue>> {
match (internal) {
KPValue_int::Vector(v) {
return v
}
}
error("Tried to get vec on not a vec" + pr_str(*this, true))
}
fun is_symbol(): bool {
match (internal) {
KPValue_int::Symbol(s) {
return true
}
}
return false
}
fun is_symbol(text: *char): bool {
match (internal) {
KPValue_int::Symbol(s) {
return s == text
}
}
return false
}
fun get_symbol_text(): str {
match (internal) {
KPValue_int::Symbol(s) {
return s
}
}
error("get_symbol_text on not symbol")
}
fun is_string(): bool {
match (internal) {
KPValue_int::String(s) {
return true
}
}
return false
}
fun get_string(): str {
match (internal) {
KPValue_int::String(s) {
return s
}
}
error("get_string on not a string")
}
fun is_int(): bool {
match (internal) {
KPValue_int::Int(i) {
return true
}
}
return false
}
fun get_int(): int {
match (internal) {
KPValue_int::Int(i) {
return i
}
}
error("get_int on not an int")
}
fun is_nil(): bool {
match (internal) {
KPValue_int::Nil() {
return true
}
}
return false
}
fun is_truthy(): bool {
match (internal) {
KPValue_int::False() {
return false
}
KPValue_int::Nil() {
return false
}
}
return true
}
fun is_pair(): bool {
return is_vector() && get_vector_rc().get().size > 0
}
}
fun nmMV(i: ref KPValue_int): KPValue {
var to_ret.construct(i, null<KPValue>()): KPValue
return to_ret
}
fun kpTrue(): KPValue {
return nmMV(KPValue_int::True())
}
fun kpFalse(): KPValue {
return nmMV(KPValue_int::False())
}
fun bool_to_KPValue(b: bool): KPValue {
if b {
return nmMV(KPValue_int::True())
} else {
return nmMV(KPValue_int::False())
}
}
fun kpString(s: ref str): KPValue {
return nmMV(KPValue_int::String(s))
}
fun kpSymbol(s: ref str): KPValue {
return nmMV(KPValue_int::Symbol(s))
}
fun kpInt(i: int): KPValue {
return nmMV(KPValue_int::Int(i))
}
fun kpVector(v: ref vec<KPValue>): KPValue {
var rcd.construct(v): rc<vec<KPValue>>
return nmMV(KPValue_int::Vector(rcd))
}
fun kpNil(): KPValue {
return nmMV(KPValue_int::Nil())
}
fun kpEnv(e: *KPEnv): KPValue {
return nmMV(KPValue_int::Env(e))
}
fun read_str(grammar: ref Grammer<KPResult,KPValue>, s: str): pair<int, KPResult> {
var BSR = fungll(grammar, grammar.start_symbol, s)
var longest = -1
for (var i = 0; i < BSR.data.size; i++;) {
if BSR.data[i].nonterminal == grammar.start_symbol && BSR.data[i].left == 0 && BSR.data[i].idx_into_rule == grammar.nonterminals[(-1*BSR.data[i].nonterminal)-1][BSR.data[i].rule_idx].size {
longest = BSR.data[i].right
}
}
if longest >= 0 {
return make_pair(longest, grammar.eval_BSR(s.slice(0, longest), BSR))
} else {
println("trying to parse: " + s)
println(str("length of BSR is: ") + BSR.size())
for (var i = 0; i < BSR.data.size; i++;) {
println(str() + i + ": " + grammar.to_string(BSR.data[i]))
}
println("Parse failed")
return make_pair(-1, KPResult::Err(kpString(str("failed to parse"))))
}
}
adt KPResult {
Ok: KPValue,
Err: KPValue
}
fun is_err(r: KPResult): bool {
match (r) {
KPResult::Err(e) {
return true
}
}
return false
}
fun get_err(r: KPResult): KPValue {
match (r) {
KPResult::Err(e) {
return e
}
}
/*return kpSymbol(str("get-err-not-error"))*/
error("get-err-not-error")
}
fun get_value(r: KPResult): KPValue {
match (r) {
KPResult::Ok(v) {
return v
}
}
/*return kpSymbol(str("get-value-is-error"))*/
error("get-value-is-error")
}
fun pr_str(v: KPValue, print_readably: bool): str {
match (v.internal) {
KPValue_int::Vector(l) {
var to_ret = str("( ")
for (var i = 0; i < l.get().size; i++;) {
if (i != 0) {
to_ret += " "
}
to_ret += pr_str(l.get()[i], print_readably)
}
return to_ret + " )"
}
KPValue_int::Int(i) {
return to_string(i)
}
KPValue_int::String(s) {
if print_readably {
var to_ret = str("\"") //"
for (var i = 0; i < s.length(); i++;) {
if s[i] == '\n' {
to_ret += '\\'
to_ret += 'n'
} else if s[i] == '\\' || s[i] == '"' {
to_ret += '\\'
to_ret += s[i]
} else {
to_ret += s[i]
}
}
return to_ret + "\"" //"
} else {
return s
}
}
KPValue_int::Symbol(s) {
if print_readably {
return "'" + s
} else {
return s
}
}
KPValue_int::BuiltinCombiner(f) {
return str("builtin combiner")
}
KPValue_int::Combiner(f) {
return str("combiner")
}
KPValue_int::Env(e) {
return str("environment")
}
KPValue_int::True() {
return str("true")
}
KPValue_int::False() {
return str("false")
}
KPValue_int::Nil() {
return str("nil")
}
}
error("can't print")
}
fun READ(grammar: ref Grammer<KPResult, KPValue>, s: str): KPResult {
var to_ret = read_str(grammar, s)
if to_ret.first != s.length() {
if is_err(to_ret.second) {
return to_ret.second
} else {
println("parsed to var: " + pr_str(get_value(to_ret.second), true))
}
error("parsed some, but not all")
}
return to_ret.second
}
fun EVAL(env: *KPEnv, ast: KPValue): KPResult {
// for tco
while (true) {
match (ast.internal) {
KPValue_int::Vector(l) {
if (l.get().size == 0) {
return KPResult::Err(kpString(str("Eval a zero length vector")))
} else {
// this breaks tco?
var combiner = EVAL(env, l.get()[0])
if is_err(combiner) {
return combiner
}
match (get_value(combiner).internal) {
KPValue_int::BuiltinCombiner(f) {
return f.call(l.get().slice(1,-1), kpEnv(env))
}
KPValue_int::Combiner(f) {
var call_pair = f.prep_call(l.get().slice(1, -1), kpEnv(env))
if is_err(call_pair.second) {
return call_pair.second
}
env = call_pair.first
ast = get_value(call_pair.second)
continue
}
}
return KPResult::Err(kpString(str("trying to call not a combiner: ") + pr_str(l.get()[0], true)))
}
}
KPValue_int::Symbol(s) {
return env->get(s)
}
}
// everything else is self-evaluating
return KPResult::Ok(ast)
}
}
fun rep(grammar: ref Grammer<KPResult, KPValue>, env: *KPEnv, a: str): str {
var read = READ(grammar, a)
if is_err(read) {
return pr_str(get_err(read), true)
} else {
var evaled = EVAL(env, get_value(read))
if is_err(evaled) {
return str("Exception: ") + pr_str(get_err(evaled), true)
} else {
return pr_str(get_value(evaled), true)
}
}
}
fun function_call(f: KPValue, params: ref vec<KPValue>, env: KPValue): KPResult {
match (f.internal) {
KPValue_int::BuiltinCombiner(f) {
return f.call(params, env)
}
KPValue_int::Combiner(f) {
var call_pair = f.prep_call(params, env)
if is_err(call_pair.second) {
return call_pair.second
}
return EVAL(call_pair.first, get_value(call_pair.second))
}
}
return KPResult::Err(kpString(str("trying to apply not a combiner: ") + pr_str(f ,true)))
}
fun print_wrapper(params: ref vec<KPValue>, sep: *char, print_readably: bool): str {
var to_ret = str()
for (var i = 0; i < params.size; i++;) {
to_ret += pr_str(params[i], print_readably)
if i != params.size-1 {
to_ret += sep
}
}
return to_ret
}
fun main(argc: int, argv: **char): int {
var grammar.construct(): Grammer<KPResult, KPValue>
var ret_nil_term: fun(ref KPValue, ref str, int, int): KPResult = fun(_: ref KPValue, input: ref str, l: int, r: int): KPResult { return KPResult::Ok(kpNil()); }
var ret_nil_sym: fun(ref KPValue, ref vec<KPResult>): KPResult = fun(_: ref KPValue, x: ref vec<KPResult>): KPResult { return KPResult::Ok(kpNil()); }
var ret_0_sym: fun(ref KPValue, ref vec<KPResult>): KPResult = fun(_: ref KPValue, x: ref vec<KPResult>): KPResult { return x[0]; }
var WS = grammar.add_new_nonterminal("WS", vec(grammar.add_terminal("( | |
|(;[ -~]*
))+", kpNil(), ret_nil_term)), kpNil(), ret_nil_sym)
var optional_WS = grammar.add_new_nonterminal("optional_WS", vec<int>(), kpNil(), ret_nil_sym)
grammar.add_to_nonterminal(optional_WS, vec(WS), kpNil(), ret_nil_sym)
var atom = grammar.add_new_nonterminal("atom", vec(grammar.add_terminal("-?[0-9]+", kpNil(), fun(_: ref KPValue, input: ref str, l: int, r: int): KPResult { return KPResult::Ok(kpInt(string_to_num<int>(input.slice(l,r)))); })), kpNil(), ret_0_sym)
grammar.add_to_nonterminal(atom, vec(grammar.add_terminal("\"([#-[]| |[]-~]|(\\\\)|(\\n)|(\\t)|(\\\*)|(\\0)|
|[ -!]|(\\\\\"))*\"", kpNil(), fun(_: ref KPValue, input: ref str, l: int, r: int): KPResult { //"
var to_ret = str()
for (var i = l+1; i < r-1; i++;) {
if input[i] == '\\' {
if input[i+1] == 'n' {
to_ret += '\n'
} else if input[i+1] == '\\' || input[i+1] == '"' {
to_ret += input[i+1]
} else {
return KPResult::Err(kpString(str("bad string escape")))
}
// skip
i++
} else {
to_ret += input[i]
}
}
return KPResult::Ok(kpString(to_ret));
})), kpNil(), ret_0_sym)
grammar.add_to_nonterminal(atom, vec(grammar.add_terminal("-|(([a-z]|[A-Z]|_|\\*|/|\\?|\\+|!|=|&|<|>)([a-z]|[A-Z]|_|[0-9]|\\*|\\?|\\+|-|!|=|&|<|>)*)", kpNil(), fun(_: ref KPValue, input: ref str, l: int, r: int): KPResult {
var s = input.slice(l,r)
if s == "true" {
return KPResult::Ok(kpTrue());
} else if s == "false" {
return KPResult::Ok(kpFalse());
} else if s == "nil" {
return KPResult::Ok(kpNil());
} else {
return KPResult::Ok(kpSymbol(input.slice(l,r)));
}
})), kpNil(), ret_0_sym)
var form = grammar.add_new_nonterminal("form", vec(atom), kpNil(), ret_0_sym)
var space_forms = grammar.add_new_nonterminal("space_forms", vec<int>(), kpNil(), fun(_: ref KPValue, x: ref vec<KPResult>): KPResult {
return KPResult::Ok(kpVector(vec<KPValue>()))
})
grammar.add_to_nonterminal(space_forms, vec(form), kpNil(), fun(_: ref KPValue, x: ref vec<KPResult>): KPResult {
if is_err(x[0]) {
return x[0]
}
return KPResult::Ok(kpVector(vec(get_value(x[0]))))
})
grammar.add_to_nonterminal(space_forms, vec(form, WS, space_forms), kpNil(), fun(_: ref KPValue, x: ref vec<KPResult>): KPResult {
if is_err(x[0]) {
return x[0]
}
if is_err(x[2]) {
return x[2]
}
return KPResult::Ok(kpVector(vec(get_value(x[0])) + get_value(x[2]).get_vector_rc().get()))
})
grammar.add_to_nonterminal(form, vec(grammar.add_terminal("\\(", kpNil(), ret_nil_term),
optional_WS,
grammar.add_terminal("\\)", kpNil(), ret_nil_term)), kpNil(), fun(_: ref KPValue, x: ref vec<KPResult>): KPResult { return KPResult::Ok(kpVector(vec<KPValue>())); })
grammar.add_to_nonterminal(form, vec(grammar.add_terminal("\\(", kpNil(), ret_nil_term),
optional_WS,
space_forms,
optional_WS,
grammar.add_terminal("\\)", kpNil(), ret_nil_term)), kpNil(), fun(_: ref KPValue, x: ref vec<KPResult>): KPResult { return x[2]; })
grammar.set_start_symbol(form)
var env = new<KPEnv>()->construct()
env->set(str("+"), make_builtin_combiner(str("+"), fun(params: vec<KPValue>, dynamic_env: *KPEnv): KPResult {
var to_ret = 0
for (var i = 0; i < params.size; i++;) {
var ip = EVAL(dynamic_env, params[i])
if is_err(ip) {
return ip
}
match (get_value(ip).internal) {
KPValue_int::Int(v) {
to_ret += v
continue
}
}
return KPResult::Err(kpString(str("called + with not an int: ") + pr_str(params[i], false)))
}
return KPResult::Ok(kpInt(to_ret))
}));
if argc == 3 && str(argv[1]) == "-C" {
error("-C not implemented")
//env->set(str("*ARGV*"), kpNil())
//var evaled = ERS(vec(kpString(str(argv[2]))))
//if is_err(evaled) {
// printlnerr(str("Exception: ") + pr_str(get_err(evaled), true))
//} else {
// println("Result: " + pr_str(get_value(evaled), true))
//}
} else if argc >= 2 {
var params = vec<KPValue>()
for (var i = 2; i < argc; i++;) {
params.add(kpString(str(argv[i])))
}
env->set(str("*ARGV*"), kpVector(params))
var eval_result_str = rep(grammar, env, str("(load-file \"") + argv[1] + "\")")
println(eval_result_str)
if eval_result_str.length() >= 11 && eval_result_str.slice(0,11) == "Exception: " {
error("aborting compile")
}
// check for compile
var main = env->get(str("main"))
if !is_err(main) {
println("Starting compile!")
error("Compiler not implemented")
} else {
println("No main function to compile, exiting")
}
} else {
while (true) {
var line = get_line(str("user> "), 1024)
if (line == "***EOF***")
break
println(rep(grammar, env, line))
}
}
}