[From nobody Sat Mar 13 18:15:22 2010
Return-path: &lt;Najem.Karim@centrotherm.de&gt;
Envelope-to: tismer@tismer.com
Delivery-date: Thu, 12 Mar 2009 11:07:30 +0100
Received: from mail.centrotherm.de ([194.127.107.2])
	by chewwy.tismer.com with esmtp (Exim 4.69)
	(envelope-from &lt;Najem.Karim@centrotherm.de&gt;) id 1Lhhp3-00079R-Cj
	for tismer@tismer.com; Thu, 12 Mar 2009 11:07:30 +0100
Received: from GWiDom-MTA by mail.centrotherm.de
	with Novell_GroupWise; Thu, 12 Mar 2009 10:59:10 +0100
Message-Id: &lt;49B8EAFA.BFE4.00D0.0@centrotherm.de&gt;
X-Mailer: Novell GroupWise Internet Agent 7.0.3 
Date: Thu, 12 Mar 2009 10:59:06 +0100
From: &quot;Najem Karim&quot; &lt;Najem.Karim@centrotherm.de&gt;
To: &lt;tismer@tismer.com&gt;
Subject: Wtrlt: Antw: Re: implementation of 'goto' for stackless python
References: &lt;49B687B4.BFE4.00D0.0@centrotherm.de&gt;
	&lt;49B6C82E.4040806@stackless.com&gt; &lt;49B76C88.BFE4.00D0.0@centrotherm.de&gt;
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary=&quot;=__PartBF9743FA.0__=&quot;

--=__PartBF9743FA.0__=
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

I apologize if I am causing you any inconvenience with my emails.
I tried to be short in my 2 previous mails but unfortunately I was not =
precise enough! =20

Here is again example that I used:

def testGOTO():
   print (&quot;testGOTO statred&quot;)
    i =3D 2
   =20
    label .start
    print(i)

    if i =3D=3D 2:
       goto .rogg
    elif i =3D=3D 4:
       goto .ronny
    else:
       print(&quot;finished&quot;)
       goto .end
=20
    label .ronny
    print(&quot;working &quot;, i)
    i =3D 6
    goto .start

    label .rogg
    print(&quot;sleeping &quot;, i)
    i =3D 4
    goto .start

    label .end
    print(&quot;exit ronny's goto hell &quot;, i)

Here is my main:
if __name__ =3D=3D '__main__':

    #Call without tasklet
   =20
    testGOTO()
   =20
    stackless.tasklet(testGOTO)()
    stackless.run()

Actually you were right the  testGOTO() above works without any problem
and here is the output:
testGOTO statred
2
Jump to line:  53
sleeping  2
Jump to line:  37
4
Jump to line:  48
working  4
Jump to line:  37
6
finished
Jump to line:  58
exit ronny's goto hell  6=20
----------------------------------------------------------
I am interested in the second one=20
 stackless.tasklet(testGOTO)()

First of all when I run it I get a failure:
Traceback (most recent call last):
  File &quot;D:\eclipse_workspace\TestStackless1\src\start.py&quot;, line 137, in =
&lt;module&gt;
    t =3D stackless.run(1) # Run one step of the task
  File &quot;D:\eclipse_workspace\TestStackless1\src\start.py&quot;, line 41, in =
testGOTO
    goto .rogg
AttributeError: 'NoneType' object has no attribute 'rogg'

Then I changed in goto.py the definition of
goto =3D None

to:
goto =3D _Goto()
and defined _Goto() as a class type:

class _Goto():
    def __getattr__(self, name):
        return None=20

When I run now although I do not get the error
but Stackless ignores the goto jumps

Here is the output:
testGOTO statred
2
working  2
sleeping  6
exit ronny's goto hell  4
----------------------------------

Please let me know what is wrong or if I am using 'tasklet' wrong.

Best regards,
Najem Karim



--=__PartBF9743FA.0__=
Content-Type: text/plain; name=&quot;goto.py&quot;
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment; filename=&quot;goto.py&quot;

# Copyright (c) 2003 Entrian Solutions. All rights reserved.
# Released under the Python Software License - see www.python.org

&quot;&quot;&quot;Adds the 'goto' and 'comefrom' keywords to Python.

The 'goto' and 'comefrom' keywords add flexibility to Python's control =
flow
mechanisms, and allow Python programmers to use many common control flow
idioms that were previously denied to them.  Some examples are given =
below.


*goto*

'goto' jumps the program execution directly to another line of code.  The
target line must be identified using a 'label' statement.  Labels are =
defined
using the 'label' keyword, and have names which are arbitrary Python
identifiers prefixed with a single dot, like this::

label .myLabel

To jump to a label, use the 'goto' keyword like this::

goto .myLabel


*Computed goto*

You can use a computed goto by assigning the name of the label to a =
variable
at runtime and referencing it using an asterisk like this::

x =3D calculateLabelName()
goto *x

The value of 'x' should not include the leading dot.  See Example 5 below
for a full example.


*comefrom*

'comefrom' is the opposite of 'goto'.  It allows a piece of code to say
&quot;Whenever label X is reached, jump to here instead.&quot;  For example::

# ...code 1...
label .somewhere
# ...code 2...
comefrom .somewhere

Here, &quot;code 2&quot; will not run - execution will jump directly from the
&quot;label .somewhere&quot; line to the &quot;comefrom .somewhere&quot; line.  'comefrom' is
typically used as a debugging aid - its use in production code is
discouraged since it can lead to surprising behaviour.


*Restrictions*

There are some classes of goto and comefrom which would be unpythonic, and
hence there are some restrictions on where jumps can go:

 o No jumping between modules or functions

 o No jumping into the middle of a loop or a 'finally' clause

 o No jumping onto an 'except' line (because there is no exception)


*Examples*

Here are some examples of how goto and comefrom can be used::

# Example 1: Breaking out from a deeply nested loop:
from goto import goto, label
for i in range(1, 10):
    for j in range(1, 20):
        for k in range(1, 30):
            print i, j, k
            if k =3D=3D 3:
                goto .end
label .end
print &quot;Finished\n&quot;
=20
=20
# Example 2: Restarting a loop:
from goto import goto, label
label .start
for i in range(1, 4):
    print i
    if i =3D=3D 2:
        try:
            output =3D message
        except NameError:
            print &quot;Oops - forgot to define 'message'!  Start again.&quot;
            message =3D &quot;Hello world&quot;
            goto .start
print output, &quot;\n&quot;
=20
=20
# Example 3: Cleaning up after something fails:
from goto import goto, label
=20
# Imagine that these are real worker functions.
def setUp(): print &quot;setUp&quot;
def doFirstTask(): print 1; return True
def doSecondTask(): print 2; return True
def doThirdTask(): print 3; return False  # This one pretends to fail.
def doFourthTask(): print 4; return True
def cleanUp(): print &quot;cleanUp&quot;
=20
# This prints &quot;setUp, 1, 2, 3, cleanUp&quot; - no &quot;4&quot; because doThirdTask =
fails.
def bigFunction1():
    setUp()
    if not doFirstTask():
        goto .cleanup
    if not doSecondTask():
        goto .cleanup
    if not doThirdTask():
        goto .cleanup
    if not doFourthTask():
        goto .cleanup
=20
    label .cleanup
    cleanUp()
=20
bigFunction1()
print &quot;bigFunction1 done\n&quot;
=20
=20
# Example 4: Using comefrom to let the cleanup code take control itself.
from goto import comefrom, label
def bigFunction2():
    setUp()
    if not doFirstTask():
        label .failed
    if not doSecondTask():
        label .failed
    if not doThirdTask():
        label .failed
    if not doFourthTask():
        label .failed
=20
    comefrom .failed
    cleanUp()
=20
bigFunction2()
print &quot;bigFunction2 done\n&quot;
=20
=20
# Example 5: Using a computed goto:
from goto import goto, label
=20
label .getinput
i =3D raw_input(&quot;Enter either 'a', 'b' or 'c', or any other letter to =
quit: &quot;)
if i in ('a', 'b', 'c'):
    goto *i
else:
    goto .quit
=20
label .a
print &quot;You typed 'a'&quot;
goto .getinput
=20
label .b
print &quot;You typed 'b'&quot;
goto .getinput
=20
label .c
print &quot;You typed 'c'&quot;
goto .getinput
=20
label .quit
print &quot;Finished\n&quot;
=20
=20
# Example 6: What happens when a label is missing:
from goto import goto, label
label .real
goto .unreal      # Raises a MissingLabelError exception.


This module is released under the Python Software Foundation license, =
which
can be found at http://www.python.org/  It requires Python 2.3 or later.

Richie Hindle, _richie@entrian.com_

Version 1.0, released 1st April 2004.
&quot;&quot;&quot;

__author__ =3D &quot;Richie Hindle &lt;richie@entrian.com&gt;&quot;
__version__ =3D 1.0


import sys, token, tokenize

class MissingLabelError(Exception):
    &quot;&quot;&quot;'goto' without matching 'label'.&quot;&quot;&quot;
    pass

# Source filenames -&gt; line numbers of plain gotos -&gt; target label names.
_plainGotoCache =3D {}

# Source filenames -&gt; line numbers of computed gotos -&gt; identifier names.
_computedGotoCache =3D {}

# Source filenames -&gt; line numbers of labels -&gt; label names.
_labelCache =3D {}

# Source filenames -&gt; label names -&gt; line numbers of those labels.
_labelNameCache =3D {}

# Source filenames -&gt; comefrom label names -&gt; line numbers of those =
comefroms.
_comefromNameCache =3D {}

def _addToCaches(moduleFilename):
    &quot;&quot;&quot;Finds the labels and gotos in a module and adds them to the =
caches.&quot;&quot;&quot;

    # The token patterns that denote gotos and labels.
    plainGotoPattern =3D [(token.NAME, 'goto'), (token.OP, '.')]
    computedGotoPattern =3D [(token.NAME, 'goto'), (token.OP, '*')]
    labelPattern =3D [(token.NAME, 'label'), (token.OP, '.')]
    comefromPattern =3D [(token.NAME, 'comefrom'), (token.OP, '.')]

    # Initialise this module's cache entries.
    _plainGotoCache[moduleFilename] =3D {}
    _computedGotoCache[moduleFilename] =3D {}
    _labelCache[moduleFilename] =3D {}
    _labelNameCache[moduleFilename] =3D {}
    _comefromNameCache[moduleFilename] =3D {}

    # Tokenize the module; 'window' is the last two (type, string) pairs.
    window =3D [(None, ''), (None, '')]
    for tokenType, tokenString, (startRow, startCol), (endRow, endCol), =
line \
            in tokenize.generate_tokens(open(moduleFilename, 'r').readline)=
:
        # Plain goto: &quot;goto .x&quot;
        if window =3D=3D plainGotoPattern:
            _plainGotoCache[moduleFilename][startRow] =3D tokenString

        # Computed goto: &quot;goto *identifier&quot;  XXX Allow expressions.
        elif window =3D=3D computedGotoPattern:
            _computedGotoCache[moduleFilename][startRow] =3D tokenString

        # Comefrom: &quot;comefrom .x&quot;  XXX Non-determinism via multiple =
comefroms.
        if window =3D=3D comefromPattern:
            _comefromNameCache[moduleFilename][tokenString] =3D startRow

        # Label: &quot;label .x&quot;  XXX Computed labels.
        elif window =3D=3D labelPattern:
            _labelCache[moduleFilename][startRow] =3D tokenString
            _labelNameCache[moduleFilename][tokenString] =3D startRow

        # Move the token window back by one.
        window =3D [window[1], (tokenType, tokenString)]

def _trace(frame, event, arg):
    # If this is the first time we've seen this source file, cache it.
    filename =3D frame.f_code.co_filename
    if filename not in _plainGotoCache:
        _addToCaches(filename)

    # Is there a goto on this line?
    targetLabel =3D _plainGotoCache[filename].get(frame.f_lineno)
    if not targetLabel:
        # No plain goto.  Is there a computed goto?
        identifier =3D _computedGotoCache[filename].get(frame.f_lineno)
        if identifier:
            # If eval explodes, just let the exception propagate.
            targetLabel =3D eval(identifier, frame.f_globals, frame.f_local=
s)

    # Jump to the label's line.
    if targetLabel:
        try:
            targetLine =3D _labelNameCache[filename][targetLabel]
        except KeyError:
            raise MissingLabelError, &quot;Missing label: %s&quot; % targetLabel
        frame.f_lineno =3D targetLine

    # Is there a label on this line with a corresponding comefrom?
    label =3D _labelCache[filename].get(frame.f_lineno)
    if label:
        targetComefromLine =3D _comefromNameCache[filename].get(label)
        if targetComefromLine:
            frame.f_lineno =3D targetComefromLine

    return _trace

# Install the trace function, including all preceding frames.
sys.settrace(_trace)
frame =3D sys._getframe().f_back
while frame:
    frame.f_trace =3D _trace
    frame =3D frame.f_back

# Define the so-called keywords for importing: 'goto', 'label' and =
'comefrom'.
class _Label:
    &quot;&quot;&quot;Allows arbitrary x.y attribute lookups.&quot;&quot;&quot;
    def __getattr__(self, name):
        return None

goto =3D None
label =3D _Label()
comefrom =3D _Label()

--=__PartBF9743FA.0__=--
]