matlab: step7, fix reader bug.
[jackhill/mal.git] / matlab / step5_tco.m
CommitLineData
23c5aa44
JM
1function step5_tco(varargin), main(varargin), end
2
3% read
4function ret = READ(str)
5 ret = reader.read_str(str);
6end
7
8% eval
9function ret = eval_ast(ast, env)
10 switch class(ast)
11 case 'types.Symbol'
12 ret = env.get(ast);
13 case 'cell'
14 ret = {};
15 for i=1:length(ast)
16 ret{end+1} = EVAL(ast{i}, env);
17 end
18 otherwise
19 ret = ast;
20 end
21end
22
23function ret = EVAL(ast, env)
24 while true
25 if ~iscell(ast),
26 ret = eval_ast(ast, env);
27 return;
28 end
29
30 % apply
31 if isa(ast{1},'types.Symbol')
32 a1sym = ast{1}.name;
33 else
34 a1sym = '_@$fn$@_';
35 end
36 switch (a1sym)
37 case 'def!'
38 ret = env.set(ast{2}, EVAL(ast{3}, env));
39 return;
40 case 'let*'
41 let_env = Env(env);
42 for i=1:2:length(ast{2})
43 let_env.set(ast{2}{i}, EVAL(ast{2}{i+1}, let_env));
44 end
45 env = let_env;
46 ast = ast{3}; % TCO
47 case 'do'
48 el = eval_ast(ast(2:end-1), env);
49 ast = ast{end}; % TCO
50 case 'if'
51 cond = EVAL(ast{2}, env);
52 if strcmp(class(cond), 'types.Nil') || ...
53 (islogical(cond) && cond == false)
54 if length(ast) > 3
55 ast = ast{4}; % TCO
56 else
57 ret = types.nil;
58 return;
59 end
60 else
61 ast = ast{3}; % TCO
62 end
63 case 'fn*'
64 fn = @(varargin) EVAL(ast{3}, Env(env, ast{2}, varargin));
65 ret = Function(fn, ast{3}, env, ast{2});
66 return;
67 otherwise
68 el = eval_ast(ast, env);
69 f = el{1};
70 args = el(2:end);
71 if isa(f, 'Function')
72 env = Env(f.env, f.params, args);
73 ast = f.ast; % TCO
74 else
75 ret = f(args{:});
76 return
77 end
78 end
79 end
80end
81
82% print
83function ret = PRINT(ast)
84 ret = printer.pr_str(ast, true);
85end
86
87% REPL
88function ret = rep(str, env)
89 ret = PRINT(EVAL(READ(str), env));
90end
91
92function main(args)
93 repl_env = Env(false);
94
95 % core.m: defined using matlab
96 ns = core.ns(); ks = ns.keys();
97 for i=1:length(ks)
98 k = ks{i};
99 repl_env.set(types.Symbol(k), ns(k));
100 end
101
102 % core.mal: defined using the langauge itself
103 rep('(def! not (fn* (a) (if a false true)))', repl_env);
104
105 %cleanObj = onCleanup(@() disp('*** here1 ***'));
106 while (true)
107 line = input('user> ', 's');
108 if strcmp(strtrim(line),''), continue, end
109 try
110 fprintf('%s\n', rep(line, repl_env));
111 catch err
112 fprintf('Error: %s\n', err.message);
113 fprintf('%s\n', getReport(err, 'extended'));
114 end
115 end
116end