Datasets:

Languages:
English
Size:
n<1K
DOI:
Libraries:
License:
miniCodeProps / utils.py
elohn's picture
baselines working on Linux
8d5ba38
raw
history blame
8.03 kB
import pexpect
import json_stream
import json
MACOS = 'MacOS'
LINUX = 'Linux'
OS = LINUX #MACOS
LEAN_REPL_CMD = 'lake env ../repl/.lake/build/bin/repl'
SHELL_CMD = '/bin/sh' if OS == MACOS else '/bin/bash' #zsh doesn't play well with non-canonical input: https://github.com/samapriya/geeup/issues/41
BASE_PATH = 'LeanSrc/LeanSrc'
def make_lean_repl(repl_type='zsh'):
# there are maximum line lengths that can be sent over tty, this will cause some things we send to
# lean repl to be cut off at e.g. 1024 characters for MacOS unless we use this workaround.
# See https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.send
print('making repl')
if repl_type == 'icanon':
lean_repl = pexpect.spawn(SHELL_CMD, cwd='LeanSrc', maxread=5000, timeout=20, echo=False)
lean_repl.sendline('stty -icanon') # this is the magic that allows a bunch of chars to be sent
lean_repl.sendline(LEAN_REPL_CMD)
if OS == MACOS:
print(lean_repl.readline()) # my mac prints out some garbage when I run /bin/sh
print(lean_repl.readline())
elif repl_type == 'zsh':
lean_repl = pexpect.spawn(LEAN_REPL_CMD,cwd='LeanSrc', maxread=1025, timeout=5)
return lean_repl
# To reliably read multiple json objects from a single byte string where the objects are
# separated by newlines but the content also contains newlines, we treat the byte string
# as a stream using the json-stream python library, and consume from the stream repeatedly until
# we reach the end of the byte array.
#
# The simplest thing to do is just feed json-stream the byte array one byte at a time, but this
# produces errors due to multi-byte unicode characters being split. So, we solve this in another
# simple way: produce chunks up to and including the next '}' byte. This makes sure weird byte sequences
# get sent together and thus decoded correctly.
def json_stream_itr(bstr):
start = 0
for end in range(len(bstr)):
#print(bstr[end:end+1], b'}')
if bstr[end:end+1] == b'}':
yield bstr[start: end + 1]
start = end + 1
def load_mult_json(jsons):
#NOTE: when using the non-canonical input mode and /bin/sh to spawn lean repl,
# sometimes multiple json lines get output! I collect them all into a single
# dictionary to return.
itr = json_stream_itr(jsons)
ps_out = {'messages': []}
while True:
try:
data = json_stream.load(itr, persistent=True)
except StopIteration:
break
data.read_all()
data = json_stream.to_standard_types(data)
for k in data:
# special case: for some reason when their is a single message the key is not plural, and
# is just a string, which is a problem for later when I try to look at the error severity.
if k == 'message':
if data[k].strip().startswith('Lean error:'):
dct = {'severity': 'error', 'data': data[k].replace('Lean error:', '')}
else:
dct = {'severity': 'warning', 'data': data[k]}
print('got unexpected non-error message', dct) #TODO: if these don't occur in practice we can delete this
exit()
ps_out['messages'].append(dct)
elif isinstance(data[k], list) and k in ps_out:
ps_out[k].extend(data[k])
else:
assert k not in ps_out, k +',' +str(ps_out[k])
ps_out[k] = data[k]
#ps_out = json_stream.to_standard_types(ps_out)
#print('yo', ps_out)
#ps_out = json.loads(output)
assert ps_out is not None, 'parsing failed: ' + jsons.decode()
#print('parsed output:', ps_out)
return ps_out
def make_repl_command(def_str, env=None):
jsn = {'cmd': def_str}
if env is not None:
jsn['env'] = env
return json.dumps(jsn)
# This is the standard way to send commands to lean repl using most normal shells in canonical input mode.
# unfortunately, in canonical input mode there is a maximum character limit that can be sent over terminal:
# see https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.send for more details.
# unfortunately this can't be solved by just chunking up the message to send; we're not sure why, but
# lean repl stubbornly insists it has only received the first 1024 (on Mac) characters.
#
# you can use send_command_icanon to handle sending longer strings, although we have found that the messages
# lean repl sends change for some reason, causing some inconsistencies in how we parse successful or failed proofs.
def send_command_zsh(repl, command, env=None, timeout=5, first=False):
rpl_comm = make_repl_command(command, env=env)
#print(rpl_comm)
"""
num_splits = len(rpl_comm)//1024 + 1
for split in range(num_splits):
#print(rpl_comm) # NOTE: uncomment to see everything being sent to lean repl
spl_comm = rpl_comm[split*1024:(split+1)*1024]
print(spl_comm)
#print('sent and expecting:')
#print(len(rpl_comm), rpl_comm)
if split < num_splits - 1:
repl.sendline(spl_comm)
else:
repl.sendline(spl_comm)
repl.expect_exact(rpl_comm+'\r\n')
"""
#print(repl.readline())
#repl.sendline()
#repl.expect_exact('\r\n')
#print('sup', repl.readline())
repl.sendline(rpl_comm)
repl.expect_exact(rpl_comm + '\r\n')
repl.sendline()
repl.expect_exact('\r\n')
_index = repl.expect('env": \d+\}', timeout=timeout)
env_str = repl.match.group().decode()
new_env = int(env_str.split(':')[1].strip()[:-1])
output = repl.before + repl.match.group()
#print('js outp', output)
return load_mult_json(output), new_env
def send_command_icanon(repl, command, env=None, timeout=20, first=False):
#print('sending command:', command)
rpl_comm = make_repl_command(command, env=env)
repl.sendline(rpl_comm + '\n')
if OS == MACOS:
if first:
repl.expect_exact('~>')
first = False
else:
try:
repl.expect_exact('\r\n\r\n')
except pexpect.exceptions.TIMEOUT as e:
print('did not find newlines')
elif OS == LINUX and first:
repl.expect_exact('\r{')
try:
_index = repl.expect('env": \d+\}', timeout=60)
command_sent = True
except pexpect.exceptions.TIMEOUT as e:
raise(e)
print('did not find env in output')
return None, None
env_str = repl.match.group().decode()
new_env = int(env_str.split(':')[1].strip()[:-1])
output = repl.before + repl.match.group()
if OS == LINUX and first:
output = '{'.encode() + output
return load_mult_json(output), new_env
def make_repl_tactic(tac, proofState):
return json.dumps({'tactic': tac, 'proofState': proofState})
def send_tactic(repl, tactic, proofState):
rpl_comm = make_repl_tactic(tactic, proofState)
#repl.sendline(rpl_comm)
#repl.expect_exact(rpl_comm + "\r\n")
#repl.sendline()
#repl.expect_exact("\r\n")
repl.sendline(rpl_comm+'\n')
# the icanon mode sometimes sends a single dict with just one field: 'message'.
# when we get that with a lean error, the tactic failed so we return None
_index = repl.expect('(]})|(\"}\r\n\r\n)', timeout=60)
#ps_str = repl.match.group().decode()
#new_ps = int(ps_str.split(':')[1].strip()[:-1])
output = repl.before + repl.match.group()
#if verbose:
#print('js outp 2', output)
ps_out = load_mult_json(output)
#print('ps out', ps_out)
if 'proofState' not in ps_out:
return None, None
return ps_out, ps_out['proofState']
#except pexpect.exceptions.TIMEOUT:
# print("FAILED DUE TO TIMEOUT")
# return None, None
def get_errs(outp):
return [m for m in outp.get('messages', []) if m.get('severity', 'error') == 'error']