"""Connect the existing step compiler to the selected work environment.""" import ast import hashlib import os from pathlib import Path import re import textwrap import threading _LOCK = threading.RLock() def build(root, args, runenv=None): import make import work_tasks as work root = Path(root).resolve() description = args.get('description') destination = args.get('file') check = args.get('check') postcondition = args.get('postcondition') if not isinstance(description, str) or not description.strip() or not isinstance(destination, str): raise work.WorkHole('input', 'receive the complete program description and its destination file') if not isinstance(check, (str, list)) or not check: raise work.WorkHole('postcondition', 'name a behavior check for the described program before calling it complete') target = work._path(root, destination) received_target = target.read_bytes() if target.is_file() else None for name, expected in args.get('source_files', {}).items(): if hashlib.sha256(work._path(root, name).read_bytes()).hexdigest() != expected: raise work.WorkHole('changed-input', 'the received program description changed: ' + name) if target.suffix != '.py': raise work.WorkHole('input', 'the existing step compiler emits a Python file') work.guard_write(target) from work_synthesis import _evidence_files, _changed_evidence evidence_files = _evidence_files(root, check, postcondition) items = work.inventory(root) if items.get('clipped'): raise work.WorkHole('inventory', 'open a smaller repository folder so the function inventory is complete') records, modules, hashes, proposed, unbound = [], {}, {}, {}, [] def index_source(name, raw, prepared=False): try: tree = ast.parse(raw) except (SyntaxError, UnicodeError): return modules[name] = tree if not prepared: hashes[name] = hashlib.sha256(raw).hexdigest() records[:] = [record for record in records if record['path'] != name] for node in tree.body: if not isinstance(node, ast.FunctionDef) or node.name.startswith('_'): continue positional = node.args.posonlyargs + node.args.args required = len(positional) - len(node.args.defaults) if node.args.vararg or node.args.kwarg or any(v is None for v in node.args.kw_defaults): continue records.append({'name': node.name, 'path': name, 'kind': 'def', 'args': [x.arg for x in positional], 'required': required, 'doc': ast.get_docstring(node) or ''}) for name in items['files']: if name.endswith('.py') and work._path(root, name) != target: index_source(name, work._path(root, name).read_bytes()) def matches(step): found = [r for r in records if re.search(r'\b' + re.escape(r['name']) + r'\b', step)] qualified = [r for r in found if r['path'] in step] return qualified or found filler = {'apply', 'use', 'compute', 'calculate', 'call', 'run', 'take', 'get', 'return', 'it', 'them', 'this', 'that', 'the', 'result', 'on', 'to', 'from', 'in', 'of', 'a', 'an'} def described(step): wanted = set(re.findall(r'[A-Za-z_]+', step.lower())) - filler if len(wanted) < 2: return [] # A repository part's own documented face supplies vocabulary. Every # requested word must occur there; ties remain holes, not guessed calls. return [record for record in records if record['doc'] and wanted <= set(re.findall(r'[A-Za-z_]+', record['doc'].lower()))] def find(step): found = matches(step) by_description = not found if by_description: found = described(step) if len(found) > 1: raise work.WorkHole('binding', 'several repository functions match this step: ' + step) if found and not by_description: remaining = step.replace(found[0]['path'], '').replace(found[0]['name'], '') if set(re.findall(r'[A-Za-z_]+', remaining.lower())) - filler: unbound.append(step) return [] # a named function cannot silently consume extra requested behavior if not found: unbound.append(step) return [(record, 1.0) for record in found] find.required = lambda record: record['required'] used = dict(args.get('source_files') or {}) def read(record): tree = modules[record['path']] top = {} imports = [] for node in tree.body: if isinstance(node, (ast.Import, ast.ImportFrom)): if isinstance(node, ast.ImportFrom) and node.level: raise work.WorkHole('binding', 'relative-import function reuse needs its package context: ' + record['path']) imports.append(node) elif isinstance(node, (ast.FunctionDef, ast.ClassDef)): top[node.name] = node elif isinstance(node, (ast.Assign, ast.AnnAssign)): for child in ast.walk(node): if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store): top[child.id] = node todo, selected = [record['name']], {} while todo: name = todo.pop() if name not in top or name in selected: continue node = top[name] if any(isinstance(child, (ast.Global, ast.Nonlocal)) for child in ast.walk(node)): raise work.WorkHole('binding', 'this function changes module scope; receive it as an explicit effect part') selected[name] = node todo += [child.id for child in ast.walk(node) if isinstance(child, ast.Name) and child.id in top] nodes = sorted({id(n): n for n in imports + list(selected.values())}.values(), key=lambda n: n.lineno) body = '\n\n'.join(ast.unparse(node) for node in nodes) # A local closure keeps each source module's constants/import aliases # separate when several repository functions are composed together. source = 'def %s(x):\n%s\n return %s(x)' % ( record['name'], textwrap.indent(body, ' '), record['name']) if record['path'] not in proposed: used[record['path']] = hashes[record['path']] return source, set() # The existing compiler's function/parameter registers are module globals. # Serialize this connection; make.compose itself also owns the shared lock. with _LOCK: source, plan = make.compose(description, find, read) prepared = None if plan.gaps and unbound: import compose_code as composer import work_synthesis as synthesis tests = composer.read_tests(root) targets = [] for name, evidence in tests.items(): filename = evidence['module'].replace('.', '/') + '.py' # Only an explicitly named, otherwise unqualified missing step can # receive these examples. Never fall back to unrelated test targets. relevant = [step for step in unbound if re.search(r'\b' + re.escape(name) + r'\b', step) and not (set(re.findall(r'[A-Za-z_]+', step.replace(filename, '').replace(name, '').lower())) - filler)] if not relevant: continue identities = {composer.read_tests(root, only=[test_file]).get(name, {}).get('module') for test_file in evidence['files']} identities.discard(None) if len(identities) != 1: raise work.WorkHole('binding', 'the missing function name has examples in several modules: ' + name) path = work._path(root, filename) if path == target: raise work.WorkHole('binding', 'the missing helper and parent program need distinct destinations: ' + name) if name in synthesis._definitions(path.read_text(encoding='utf-8') if path.is_file() else ''): continue targets.append({'file': filename, 'function': name, 'mode': 'create', 'examples': evidence['examples'], 'test_files': evidence['files']}) step_of = {} received_examples = [e for e in (args.get('examples') or []) if isinstance(e, dict) and 'input' in e and 'expected' in e] if not targets and received_examples and len(set(unbound)) == 1: # The request's own examples ("100 should give 212") describe its one unconnected step: the composer # constructs that step as a helper from them, checked with its parent under the original check (11-17). # The examples are recorded as supplied assistance; a step they do not determine stays a hole. step = unbound[0] words = [w for w in re.findall(r'[a-z]+', step.lower()) if w not in filler][:5] or ['step'] name = '_'.join(words) helper = Path(destination).stem + '_parts.py' if name not in synthesis._definitions(work._path(root, helper).read_text(encoding='utf-8') if work._path(root, helper).is_file() else ''): targets.append({'file': helper, 'function': name, 'mode': 'create', 'examples': [((e['input'],), e['expected'], None) for e in received_examples], 'test_files': []}) step_of[name] = step if targets: changed = _changed_evidence(root, evidence_files) if changed: raise work.WorkHole('evidence', 'the received behavior evidence changed before helper preparation', changed=changed) try: prepared = synthesis.prepare(root, description, [{k: v for k, v in t.items()} for t in targets], check, postcondition, runenv, require_failing_baseline=False) proposed.update(prepared['sources']) for name, text in proposed.items(): index_source(name, text.encode('utf-8'), prepared=True) # a step constructed from the request's own examples is named by the helper built for it for function, step in step_of.items(): if step in description: description = description.replace(step, function) unbound.clear() with _LOCK: source, plan = make.compose(description, find, read) synthesis.validate_prepared(root, prepared) except work.WorkHole as exc: exc.hole['parent'] = {'request': description, 'file': destination, 'check': check} exc.hole['missing_steps'] = list(dict.fromkeys(unbound)) raise if plan.gaps: raise work.WorkHole('composition', 'Unconnected program steps: ' + '; '.join(plan.gaps), parent={'request': description, 'file': destination, 'check': check}, obligations=[{'step': step, 'receiver': 'work_synthesis', 'needs': 'a named callable with examples, or a connected existing part'} for step in dict.fromkeys(unbound)], prepared_helpers=[item['function'] for item in prepared['received']] if prepared else []) for name, expected in used.items(): path = work._path(root, name) if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != expected: raise work.WorkHole('changed-input', 'the source function changed while composing: ' + name) before_bytes = target.read_bytes() if target.is_file() else None if before_bytes != received_target: raise work.WorkHole('changed-input', 'the destination changed while its described program was composed') before = target.read_text(encoding='utf-8') if target.is_file() else None edit = {'path': destination, 'content': source} if before is not None: edit['before'] = before edits = (prepared['edits'] if prepared else []) + [edit] originals = dict(prepared['original_bytes'] if prepared else {}, **{destination: before_bytes}) published = dict(proposed, **{destination: source}) result = work.edit_transaction(root, edits, check=check, runenv=runenv, postcondition=postcondition, witness=True) changed = _changed_evidence(root, dict(evidence_files, **used)) if changed: restored = {name: work._rollback_owned(work._path(root, name), {'before': originals[name], 'after': text.replace('\n', os.linesep).encode('utf-8')}) for name, text in published.items()} raise work.WorkHole('evidence', 'the received source or behavior check changed while building; reread it before completion', changed=changed, restored=restored) result['trace'] = list(plan.trace) result['source_files'] = used result['evidence_files'] = evidence_files result['description'] = description if prepared: result['construction'] = synthesis.admit_prepared(root, prepared) return result