forked from pharo-project/pharo
/
Context.class.st
2298 lines (1898 loc) · 74.2 KB
/
Context.class.st
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
"
Instance variables:
receiver: <Object> (self)
closureOrNil: <BlockClosure|nil>
nil if I'm a method context
the blockClosure being executed if I'm a block context
method <CompiledMethod>
method being executed if I'm a method context
method holding the block if I'm a block context
variable fields: <Object> temporary variables (including arguments)
My instances hold all the dynamic state associated with the execution of either a method activation resulting from a message send or a block activation resulting from a block evaluation.
MethodContexts, though normal in their variable size, are actually only used in two sizes, small and large, which are determined by the temporary space required by the method being executed.
MethodContexts must only be created using the method newForMethod:. Note that it is impossible to determine the real object size of a MethodContext except by asking for the frameSize of its method. Any fields above the stack pointer (stackp) are truly invisible -- even (and especially!) to the garbage collector. Any store into stackp other than by the primitive method stackp: is potentially fatal.
"
Class {
#name : #Context,
#superclass : #InstructionStream,
#type : #variable,
#instVars : [
'stackp',
'method',
'closureOrNil',
'receiver'
],
#classVars : [
'PrimitiveFailToken',
'SpecialPrimitiveSimulators',
'TryNamedPrimitiveTemplateMethod'
],
#category : #'Kernel-Methods'
}
{ #category : #enumerating }
Context class >> allInstances [
"Answer all instances of the receiver."
<primitive: 177>
"The primitive can fail because memory is low. If so, fall back on the old
enumeration code, which gives the system a chance to GC and/or grow.
Because aBlock might change the class of inst (for example, using become:),
it is essential to compute next before aBlock value: inst.
Only count until thisContext since this context has been created only to
compute the existing instances."
| inst insts next |
insts := WriteStream on: (Array new: 64).
inst := self someInstance.
[inst == thisContext or: [inst == nil]] whileFalse:
[next := inst nextInstance.
insts nextPut: inst.
inst := next].
^insts contents
]
{ #category : #hacks }
Context class >> allInstancesDo: aBlock [
"Evaluate aBlock with each of the current instances of the receiver."
| instances inst next |
instances := self allInstancesOrNil.
instances ifNotNil:
[instances do: aBlock.
^self].
"allInstancesOrNil can fail because memory is low. If so, fall back on the old
enumeration code. Because aBlock might change the class of inst (for example,
using become:), it is essential to compute next before aBlock value: inst.
Only count until thisContext since evaluation of aBlock will create new contexts."
inst := self someInstance.
[inst == thisContext or: [inst == nil]] whileFalse:
[next := inst nextInstance.
aBlock value: inst.
inst := next]
]
{ #category : #'instance creation' }
Context class >> basicNew: size [
self error: 'Contexts must only be created with newForMethod:'
]
{ #category : #private }
Context class >> carefullyPrint: anObject on: aStream [
aStream nextPutAll: ([anObject printString]
on: Error
do: ['unprintable ' , anObject class name])
]
{ #category : #'special context creation' }
Context class >> contextEnsure: block [
"Create an #ensure: context that is ready to return from executing its receiver"
| ctxt chain |
ctxt := thisContext.
[chain := thisContext sender cut: ctxt.
"As the jump will return to the current context inside the context ensure:
It is needed to emulate the return value of sending the message ensure:
If this is not done, the context will do an additional pop, affecting the temporary variables.
This is required because we are breaking a condition on Context >> jump.
The receiver of jump should be a Top context, in this case it is not. "
ctxt push: nil.
ctxt jump] ensure: block.
"jump above will resume here without unwinding chain"
^ chain
]
{ #category : #'special context creation' }
Context class >> contextOn: exceptionClass do: block [
"Create an #on:do: context that is ready to return from executing its receiver"
| ctxt chain |
ctxt := thisContext.
[chain := thisContext sender cut: ctxt.
"As the jump will return to the current context inside the context on:do:
It is needed to emulate the return value of sending the message on:do:
If this is not done, the context will do an additional pop, affecting the temporary variables.
This is required because we are breaking a condition on Context >> jump.
The receiver of jump should be a Top context, in this case it is not. "
ctxt push:nil.
ctxt jump] on: exceptionClass do: block.
"jump above will resume here without unwinding chain"
^ chain
]
{ #category : #simulation }
Context class >> initialize [
"A unique object to be returned when a primitive fails during simulation"
PrimitiveFailToken := Object new.
self initializeTryNamedPrimitiveTemplateMethod.
SpecialPrimitiveSimulators := nil
]
{ #category : #simulation }
Context class >> initializePrimitiveSimulators [
"extra primitive simulators can be registered by implementing
#registerPrimitiveSimulators method in class side of your class."
<ignoreUnimplementedCalls: #(#registerPrimitiveSimulators)>
SpecialPrimitiveSimulators := Dictionary new.
Class allSubclassesDo: [:metaclass |
(metaclass includesSelector: #registerPrimitiveSimulators) ifTrue: [
metaclass instanceSide registerPrimitiveSimulators.
]
].
]
{ #category : #simulation }
Context class >> initializeTryNamedPrimitiveTemplateMethod [
| source method |
source := 'tryNamedPrimitive
"This method is a template that the Smalltalk simulator uses to
execute primitives. See Object documentation whatIsAPrimitive."
<primitive:'' module:'' error: errorCode>
^ Context primitiveFailTokenFor: errorCode'.
method := Smalltalk compiler
class: UndefinedObject;
source: source;
compile.
TryNamedPrimitiveTemplateMethod := method copyWithSource: source.
]
{ #category : #testing }
Context class >> isContextClass [
^true
]
{ #category : #'instance creation' }
Context class >> new [
self error: 'Contexts must only be created with newForMethod:'
]
{ #category : #'instance creation' }
Context class >> new: size [
self error: 'Contexts must only be created with newForMethod:'
]
{ #category : #'instance creation' }
Context class >> newForMethod: aMethod [
"This is the only method for creating new contexts, other than primitive cloning.
Any other attempts, such as inherited methods like shallowCopy, should be
avoided or must at least be rewritten to determine the proper size from the
method being activated. This is because asking a context its size (even basicSize!)
will not return the real object size but only the number of fields currently
accessible, as determined by stackp."
^ super basicNew: aMethod frameSize
]
{ #category : #simulation }
Context class >> primitiveFailToken [
^ self primitiveFailTokenFor: nil
]
{ #category : #simulation }
Context class >> primitiveFailTokenFor: errorCode [
^ { PrimitiveFailToken. errorCode }
]
{ #category : #'instance creation' }
Context class >> sender: s receiver: r method: m arguments: args [
"Answer an instance of me with attributes set to the arguments."
^(self newForMethod: m) setSender: s receiver: r method: m arguments: args
]
{ #category : #accessing }
Context class >> specialPrimitiveSimulators [
SpecialPrimitiveSimulators ifNil: [ self initializePrimitiveSimulators ].
^ SpecialPrimitiveSimulators
]
{ #category : #'special context creation' }
Context class >> theReturnMethod [
| meth |
meth := self lookupSelector: #return:.
meth isPrimitive ifTrue: [^ self error: 'expected #return: to not be a primitive'].
^ meth
]
{ #category : #accessing }
Context class >> tryNamedPrimitiveTemplateMethod [
^ TryNamedPrimitiveTemplateMethod
]
{ #category : #private }
Context >> aboutToReturn: result through: firstUnwindContext [
"Called from VM when an unwindBlock is found between self and its home.
Return to home's sender, executing unwind blocks on the way."
self methodReturnContext return: result through: firstUnwindContext
]
{ #category : #controlling }
Context >> activateMethod: newMethod withArgs: args receiver: rcvr class: class [
"Answer a Context initialized with the arguments."
^Context
sender: self
receiver: rcvr
method: newMethod
arguments: args
]
{ #category : #private }
Context >> activateReturn: aContext value: value [
"Activate 'aContext return: value' in place of self, so execution will return to aContext's sender"
^ self
activateMethod: Context theReturnMethod
withArgs: {value}
receiver: aContext
class: aContext class
]
{ #category : #accessing }
Context >> activeHome [
"If executing closure, search senders for the activation of the original
(outermost) method that (indirectly) created my closure (the closureHome).
If the closureHome is not found on the sender chain answer nil."
| methodReturnContext |
self isBlockContext ifFalse: [^self].
self sender ifNil: [^nil].
methodReturnContext := self methodReturnContext.
^self sender findContextSuchThat: [:ctxt | ctxt = methodReturnContext]
]
{ #category : #accessing }
Context >> activeOuterContext [
"If executing closure, search senders for the activation in which the receiver's
closure was created (the receiver's outerContext). If the outerContext is not
found on the sender chain answer nil."
| outerContext |
self isBlockContext ifFalse: [^self].
self sender ifNil: [^nil].
outerContext := self outerContext.
^self sender findContextSuchThat: [:ctxt | ctxt = outerContext]
]
{ #category : #accessing }
Context >> arguments [
"returns the arguments of a message invocation"
| arguments numargs |
numargs := self compiledCode numArgs.
arguments := Array new: numargs.
1 to: numargs do: [ :i | arguments at: i put: (self tempAt: i) ].
^ arguments
]
{ #category : #'closure support' }
Context >> asContext [
^ self
]
{ #category : #accessing }
Context >> at: index [
"Primitive. Assumes receiver is indexable. Answer the value of an
indexable element in the receiver. Fail if the argument index is not an
Integer or is out of bounds. Essential. See Object documentation
whatIsAPrimitive. Override the default primitive to give latitude to
the VM in context management."
<primitive: 210>
index isInteger ifTrue:
[self errorSubscriptBounds: index].
index isNumber
ifTrue: [^self at: index asInteger]
ifFalse: [self errorNonIntegerIndex]
]
{ #category : #accessing }
Context >> at: index put: value [
"Primitive. Assumes receiver is indexable. Answer the value of an
indexable element in the receiver. Fail if the argument index is not
an Integer or is out of bounds. Essential. See Object documentation
whatIsAPrimitive. Override the default primitive to give latitude to
the VM in context management."
<primitive: 211>
index isInteger ifTrue:
[self errorSubscriptBounds: index].
index isNumber
ifTrue: [^self at: index asInteger put: value]
ifFalse: [self errorNonIntegerIndex]
]
{ #category : #accessing }
Context >> basicAt: index [
"Primitive. Assumes receiver is indexable. Answer the value of an
indexable element in the receiver. Fail if the argument index is not an
Integer or is out of bounds. Essential. See Object documentation
whatIsAPrimitive. Override the default primitive to give latitude to
the VM in context management."
<primitive: 210>
index isInteger ifTrue:
[self errorSubscriptBounds: index].
self errorNonIntegerIndex
]
{ #category : #accessing }
Context >> basicAt: index put: value [
"Primitive. Assumes receiver is indexable. Answer the value of an
indexable element in the receiver. Fail if the argument index is not
an Integer or is out of bounds. Essential. See Object documentation
whatIsAPrimitive. Override the default primitive to give latitude to
the VM in context management."
<primitive: 211>
index isInteger ifTrue:
[self errorSubscriptBounds: index].
self errorNonIntegerIndex
]
{ #category : #accessing }
Context >> basicSize [
"Primitive. Answer the number of indexable variables in the receiver.
This value is the same as the largest legal subscript. Essential. Do not
override in any subclass. See Object documentation whatIsAPrimitive. Override the default primitive to give latitude to
the VM in context management."
<primitive: 212>
"The number of indexable fields of fixed-length objects is 0"
^self primitiveFail
]
{ #category : #'instruction decoding' }
Context >> blockReturnConstant: value [
"Simulate the interpreter's action when a ReturnConstantToCaller
bytecode is
encountered in the receiver. This should only happen in a closure
activation. "
self assert: closureOrNil isClosure.
^ self return: value from: self
]
{ #category : #'instruction decoding' }
Context >> blockReturnTop [
"Simulate the interpreter's action when a ReturnTopOfStackToCaller bytecode is
encountered in the receiver. This should only happen in a closure activation."
[closureOrNil isClosure] assert.
^self return: self pop from: self
]
{ #category : #query }
Context >> bottomContext [
"Return the last context (the first context invoked) in my sender chain"
^ self findContextSuchThat: [ :context | context sender isNil]
]
{ #category : #'private-exceptions' }
Context >> canHandleSignal: exception [
"Sent to handler (on:do:) contexts only. If my exception class (first arg) handles exception then return true, otherwise forward this message to the next handler context. If none left, return false (see nil>>canHandleSignal:)"
^ (self exceptionClass handles: exception)
or: [ self nextHandlerContext canHandleSignal: exception ].
]
{ #category : #'private-exceptions' }
Context >> cannotReturn: result [
closureOrNil ifNotNil: [
^ BlockCannotReturn result: result from: self home ].
UIManager default
requestDebuggerOpeningNamed: 'computation has been terminated'
inContext: thisContext
]
{ #category : #private }
Context >> cannotReturn: result to: aContext [
"The receiver tried to return result to homeContext that no longer exists."
^ ContextCannotReturn result: result to: aContext
]
{ #category : #accessing }
Context >> client [
"Answer the client, that is, the object that sent the message that created this context."
^sender receiver
]
{ #category : #accessing }
Context >> closure [
^closureOrNil
]
{ #category : #controlling }
Context >> closureCopy: numArgs copiedValues: anArray [
"Distinguish a block of code from its enclosing method by
creating a BlockClosure for that block. The compiler inserts into all
methods that contain blocks the bytecodes to send the message
closureCopy:copiedValues:. Do not use closureCopy:copiedValues: in code that you write! Only the
compiler can decide to send the message closureCopy:copiedValues:. Fail if numArgs is
not a SmallInteger. Optional. No Lookup. See Object documentation
whatIsAPrimitive."
<primitive: 200>
^BlockClosure
outerContext: self
startpc: pc + 2
numArgs: numArgs
copiedValues: anArray
]
{ #category : #accessing }
Context >> compiledCode [
^method
]
{ #category : #accessing }
Context >> contextClass [
"The context class of a message send should be the one of the method to be evaluated, because if that method has some super sends, the method lookup won't work as expected'"
^self compiledCode methodClass
]
{ #category : #'debugger access' }
Context >> contextStack [
"Answer an Array of the contexts on the receiver's sender chain."
^self stackOfSize: 100000
]
{ #category : #'closure support' }
Context >> contextTag [
"Context tags may be used for referring to contexts instead of contexts themselves as they can be copied and will continue to work in other processes (continuations). By default, we use the context itself to as its tag."
^self
]
{ #category : #query }
Context >> copyStack [
^ self copyTo: nil
]
{ #category : #query }
Context >> copyTo: aContext [
"Copy self and my sender chain down to, but not including, aContext. End of copied chain will have nil sender."
| copy |
self == aContext ifTrue: [^ nil].
self pc. "this is a workaround, see https://github.com/pharo-project/pharo/issues/2949"
copy := self copy.
self sender ifNotNil: [
copy privSender: (self sender copyTo: aContext)].
^ copy
]
{ #category : #private }
Context >> cut: aContext [
"Cut aContext and its senders from my sender chain"
| context callee |
context := self.
[ context == aContext ] whileFalse: [
callee := context.
context := context sender.
context ifNil: [
aContext ifNotNil: [
self error: 'aContext not a sender' ]]].
callee privSender: nil.
]
{ #category : #printing }
Context >> debugStack: stackSize on: aStream [
"print a condensed version of the stack up to stackSize on aStream"
(self stackOfSize: stackSize)
do: [ :item |
item printDebugOn: aStream.
aStream cr ]
]
{ #category : #printing }
Context >> debugStackOn: aStream [
"print the top ten contexts on my sender chain."
^ self debugStack: 100 on: aStream
]
{ #category : #'debugger access' }
Context >> depthBelow: aContext [
"Answer how many calls there are between this and aContext."
| context depth |
context := self.
depth := 0.
[ context == aContext or: [ context == nil ]]
whileFalse: [
context := context sender.
depth := depth + 1 ].
^ depth
]
{ #category : #'instruction decoding' }
Context >> directedSuperSend: selector numArgs: numArgs [
| lookupClass arguments currentReceiver |
lookupClass := self pop superclass.
arguments := Array new: numArgs.
numArgs to: 1 by: -1 do: [ :i |
arguments at: i put: self pop ].
currentReceiver := self pop.
^ self send: selector to: currentReceiver with: arguments lookupIn: lookupClass
]
{ #category : #'instruction decoding' }
Context >> doDup [
"Simulate the action of a 'duplicate top of stack' bytecode."
self push: self top
]
{ #category : #'instruction decoding' }
Context >> doNop [
"do nothing"
]
{ #category : #'instruction decoding' }
Context >> doPop [
"Simulate the action of a 'remove top of stack' bytecode."
self pop
]
{ #category : #private }
Context >> doPrimitive: primitiveIndex method: meth receiver: aReceiver args: arguments [
"Simulate a primitive method whose index is primitiveIndex. The simulated receiver and
arguments are given as arguments to this message. If successful, push result and return
resuming context, else ^ {errCode, PrimitiveFailToken}. Any primitive which provokes
execution needs to be intercepted and simulated to avoid execution running away."
| value |
"Judicious use of primitive 19 (a null primitive that doesn't do anything) prevents
the debugger from entering various run-away activities such as spawning a new
process, etc. Injudicious use results in the debugger not being able to debug
interesting code, such as the debugger itself. hence use primitive 19 with care :-)"
"SystemNavigation new browseAllSelect: [:m| m primitive = 19]"
"primitiveIndex = 19 ifTrue: [ | debugSession |
debugSession := Processor activeProcess newDebugSessionNamed: 'Code simulation error' startedAt: self.
Smalltalk tools debugger openOn: debugSession withFullView: true]."
((primitiveIndex between: 201 and: 222)
and: [(self objectClass: aReceiver) includesBehavior: BlockClosure]) ifTrue:
[((primitiveIndex between: 201 and: 205) "BlockClosure>>value[:value:...]"
or: [primitiveIndex between: 221 and: 222]) ifTrue: "BlockClosure>>valueNoContextSwitch[:]"
[^aReceiver simulateValueWithArguments: arguments caller: self].
primitiveIndex = 206 ifTrue: "BlockClosure>>valueWithArguments:"
[^aReceiver simulateValueWithArguments: arguments first caller: self]].
((primitiveIndex between: 207 and: 209) "FullBlockClosure primitives"
and: [(self objectClass: aReceiver) includesBehavior: FullBlockClosure]) ifTrue:
[^primitiveIndex = 208
ifTrue: [aReceiver simulateValueWithArguments: arguments first caller: self]
ifFalse: [aReceiver simulateValueWithArguments: arguments caller: self]].
primitiveIndex = 83 ifTrue: "afr 9/11/1998 19:50" "Object>>perform:[with:...]"
[^self send: arguments first to: aReceiver with: arguments allButFirst super: false].
primitiveIndex = 84 ifTrue: "afr 9/11/1998 19:50 & eem 8/18/2009 17:04" "Object>>perform:withArguments:"
[^self send: arguments first to: aReceiver with: (arguments at: 2) lookupIn: (self objectClass: aReceiver)].
primitiveIndex = 100 ifTrue: "eem 8/18/2009 16:57" "Object>>perform:withArguments:inSuperclass:"
[arguments size = 3
ifTrue: [ ^self send: arguments first to: aReceiver with: (arguments at: 2) lookupIn: (arguments at: 3)]
ifFalse: [ ^self send: (arguments at: 2) to: (arguments at: 1) with: (arguments at: 3) lookupIn: (arguments at: 4) ]
].
"Mutex>>primitiveEnterCriticalSection
Mutex>>primitiveTestAndSetOwnershipOfCriticalSection"
(primitiveIndex = 186 or: [primitiveIndex = 187]) ifTrue:
[| active effective |
active := Processor activeProcess.
effective := active effectiveProcess.
"active == effective"
value := primitiveIndex = 186
ifTrue: [aReceiver primitiveEnterCriticalSectionOnBehalfOf: effective]
ifFalse: [aReceiver primitiveTestAndSetOwnershipOfCriticalSectionOnBehalfOf: effective].
^(self isPrimFailToken: value)
ifTrue: [value]
ifFalse: [self push: value]].
primitiveIndex = 188 ifTrue: "eem 5/27/2008 11:10 Object>>withArgs:executeMethod:"
[arguments size = 2
ifTrue: "normal primitive"
[^Context
sender: self
receiver: aReceiver
method: (arguments at: 2)
arguments: (arguments at: 1)]
ifFalse: "mirror primitive"
[^Context
sender: self
receiver: (arguments at: 1)
method: (arguments at: 3)
arguments: (arguments at: 2)]
].
"Closure primitives"
(primitiveIndex = 200 and: [self == aReceiver]) ifTrue:
"ContextPart>>closureCopy:copiedValues:; simulated to get startpc right"
[^self push: (BlockClosure
outerContext: aReceiver
startpc: pc + 2
numArgs: arguments first
copiedValues: arguments last)].
primitiveIndex = 118 ifTrue: "tryPrimitive:withArgs:; avoid recursing in the VM"
[(arguments size = 2
and: [arguments first isInteger
and: [(self objectClass: arguments last) == Array]]) ifFalse:
[^Context primitiveFailTokenFor: nil].
^self doPrimitive: arguments first method: meth receiver: aReceiver args: arguments last].
value := primitiveIndex = 120 "FFI method"
ifTrue: [(meth literalAt: 1) tryInvokeWithArguments: arguments]
ifFalse:
[primitiveIndex = 117 "named primitives"
ifTrue: [self tryNamedPrimitiveIn: meth for: aReceiver withArgs: arguments]
ifFalse: [aReceiver tryPrimitive: primitiveIndex withArgs: arguments]].
^(self isPrimFailToken: value)
ifTrue: [value]
ifFalse: [self push: value]
]
{ #category : #private }
Context >> endPC [
^closureOrNil
ifNil: [self compiledCode endPC]
ifNotNil: [closureOrNil endPC]
]
{ #category : #'debugger access' }
Context >> errorReportOn: stream [
"Write a detailed error report on the stack (above me) on a
stream. For both the error file, and emailing a bug report.
Suppress any errors while getting printStrings. Limit the length."
| stackDepth aContext |
stream print: Date today; space; print: Time now; cr.
stream cr.
stream nextPutAll: 'VM: ';
nextPutAll: Smalltalk os name asString;
nextPutAll: ' - ';
nextPutAll: Smalltalk os subtype asString;
nextPutAll: ' - ';
nextPutAll: Smalltalk os version asString;
nextPutAll: ' - ';
nextPutAll: Smalltalk vm version asString;
cr.
stream nextPutAll: 'Image: ';
nextPutAll: SystemVersion current version asString;
nextPutAll: ' [';
nextPutAll: Smalltalk lastUpdateString asString;
nextPutAll: ']';
cr.
stream cr.
"Note: The following is an open-coded version of Context>>stackOfSize: since this method may be called during a low space condition and we might run out of space for allocating the full stack."
stackDepth := 0.
aContext := self.
[ aContext notNil and: [ (stackDepth := stackDepth + 1) < 40 ]]
whileTrue: [
"variable values"
aContext printDetails: stream.
stream cr.
aContext := aContext sender ].
stream cr; nextPutAll: '--- The full stack ---'; cr.
aContext := self.
stackDepth := 0.
[ aContext == nil ] whileFalse: [
stackDepth := stackDepth + 1.
stackDepth = 40 ifTrue: [ stream nextPutAll: ' - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -'; cr ].
"just class>>selector"
stream print: aContext; cr.
stackDepth > 200 ifTrue: [
stream nextPutAll: '-- and more not shown --'.
^ self ].
aContext := aContext sender ].
]
{ #category : #'private-exceptions' }
Context >> evaluateSignal: exception [
"The following primitive is just a marker used to find the evaluation context.
See MethodContext>>#isHandlerOrSignalingContext. "
<primitive: 199>
<debuggerCompleteToSender>
| value |
exception privHandlerContext: self contextTag.
value := self exceptionHandlerBlock cull: exception.
"default return if not otherwise directed in handle block"
exception return: value
]
{ #category : #'special context access' }
Context >> exception [
"signaling context (Context>>evaluateSignal:) only. Access the exception argument."
^self tempAt: 1
]
{ #category : #'special context access' }
Context >> exceptionClass [
"handlercontext only. access temporaries from BlockClosure>>#on:do:"
^self tempAt: 1
]
{ #category : #'special context access' }
Context >> exceptionHandlerBlock [
"handlercontext only. access temporaries from BlockClosure>>#on:do:"
^self tempAt: 2
]
{ #category : #'system simulation' }
Context >> failPrimitiveWith: maybePrimFailToken [
"The receiver is a freshly-created context on a primitive method. Skip the callPrimitive:
bytecode and store the primitive fail code if there is one and the method consumes it."
self skipCallPrimitive.
((self isPrimFailToken: maybePrimFailToken)
and: [method encoderClass isStoreAt: pc in: method]) ifTrue:
[self at: stackp put: maybePrimFailToken last]
]
{ #category : #query }
Context >> findContextSuchThat: testBlock [
"Search self and my sender chain for first one that satisfies testBlock. Return nil if none satisfy"
| context |
context := self.
[ context isNil ] whileFalse: [
(testBlock value: context)
ifTrue: [ ^ context ].
context := context sender ].
^ nil
]
{ #category : #'private-exceptions' }
Context >> findNextHandlerContext [
"Return the next handler marked context, returning nil if there is none.
Search starts with self and proceeds up to nil."
| context searchStartContext |
context := self findNextHandlerOrSignalingContext.
context ifNil: [ ^ nil ].
context isHandlerContext ifTrue: [ ^ context ].
"If it isn't a handler context, it must be a signaling context.
When we reach a signaling context we must skip over any handlers
that might be on the stack between the signaling context and the handler context for that signal"
searchStartContext := context exception privHandlerContext ifNil: [ context ].
^searchStartContext nextHandlerContext
]
{ #category : #'private-exceptions' }
Context >> findNextHandlerOrSignalingContext [
"Return the next handler/signaling marked context, answering nil if there is none.
Search starts with self and proceeds up to nil."
<primitive: 197>
| context |
context := self.
[
context isHandlerOrSignalingContext
ifTrue: [ ^ context ].
(context := context sender) == nil ] whileFalse.
^ nil
]
{ #category : #'private-exceptions' }
Context >> findNextUnwindContextUpTo: aContext [
"Return the next unwind marked above the receiver, returning nil if there is none. Search proceeds up to but not including aContext."
| context |
<primitive: 195>
context := self.
[
(context := context sender) == nil
or: [ context == aContext ]
] whileFalse: [
context isUnwindContext
ifTrue: [ ^context ]].
^nil
]
{ #category : #query }
Context >> findSecondToOldestSimilarSender [
"Search the stack for the second-to-oldest occurance of self's method. Very useful for an infinite recursion. Gets back to the second call so you can see one complete recursion cycle, and how it was called at the beginning."
| secondContext context lastContext |
secondContext := self.
context := self.
[ lastContext := context findSimilarSender.
lastContext isNil
] whileFalse: [
secondContext := context.
context := lastContext.
].
^ secondContext
]
{ #category : #query }
Context >> findSimilarSender [
"Return the closest sender with the same method, return nil if none found"
^ self sender findContextSuchThat: [ :context |
context compiledCode == method ]
]
{ #category : #'private-exceptions' }
Context >> handleSignal: exception [
"Sent to handler (on:do:) contexts only. If my exception class (first arg) handles exception then execute my handle block (second arg), otherwise forward this message to the next handler context. If none left, execute exception's defaultAction (see nil>>handleSignal:)."
<debuggerCompleteToSender>
(self exceptionClass handles: exception)
ifFalse: [ ^ self nextHandlerContext handleSignal: exception ].
self evaluateSignal: exception
]
{ #category : #testing }
Context >> hasContext: aContext [
"Answer whether aContext is me or one of my senders"
^ (self findContextSuchThat: [ :context | context == aContext ]) notNil
]
{ #category : #accessing }
Context >> hasInstVarRef [
"Answer whether the receiver references an instance variable."
^self compiledCode hasInstVarRef.
]
{ #category : #testing }
Context >> hasMethodReturn [
^closureOrNil hasMethodReturn
]
{ #category : #testing }
Context >> hasSender: context [
"Answer whether the receiver is strictly above context on the stack."
| senderContext |
self == context
ifTrue: [^false].
senderContext := sender.
[senderContext == nil]
whileFalse: [
senderContext == context
ifTrue: [^true].
senderContext := senderContext sender].
^false
]
{ #category : #testing }
Context >> hasTemporaryVariableNamed: aName [
^ self tempNames includes: aName
]
{ #category : #accessing }
Context >> home [
"Answer the context in which the receiver was defined, i.e. the context from which an ^-return should return from."
closureOrNil == nil ifTrue:
[^self].
^closureOrNil outerContext home
]
{ #category : #private }
Context >> insertSender: aContext [
"Insert aContext and its sender chain between me and my sender. Return new callee of my original sender."
| context |
context := aContext bottomContext.
context privSender: self sender.
self privSender: aContext.
^ context
]
{ #category : #private }
Context >> instVarAt: index put: value [
index = 3
ifTrue: [
self stackp: value.
^ value].
^ super instVarAt: index put: value
]
{ #category : #testing }
Context >> isBlockContext [
"Is this executing a block versus a method? In the new closure
implemetation this is true if closureOrNil is not nil, in which case
it should be holding a BlockClosure."
^closureOrNil isClosure
]
{ #category : #testing }
Context >> isBottomContext [
"Answer if this is the last context (the first context invoked) in my sender chain"
^sender isNil
]
{ #category : #testing }
Context >> isContext [
^true
]
{ #category : #testing }
Context >> isDead [
"Has self finished"
^ pc isNil
]
{ #category : #testing }
Context >> isExecutingBlock [
"for compatibility"
^self isBlockContext
]
{ #category : #private }
Context >> isFailToken: anObject [
^ (self objectClass: anObject) == Array
and: [ anObject size = 2 and: [(anObject at: 1) == PrimitiveFailToken]]
]
{ #category : #'private-exceptions' }
Context >> isHandlerContext [
"is this context for #on:do:?"
^self isHandlerOrSignalingContext and: [ self selector == #on:do: ]
]
{ #category : #'private-exceptions' }
Context >> isHandlerOrSignalingContext [