File size: 13,374 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
"""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