Search code examples
smalltalk

Why doesn't this code cause an infinite loop?


Let's say I define a new class, and I override class:

class
   ^self class.

And then I run:

var:=NewClass new.
Transcript show:(var class);cr.

Why doesn't this code cause an infinite loop?

The runtime class is NewClass, so how come the code calls the class defined in Object, and not the class defined in NewClass?


Solution

  • Smalltalk implementations may implement certain shortcuts for special messages. You didn't specify your Smalltalk implementation, but most likely it has a special bytecode to retrieve the class of an object. When the Smalltalk VM encounters that bytecode, it does not really send the message class to the receiver, so your method is never invoked and the infinite recursion does not happen. The Smalltalk compiler will emit that special bytecode instead of the bytecode(s) for a message send if it sees that you use class.

    The same typically happens with ifTrue: ifFalse:, instead of compiling message sends to the receiver (boolean) object, the Smalltalk compiler will emit conditional jumps in the bytecode of the "calling" method.

    To get such an infinite loop, you could try with perform: #class both in your script and in the implementation of NewClass>>class.

    class
       ^ self perform: #class