1 /**
2 * Authors: k.inaba
3 * License: NYSL 0.9982 http://www.kmonos.net/nysl/
4 *
5 * Evaluator for Polemy programming language.
6 */
7 module polemy.eval;
8 import polemy._common;
9 import polemy.lex : LexPosition;
10 import polemy.ast;
11 import polemy.parse;
12 import polemy.value;
13 import std.typecons;
14 import std.stdio;
15
16 ///
17 Table createGlobalContext()
18 {
19 auto ctx = new Table;
20 ctx.set("+", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(lhs.data + rhs.data);} ));
21 ctx.set("-", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(lhs.data - rhs.data);} ));
22 ctx.set("*", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(lhs.data * rhs.data);} ));
23 ctx.set("/", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(lhs.data / rhs.data);} ));
24 ctx.set("%", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(lhs.data % rhs.data);} ));
25 ctx.set("||", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(BigInt((lhs.data!=0) || (rhs.data!=0) ? 1:0));} ));
26 ctx.set("&&", "@v", native( (IntValue lhs, IntValue rhs){return new IntValue(BigInt((lhs.data!=0) && (rhs.data!=0) ? 1:0));} ));
27 ctx.set("<", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs < rhs ? 1: 0));} ));
28 ctx.set(">", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs > rhs ? 1: 0));} ));
29 ctx.set("<=", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs <= rhs ? 1: 0));} ));
30 ctx.set(">=", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs >= rhs ? 1: 0));} ));
31 ctx.set("==", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs == rhs ? 1: 0));} ));
32 ctx.set("!=", "@v", native( (Value lhs, Value rhs){return new IntValue(BigInt(lhs != rhs ? 1: 0));} ));
33 ctx.set("print", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
34 foreach(a; args)
35 write(a);
36 writeln("");
37 return new IntValue(BigInt(178));
38 }));
39 ctx.set("if", "@v", new FunValue(delegate Value(immutable LexPosition pos, Layer lay, Value[] args){
40 if( args.length != 3 )
41 throw genex!RuntimeException(pos, "if takes three arguments!!");
42 if( auto x = cast(IntValue)args[0] )
43 if( auto ft = cast(FunValue)args[1] )
44 if( auto fe = cast(FunValue)args[2] )
45 return (x.data == 0 ? fe : ft).call(pos,lay,[]);
46 throw genex!RuntimeException(pos, "type mismatch in if");
47 }));
48 ctx.set("_isint", "@v", native( (Value v){return new IntValue(BigInt(cast(IntValue)v is null ? 0 : 1));} ));
49 ctx.set("_isstr", "@v", native( (Value v){return new IntValue(BigInt(cast(StrValue)v is null ? 0 : 1));} ));
50 ctx.set("_isfun", "@v", native( (Value v){return new IntValue(BigInt(cast(FunValue)v is null ? 0 : 1));} ));
51 ctx.set("_isundefined", "@v", native( (Value v){return new IntValue(BigInt(cast(UndValue)v is null ? 0 : 1));} ));
52 ctx.set("_istable", "@v", native( (Value v){return new IntValue(BigInt(cast(Table)v is null ? 0 : 1));} ));
53 ctx.set(".", "@v", native( (Table t, StrValue s){
54 return (t.has(s.data, "@v") ? t.get(s.data, "@v") : new UndValue);
55 }) );
56 ctx.set(".?", "@v", native( (Table t, StrValue s){
57 return new IntValue(BigInt(t.has(s.data, "@v") ? 1 : 0));
58 }) );
59 ctx.set(".=", "@v", native( (Table t, StrValue s, Value v){
60 auto t2 = new Table(t, Table.Kind.NotPropagateSet);
61 t2.set(s.data, "@v", v);
62 return t2;
63 }) );
64 ctx.set("{}", "@v", native( (){
65 return new Table;
66 }) );
67 return ctx;
68 }
69
70 /// Entry point of this module
71
72 Tuple!(Value,"val",Table,"ctx") evalString(S,T...)(S str, T fn_ln_cn)
73 {
74 return eval( polemy.parse.parseString(str, fn_ln_cn) );
75 }
76
77 /// Entry point of this module
78
79 Tuple!(Value,"val",Table,"ctx") evalFile(S, T...)(S filename, T ln_cn)
80 {
81 return eval( polemy.parse.parseFile(filename, ln_cn) );
82 }
83
84 /// Entry point of this module
85
86 Tuple!(Value,"val",Table,"ctx") eval(AST e)
87 {
88 Table ctx = createGlobalContext();
89 return typeof(return)(eval(e, ctx, false, "@v"), ctx);
90 }
91
92 /// Entry point of this module
93 /// If splitCtx = true, then inner variable declaration do not overwrite ctx.
94 /// lay is the layer ID for evaluation (standard value semantics uses "@v").
95
96 Value eval(AST e, Table ctx, bool splitCtx, Layer lay)
97 {
98 return e.match(
99 (StrLiteral e)
100 {
101 Value v = new StrValue(e.data);
102 if( lay == "@v" )
103 return v;
104 else // rise
105 return (cast(FunValue)ctx.get(lay, "(system)", e.pos)).call(e.pos, "@v", [v]);
106 },
107 (IntLiteral e)
108 {
109 Value v = new IntValue(e.data);
110 if( lay == "@v" )
111 return v;
112 else // rise
113 return (cast(FunValue)ctx.get(lay, "(system)", e.pos)).call(e.pos, "@v", [v]);
114 },
115 (VarExpression e)
116 {
117 if( lay == "@v" )
118 return ctx.get(e.var, lay, e.pos);
119 try {
120 return ctx.get(e.var, lay, e.pos);
121 } catch( Throwable ) { // [TODO] more precise...
122 // rise from @v
123 return (cast(FunValue)ctx.get(lay, "(system)", e.pos)).call(e.pos, "@v",
124 [ctx.get(e.var, "@v", e.pos)]
125 );
126 }
127 },
128 (LayeredExpression e)
129 {
130 return eval(e.expr, ctx, false, e.lay);
131 },
132 (LetExpression e)
133 {
134 // for letrec, we need this, but should avoid overwriting????
135 // ctx.set(e.var, "@v", new UndefinedValue, e.pos);
136 Value v = eval(e.init, ctx, true, lay);
137 if(splitCtx)
138 ctx = new Table(ctx, Table.Kind.NotPropagateSet);
139 ctx.set(e.var, (e.layer.length ? e.layer : lay), v, e.pos);
140 return eval(e.expr, ctx, false, lay);
141 },
142 (FuncallExpression e)
143 {
144 Value _f = eval(e.fun, ctx, true, lay);
145 if( auto f = cast(FunValue)_f ) {
146 Value[] args;
147 foreach(a; e.args)
148 args ~= eval(a, ctx, true, lay);
149 return f.call(e.pos, lay, args);
150 }
151 throw genex!RuntimeException(e.pos, "Non-funcion is applied");
152 },
153 (FunLiteral e)
154 {
155 Value[Value[]][Layer] memo;
156
157 // funvalue need not be rised
158 // no, need to be rised !! suppose @t(fib)("int")
159 return new FunValue(delegate Value(immutable LexPosition pos, string lay, Value[] args){
160 // TODO: only auto raised ones need memo? no?
161 // auto memoization
162 if( lay != "@v" )
163 {
164 if( auto memolay = lay in memo )
165 if( auto pv = args in *memolay )
166 return *pv;
167 memo[lay][args] = (cast(FunValue)ctx.get(lay, "(system)", e.pos)).call(e.pos, "@v",
168 [new UndValue]
169 );
170 }
171
172 if( e.params.length != args.length )
173 throw genex!RuntimeException(e.pos, sprintf!"Argument Number Mismatch (%d required but %d given)"
174 (e.params.length, args.length));
175 Table ctxNeo = new Table(ctx, Table.Kind.NotPropagateSet);
176 foreach(i,p; e.params)
177 ctxNeo.set(p.name, lay, args[i]);
178 auto v = eval(e.funbody, ctxNeo, true, lay);
179 // auto memoization
180 if( lay != "@v" )
181 memo[lay][args] = v;
182 return v;
183 });
184 },
185 delegate Value (AST e)
186 {
187 throw genex!RuntimeException(e.pos, sprintf!"Unknown Kind of Expression %s"(typeid(e)));
188 }
189 );
190 }
191
192 unittest
193 {
194 auto r = assert_nothrow( evalString(`var x = 21; x + x*x;`) );
195 assert_eq( r.val, new IntValue(BigInt(21+21*21)) );
196 assert_eq( r.ctx.get("x","@v"), new IntValue(BigInt(21)) );
197 assert_nothrow( r.ctx.get("x","@v") );
198 assert_throw!RuntimeException( r.ctx.get("y","@v") );
199 }
200 unittest
201 {
202 auto r = assert_nothrow( evalString(`var x = 21; var x = x + x*x;`) );
203 assert_eq( r.val, new IntValue(BigInt(21+21*21)) );
204 assert_eq( r.ctx.get("x","@v"), new IntValue(BigInt(21+21*21)) );
205 assert_nothrow( r.ctx.get("x","@v") );
206 assert_throw!RuntimeException( r.ctx.get("y","@v") );
207 }
208 unittest
209 {
210 assert_eq( evalString(`let x=1; let y=(let x=2); x`).val, new IntValue(BigInt(1)) );
211 assert_eq( evalString(`let x=1; let y=(let x=2;fun(){x}); y()`).val, new IntValue(BigInt(2)) );
212 }
213 unittest
214 {
215 assert_eq( evalString(`@a x=1; @b x=2; @a(x)`).val, new IntValue(BigInt(1)) );
216 assert_eq( evalString(`@a x=1; @b x=2; @b(x)`).val, new IntValue(BigInt(2)) );
217 assert_eq( evalString(`let x=1; let _ = (@a x=2;2); x`).val, new IntValue(BigInt(1)) );
218 assert_throw!Throwable( evalString(`let x=1; let _ = (@a x=2;2); @a(x)`) );
219 }
220
221 unittest
222 {
223 assert_eq( evalString(`var fac = fun(x){
224 if(x)
225 { x*fac(x-1); }
226 else
227 { 1; };
228 };
229 fac(10);`).val, new IntValue(BigInt(10*9*8*5040)));
230 assert_eq( evalString(`var fib = fun(x){
231 if(x<2)
232 { 1; }
233 else
234 { fib(x-1) + fib(x-2); };
235 };
236 fib(10);`).val, new IntValue(BigInt(89)));
237 }
238
239 unittest
240 {
241 assert_throw!Throwable( evalString(`@@s(x){x}; @s "+"=fun(x,y){x-y};@s(1+2)`) );
242 assert_eq( evalString(`@@s(x){x}; @s "+"=fun(x,y){x-y};1+2`).val, new IntValue(BigInt(3)) );
243 assert_eq( evalString(`@@s(x){x}; @s "+"=fun(x,y){@v(@s(x)-@s(y))};1+2`).val, new IntValue(BigInt(3)) );
244 assert_eq( evalString(`@@s(x){x}; @s "+"=fun(x,y){@v(@s(x)-@s(y))};@s(1+2)`).val, new IntValue(BigInt(-1)) );
245 }
246
247 unittest
248 {
249 assert_eq( evalString(`@@t = fun(x){x+1}; @t(123)`).val, new IntValue(BigInt(124)) );
250 }