-
Notifications
You must be signed in to change notification settings - Fork 2
/
interpreter.pas
421 lines (364 loc) · 10.4 KB
/
interpreter.pas
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
unit interpreter;
{$ifdef FPC}
{$mode delphi}
{$endif}
{$IFOPT D+}
{$DEFINE DEBUG}
{$ENDIF}
interface
uses
Classes, SysUtils, Generics.Collections
, token, expression, statement, environment, rterror;
type
{ TInterpreter }
TInterpreter = class(IExpressionVisitor, IStatementVisitor)
private
FEnvir: TEnvironment;
function Evaluate(expr: TExpression): TObject;
function IsTruthy(obj: TObject): boolean;
function IsEqual(left, right: TObject): boolean;
function Stringify(obj: TObject): string;
public
constructor Create;
destructor Destroy; override;
{ Expression visitor }
function VisitLit(expr: TLiteralExpression): TObject;
function VisitLogic(expr: TLogicalExpression): TObject;
function VisitUn(expr: TUnaryExpression): TObject;
function VisitBin(expr: TBinaryExpression): TObject;
function VisitGroup(expr: TGroupingExpression): TObject;
function VisitVar(expr: TVariableExpression): TObject;
function VisitAssign(expr: TAssignmentExpression): TObject;
{ Statement visitor }
procedure VisitBlockStm(stm: TBlockStatement);
procedure VisitExprStm(stm: TExpressionStatement);
procedure VisitIfStm(stm: TIfStatement);
procedure VisitWhileStm(stm: TWhileStatement);
procedure VisitPrintStm(stm: TPrintStatement);
procedure VisitPrintDOTStm(stm: TPrintDOTStatement);
procedure VisitVarStm(stm: TVariableStatement);
{ helper }
procedure Execute(stm: TStatement);
{ do job }
procedure Interpret(stm: TObjectList<TStatement>);
end;
implementation
uses ptypes, lox, astutils;
{ TInterpreter }
function TInterpreter.Evaluate(expr: TExpression): TObject;
begin
{$IFDEF TRACE}
WriteLn(Format('[DEBUG] (TInterpreter) Evaluating %s.', [expr.ClassName]));
{$ENDIF}
Result := expr.Accept(self);
end;
function TInterpreter.IsTruthy(obj: TObject): boolean;
begin
{ Ruby’s simple rule: false and nil are falsey and everything else is truthy. }
if obj = nil then
Exit(False);
if obj is TLoxBool then
Exit(TLoxBool(obj).Value);
Exit(True);
end;
function TInterpreter.IsEqual(left, right: TObject): boolean;
begin
if (left = nil) and (right = nil) then
Exit(True);
if left = nil then
Exit(False);
if left is TLoxBool then
if right is TLoxBool then
Exit(TLoxBool(left).Value = TLoxBool(right).Value)
else
Exit(False);
if left is TLoxNum then
if right is TLoxNum then
Exit(TLoxNum(left).Value = TLoxNum(right).Value)
else
Exit(False);
if left is TLoxStr then
if right is TLoxStr then
Exit(TLoxStr(left).Value = TLoxStr(right).Value)
else
Exit(False);
Result := left.Equals(right);
end;
function TInterpreter.Stringify(obj: TObject): string;
begin
Result := ObjToStr(obj);
end;
constructor TInterpreter.Create;
begin
FEnvir := TEnvironment.Create;
end;
destructor TInterpreter.Destroy;
begin
FreeAndNil(self.FEnvir);
inherited;
end;
function TInterpreter.VisitLit(expr: TLiteralExpression): TObject;
begin
if expr.Value is TLoxObject then
Result := TLoxObject(expr.Value).Clone()
else
Result := expr.Value; { nil ? }
end;
function TInterpreter.VisitLogic(expr: TLogicalExpression): TObject;
var
left: TObject;
begin
left := nil;
left := self.Evaluate(expr.left);
case expr.op.tokenKind of
TTokenKind.tkOR:
if self.IsTruthy(left) then
Exit(left);
TTokenKind.tkAND:
if not self.IsTruthy(left) then
Exit(left);
end;
FreeAndNil(left);
Result := self.Evaluate(expr.right);
end;
function TInterpreter.VisitUn(expr: TUnaryExpression): TObject;
var
right: TObject;
obj: TObject;
rte: ERunTimeError;
begin
right := nil;
obj := nil;
rte := nil;
right := self.Evaluate(expr.right);
case expr.op.tokenKind of
TTokenKind.tkBANG:
obj := TLoxBool.Create(not self.IsTruthy(right));
TTokenKind.tkMINUS:
if right is TLoxNum then
obj := TLoxNum.Create(-TLoxNum(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operand must be a number.');
end;
FreeAndNil(right);
Result := obj;
if rte <> nil then
raise rte;
end;
// TO DO CHECK OP with nil
function TInterpreter.VisitBin(expr: TBinaryExpression): TObject;
var
left, right: TObject;
obj: TObject;
rte: ERunTimeError;
begin
left := nil;
right := nil;
obj := nil;
rte := nil;
left := self.Evaluate(expr.left);
right := self.Evaluate(expr.right);
case expr.op.tokenKind of
TTokenKind.tkPLUS: { + }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxNum.Create(TLoxNum(left).Value + TLoxNum(right).Value)
else
if (left is TLoxStr) or (right is TLoxStr) then
obj := TLoxStr.Create(left.ToString() + right.ToString())
else
rte := ERuntimeError.Create(expr.op,
'Operands must be numbers or either string.');
TTokenKind.tkMINUS: { - }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxNum.Create(TLoxNum(left).Value - TLoxNum(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers.');
TTokenKind.tkSTAR: { * }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxNum.Create(TLoxNum(left).Value * TLoxNum(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers.');
TTokenKind.tkSLASH: { / }
if (left is TLoxNum) and (right is TLoxNum) then
if TLoxNum(right).Value <> 0 then
obj := TLoxNum.Create(TLoxNum(left).Value / TLoxNum(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Division by zero.')
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers.');
TTokenKind.tkGREATER: { > }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxBool.Create(TLoxNum(left).Value > TLoxNum(right).Value)
else
if (left is TLoxStr) and (right is TLoxStr) then
obj := TLoxBool.Create(TLoxStr(left).Value > TLoxStr(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers or strings.');
{ TO DO Add bool comparison Rewrite comp proc }
TTokenKind.tkGREATER_EQUAL: { >= }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxBool.Create(TLoxNum(left).Value >= TLoxNum(right).Value)
else
if (left is TLoxStr) and (right is TLoxStr) then
obj := TLoxBool.Create(TLoxStr(left).Value >= TLoxStr(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers or strings.');
TTokenKind.tkLESS: { < }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxBool.Create(TLoxNum(left).Value < TLoxNum(right).Value)
else
if (left is TLoxStr) and (right is TLoxStr) then
obj := TLoxBool.Create(TLoxStr(left).Value < TLoxStr(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers or strings.');
TTokenKind.tkLESS_EQUAL: { <= }
if (left is TLoxNum) and (right is TLoxNum) then
obj := TLoxBool.Create(TLoxNum(left).Value <= TLoxNum(right).Value)
else
if (left is TLoxStr) and (right is TLoxStr) then
obj := TLoxBool.Create(TLoxStr(left).Value <= TLoxStr(right).Value)
else
rte := ERuntimeError.Create(expr.op, 'Operands must be numbers or strings.');
TTokenKind.tkEQUAL_EQUAL: { == }
obj := TLoxBool.Create(self.IsEqual(left, right));
TTokenKind.tkBANG_EQUAL: { != }
obj := TLoxBool.Create(not self.IsEqual(left, right));
end;
FreeAndNil(left);
FreeAndNil(right);
Result := obj;
if rte <> nil then
raise rte;
end;
function TInterpreter.VisitGroup(expr: TGroupingExpression): TObject;
begin
Result := self.Evaluate(expr.expr);
end;
function TInterpreter.VisitVar(expr: TVariableExpression): TObject;
begin
Result := FEnvir.Get(expr.varName);
end;
function TInterpreter.VisitAssign(expr: TAssignmentExpression): TObject;
var
obj: TObject;
begin
obj := self.Evaluate(expr.Value);
self.FEnvir.Assign(expr.varName, obj);
Result := obj;
end;
{ Statements }
procedure TInterpreter.VisitBlockStm(stm: TBlockStatement);
var
prev: TEnvironment;
s: TStatement;
begin
prev := self.FEnvir;
stm.environment.enclosing := prev;
self.FEnvir := stm.environment;
try
for s in stm.block do
self.Execute(s);
//block.environment.Finalize;
finally
self.FEnvir := prev;
end;
end;
procedure TInterpreter.VisitExprStm(stm: TExpressionStatement);
var
r: TObject;
begin
r := nil;
r := self.Evaluate(stm.expr);
FreeAndNil(r);
end;
procedure TInterpreter.VisitIfStm(stm: TIfStatement);
var
cond: TObject;
begin
cond := self.Evaluate(stm.cond);
if self.IsTruthy(cond) then
self.Execute(stm.thenStm)
else
if stm.elseStm <> nil then
self.Execute(stm.elseStm);
FreeAndNil(cond);
end;
procedure TInterpreter.VisitWhileStm(stm: TWhileStatement);
var
obj: TObject;
begin
obj := self.Evaluate(stm.cond);
while self.IsTruthy(obj) do
begin
self.Execute(stm.body);
FreeAndNil(obj);
obj := self.Evaluate(stm.cond);
end;
FreeAndNil(obj)
end;
procedure TInterpreter.VisitPrintStm(stm: TPrintStatement);
var
obj: TObject;
prn: TASTPrinter;
begin
obj := nil;
prn := nil;
try
{$IFDEF DEBUG}
prn := TASTPrinter.Create();
WriteLn('[DEBUG] (TASTPrinter) ' + prn.Print(stm.expr, False));
WriteLn('[DEBUG] (TASTPrinter RPN) ' + prn.Print(stm.expr, True));
{$ENDIF}
obj := self.Evaluate(stm.expr);
WriteLn(ObjToStr(obj));
finally
FreeAndNil(obj);
FreeAndNil(prn);
end;
end;
procedure TInterpreter.VisitPrintDOTStm(stm: TPrintDOTStatement);
var
dot: TStringList;
dm: TASTDOTMaker;
begin
dot := nil;
dm := nil;
try
dm := TASTDOTMaker.Create();
dot := dm.Make(stm.expr);
WriteLn(dot.Text);
finally
FreeAndNil(dot);
FreeAndNil(dm);
end;
end;
procedure TInterpreter.VisitVarStm(stm: TVariableStatement);
var
obj: TObject;
begin
obj := nil;
if stm.expr <> nil then
obj := self.Evaluate(stm.expr);
self.FEnvir.Define(stm.token.lexeme, obj);
FreeAndNil(obj);
end;
procedure TInterpreter.Execute(stm: TStatement);
begin
{$IFDEF TRACE}
WriteLn(Format('[DEBUG] (TInterpreter) Executing %s.', [stm.ClassName]));
{$ENDIF}
stm.Accept(self);
end;
procedure TInterpreter.Interpret(stm: TObjectList<TStatement>);
var
s: TStatement;
begin
try
for s in stm do
self.Execute(s);
except
on e: ERunTimeError do
TLox.RunTimeError(e)
end;
end;
end.