Reorganize code to make it a bit more modular.

This commit is contained in:
Russ Olsen 2020-04-17 13:42:41 -04:00
parent 6925755432
commit 8785b97f03

View file

@ -1,22 +1,13 @@
import os
import sys
import atexit
from kernel import Forth
from lex import tokenize
import readline
HistoryFile=".sallyforth"
histfile = os.path.join(os.path.expanduser("~"), HistoryFile)
try:
readline.read_history_file(histfile)
except FileNotFoundError:
pass
source_dir = os.path.dirname(os.path.abspath(__file__))
startup_file = f'{source_dir}/startup.sf'
f = Forth()
hist_file = os.path.join(os.path.expanduser("~"), HistoryFile)
class Completer:
def __init__(self, f):
@ -28,17 +19,32 @@ class Completer:
except IndexError:
return None
completer = Completer(f)
def setup_readline(history_path, f):
completer = Completer(f)
try:
readline.read_history_file(history_path)
except FileNotFoundError:
pass
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
def save_history():
readline.write_history_file(history_path)
atexit.register(save_history)
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
def setup_forth():
f = Forth()
f.defvar("argv", sys.argv[1::])
f.defvar("argv", sys.argv[1::])
source_dir = os.path.dirname(os.path.abspath(__file__))
startup_file = f'{source_dir}/startup.sf'
if os.path.exists(startup_file):
if os.path.exists(startup_file):
f.execute_file(startup_file)
while True:
return f
def repl(f):
while True:
p = f.evaluate_token('*prompt*')
try:
line = input(p)
@ -57,6 +63,9 @@ while True:
print("Error:", exc_value)
print("Error:", exc_traceback)
readline.write_history_file(histfile)
print("Bye!")
if __name__ == "__main__":
f = setup_forth()
setup_readline(hist_file, f)
repl(f)
print("Bye!")