/
class.rb
793 lines (685 loc) · 19 KB
/
class.rb
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# -*- coding: utf-8 -*-
$debug = 1;
require 'pp'
# Define exceptions that will be used to signal errors
class VarNotFound < StandardError
end
class FuncNotFound < StandardError
end
class ObjAlreadyDefined < StandardError
end
class NoValueError < StandardError
end
class Scope
# Ugly solution, might be able to fix it later
attr_accessor :scope_var, :scope_func, :parent
def initialize(parent = nil)
@scope_var, @scope_func, @parent = {}, {}, parent
end
def add_var(var)
if $debug then
temp = self
while not temp.parent.nil? and not temp.scope_var.has_key? var.name do
temp = temp.parent
end
if temp != nil and temp != self then
puts "Shadowing variable #{var.name.eval} from previous scope" if $debug
end
end
@scope_var[var.name] = var.value
puts "-----ADD_VAR IN SCOPE-----" if $debug
puts "added #{var.name.inspect} with value" if $debug
PP.pp var.value if $debug
end
def get_var(name)
#puts "-----GET_VAR IN SCOPE-----" if $debug
# We start searching from ourselves
scope = self
# dynamic scope, iterate backwards through scopes until we find the variable
while not scope.parent.nil? and not scope.scope_var.has_key? name do
scope = scope.parent
end
# if we have the key, we return it.
# if we don't, we know we've iterated to nil and we can raise an exception
#puts "#{name.inspect} return #{scope.scope_var[name].inspect}" if $debug and
#scope.scope_var.has_key? name
return scope.scope_var[name] if scope.scope_var.has_key? name
raise VarNotFound, "Unable to find variable with name #{name.inspect}"
end
# name will be a NameNode
def update_var(name, value)
puts "-----UPDATE VAR IN SCOPE-----" if $debug if $debug
temp = self
while not temp.parent.nil? and not temp.scope_var.has_key? name do
temp = temp.parent
end
if $debug and temp != self then
puts "Updated variable in older scope" if $debug
end
if not temp.nil? and temp.scope_var.has_key? name then
puts "updated #{name.inspect} with #{value.inspect}" if $debug if $debug
temp.scope_var[name] = value
end
end
def add_func(func)
if $debug then
temp = self
while not temp.parent.nil? and not temp.scope_func.has_key? func.name do
temp = temp.parent
end
if temp != self then
puts "Shadowing function #{func.name} from previous scope" if $debug
end
end
@scope_func[func.id] = func
end
def get_func(name)
temp = self
# dynamic scope, iterate backwards through scopes until we find the variable
while not temp.parent.nil? and not temp.scope_func.has_key? name do
temp = temp.parent
end
# if we have the key, we return it.
# if we don't, we know we've iterated to nil and we can cast an exception
if temp.scope_func.has_key? name then
return temp.scope_func[name]
end
raise FuncNotFound, "Scope: Couldn't find function #{name.inspect}"
end
end
# A helper function that takes a scope and a variable as a argument.
# Will return a value based on the type of object, or nil if there is no value.
def get_var(scope, var)
puts "-----GET_VAR() OUTSIDE SCOPE-----" if $debug
puts "var: #{var.inspect}" if $debug
if var.is_a? NameNode then
puts "namenode" if $debug
return get_var(scope, scope.get_var(var))
elsif var.is_a? IdentifierNode then
puts "identnode" if $debug
return get_var(scope, scope.get_var(var))
else
puts "returning #{var.inspect}" if $debug
return var
end
return nil
end
# A helper function that gets the Ruby value of the object, if any
def get_val(scope, var)
var = get_var(scope, var)
if var.is_a? ValueNode then
return var.eval(scope)
elsif var.is_a? BinaryOperatorNode then
return get_val(scope, var.eval(scope))
elsif var.is_a? Fixnum or Float then
return var
else
raise ArgumentError, "get_val: Invalid type #{var.class}"
end
end
# ProgramRoot will act as the root node of the program tree
class ProgramRoot
def initialize(stmt_list)
@stmt_list = stmt_list
@scope = Scope.new
end
def eval
puts "----------" if $debug
puts "begin eval in programroot" if $debug
puts "----------" if $debug
PP.pp @stmt_list if $debug
puts "\n"*15 if $debug
puts @stmt_list, "\n" if $debug
@stmt_list.each do |stmt|
stmt.eval(@scope)
end
end
end
# Implementation of common functions
# A basic node handling output
class PrintNode
def initialize(input)
@input = input
end
def eval(scope)
@input.each do |stmt|
puts "--------------------PRINT" if $debug
stmt = get_var(scope, stmt)
if stmt.is_a? Array then
stmt.each { |item| puts item.eval(scope) }
elsif stmt.is_a? ValueNode then
puts(stmt)
elsif stmt.respond_to? :eval then
puts(stmt.eval(scope))
else
puts(stmt)
end
puts "--------------------------------------------------" if $debug
end
end
end
# A basic node allowing input to be retrieved
class InputNode
def initialize(input)
@input = input
end
# TODO: Get previous type of the variable so that we save the correct type
def eval(scope)
@input.each do |stmt|
old_val = scope.get_var(stmt)
puts "-----INPUT-----" if $debug
invalid = 1
while invalid do
begin
user_input = gets
if old_val.is_a? IntegerNode
new_node = IntegerNode.new(Integer(user_input))
elsif old_val.is_a? FloatNode
new_node = FloatNode.new(Float(user_input))
elsif old_val.is_a? StringNode
new_node = StringNode.new(String(user_input))
end
invalid = nil
rescue ArgumentError => detail
puts detail.message if $debug
puts detail.backtrace if $debug
end
end
scope.update_var(stmt, new_node)
end
end
end
class InsertNode
def initialize(id, expr, index = nil)
@id, @expr, @index = id, expr, index
end
def eval(scope)
puts "-----INSERTNODE EVAL-----" if $debug
new_list = get_var(scope, @id)
# new_list might be nil
# new_list.size could be the new last index, so (size + 1) would be too much
if (not new_list.nil?) and (not @index.nil?) and
(@index.abs > (new_list.size + 1)) then
raise(IndexError, "Index out of bounds")
end
puts "\t#{new_list.class} #{new_list.inspect}" if $debug
if new_list.nil? then
new_list = [@expr.eval(scope)]
elsif @index then
new_list.insert(@index, get_var(scope, @expr).eval(scope))
else
new_list.insert(new_list.size, get_var(scope, @expr).eval(scope))
end
scope.update_var(@id, ListNode.new(new_list))
end
end
# A node handling removal of items from the built-in list
# A index of -1 will remove the last item
class RemoveNode
def initialize(id, index = nil)
@id, @index = id, index
end
def eval(scope)
puts "-----REMOVENODE EVAL-----" if $debug
new_list = get_var(scope, @id)
if @index.nil? then
new_list.delete_at new_list.size - 1
else
temp = get_var(scope, @index)
raise(IndexError, "Out of bounds") if temp.abs > (new_list.size)
new_list.delete_at temp
end
scope.update_var(@id, new_list)
end
end
class AtNode
def initialize(id, index = nil)
@id, @index = id, index
end
def eval(scope)
new_list = get_var(scope, @id)
num_index = if @index.nil?then new_list.size else get_var(scope, @index) end
puts "index: #{@index.inspect}, num_index: #{num_index.inspect}" if $debug
raise IndexError, "Index out of bounds" if num_index.abs > new_list.size - 1
return new_list[num_index]
end
end
class LengthNode
def initialize(id)
@id = id
end
def eval(scope)
IntegerNode.new(get_var(scope, @id).size)
end
end
class IfElseifElseNode
def initialize(parts)
@parts = parts
end
def eval(scope)
@parts.each { |stmt|
ret = stmt.eval(scope) if stmt
if not (ret.is_a? TrueClass or ret.is_a? FalseClass) then
puts "return from ifelseifelsenode"
return ret
end
break if ret
}
end
end
class IfStmtNode
def initialize(cond = nil, stmts)
@cond, @stmts = cond, stmts
end
def eval(scope)
child_scope = Scope.new(scope)
# if the IfNode has a condition. else-branch will have a empty condition
# and is always last in the code.
if @cond then
# If the condition is evaluated to true
if @cond.eval(scope) then
@stmts.each do |stmt|
stmt.eval(child_scope)
end
# Will break the chain of if-elseif-...-elseif-else
return true
else
# Continue with next elseif/else
return false
end
else
# We've reached the else-branch
@stmts.each do |stmt|
stmt.eval(child_scope)
end
end
end
end
class ForStmtNode
def initialize(assign_stmt, test_stmt, incr_expr, stmts)
@assign_stmt, @test_stmt = assign_stmt, test_stmt
@incr_expr, @stmts = incr_expr, stmts
end
def eval(scope)
# We want the execution to take place in its own scope
new_scope = Scope.new(scope)
@assign_stmt.eval(new_scope)
while @test_stmt.eval(new_scope) do
@stmts.each do |stmt|
stmt.eval(new_scope)
end
# eval @incr_expr after each loop as to (hopefully) avoid an infinite loop
@incr_expr.eval(new_scope)
end
end
end
class WhileStmtNode
def initialize(expr, stmts)
@expr, @stmts = expr, stmts
end
def eval(scope)
@new_scope = Scope.new(scope)
while @expr.eval(@new_scope) do
#puts "-----IN WHILESTMTNODE EVAL-----"
#puts "expr eval: #{@expr.eval(@new_scope)}"
#sleep(5)
@stmts.each do |stmt|
stmt.eval(@new_scope)
end
end
end
end
# TODO: Create this function.
# Maybe it can be empty, and we instead check if we find a ReturnNode
# where appropriate(in WhileStmtNode etc.)
class ReturnNode
def initialize(expr)
@expr = expr
end
def eval(scope)
return get_var(scope, @expr)
end
end
class IncrementNode
def initialize(id, incr_decr, expr = nil)
@id, @incr_decr, @expr = id, incr_decr, expr
end
def eval(scope)
puts "-----INCREMENTNODE EVAL-----" if $debug
old_val = scope.get_var(@id)
new_val = 0
case @incr_decr
when :pleq # plus equals(+=)
new_val = old_val.eval(scope) + @expr.eval(scope)
when :mieq # minus equals(-=)
new_val = old_val.eval(scope) - @expr.eval(scope)
when :mueq
new_val = old_val.eval(scope) * @expr.eval(scope)
when :dieq
new_val = old_val.eval(scope) / @expr.eval(scope)
end
new_val = old_val.class.new(new_val)
scope.update_var(@id, new_val)
end
end
class AssignmentNode
def initialize(name, val)
@name, @val = name, val
end
def eval(scope)
puts "-----ASSIGNMENT EVAL-----" if $debug
new_val = get_var(scope, @val).eval(scope)
puts "new_val: #{new_val.inspect}" if $debug
scope.update_var(@name, new_val)
end
end
# Data types
# A simple, constant node
class ValueNode
attr_reader :val
def initialize(val = nil)
@val = val
end
def to_s
"#{@val}"
end
def eval(scope)
puts "in valuenode eval()" if $debug
puts "val: #{@val}" if $debug
raise NoValueError, "Attempted to use a variable without value" if @val.nil?
@val
end
end
class IntegerNode < ValueNode
end
class FloatNode < ValueNode
end
class StringNode < ValueNode
end
class BoolNode < ValueNode
end
class ListNode < ValueNode
end
class FunctionNode
attr_reader :id, :ret_type, :idlist, :block
def initialize(id, ret_type, idlist, block)
@id, @ret_type, @idlist, @block = id, ret_type, idlist, block
end
def eval(scope)
puts "-----FUNCTIONNODE EVAL-----" if $debug
scope.add_func(self)
end
end
class FuncCallNode
def initialize(id, args)
@id, @args = id, args
end
def eval(scope)
puts "-----FUNCCALLNDODE EVAL-----" if $debug
new_scope = Scope.new(scope)
func_obj = scope.get_func(@id)
raise(ArgumentError,
"Wrong number of arguments") if @args.size != func_obj.idlist.size
@args.zip(func_obj.idlist).each do |arg1, arg2|
puts "arg1: #{arg1.inspect}", "arg2: #{arg2.inspect}" if $debug
arg1_t = if arg1.is_a? NameNode then
arg1.get_type(scope)
else
arg1.class
end
arg2_t = arg2.value.class
puts "#{arg1_t} == #{arg2_t} ?" if $debug
if arg1_t != arg2_t then
raise(ArgumentError, "incompatible types #{arg1_t}, #{arg2_t}")
end
end
puts "INSTANTIATING EMPTY VARIABLES" if $debug
puts "AND SETTING VALUES" if $debug
@args.zip(func_obj.idlist).each do |arg1,arg2|
puts "adding variable #{arg2.inspect}" if $debug
arg2.eval(new_scope)
arg1_v = get_val(scope, arg1)
puts "#{arg2.inspect} updated with #{arg1_v.inspect}" if $debug
new_scope.update_var(arg2.name, arg1_v)
end
#puts "NEW_SCOPE" if $debug
#PP.pp new_scope if $debug
#puts "\n"*3 if $debug
puts "\n"*3 if $debug
puts "IN FUNCTION"
puts "\n"*3 if $debug
func_obj.block.each do |stmt|
if stmt.is_a? ReturnNode then
res = stmt.eval(new_scope)
puts "returning #{res}"
return res
else
stmt.eval(new_scope)
end
end
end
end
class NameNode
attr_reader :name
def initialize(name)
@name = name
end
def eql?(op2)
return @name == op2.name
end
def hash
return @name.hash
end
def get_type(scope)
return scope.get_var(self).class
end
def eval
@name
end
end
class IdentifierNode
attr_reader :name, :value
# TODO: Type safety
def initialize(name, type, value = nil)
# Encapsulates the value in the appropriate node
if value.nil? then
case type
when "int"
value = IntegerNode.new(value)
when "float"
value = FloatNode.new(value)
when "string"
value = StringNode.new(value)
when "bool"
value = BoolNode.new(value)
when "list"
value = ListNode.new([])
end
end
@name, @value = name, value
end
def ===(op2)
raise TypeError, "Incompatible types #{self}!=#{op2}" unless op2.is_a? self
@name === op2.name
end
def eval(scope)
puts "-----IDENTIFIERNODE EVAL-----" if $debug
puts "adding: #{self.inspect}" if $debug
scope.add_var(self)
end
def get_val(scope)
@value.eval(scope)
end
end
# Boolean statements and Numerical statements
# This function will, given a value, ``calculate'' whether it's true or false.
def val_to_bool(scope, value)
puts "-----VAL_TO_BOOL-----" if $debug
puts "value.class: #{value.class}" if $debug
res = nil
if value.is_a? NameNode then
# Next time value_to_boolean() evaluates it won't get a IdentifierNode
res = val_to_bool(scope.get_var(value), scope)
elsif value.is_a? IntegerNode then
res = value.eval(scope) > 0
elsif value.is_a? FloatNode then
# Doesn't make a lot of sense. Provided as a convenience.
res = value.eval(scope) > 0
elsif value.is_a? StringNode then
# Convenience.
res = value.eval(scope).size > 0
elsif value.is_a? BoolNode then
# SHOULD already be a boolean value
res = value.eval(scope)
elsif value.is_a? ListNode then
res = value.eval(scope).size > 0
else
raise ArgumentError, "Incompatible type #{value.class}"
end
puts "res: #{res.inspect}" if $debug
return res
end
class BinaryComparisonNode
def initialize(op1, oper, op2)
@op1, @oper, @op2 = op1, oper, op2
end
def eval(scope)
puts "-----BINARYCOMPARISON EVAL-----" if $debug
op1 = get_var(scope, @op1)
op2 = get_var(scope, @op2)
puts "ope1: #{op1.inspect}" if $debug
puts "oper: #{@oper.inspect}" if $debug
puts "ope2: #{op2.inspect}" if $debug
var1 = get_var(scope, @op1)
var2 = get_var(scope, @op2)
if var1.respond_to? :eval then
if var2.respond_to? :eval then # op1 and op2 has eval
return var1.eval(scope).send(@oper, var2.eval(scope))
else # op1 has eval but op2 does not
return var1.eval(scope).send(@oper, var2)
end
elsif var2.respond_to? :eval then # op1 does not have eval but op2 does
return var1.send(@oper, var2.eval(scope))
else # no operator has eval
return var1.send(@oper, var2)
end
end
end
class BooleanNode
def initialize(stmt)
@stmt = stmt
end
def eval(scope)
puts "-----BOOLEANNODE EVAL-----" if $debug
puts "@stmt: #{@stmt.class}" if $debug
if @stmt.is_a? BinaryComparisonNode then
return @stmt.eval(scope)
elsif @stmt.is_a? ValueNode then
return val_to_bool(scope, @stmt)
else
raise ArgumentError, "Invalid type: #{@stmt.class}"
end
end
end
class BinaryBooleanNode
def initialize(op1, oper, op2)
@op1, @oper, @op2 = op1, oper, op2
end
def eval(scope)
# Works like this:
# 1. get boolean value of @op1
# 2. We then use send to send the following parameters:
# The first is a lookup of what operator to use
# Then we get the boolean value and send this to the operator
# We are left with a boolean value which is returned
val_to_bool(scope, @op1).send(@oper, val_to_bool(scope, @op2))
end
end
class AndNode < BinaryBooleanNode
def initialize(op1, op2)
super(op1, :&, op2)
end
end
class OrNode < BinaryBooleanNode
def initialize(op1, op2)
super(op1, :|, op2)
end
end
class UnaryBooleanNode
def initialize(op1, oper, op2)
@op1, @oper = op1, oper
end
def eval(scope)
val_to_bool(scope, @op1).send(@oper)
end
end
class NotNode < UnaryBooleanNode
def initialize(op1)
super(op1, :!)
end
end
class BinaryOperatorNode
def initialize(op1, oper, op2)
@op1, @oper, @op2 = op1, oper, op2
end
def eval(scope)
puts "-----BINARYOPERATORNODE EVAL-----" if $debug
puts "OP1 #{@op1.inspect}" if $debug
puts "OPER #{@oper.inspect}" if $debug
puts "OP2 #{@op2.inspect}" if $debug
op1 = get_var(scope, @op1)
op2 = get_var(scope, @op2)
# if one of the numbers are float, then the result will be float
res = if op1.class == FloatNode or op2.class == FloatNode then
FloatNode
else
IntegerNode
end
res = res.new(get_val(scope, op1).send(@oper, get_val(scope, op2)))
puts "Returning res: #{res.inspect}" if $debug
return res
end
end
class AddNode < BinaryOperatorNode
def initialize(op1, op2)
super(op1, :+, op2)
end
end
class SubtractNode < BinaryOperatorNode
def initialize(op1, op2)
super(op1, :-, op2)
end
end
class MultiplyNode < BinaryOperatorNode
def initialize(op1, op2)
super(op1, :*, op2)
end
end
class DivisionNode < BinaryOperatorNode
def initialize(op1, op2)
super(op1, :/, op2)
end
end
class PowerNode < BinaryOperatorNode
def initialize(op1, op2)
super(op1, :**, op2)
end
end
class UnaryOperatorNode
def initialize(op1, oper)
@op1, @oper = op1, oper
end
def eval(scope)
@op1.send(@oper)
end
end
class UnaryPlusNode < UnaryOperatorNode
def initialize(op1)
super(op1, :+@)
end
end
class UnaryMinusNode < UnaryOperatorNode
def initialize(op1)
super(op1, :-@)
end
end