File size: 21,336 Bytes
d9b105f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | """Receive a described program through the existing work ledger and compiler.
Project nouns are kept verbatim. The existing parts decide which described
stages connect; missing destination/evidence/meaning is filled on later turns.
"""
import ast
import copy
import hashlib
import json
from pathlib import Path
import re
import sys
import tempfile
_OBJECT = r'(?:program|tool|script|app|application|workflow)'
_START = re.compile(r'(?is)^\s*(?:(?:can|could|would)\s+you\s+)?(?:please\s+)?(?:(?:build|create|make|write)\s+|I\s+(?:want|need|would like)\s+(?:you\s+to\s+(?:build|create|make|write)\s+)?)' +
r'(?:(?![.;\n]).){0,100}?(?:\b' + _OBJECT + r'\b|[\w./-]+\.py\b)')
_DEST = re.compile(r'(?is)^(?:(?:call|name)\s+(?:it|the\s+' + _OBJECT + r')\s+|(?:save|write)\s+it\s+as\s+)[`\"\']?([\w./-]+\.py)[`\"\']?[.!]?$')
_CHECK = re.compile(r'(?is)^(?:(?:check|test|verify)(?:\s+it)?\s+(?:with|using)|run)\s+`([^`]+)`[.!]?$')
_REVISION = re.compile(r'(?is)^\s*(?:instead\s*[,;:]?\s*|I meant\s+|actually\s*[,;:]?\s*)(.+)$')
def _native_opening(reading):
graph = (reading or {}).get('graph') or {}
if graph.get('act') != 'request':
return None
parents = {link.get('to') for link in graph.get('links', []) if link.get('kind') == 'relative'}
return next((node for node in graph.get('nodes', []) if node.get('id') in parents and
node.get('speech_act') == 'request' and node.get('polarity') == 'positive' and
node.get('predicate', {}).get('lemma') in {'build', 'create', 'make', 'write', 'want', 'need'}), None)
def _delegated_reasons(text, reading):
"""Exact reason nodes remain owned here while executable parts read actions."""
result = copy.deepcopy(reading or {})
graph = result.get('graph') or {}
nodes = {node.get('id'): node for node in graph.get('nodes', [])}
delegated, reasons = [], []
for link in graph.get('links', []):
if link.get('kind') != 'reason':
continue
node, connector = nodes.get(link.get('from'), {}), link.get('connector') or {}
pieces = []
for atom in (connector, node):
span = atom.get('span')
if not isinstance(span, list) or len(span) != 2 or atom.get('source', graph.get('original')) != text:
pieces = []; break
lo, hi = span
if not isinstance(lo, int) or not isinstance(hi, int) or not 0 <= lo <= hi <= len(text) or text[lo:hi] != atom.get('text'):
pieces = []; break
pieces.append({'span': list(span), 'owner': 'reason', 'text': text[lo:hi], 'node': node.get('id')})
if pieces:
for piece in pieces:
if not any(existing['span'] == piece['span'] for existing in delegated):
delegated.append(piece)
reason = ' '.join(piece['text'] for piece in pieces)
if reason not in reasons:
reasons.append(reason)
result['project_delegated'] = delegated
return result, reasons
def _masked(text):
literals = {}
def keep(match):
key = 'O7LITERAL%dTOKEN' % len(literals)
literals[key] = match.group()
return key
masked = re.sub(r'`[^`]*`|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', keep, text)
return masked, literals
def _restore(text, literals):
for key, value in literals.items():
text = text.replace(key, value)
return text
def clauses(text):
masked, literals = _masked(text)
return [_restore(piece.strip(' \t\r\n.;'), literals) for piece in
re.split(r'[;\n]+|(?<=[.!?])\s+(?=[A-Z])', masked) if piece.strip(' \t\r\n.;')]
def _literal(text):
text = text.strip().rstrip('.').strip()
try:
value = json.loads(text)
except (ValueError, TypeError):
value = ast.literal_eval(text)
json.dumps(value, allow_nan=False)
return value
def example(text):
"""Examples supply answers independently of the compiler's emitted moves."""
masked, literals = _masked(text)
head = re.match(r'(?is)^(?:for|with)\s+(?:the\s+)?input\s+(.+)$', masked)
filehead = re.match(r'(?is)^when\s+([\w./-]+)\s+(?:contains|has)\s+(.+)$', masked)
bare = not head and not filehead
# any clause "<value> (should|must)? give|return|produce|expect|=> <value>" ("100 should give 212") is an example
# when both sides read as exact values; nothing else in the clause is guessed (11-17)
body = masked if bare else (head.group(1) if head else filehead.group(2))
for divider in re.finditer(r'(?i),?\s+(?:(?:it|the\s+' + _OBJECT + r')\s+)?(?:should\s+|must\s+)?(?:return|produce|give|expect)s?\s+|\s*=>\s*', body):
try:
value = _literal(_restore(body[:divider.start()], literals))
expected = _literal(_restore(body[divider.end():], literals))
if filehead:
if not isinstance(value, str):
continue
return {'files': {filehead.group(1): value}, 'expected': expected}
return {'input': value, 'expected': expected}
except (ValueError, SyntaxError, TypeError):
continue
if bare:
# several examples in one clause ("2 gives 7 and 10 gives 23"): every part must read as an example on its own
parts = [p for p in re.split(r'(?i)\s*(?:;|,|\band\b)\s*', _restore(masked, literals)) if p.strip()]
if len(parts) > 1:
read = [example(p) for p in parts]
if all(r and 'input' in r for r in read):
return dict(read[0], more=read[1:])
return None
return {'hole': 'Give the input and expected result as literal values, for example: For input [1, 2], return 3.'}
def _directive(text, reading=None):
# Only grammatical wrappers and verb inflection are changed. The compiler
# must still connect every remaining stage; no requested behavior is guessed.
t = re.sub(r'(?is)^(?:it|the\s+' + _OBJECT + r')\s+(?:should|must|will|can)\s+', '', text.strip())
first = re.match(r'([A-Za-z]+)\b', t)
if first:
word = first.group(1)
native = next((node.get('predicate', {}).get('lemma') for node in (reading or {}).get('graph', {}).get('nodes', [])
if node.get('predicate', {}).get('text', '').lower() == word.lower() and node.get('predicate', {}).get('lemma')), None)
if native:
word = native
elif word.endswith('ies'):
word = word[:-3] + 'y'
elif word.endswith('s') and not word.endswith(('ss', 'us')):
word = word[:-1]
t = word + t[first.end():]
return t
def _stages(text, reading=None):
import make
masked, literals = _masked(text)
# A coordinated requested action stays a separate obligation, even when the
# old compiler would otherwise accept only its first verb.
masked = re.sub(r'\s+and\s+', '; ', masked, flags=re.I)
return [_directive(_restore(stage, literals), reading) for stage in make.steps_of(masked)]
def _is_continuation(text, intent):
if not intent:
return False
t = text.strip()
if _DEST.match(t) or _CHECK.match(t) or example(t) is not None or _REVISION.match(t):
return True
if re.fullmatch(r'[\w./-]+\.py[.!]?', t) and not intent.get('file'):
return True
return bool(re.match(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?|drop\s+(?:the\s+)?requirement\s+|replace\s+|change\s+|because\s+|'
r'(?:it|the\s+\w+)\s+(?:should|must|needs? to|remembers?|retains?|starts?)\b)', t))
def owns_turn(text, work=None, reading=None):
"""Conversation can defer an actual build/fill while retaining ordinary questions."""
if re.match(r'(?i)^\s*(?:why|how|what|explain|discuss|compare|tell me)\b', text) or text.rstrip().endswith('?') and not (_START.match(text) or _native_opening(reading)):
return False
return accepts(text, kept=work, reading=reading)
def accepts(text, root=None, kept=None, reading=None):
intent = (kept or {}).get('build_intent')
if _is_continuation(text, intent):
return True
try:
import program_prose
if program_prose.receive(text, kept=(intent or {}).get('interactive'), reading=reading) is not None:
return True
except ImportError:
pass
if not _START.match(text) and not _native_opening(reading):
return False
if re.match(r'(?i)^\s*(?:what if|explain|discuss|compare)\b', text):
return False
# Explicit existing table-project command syntax retains its owner.
import project
if project.ENTRY.search(text):
return False
# A build over a named table with an outcome someone can see is the table
# project's request (its store, sha reuse and judges): the same ownership
# work_tasks.accepts states, applied before this receiver takes the turn.
if project.DATA.search(text) and project.is_project(text, None, root):
return False
mask, unused = _masked(text)
if re.match(r'(?is)^\s*(?:build|create|make|write)\s+[\w./-]+\.py\s+from\s+[\w./-]+\.(?:steps|txt|md)\b', mask):
return False # the earlier description-file connection keeps its owner
return bool(re.search(r'(?i)\b(?:that|which|to)\b|:\s*\S|\b(?:browser|interactive)\b', mask))
def receive(text, kept=None, reading=None):
prior = copy.deepcopy(kept) if kept else None
if prior and (prior.get('original') == text or prior.get('turns') and prior['turns'][-1]['text'] == text):
return prior
part_reading, native_reasons_received = _delegated_reasons(text, reading)
try:
import program_prose
interactive = program_prose.receive(text, kept=(prior or {}).get('interactive'), reading=part_reading)
except ImportError:
interactive = None
fresh = bool(_START.match(text) or _native_opening(reading)) and not _REVISION.match(text)
fresh = fresh or bool(interactive and interactive.get('original') == text and (prior or {}).get('original') != text)
intent = {'version': 1, 'original': text, 'turns': [], 'mode': 'pipeline', 'file': None,
'stages': [], 'examples': [], 'reasons': [], 'constraints': [], 'requirements': [], 'unbound': []} if fresh or not prior else prior
intent['turns'].append({'text': text, 'reading': copy.deepcopy(reading)})
if reading and reading.get('graph'):
intent.setdefault('graphs', []).append(copy.deepcopy(reading['graph']))
if interactive is not None:
intent['mode'], intent['interactive'] = 'interactive', interactive
for reason in native_reasons_received:
if reason not in intent['reasons']:
intent['reasons'].append(reason)
correction = _REVISION.match(text)
pieces = clauses(correction.group(1) if correction else text)
if fresh and pieces:
destinations = re.findall(r'(?<![\w])([\w./-]+\.py)\b', pieces[0])
if len(set(destinations)) == 1:
intent['file'] = destinations[0]
graph = (reading or {}).get('graph') or {}
reason_ids = {link.get('from') for link in graph.get('links', []) if link.get('kind') == 'reason'}
native_reasons = {node.get('text', '').strip(' .;') for node in graph.get('nodes', []) if node.get('id') in reason_ids}
for piece in pieces:
record = {'id': 'I%d' % (len(intent['requirements']) + 1), 'text': piece, 'kind': 'behavior'}
record['reading_nodes'] = [node['id'] for node in graph.get('nodes', []) if node.get('text') and node['text'] in piece]
dest = _DEST.match(piece)
drop = re.match(r'(?is)^drop\s+(?:the\s+)?requirement\s+(.+)$', piece)
if drop:
named = drop.group(1).strip('`"\' ')
matching = [item for item in intent['unbound'] if item['text'].strip(' .;') == named.strip(' .;')]
stage_matches = [stage for stage in intent['stages'] if stage == named]
if len(matching) + len(stage_matches) == 1:
intent['unbound'] = [item for item in intent['unbound'] if item not in matching]
intent['stages'] = [stage for stage in intent['stages'] if stage not in stage_matches]
intent.setdefault('revisions', []).append({'before': named, 'after': None, 'request': piece})
record['kind'] = 'revision'
else:
intent['unbound'].append({'text': piece, 'hole': 'Name one exact kept requirement to drop.'})
elif not dest and not intent.get('file') and re.fullmatch(r'[\w./-]+\.py', piece):
intent['file'] = piece; record.update(kind='destination', field='file')
elif dest:
intent['file'] = dest.group(1); record.update(kind='destination', field='file')
elif _CHECK.match(piece):
intent['check'] = _CHECK.match(piece).group(1); record.update(kind='evidence', field='check')
elif example(piece) is not None:
received = example(piece)
if 'hole' in received:
intent['unbound'].append({'text': piece, 'hole': received['hole'], 'field': 'examples'})
else:
intent['unbound'] = [item for item in intent['unbound'] if item.get('field') != 'examples']
# An explicitly revised example replaces its same input only.
for one in [dict((k, v) for k, v in received.items() if k != 'more')] + list(received.get('more') or []):
key = {k: v for k, v in one.items() if k != 'expected'}
intent['examples'] = [old for old in intent['examples'] if {k: v for k, v in old.items() if k != 'expected'} != key]
intent['examples'].append(one)
record.update(kind='evidence', field='examples')
elif re.match(r'(?i)^because\b', piece) or piece in native_reasons:
intent['reasons'].append(piece); record['kind'] = 'reason'
elif re.search(r"(?i)\b(?:do not|don't|must not|never|without)\b", piece):
intent['constraints'].append({'text': piece}); record['kind'] = 'constraint'
elif intent['mode'] == 'interactive':
record['owner'] = 'interactive'
if interactive is None:
intent['unbound'].append({'text': piece, 'hole': 'The browser program has no connected meaning for this requirement yet: ' + piece,
'field': 'behavior'})
else:
body = piece
header = _START.match(body)
native_header = _native_opening(reading)
if not header and native_header and body.startswith(native_header['text']):
body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[len(native_header['text']):])
record.update(kind='goal', native_owner=native_header['id'])
if header:
prefix = header.group()
output = re.findall(r'[\w./-]+\.py\b', prefix)
if len(output) == 1:
intent['file'] = output[0]
body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[header.end():])
# Named project purpose is retained in the original; every
# remaining requested stage must be connected below.
record['kind'] = 'goal'
masked, literals = _masked(body)
reason = re.search(r'(?i)\s+because\s+', masked)
if reason:
intent['reasons'].append(_restore(masked[reason.start():].strip(), literals))
body = _restore(masked[:reason.start()], literals)
change = re.match(r'(?is)^(?:replace|change)\s+(.+?)\s+(?:with|to)\s+(.+)$', body)
if change:
old, new = change.groups()
matches = [i for i, stage in enumerate(intent['stages']) if stage.lower() == old.strip('`"\' ').lower()]
if len(matches) == 1:
intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': new, 'request': piece})
intent['stages'][matches[0]:matches[0]+1] = _stages(new.strip('`"\' '), reading)
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the exact stage to replace; the earlier stages remain kept.'})
elif correction:
stages = _stages(body, reading)
if len(stages) == 1:
verb = stages[0].split()[0].lower() if stages[0].split() else ''
matches = [i for i, stage in enumerate(intent['stages']) if stage.split()[0].lower() == verb]
if len(matches) == 1:
intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': stages[0], 'request': piece})
intent['stages'][matches[0]] = stages[0]
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the stage this correction replaces; the full correction is kept.'})
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the stage or complete description this correction replaces.'})
elif body.strip():
body = re.sub(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?\s*)', '', body)
for stage in _stages(body, reading):
# a stage that names the destination ("call it temps.py") or gives examples ("2 gives 7") is that
# destination or evidence, not a program step; a stage mixing them is read part by part
parts = [p.strip().rstrip('.') for p in re.split(r',\s*', stage) if p.strip()]
kinds = [('dest', _DEST.match(p)) if _DEST.match(p) else ('example', example(p)) for p in parts]
if all(found and (kind == 'dest' or 'input' in found) for kind, found in kinds):
for kind, found in kinds:
if kind == 'dest':
intent['file'] = found.group(1)
else:
intent['examples'] += [dict((k, v) for k, v in found.items() if k != 'more')] + list(found.get('more') or [])
else:
intent['stages'].append(stage)
intent['requirements'].append(record)
return intent
def semantic(intent):
result = {key: copy.deepcopy(intent.get(key)) for key in ('mode', 'file', 'stages', 'examples', 'check', 'constraints', 'unbound')}
if intent.get('interactive'):
result['interactive'] = {key: copy.deepcopy(intent['interactive'].get(key)) for key in ('contract', 'holes', 'ready')}
return result
def holes(intent):
found = [{'kind': 'meaning', 'text': item['hole'], 'received': item['text']} for item in intent.get('unbound', [])]
if not intent.get('file'):
found.append({'kind': 'destination', 'text': 'What should the program file be called? For example, call it report.py.'})
if intent['mode'] == 'interactive':
found.extend(dict(item, text=item.get('needed') or item['text'], received=item.get('text'))
for item in intent['interactive'].get('holes', []))
else:
if not intent.get('stages'):
found.append({'kind': 'description', 'text': 'Describe what the program should do to its input.'})
if not intent.get('examples') and not intent.get('check'):
found.append({'kind': 'behavior', 'text': 'Give an input and its expected result, or name the existing behavior check. The described stages are kept.'})
return found
def build(root, intent, runenv=None):
import work_tasks as work
missing = holes(intent)
if missing:
raise work.WorkHole('project-input', ' '.join(item['text'] for item in missing), fields=missing)
if intent['mode'] == 'interactive':
import work_bindings
result = work_bindings.execute('interactive_program', {'contract': intent['interactive']['contract'], 'file': intent['file']}, root, runenv)
else:
import program_steps
args = {'description': '; '.join(intent['stages']), 'file': intent['file'], 'examples': intent.get('examples') or []}
if intent.get('check') and not intent.get('examples'):
args['check'] = intent['check']
result = program_steps.build(root, args, runenv)
else:
with tempfile.TemporaryDirectory(prefix='oracle7-received-check-') as directory:
request = Path(directory) / 'examples.json'
request.write_text(json.dumps({'source': str(work._path(root, intent['file'])), 'examples': intent['examples']}, allow_nan=False), encoding='utf-8')
example_check = [sys.executable, '-I', str(Path(__file__).with_name('program_examples.py')), str(request)]
args['check'] = intent.get('check') or example_check
if intent.get('check'):
args['postcondition'] = example_check
result = program_steps.build(root, args, runenv)
result['received'] = {'original': intent['original'], 'requirements': intent['requirements'], 'reasons': intent['reasons'],
'examples': intent['examples'], 'revisions': intent.get('revisions', [])}
return result
|