robhagemans / pcbasic

PC-BASIC - A free, cross-platform emulator for the GW-BASIC family of interpreters
http://www.pc-basic.org
Other
393 stars 48 forks source link

Session: executing "GOSUB line" after entering program → strange result #184

Closed Marrin closed 2 years ago

Marrin commented 2 years ago

PC-BASIC version: 2.0.4

I get a strange result when entering a program in a Session and the GOSUB to a specific line. Here is a small test case:

#!/usr/bin/env python3
import pcbasic

SOURCE = """\
10 PRINT "Main"
30 PRINT 42
40 END
50 PRINT "After End"
60 PRINT "Sub"
70 RETURN
"""

def main():
    with pcbasic.Session() as session:
        session.execute(SOURCE)
        # session.execute("RUN")
        session.execute("GOSUB 60")

if __name__ == "__main__":
    main()

The output I get:

Sub
 42

What I expected was just the "Sub" without the 42 from line 30. And extra confusing is that "Main" is not printed. So why is the RETURN apparently jumping to line 20 instead of just return to the ”prompt” like it is done if the program and the GOSUB is entered manually?

robhagemans commented 2 years ago

Thanks, that's odd indeed. Your expectation is correct. It does the wrong thing on the prompt as well so the problem is not specific to calling from the Session interface, it's a problem with the program pointer in the GOSUB or RETURN implementation itself in version 2.x. Version 1.x did the right thing here.

robhagemans commented 2 years ago

It looks like the runmode flag gets set on executing the GOSUB in direct mode, which means the RETURN jumps back to the program stream rather than the direct line. The weird return location arises because it records its stream position in the direct line on the jump (after a tokenised :GOSUB 60), then jumps to that position in the programme stream, which ends up on the second line of the program in this case.

robhagemans commented 2 years ago

The issue is that Interpreter.jump() sets Interpreter.run_mode, so the original runmode needs to be stored before executing the jump. I have a fix.

robhagemans commented 2 years ago

Fixed by commit 52e24aa0. Thanks for reporting!