Files
Eremey Valetov ff7babdec9
Verify and publish documentation / test (macos-latest) (push) Canceled after 0s
Verify and publish documentation / test (ubuntu-latest) (push) Canceled after 0s
Verify and publish documentation / docs (push) Canceled after 0s
Verify and publish documentation / deploy (push) Canceled after 0s
Harden runtime and notebook integration and publish documentation
Validate physical cards and CLI arguments, guard live DO cells, and share
word encoding and checked numeric conversion. Preserve media on failed runs
and bound notebook input, output, execution time and process cleanup.

Clarify fixed-form editor support and compatibility evidence, add executable
quick-start examples, and gate GitHub Pages on Linux/macOS and strict docs CI.
2026-11-21 15:13:01 -05:00

501 lines
18 KiB
Python

"""Jupyter kernel for IBM 704 FORTRAN.
The runtime is a batch program: one cell that contains END, or a
%run of the accumulated deck, writes a fixed-form source file and
runs fortran704. Variables do not survive that process. The session
does keep the card deck, the dialect (--std), and the sense switches.
GW-BASIC 2026 keeps one interpreter process and answers INPUT with
"? ". This kernel prompts with "READ " only when a card deck contains
a card READ and the cell gave no input deck.
"""
import os
import errno
import shutil
import subprocess
import tempfile
import time
from ipykernel.kernelbase import Kernel
from . import __version__
OUTPUT_LIMIT = 1024 * 1024 # Per stream, including failed runs.
class OutputLimitExceeded(Exception):
pass
KEYWORDS = [
'ASSIGN', 'BACKSPACE', 'CALL', 'COMMON', 'CONTINUE', 'DIMENSION',
'DO', 'END', 'EQUIVALENCE', 'FORMAT', 'FREQUENCY', 'FUNCTION',
'GO', 'GOTO', 'IF', 'PAUSE', 'PRINT', 'PUNCH', 'READ', 'RETURN',
'RELABEL', 'RELATIVE', 'CONSTANTS', 'REWIND', 'STOP', 'SUBROUTINE', 'TO', 'WRITE',
'ABSF', 'ATANF', 'COSF', 'EXPF', 'INTF', 'LOGF', 'SINF', 'SQRTF',
]
def is_end_card(text):
if not text:
return False
u = text.replace(' ', '').upper()
return u == 'END' or u.startswith('END(')
def statement_fields(lines):
"""Assemble fixed-form continuation fields for execution detection."""
statement = None
for line in lines:
raw = line.rstrip('\r\n')
if not raw.ljust(72)[:72].strip(' ') or raw[:1] in ('C', 'c'):
continue
raw = raw.ljust(72)
field = raw[6:72]
if raw[5] not in ' 0':
if statement is not None:
statement += field
else:
if statement is not None:
yield statement.replace(' ', '').upper()
statement = field
if statement is not None:
yield statement.replace(' ', '').upper()
def program_has_end(lines):
return any(is_end_card(text) for text in statement_fields(lines))
def blank_cell(code):
return all(not line.rstrip('\r').strip(' ') for line in code.split('\n'))
def ignored_card(line):
if '\0' in line or '\t' in line:
return False
raw = line.rstrip('\r\n')
return raw[:1] in ('C', 'c') or not raw[:72].strip(' ')
def needs_stdin(lines):
for text in statement_fields(lines):
if not text.startswith('READ'):
continue
depth, assignment = 0, False
for ch in text:
if ch == '(':
depth += 1
elif ch == ')':
depth -= 1
elif ch == '=' and depth == 0:
assignment = True
if assignment or text.startswith(('READTAPE', 'READINPUTTAPE', 'READDRUM')):
continue
return True
return False
def split_cell(code):
"""Split a cell into magic lines, source cards, and an optional deck.
%deck takes the following lines as the input deck until %enddeck
or the end of the cell. Other % lines are magics. The rest are cards.
"""
magics = []
source = []
deck = None
in_deck = False
# Only LF/CRLF are physical card boundaries. Other control characters
# must reach the runtime unchanged, not silently become extra cards.
for line in code.replace('\r\n', '\n').removesuffix('\n').split('\n'):
stripped = line.strip()
if in_deck:
if line.startswith('%') and stripped.lower() == '%enddeck':
in_deck = False
else:
deck.append(line)
continue
if line.startswith('%') and stripped.lower() == '%deck':
deck = []
in_deck = True
continue
if line.startswith('%'):
magics.append(stripped)
continue
source.append(line)
return magics, source, deck
def timeout_seconds(value):
seconds = int(value)
if not 1 <= seconds <= 86400:
raise ValueError('Timeout must be between 1 and 86400 seconds.')
return seconds
def find_binary():
env = os.environ.get('FORTRAN704')
if env:
env = os.path.abspath(env)
if os.path.isfile(env) and os.access(env, os.X_OK):
return env
return None
here = os.path.join(os.path.dirname(__file__), '..', 'fortran704')
if os.path.isfile(here) and os.access(here, os.X_OK):
return os.path.abspath(here)
return shutil.which('fortran704')
def _ok(kernel):
return {
'status': 'ok',
'execution_count': kernel.execution_count,
'payload': [],
'user_expressions': {},
}
def _err(kernel, ename, evalue):
return {
'status': 'error',
'execution_count': kernel.execution_count,
'ename': ename,
'evalue': evalue,
'traceback': [],
}
class Fortran704Kernel(Kernel):
implementation = 'fortran704kernel'
implementation_version = __version__
language = 'fortran'
language_version = '704'
language_info = {
'name': 'fortran',
'mimetype': 'text/x-fortran704',
'file_extension': '.f',
'pygments_lexer': 'fortran704kernel.fortran_lexer.Fortran704Lexer',
}
banner = (
'FORTRAN 704 kernel. Fixed-form cards. '
'A cell with END runs. %run runs the deck. %std 0|1|2.'
)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._init_session()
def _init_session(self):
self._std = 2
self._ss = 'UUUUUU'
self._timeout = timeout_seconds(os.environ.get('FORTRAN704_TIMEOUT', '30'))
self._deck = []
self._pending_input = None
self._proc = None
def _stream(self, name, text, silent):
if silent or not text:
return
if not text.endswith('\n'):
text += '\n'
self.send_response(self.iopub_socket, 'stream', {'name': name, 'text': text})
def _apply_state_magic(self, line):
"""Apply one session magic. Return (message, error) . message may be None."""
body = line[1:]
head, _, arg = body.partition(' ')
if '=' in head and not arg:
head, _, arg = head.partition('=')
head = head.lower()
arg = arg.strip()
if head == 'std':
if arg not in ('0', '1', '2'):
return None, 'Usage: %std 0|1|2'
self._std = int(arg)
name = {0: 'FORTRAN 0', 1: 'FORTRAN I', 2: 'FORTRAN II'}[self._std]
return 'Dialect is %s.' % name, None
if head == 'ss':
ss = arg.upper()
if len(ss) != 6 or any(c not in 'UD' for c in ss):
return None, 'Usage: %ss UUUUUU'
self._ss = ss
return 'Sense switches are %s.' % self._ss, None
if head == 'timeout':
if not arg:
return 'Timeout is %ds.' % self._timeout, None
try:
self._timeout = timeout_seconds(arg)
except ValueError:
return None, 'Usage: %timeout <seconds>, from 1 to 86400'
return 'Timeout is %ds.' % self._timeout, None
if head == 'reset':
self._std = 2
self._ss = 'UUUUUU'
self._deck = []
self._pending_input = None
return 'Session reset. Dialect is FORTRAN II.', None
if head == 'new':
self._deck = []
return 'Deck cleared.', None
if head in ('run', 'list', 'deck', 'enddeck'):
return None, None
return None, 'Unknown magic %%%s.' % head
def _run_compiler(self, source, deck_text, allow_stdin):
binary = find_binary()
if not binary:
return None, '', 'fortran704 binary not found. Set FORTRAN704 or build ./fortran704.\n', 127
text = '\n'.join(source) + '\n'
path = None
proc = None
out, err = bytearray(), bytearray()
early = ''
rc = 0
try:
source_bytes = text.encode('ascii')
data = None if deck_text is None else deck_text.encode('ascii')
fd, path = tempfile.mkstemp(suffix='.f', prefix='ftn704-')
with os.fdopen(fd, 'wb') as fh:
fh.write(source_bytes)
proc = subprocess.Popen(
[binary, '--std=%d' % self._std, '--ss=%s' % self._ss, path],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._proc = proc
interactive = deck_text is None and allow_stdin and needs_stdin(source)
self._read_process(proc, data, interactive, out, err)
rc = proc.returncode
except UnicodeEncodeError:
early, rc = 'Source cards and input decks must use ASCII characters.\n', 65
except subprocess.TimeoutExpired:
early, rc = 'Execution timed out after %ds.\n' % self._timeout, 124
except OutputLimitExceeded:
early, rc = 'Execution exceeded the 1 MiB per-stream output limit.\n', 125
except KeyboardInterrupt:
early, rc = 'Execution interrupted.\n', 130
except OSError as error:
early, rc = 'Could not run fortran704: %s.\n' % error, 126
finally:
# This launcher owns termination and reaping on every read path.
# State reset and source removal must survive cleanup errors too.
try:
if proc is not None:
if proc.poll() is None:
try:
proc.kill()
except ProcessLookupError:
pass
proc.wait()
except OSError as error:
early, rc = 'Could not clean up fortran704: %s.\n' % error, 126
finally:
self._proc = None
if proc is not None:
for stream in (proc.stdin, proc.stdout, proc.stderr):
try:
if stream is not None:
stream.close()
except OSError:
pass
if path is not None:
try:
os.remove(path)
except OSError:
pass
return out.decode('utf-8', errors='replace'), err.decode('utf-8', errors='replace'), early, rc
def _read_process(self, proc, data, interactive, out, err):
"""Drain bounded output and send input under one execution deadline.
Interactive prompts exclude synchronous human reply time. Batch input
closes stdin after its last byte; cancellation closes it once. The
launcher owns child termination and reaping on every exit path.
"""
import select
pending = data or b''
offset = 0
os.set_blocking(proc.stdin.fileno(), False)
if not pending and not interactive:
proc.stdin.close()
deadline = time.monotonic() + self._timeout
def check_time():
now = time.monotonic()
if now >= deadline:
raise subprocess.TimeoutExpired(proc.args, self._timeout)
return now
streams = {proc.stdout: out, proc.stderr: err}
while streams or proc.poll() is None:
remaining = deadline - check_time()
writes = pending and not proc.stdin.closed
poller = select.poll()
for stream in streams:
poller.register(stream, select.POLLIN)
if writes:
poller.register(proc.stdin, select.POLLOUT)
events = dict(poller.poll(max(1, int(min(0.2, remaining) * 1000))))
check_time()
if any(event & select.POLLNVAL for event in events.values()):
raise OSError(errno.EBADF, os.strerror(errno.EBADF))
ready = [stream for stream in streams if events.get(stream.fileno(), 0)
& (select.POLLIN | select.POLLHUP | select.POLLERR)]
writable = writes and events.get(proc.stdin.fileno(), 0) & (
select.POLLOUT | select.POLLHUP | select.POLLERR)
if writable:
try:
offset += os.write(proc.stdin.fileno(), pending[offset:offset + 8192])
if offset == len(pending):
pending, offset = b'', 0
if not interactive:
proc.stdin.close()
except BlockingIOError:
pass
except BrokenPipeError:
proc.stdin.close()
pending = b''
if not ready and not writable:
if (not interactive or pending or not streams or proc.stdin.closed
or proc.poll() is not None):
continue
reply = None
started = check_time()
try:
reply = self.raw_input('READ ')
except EOFError:
proc.stdin.close()
finally:
deadline += time.monotonic() - started
if reply is not None and proc.poll() is None:
pending, offset = (reply + '\n').encode('ascii'), 0
continue
for stream in ready:
chunk = os.read(stream.fileno(), 8192)
if not chunk:
streams.pop(stream)
continue
buffer = streams[stream]
room = OUTPUT_LIMIT - len(buffer)
buffer.extend(chunk[:room])
if len(chunk) > room:
raise OutputLimitExceeded()
check_time()
def do_execute(self, code, silent, store_history=True,
user_expressions=None, allow_stdin=False):
try:
code.encode('ascii')
except UnicodeEncodeError:
message = 'Source cards and input decks must use ASCII characters.'
self._stream('stderr', message, silent)
return _err(self, 'UnicodeError', message)
if blank_cell(code):
return _ok(self)
magics, source, deck = split_cell(code)
notes = []
want_run = False
want_list = False
for magic in magics:
words = magic[1:].split()
if not words:
self._stream('stderr', 'A magic needs a name after %. ', silent)
return _err(self, 'UsageError', 'A magic needs a name after %.')
head = words[0].split('=')[0].lower()
if head == 'run':
want_run = True
continue
if head == 'list':
want_list = True
continue
message, error = self._apply_state_magic(magic)
if error:
self._stream('stderr', error, silent)
return _err(self, 'UsageError', error)
if message:
notes.append(message)
if deck is not None:
self._pending_input = '\n'.join(deck)
if deck:
self._pending_input += '\n'
if not source and not want_run:
n = len(deck)
word = 'line' if n == 1 else 'lines'
notes.append('Input deck has %d %s.' % (n, word))
program = None
if source and program_has_end(source):
program = list(source)
elif source and want_run:
self._deck.extend(source)
program = list(self._deck)
elif source:
self._deck.extend(source)
n = len(source)
word = 'card' if n == 1 else 'cards'
notes.append('Appended %d %s. The deck has %d.' % (n, word, len(self._deck)))
elif want_run:
program = list(self._deck)
if want_list:
if self._deck:
notes.append('\n'.join(self._deck))
else:
notes.append('The deck is empty.')
if notes:
self._stream('stdout', '\n'.join(notes), silent)
if program is None:
return _ok(self)
if all(ignored_card(line) for line in program):
self._stream('stderr', 'The deck is empty.', silent)
return _err(self, 'UsageError', 'The deck is empty.')
if not program_has_end(program):
program = program + [' END']
deck_text = self._pending_input
self._pending_input = None
out, err, early, rc = self._run_compiler(program, deck_text, allow_stdin)
self._stream('stdout', out, silent)
self._stream('stderr', err, silent)
if early:
self._stream('stderr', early, silent)
ename = {65: 'UnicodeError', 124: 'TimeoutError', 125: 'OutputLimitError',
130: 'KeyboardInterrupt',
126: 'OSError', 127: 'FileNotFoundError'}[rc]
return _err(self, ename, early.strip())
if rc != 0:
first = (err or out or 'fortran704 exited %d' % rc).strip().split('\n')[0]
return _err(self, 'FortranError', first)
return _ok(self)
def do_complete(self, code, cursor_pos):
text = code[:cursor_pos]
token = ''
i = len(text)
while i > 0 and text[i - 1].isalpha():
i -= 1
token = text[i:]
if not token:
return {'matches': [], 'cursor_start': cursor_pos,
'cursor_end': cursor_pos, 'status': 'ok'}
upper = token.upper()
matches = [kw for kw in KEYWORDS if kw.startswith(upper)]
return {
'matches': matches,
'cursor_start': cursor_pos - len(token),
'cursor_end': cursor_pos,
'status': 'ok',
}
def do_is_complete(self, code):
if blank_cell(code):
return {'status': 'incomplete', 'indent': ''}
return {'status': 'complete'}
def do_shutdown(self, restart):
if self._proc is not None and self._proc.poll() is None:
self._proc.kill()
return {'status': 'ok', 'restart': restart}