Newsgroups: comp.lang.smalltalk
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!oitnews.harvard.edu!purdue!haven.umd.edu!news.umbc.edu!eff!news.duke.edu!news.mathworks.com!newsfeed.internetmci.com!howland.reston.ans.net!torn!nott!cunews!dbuck
From: dbuck@superior.carleton.ca (Dave Buck)
Subject: Re: Why use Smalltalk as the primary development language ...
X-Nntp-Posting-Host: superior.carleton.ca
Message-ID: <DKEKvu.39E@cunews.carleton.ca>
Sender: news@cunews.carleton.ca (News Administrator)
Organization: Carleton University, Ottawa, Canada
References: <9512181732.AA07788@fred.nfuel.com> <4bmucv$p6j@news2.ios.com> <DK6DM4.8As@cunews.carleton.ca> <4c2uf4$scf@news2.ios.com>
Date: Sat, 30 Dec 1995 14:14:18 GMT
Lines: 72

In article <4c2uf4$scf@news2.ios.com>, vlad <vlad@gramercy.ios.com> wrote:
>dbuck@superior.carleton.ca (Dave Buck) wrote:
>>Smalltalk doesn't need to use recursion.  You can write loops in
>>several different ways:
>
>>1000 timesRepeat: [Transcript show: 'hello';cr]
>
>Anyway after seeing the implementation code in Smalltalk/V, it seems
>to be implemented using recursion.

Your statement is literally correct - it "seems" to be implemented
using recursion.  Most looping constructs in Smalltalk are implemented
using whileTrue:.  The implementation of whileTrue: looks quite
bizarre.

whileTrue: aBlock
   self value
      ifTrue: [
         aBlock value.
         self whileTrue: aBlock]

(or some variation depending on which Smalltalk you look at)

In fact, this method is not actually invoked in Smalltalk.  The
whileTrue: method is actually expanded inline in the caller by the
compiler.  All Smalltalks do this.  I will explain using VisualWorks
because they have a bytecode disassembler built in.

Suppose I write a method:

test
   | i |
   i := 0.
   [i < 10] whileTrue: [i := i + 1]

The actual bytecodes produced by the compiler are:
  1 <49> push 0
  2 <4C> store local 0; pop
  3 <67> loop head
  4 <10> push local 0
  5 <D8 0A> push 10
  7 <A2> send <
  8 <C4> jump false 14
  9 <10> push local 0
  10 <C8> push 1; send +
  11 <4C> store local 0; pop
  12 <E3 F5> jump 3
  14 <60> push self; return

As you can see, the loop is expanded inline without sending a
whileTrue: message.  The reason for having the method at all is to
document the whileTrue: message (although V should have comments
indicating that it isn't actually used - VW does).

If Smalltalk could only loop by doing recursion, it wouldn't take long
to overflow the stack and it would make debugging enormously
difficult.  It's unfortunate that the implementation of whileTrue: is
so deceiving.  It really should be commented.

There are a handful of other method in Smalltalk that are expanded
inline.  The '==' method is one.  The list varies slightly by dialect.

David Buck
dbuck@ccs.carleton.ca

_________________________________
| David K. Buck                 |
| dbuck@ccs.carleton.ca         |
| The Object People             |
|_______________________________|


