summaryrefslogtreecommitdiff
path: root/precedent.c
blob: 95d62e5d939b97294dcc96b8e814638741d25066 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdlib.h>
#include <stdio.h>
#include "precedent.h"
#include "hashtable.h"
#include "parse.h"

hashtable_t* ht;

int main() {
	sym_t* finalSymbol = parse_symbol_final("store(print(hello;) myFunc;) myFunc()");
	printf("drawing program:\n");
	write_symbol_visual(finalSymbol, 0);
	printf("\nexecuting program:\n");
	ht = init_hashtable(1000);
	eval(finalSymbol);
	return 0;
}
/* TODO: read base hashtable from file to allow modularity
pair value value? */
void exec_all(symset_t symset) {
	for (int i = 0; i < symset.count; i++) {
		/* dispose of result */
		eval(symset.symbols[i]);
	}
}
void* eval(sym_t* symbol) {
	if (symbol->province == LITERAL) {
		return symbol->name;
	}
	else if (symbol->province == KEY_REF) {
		void* ir = try_eval_internal(symbol);
		if (ir != NULL) {
			return ir;
		}
		else {
			/* not an internal function, search hashtable for
			next symbol */
			/* TODO: scope */
			pair_t* p = hashtable_get_pair(ht, (char*)symbol->name);
			if (p != NULL) {
				return eval((sym_t*)p->value);
			}
			else {
				return NULL;
			}
		}
	}
	else {
		return NULL;
	}
}
/* internal functions?
this function has side-effects */
void* try_eval_internal(sym_t* symbol) {
	unsigned int hash = get_hash((char*)symbol->name);
	if (hash == get_hash("root")) {
		/* execute all args as roots */
		symset_t symset;
		symset.symbols = symbol->args;
		symset.count = symbol->argCount;
		exec_all(symset);
		return (void*)1;
	}
	else if (hash == get_hash("store")) {
		/* TODO: scope */
		/* first arg is value, remaining args are names */
		/* TODO: recursion for multiple pairs */
		char* key = (char*)eval(symbol->args[1]);
		sym_t* value = symbol->args[0];
		pair_t* p = init_pair(key, (void*)value);
		hashtable_add_pair(ht, p);
		return (void*)1;
	}
	else if (hash == get_hash("print")) {
		/* TODO: genericize printf type */
		printf("%s\n", (char*)eval(symbol->args[0]));
		return (void*)1;
	}
	else {
		return NULL;
	}
}