-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathInterpreter.lua
2718 lines (2516 loc) · 84.6 KB
/
Interpreter.lua
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
* Copyright 2020 Rochus Keller <mailto:me@rochus-keller.ch>
*
* This file is part of the Smalltalk parser/compiler library.
*
* The following is the license that applies to this copy of the
* library. For a license to use the library under conditions
* other than those described here, please email to me@rochus-keller.ch.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License (GPL) versions 2.0 or 3.0 as published by the Free Software
* Foundation and appearing in the file LICENSE.GPL included in
* the packaging of this file. Please review the following information
* to ensure GNU General Public Licensing requirements will be met:
* http://www.fsf.org/licensing/licenses/info/GPLv2.html and
* http://www.gnu.org/copyleft/gpl.html.
]]--
--[[
This is the code from StInterpreter.cpp migrated to Lua.
What I missed from Lua for this project:
- #ifdef to hide statements only used for debugging and to avoid wasting calculation time
- constants not requiring local slots or hashed element access
- explicit inline declaration, so I can better structure the code without additionl context
switch and slot consumption
- avoid implicit global declarations; each typo is only detected at runtime otherwise
- explicit global declarations
- compiler should complain about use of locals only declared later in the file
( - switch/case control statement to avoid writing the full relation all over again )
]]--
------------------ Imports ------------------------------------------
local ffi = require 'ffi'
local C = ffi.C
local memory = require 'ObjectMemory'
local bit = require("bit")
local module = {}
local string = require "string"
ffi.cdef[[
int St_DIV( int a, int b );
int St_MOD( int a, int b );
int St_isRunning();
void St_processEvents();
int St_extractBits(int from, int to, int word);
int St_isIntegerValue( double val );
int St_round( double val );
typedef struct{
int count;
uint8_t data[?];
} ByteArray;
typedef struct{
int count; // word count
uint16_t data[];
} WordArray;
uint32_t St_toUInt( ByteArray* ba );
void St_setCursorPos( int x, int y );
int St_nextEvent();
void St_stop();
void St_start();
void St_log( const char* msg );
const char* St_toString( ByteArray* ba );
int St_extractBitsSi(int from, int to, int word);
int St_pendingEvents();
void St_beDisplay( WordArray* wa, int width, int height );
void St_beCursor( WordArray* wa, int width, int height );
void St_bitBlt( WordArray* destBits, int destW, int destH,
WordArray* sourceBits, int srcW, int srcH,
WordArray* htBits, int htW, int htH,
int combinationRule,
int destX, int destY, int width, int height,
int sourceX, int sourceY,
int clipX, int clipY, int clipWidth, int clipHeight );
void St_timeWords( ByteArray* );
void St_tickWords( ByteArray* );
void St_wakeupOn( ByteArray* );
int St_itsTime();
void St_update( WordArray* destBits,
int destX, int destY, int width, int height,
int clipX, int clipY, int clipWidth, int clipHeight );
void St_copyToClipboard( ByteArray* );
int St_openFile( ByteArray* ba );
int St_closeFile( int fd );
int St_fileSize( int fd );
int St_seekFile( int fd, int pos );
int St_readFile( int fd, ByteArray* ba );
int St_writeFile( int fd, ByteArray* ba, int toWrite );
int St_truncateFile( int fd, int size );
int St_createFile( ByteArray* ba );
int St_deleteFile( ByteArray* ba );
int St_renameFile( ByteArray* from, ByteArray* to );
]]
------------------ Module Data ------------------------------------------
local currentBytecode = 0
local instructionPointer = 0
local stackPointer = 0
local argumentCount = 0
local primitiveIndex = 0
local method, methodBytecode
local activeContext
local homeContext
local receiver
local messageSelector
local newMethod
local newProcess
local inputSemaphore
local semaphoreList = {}
local semaphoreIndex = 0
local newProcessWaiting = false
local primitive = {}
local success = true
local cycleNr = 0
local toSignal
------------------ Cached Objects ------------------------------------------
local bitand
local classSmallInteger
local classLargePositiveInteger
local classFloat
local classCompiledMethod
local classCharacter
local mathfloor
local classTrue
local classFalse
-- NOTE: requires call to memory.loadImage first before (most) cache can be filled
------------------ Functions ------------------------------------------
local function fetchClassOf(objectPointer)
if objectPointer == true then
return classTrue
elseif objectPointer == false then
return classFalse
else
return getmetatable(objectPointer)
end
end
local function prettyValue( value )
if value == nil then
return "nil"
elseif value == true then
return "true"
elseif value == false then
return "false"
end
local cls = fetchClassOf(value)
local knowns = memory.knownObjects
if cls == classSmallInteger then
return tostring(mathfloor(value))
elseif cls == classLargePositiveInteger then
return tostring(C.St_toUInt(value.data)) .. "L"
elseif cls == classFloat then
return tostring(value[0]) .. "F"
elseif cls == classCharacter then
local ch = value[0]
if ch > 0x20 and ch < 0x7f then
return "'" .. string.char(ch) .. "'"
else
return "0x" .. string.format("%x",ch)
end
elseif cls == knowns[0x38] then -- Symbol
return "#" .. ffi.string(C.St_toString( value.data ))
elseif cls == knowns[0x1a] then -- Point
return prettyValue(value[0]) .. "@" .. prettyValue(value[1])
elseif cls == knowns[0x0e] then -- String
local str = ffi.string(C.St_toString( value.data ))
local len = string.len(str)
local suff = ""
if len > 32 then
suff = ".."
end
str = string.gsub(string.sub(str,1,32), "%s+", " ")
return "\"" .. str .. "\"" .. suff
elseif cls.oop == 0x84 then -- Association
return prettyValue(value[0]) .. " = " .. prettyValue(value[1])
else
local sym = cls[6]
if fetchClassOf(sym) ~= knowns[0x38] then
sym = sym[6]
end
assert( fetchClassOf(sym) == knowns[0x38] )
local str = "<a " .. ffi.string(C.St_toString( sym.data )) .. ">"
return str
end
end
local function ST_TRACE_BYTECODE(...)
-- TODO: comment out all TRACE calls when no longer needed!
--TRACE( string.format("Bytecode <%d>\t[%d]", currentBytecode, cycleNr ), ... )
end
local function ST_TRACE_METHOD_CALL(...)
-- TODO: comment out all TRACE calls when no longer needed!
-- TRACE( "Cycle", cycleNr, "Call", ... )
end
local function ST_TRACE_PRIMITIVE(...)
-- TODO: comment out all TRACE calls when no longer needed!
-- TRACE( "Primitive", primitiveIndex, ... )
end
local function fetchByte()
local offset = instructionPointer-(method.count+1)*2
local byteCode = methodBytecode.data[offset]
instructionPointer = instructionPointer + 1
return byteCode
end
local function push( value )
stackPointer = stackPointer + 1
activeContext[stackPointer] = value
end
local function temporary(offset) -- used twice
return homeContext[ offset + 6 ] -- TempFrameStart
end
local function literal(offset) -- used ten times
return method[offset]
end
local function popStack()
local stackTop = activeContext[stackPointer]
stackPointer = stackPointer - 1
return stackTop
end
local function stackTop() -- used ten times
return activeContext[stackPointer]
end
local function extendedStoreBytecode() -- used twice
local descriptor = fetchByte()
local variableType = C.St_extractBits( 8, 9, descriptor )
local variableIndex = C.St_extractBits( 10, 15, descriptor )
if variableType == 0 then
receiver[variableIndex] = stackTop()
elseif variableType == 1 then
homeContext[variableIndex+6] = stackTop() -- TempFrameStart
elseif variableType == 2 then
error( "ERROR: illegal store", cycleNr )
-- BB: self error:
elseif variableType == 3 then
literal(variableIndex)[1] = stackTop() -- ValueIndex
end
end
local function stackBytecode()
local b = currentBytecode
if b >= 0 and b <= 15 then
-- pushReceiverVariableBytecode()
-- ST_TRACE_BYTECODE("receiver:",prettyValue(receiver))
push( receiver[ C.St_extractBits( 12, 15, currentBytecode ) ] )
elseif b >= 16 and b <= 31 then
-- pushTemporaryVariableBytecode()
local var = C.St_extractBits( 12, 15, currentBytecode )
local val = temporary( var )
-- ST_TRACE_BYTECODE("variable:", var, "value:", prettyValue(val) )
push( val )
elseif b >= 32 and b <= 63 then
-- pushLiteralConstantBytecode()
local fieldIndex = C.St_extractBits( 11, 15, currentBytecode )
local literalConstant = literal( fieldIndex )
-- ST_TRACE_BYTECODE("literal:",fieldIndex,"value:",prettyValue(literalConstant),"of method:", method.oop )
push( literalConstant )
elseif b >= 64 and b <= 95 then
-- pushLiteralVariableBytecode()
local fieldIndex = C.St_extractBits( 11, 15, currentBytecode )
local association = literal( fieldIndex )
local value = association[1] -- ValueIndex
-- ST_TRACE_BYTECODE("literal:", fieldIndex, "value:", prettyValue(value), "of method:", method.oop )
push( value )
elseif b >= 96 and b <= 103 then
-- storeAndPopReceiverVariableBytecode()
local variableIndex = C.St_extractBits( 13, 15, currentBytecode )
local val = popStack()
-- ST_TRACE_BYTECODE("var:", variableIndex, "val:", prettyValue(val) )
receiver[variableIndex] = val
elseif b >= 104 and b <= 111 then
-- storeAndPopTemporaryVariableBytecode()
local variableIndex = C.St_extractBits( 13, 15, currentBytecode )
local val = popStack()
-- ST_TRACE_BYTECODE("var:", variableIndex, "val:", prettyValue(val) )
homeContext[variableIndex+6] = val -- +6 TempFrameStart
elseif b == 112 then
-- pushReceiverBytecode()
-- ST_TRACE_BYTECODE("receiver:", prettyValue(receiver))
push( receiver )
elseif b >= 113 and b <= 119 then
-- pushConstantBytecode()
local val
if currentBytecode == 113 then
val = true
elseif currentBytecode == 114 then
val = false
elseif currentBytecode == 115 then
val = nil
elseif currentBytecode == 116 then
val = -1
elseif currentBytecode == 117 then
val = 0
elseif currentBytecode == 118 then
val = 1
elseif currentBytecode == 119 then
val = 2
end
-- ST_TRACE_BYTECODE("val:", prettyValue(val) )
push(val)
elseif b == 128 then
-- extendedPushBytecode()
local descriptor = fetchByte()
local variableType = C.St_extractBits( 8, 9, descriptor )
local variableIndex = C.St_extractBits( 10, 15, descriptor )
local val
if variableType == 0 then
val = receiver[variableIndex]
elseif variableType == 1 then
val = temporary( variableIndex )
elseif variableType == 2 then
val = literal( variableIndex )
elseif variableType == 3 then
val = literal( variableIndex )[1] -- ValueIndex
end
-- ST_TRACE_BYTECODE("val:", prettyValue(val) )
push(val)
elseif b == 129 then
-- ST_TRACE_BYTECODE()
extendedStoreBytecode()
elseif b == 130 then
-- extendedStoreAndPopBytecode()
-- ST_TRACE_BYTECODE()
extendedStoreBytecode()
-- popStackBytecode()
popStack()
elseif b == 135 then
-- popStackBytecode()
-- ST_TRACE_BYTECODE()
popStack()
elseif b == 136 then
-- duplicateTopBytecode()
local val = stackTop()
-- ST_TRACE_BYTECODE("val:", prettyValue(val) )
push( val )
elseif b == 137 then
-- pushActiveContextBytecode()
-- ST_TRACE_BYTECODE()
push( activeContext )
end
end
local function sender()
return homeContext[0] -- SenderIndex
end
local function caller()
return activeContext[0] -- CallerIndex
end
local function stackValue(offset) -- called seven times
return activeContext[stackPointer - offset]
end
local function lookupMethodInDictionary(dictionary)
local SelectorStart = 2
local MethodArrayIndex = 1
local length = dictionary.count -- this is a pointers array
local mask = length - SelectorStart - 1;
local hash = messageSelector.oop
if not hash then
hash = toaddress(messageSelector)
else
hash = hash / 2
end
local index = bitand( mask, hash ) + SelectorStart
local wrapAround = false
while true do
local nextSelector = dictionary[index]
if nextSelector == nil then
return false
end
if nextSelector == messageSelector then
local methodArray = dictionary[MethodArrayIndex]
newMethod = methodArray[index - SelectorStart]
-- function primitiveIndexOf used once, inlined
local flagValue = C.St_extractBitsSi(0,2,newMethod.header) -- flagValueOf
primitiveIndex = 0
if flagValue == 7 then
primitiveIndex = C.St_extractBitsSi(7,14, newMethod[ newMethod.count - 2 ] )
end
return true
end
index = index + 1
if index == length then
if wrapAround then
return false
end
wrapAround = true
index = SelectorStart
end
end
end
local function transfer(count, firstFrom, fromOop, firstTo, toOop)
local fromIndex = firstFrom
local lastFrom = firstFrom + count
local toIndex = firstTo
while fromIndex < lastFrom do
local oop = fromOop[fromIndex]
toOop[toIndex] = oop
fromOop[fromIndex] = nil
fromIndex = fromIndex + 1
toIndex = toIndex + 1
end
end
local function pop(number)
stackPointer = stackPointer - number
end
local function createActualMessage()
local argumentArray = { count = argumentCount }
setmetatable( argumentArray, memory.knownObjects[0x10] ) -- classArray
local message = { count = 2 } -- MessageSize
setmetatable( message, memory.knownObjects[0x20] ) -- classMessage
message[0] = messageSelector -- MessageSelectorIndex
message[1] = argumentArray -- MessageArgumentsIndex
transfer( argumentCount, stackPointer - (argumentCount - 1 ), activeContext, 0, argumentArray )
pop( argumentCount )
push( message )
argumentCount = 1
end
local function superclassOf(cls) -- three instances
return cls[0] -- SuperClassIndex
end
local function lookupMethodInClass(cls) -- called four times
local currentClass = cls
while currentClass ~= nil do
local dictionary = currentClass[1] -- MessageDictionaryIndex
if lookupMethodInDictionary( dictionary ) then
return true
end
currentClass = superclassOf(currentClass)
end
if messageSelector == memory.knownObjects[0x2a] then -- symbolDoesNotUnderstand
print( "ERROR: Recursive not understood error encountered", cycleNr )
-- BB self error:
return false
end
createActualMessage()
messageSelector = memory.knownObjects[0x2a] -- symbolDoesNotUnderstand
return lookupMethodInClass(cls)
end
local function primitiveResponse()
if primitiveIndex == 0 then
local flagValue = C.St_extractBitsSi(0,2,newMethod.header) -- flagValueOf
if flagValue == 5 then
-- NOP quickReturnSelf();
return true
elseif flagValue == 6 then
-- quickInstanceLoad() called once inlined
local thisReceiver = popStack()
local fieldIndex = C.St_extractBitsSi(3,7,newMethod.header) -- fieldIndexOf
local val = thisReceiver[fieldIndex]
push( val )
return true
end
else
success = true -- initPrimitive()
local currentPrimitive = primitive[primitiveIndex] -- dispatchPrimitives()
-- ST_TRACE_PRIMITIVE()
if currentPrimitive then
currentPrimitive()
else
success = false -- primitiveFail()
end
return success
end
return false
end
local function storeInstructionPointerValueInContext(value,contextPointer) -- called twice
contextPointer[1] = value -- InstructionPointerIndex
end
local function storeStackPointerValueInContext(value,contextPointer) -- called five times
contextPointer[2] = value -- StackPointerIndex
end
local function storeContextRegisters()
if activeContext then -- deviation from BB since activeContext is null on first call
storeInstructionPointerValueInContext( instructionPointer + 1, activeContext )
storeStackPointerValueInContext( stackPointer - 6 + 1, activeContext ) -- TempFrameStart
end
end
local function isBlockContext(contextPointer) -- called twice
local methodOrArguments = contextPointer[3] -- MethodIndex
return fetchClassOf(methodOrArguments) == classSmallInteger
end
local function fetchContextRegisters()
if isBlockContext(activeContext) then
homeContext = activeContext[5] -- HomeIndex
else
homeContext = activeContext
end
receiver = homeContext[5] -- ReceiverIndex
method = homeContext[3] -- MethodIndex
methodBytecode = method.bytecode
assert(methodBytecode)
instructionPointer = activeContext[1] - 1 -- InstructionPointerIndex instructionPointerOfContext(activeContext)
stackPointer = activeContext[2] + 6 - 1 -- StackPointerIndex stackPointerOfContext(activeContext) TempFrameStart
end
local function newActiveContext(aContext)
storeContextRegisters()
activeContext = aContext
fetchContextRegisters()
end
local function executeNewMethod()
-- ST_TRACE_METHOD_CALL()
if not primitiveResponse() then
-- function activateNewMethod() -- used once inlined
local contextSize = 6 -- TempFrameStart;
if C.St_extractBitsSi(8,8, newMethod.header ) == 1 then -- largeContextFlagOf( newMethod )
contextSize = contextSize + 32
else
contextSize = contextSize + 12;
end
local newContext = { count = contextSize }
setmetatable( newContext, memory.knownObjects[0x16] ) -- classMethodContext
newContext[0] = activeContext -- SenderIndex
-- initialInstructionPointerOfMethod( newMethod ) inlined
local iip = ( newMethod.count + 1 ) * 2 + 1
storeInstructionPointerValueInContext( iip, newContext )
local temporaryCount = C.St_extractBitsSi(3,7,newMethod.header) -- temporaryCountOf( newMethod )
storeStackPointerValueInContext( temporaryCount, newContext )
newContext[3] = newMethod -- MethodIndex
transfer( argumentCount + 1, stackPointer - argumentCount, activeContext, 5, newContext ) -- ReceiverIndex
pop( argumentCount + 1 )
newActiveContext(newContext)
--end
end
end
local function sendSelectorToClass(classPointer) -- called three times
-- deviation from BB, we currently don't have a methodCache, original: findNewMethodInClass
lookupMethodInClass(classPointer)
executeNewMethod()
end
local function sendSelector(selector,count) -- called seven times
messageSelector = selector
argumentCount = count
local newReceiver = stackValue(argumentCount) -- newReceiver might legally be nil!
sendSelectorToClass( fetchClassOf(newReceiver) ) -- fetchClassOf
end
local function returnValue(resultPointer, contextPointer)
-- ST_TRACE_BYTECODE("result:", prettyValue(resultPointer), "context:", prettyValue(contextPointer))
if contextPointer == nil then
push( activeContext )
push( resultPointer )
sendSelector( memory.knownObjects[0x2c], 1 ) -- symbolCannotReturn
end
local sendersIP = contextPointer[1] -- InstructionPointerIndex
if sendersIP == nil then
push( activeContext )
push( resultPointer )
sendSelector( memory.knownObjects[0x2c], 1 ) -- symbolCannotReturn
end
-- returnToActiveContext(contextPointer)
local aContext = contextPointer
-- function returnToActiveContext(aContext) -- called once, inlined
local tmp = aContext -- increaseReferencesTo: aContext
-- nilContextFields() -- called once inlined
activeContext[0] = nil -- SenderIndex
activeContext[1] = nil -- InstructionPointerIndex
activeContext = aContext
fetchContextRegisters()
-- end function
push( resultPointer )
end
local function returnBytecode()
if currentBytecode == 120 then
returnValue( receiver, sender() )
elseif currentBytecode == 121 then
returnValue( true, sender() )
elseif currentBytecode == 122 then
returnValue( false, sender() )
elseif currentBytecode == 123 then
returnValue( nil, sender() )
elseif currentBytecode == 124 then
returnValue( popStack(), sender() )
elseif currentBytecode == 125 then
returnValue( popStack(), caller() )
else
print( "WARNING: executing unused bytecode", currentBytecode )
end
end
local function methodClassOf(methodPointer)
local literalCount = methodPointer.count -- literalCountOf(methodPointer);
local association = methodPointer[literalCount-1]
return association[1] -- ValueIndex
end
local function fetchIntegerOfObject(fieldIndex, objectPointer)
local integerPointer = objectPointer[fieldIndex]
if fetchClassOf(integerPointer) == classSmallInteger then
return integerPointer
end
success = false -- primitiveFail
return 0
end
local function specialSelectorPrimitiveResponse()
success = true -- initPrimitive()
if currentBytecode >= 176 and currentBytecode <= 191 then
-- arithmeticSelectorPrimitive() called once, inlined
success = success and fetchClassOf( stackValue(1) ) == classSmallInteger
if not success then
return false
end
if currentBytecode == 176 then
primitive[1]() -- primitiveAdd()
elseif currentBytecode == 177 then
primitive[2]() -- primitiveSubtract()
elseif currentBytecode == 178 then
primitive[3]() -- primitiveLessThan();
elseif currentBytecode == 179 then
primitive[4]() -- primitiveGreaterThan();
elseif currentBytecode == 180 then
primitive[5]() -- primitiveLessOrEqual();
elseif currentBytecode == 181 then
primitive[6]() -- primitiveGreaterOrEqual();
elseif currentBytecode == 182 then
primitive[7]() -- primitiveEqual();
elseif currentBytecode == 183 then
primitive[8]() -- primitiveNotEqual();
elseif currentBytecode == 184 then
primitive[9]() -- primitiveMultiply();
elseif currentBytecode == 185 then
primitive[10]() -- primitiveDivide();
elseif currentBytecode == 186 then
primitive[11]() -- primitiveMod();
elseif currentBytecode == 187 then
primitive[18]() -- primitiveMakePoint();
elseif currentBytecode == 188 then
primitive[17]() -- primitiveBitShift();
elseif currentBytecode == 189 then
primitive[12]() -- primitiveDiv();
elseif currentBytecode == 190 then
primitive[14]() -- primitiveBitAnd();
elseif currentBytecode == 191 then
primitive[15]() -- primitiveBitOr();
end
elseif currentBytecode >= 192 and currentBytecode <= 207 then
-- commonSelectorPrimitive() called once, inlined
local specialSelectors = memory.knownObjects[0x30]
argumentCount = fetchIntegerOfObject( (currentBytecode - 176) * 2 + 1, specialSelectors )
local receiverClass = fetchClassOf( stackValue( argumentCount ) ) -- fetchClassOf
if currentBytecode == 198 then
primitive[110]() -- primitiveEquivalent();
elseif currentBytecode == 199 then
primitive[111]() -- primitiveClass();
elseif currentBytecode == 200 then
success = success and ( receiverClass == memory.knownObjects[0x16] or -- classMethodContext
receiverClass == memory.knownObjects[0x18] ) -- classBlockContext
if success then
primitive[80]() -- primitiveBlockCopy();
end
elseif currentBytecode == 201 or currentBytecode == 202 then
success = success and receiverClass == memory.knownObjects[0x18] -- classBlockContext
if success then
primitive[81]() -- primitiveValue();
end
else
success = false
end
end
return success
end
local function sendBytecode()
if currentBytecode == 131 then
-- singleExtendedSendBytecode()
local descriptor = fetchByte()
local selectorIndex = C.St_extractBits( 11, 15, descriptor )
local _argumentCount = C.St_extractBits( 8, 10, descriptor )
local selector = literal(selectorIndex)
-- ST_TRACE_BYTECODE("selector:", prettyValue(selector), "count:", _argumentCount )
sendSelector( selector, _argumentCount )
elseif currentBytecode == 132 then
-- doubleExtendedSendBytecode()
local count = fetchByte()
local selector = literal( fetchByte() )
-- ST_TRACE_BYTECODE("selector:", prettyValue(selector), "count:", count )
sendSelector( selector, count )
elseif currentBytecode == 133 then
-- singleExtendedSuperBytecode()
local descriptor = fetchByte()
argumentCount = C.St_extractBits( 8, 10, descriptor )
local selectorIndex = C.St_extractBits( 11, 15, descriptor )
messageSelector = literal( selectorIndex )
local methodClass = methodClassOf( method )
local super = superclassOf(methodClass)
-- ST_TRACE_BYTECODE("selector:", prettyValue(messageSelector), "super:", prettyValue(super) )
sendSelectorToClass( super )
elseif currentBytecode == 134 then
-- doubleExtendedSuperBytecode()
argumentCount = fetchByte()
messageSelector = literal( fetchByte() )
local methodClass = methodClassOf( method )
local super = superclassOf(methodClass)
-- ST_TRACE_BYTECODE("selector:", prettyValue(messageSelector), "super:", prettyValue(super) )
sendSelectorToClass( super )
elseif currentBytecode >= 176 and currentBytecode <= 207 then
-- sendSpecialSelectorBytecode()
if not specialSelectorPrimitiveResponse() then
local selectorIndex = ( currentBytecode - 176 ) * 2
local specialSelectors = memory.knownObjects[0x30]
local selector = specialSelectors[selectorIndex] -- specialSelectors
local count = fetchIntegerOfObject(selectorIndex + 1, specialSelectors )
-- ST_TRACE_BYTECODE("selector:", prettyValue(selector), "count:", count )
sendSelector( selector, count )
else
-- ST_TRACE_BYTECODE("primitive")
end
elseif currentBytecode >= 208 and currentBytecode <= 255 then
-- sendLiteralSelectorBytecode()
local litNr = C.St_extractBits( 12, 15, currentBytecode )
local selector = literal( litNr )
local argumentCount = C.St_extractBits( 10, 11, currentBytecode ) - 1
-- ST_TRACE_BYTECODE("selector:", prettyValue(selector), "count:", argumentCount )
sendSelector( selector, argumentCount )
end
end
local function jump(offset)
instructionPointer = instructionPointer + offset
end
local function unPop(number)
stackPointer = stackPointer + number
end
local function sendMustBeBoolean()
sendSelector( memory.knownObjects[0x34], 0 ) -- symbolMustBeBoolean
end
local function jumpif(condition, offset)
local boolean = popStack()
if boolean == condition then
jump(offset)
elseif not ( boolean == true or boolean == false ) then
unPop(1)
sendMustBeBoolean()
end
end
local function jumpBytecode()
local b = currentBytecode
if b >= 144 and b <= 151 then
-- shortUnconditionalJump()
local offset = C.St_extractBits( 13, 15, currentBytecode )
-- ST_TRACE_BYTECODE("offset:", offset + 1 )
jump( offset + 1 )
elseif b >= 152 and b <= 159 then
-- shortContidionalJump()
local offset = C.St_extractBits( 13, 15, currentBytecode )
-- ST_TRACE_BYTECODE("offset:", offset + 1 )
jumpif( false, offset + 1 )
elseif b >= 160 and b <= 167 then
-- longUnconditionalJump()
local offset = C.St_extractBits( 13, 15, currentBytecode )
offset = ( offset - 4 ) * 256 + fetchByte()
-- ST_TRACE_BYTECODE("offset:", offset )
jump( offset )
elseif b >= 168 and b <= 175 then
-- longConditionalJump()
local offset = C.St_extractBits( 14, 15, currentBytecode )
offset = offset * 256 + fetchByte()
-- ST_TRACE_BYTECODE("offset:", offset )
if currentBytecode >= 168 and currentBytecode <= 171 then
jumpif( true, offset )
elseif currentBytecode >= 172 and currentBytecode <= 175 then
jumpif( false, offset )
end
end
end
local function dispatchOnThisBytecode()
local b = currentBytecode
if ( b >= 0 and b <= 119 ) or ( b >= 128 and b <= 130 ) or ( b >= 135 and b <= 137 ) then
stackBytecode()
elseif b >= 120 and b <= 127 then
returnBytecode()
elseif ( b >= 131 and b <= 134 ) or ( b >= 176 and b <= 255 ) then
sendBytecode()
elseif b >= 144 and b <= 175 then
jumpBytecode()
elseif b >= 138 and b <= 143 then
print( "WARNING: running unused bytecode", b )
end
end
local function isEmptyList(aLinkedList) -- called three times
if aLinkedList == nil then
return true
end
return aLinkedList[0] == nil -- FirstLinkIndex
end
local function removeFirstLinkOfList(aLinkedList) -- called twice
local firstLink = aLinkedList[0] -- FirstLinkIndex
local lastLink = aLinkedList[1] -- LastLinkIndex
if firstLink == lastLink then
aLinkedList[0] = nil -- FirstLinkIndex
aLinkedList[1] = nil -- LastLinkIndex
else
local nextLink = firstLink[0] -- NextLinkIndex
aLinkedList[0] = nextLink -- FirstLinkIndex
end
firstLink[0] = nil -- NextLinkIndex
return firstLink
end
local function addLastLinkToList(aLink, aLinkedList) -- called twice
if isEmptyList( aLinkedList ) then
aLinkedList[0] = aLink -- FirstLinkIndex
else
local lastLink = aLinkedList[1] -- LastLinkIndex
lastLink[0] = aLink -- NextLinkIndex
end
aLinkedList[1] = aLink -- LastLinkIndex
aLink[3] = aLinkedList -- MyListIndex
end
local function schedulerPointer()
return memory.knownObjects[0x08][1] -- ObjectMemory2::processor, ValueIndex
end
local function sleep(aProcess) -- called twice
local priority = aProcess[2] -- PriorityIndex
local processLists = schedulerPointer()[0] -- ProcessListIndex
local processList = processLists[priority - 1]
addLastLinkToList( aProcess, processList )
end
local function transferTo(aProcess) -- called twice
newProcessWaiting = true
newProcess = aProcess
end
local function activeProcess()
if newProcessWaiting then
return newProcess
else
return schedulerPointer()[1] -- ActiveProcessIndex
end
end
local function resume(aProcess) -- called twice
local activeProcess_ = activeProcess()
local activePriority = activeProcess_[2] -- PriorityIndex
local newPriority = aProcess[2] -- PriorityIndex
if newPriority > activePriority then
sleep( activeProcess_ )
transferTo( aProcess )
else
sleep( aProcess )
end
end
local function synchronousSignal(aSemaphore) -- called twice
if isEmptyList(aSemaphore) then
local excessSignals = aSemaphore[2] -- ExcessSignalIndex
aSemaphore[2] = excessSignals + 1 -- ExcessSignalIndex
else
resume( removeFirstLinkOfList(aSemaphore) )
end
end
local function checkProcessSwitch()
while semaphoreIndex > 0 do
synchronousSignal( semaphoreList[semaphoreIndex] )
semaphoreIndex = semaphoreIndex - 1
end
if newProcessWaiting then
newProcessWaiting = false
local activeProcess_ = activeProcess()
if activeProcess_ then
activeProcess_[1] = activeContext -- SuspendedContextIndex
end
local scheduler = schedulerPointer()
scheduler[1] = newProcess -- ActiveProcessIndex
newActiveContext( newProcess[1] ) -- SuspendedContextIndex
newProcess = nil
end
end
local function cycle()
local pending = C.St_pendingEvents()
if pending > 0 then
for i=1,pending do
-- asynchronousSignal(inputSemaphore) inlined
if inputSemaphore then
semaphoreIndex = semaphoreIndex + 1
semaphoreList[semaphoreIndex] = inputSemaphore
end
end
elseif pending == -1 then
-- asynchronousSignal(toSignal) inlined
semaphoreIndex = semaphoreIndex + 1
semaphoreList[semaphoreIndex] = toSignal
elseif pending == -2 then
local str = memory.knownObjects.CurrentSelection[1][0]
C.St_copyToClipboard(str.data)
end
checkProcessSwitch()
currentBytecode = fetchByte()
cycleNr = cycleNr + 1
dispatchOnThisBytecode()
end
function module.interpret()
C.St_start()
cycleNr = 0
newProcessWaiting = false;
local firstContext = activeProcess()[1] -- SuspendedContextIndex
newActiveContext( firstContext )
print "start main loop"
while C.St_isRunning() ~= 0 do -- and cycleNr < 121000 do
cycle()
C.St_processEvents()
end
C.St_stop()
print "quit main loop"
end
---------------------- Primitives implementation -----------------------------------
local function popInteger()
local integerPointer = popStack()
success = success and fetchClassOf(integerPointer) == classSmallInteger
return integerPointer
end
local function isIntegerValue(value)
local isInt = C.St_isIntegerValue(value) ~= 0
return isInt
end
function primitive.Add() -- primitiveAdd
-- ST_TRACE_PRIMITIVE("primitiveAdd")
local integerArgument = popInteger()
local integerReceiver = popInteger()
local integerResult
if success then
integerResult = integerReceiver + integerArgument
success = success and isIntegerValue(integerResult)
end
if success then
push( integerResult )
else
unPop(2)
end
end
primitive[1] = primitive.Add
function primitive.Subtract() -- primitiveSubtract
--ST_TRACE_PRIMITIVE("primitiveSubtract")
local integerArgument = popInteger()
local integerReceiver = popInteger()
local integerResult
if success then
integerResult = integerReceiver - integerArgument