File size: 6,525 Bytes
8c469fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build source/target training pairs from andstor/defects4j_fixed."""

import argparse
import json
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple

from datasets import Dataset, load_dataset


Record = Dict[str, Any]


def normalize_line_endings(text: str) -> str:
    return text.replace("\r\n", "\n").replace("\r", "\n")


def collapse_whitespace(text: str) -> str:
    return " ".join((text or "").split())


def class_declaration(class_info: Dict[str, Any]) -> str:
    class_name = class_info.get("identifier", "UnknownClass")
    superclass = (class_info.get("superclass") or "").strip()
    interfaces = collapse_whitespace(class_info.get("interfaces", ""))

    declaration = f"public class {class_name}"
    if superclass:
        declaration += f" extends {superclass}"
    if interfaces:
        declaration += f" implements {interfaces}"

    return declaration + " {"


def field_lines(class_info: Dict[str, Any]) -> List[str]:
    fields = class_info.get("fields") or []
    lines: List[str] = []
    for field in fields:
        original = (field.get("original_string") or "").strip()
        if original:
            lines.append(original)
    return lines


def method_signature(method_info: Dict[str, Any]) -> str:
    signature = (method_info.get("full_signature") or "").strip()
    if signature:
        return collapse_whitespace(signature)

    modifiers = collapse_whitespace(method_info.get("modifiers", ""))
    return_type = collapse_whitespace(method_info.get("return", ""))
    identifier = method_info.get("identifier", "unknownMethod")
    parameters = collapse_whitespace(method_info.get("parameters", "()"))

    pieces = [part for part in [modifiers, return_type, f"{identifier}{parameters}"] if part]
    return " ".join(pieces)


def class_key(record: Record) -> Tuple[str, str, str]:
    class_info = record.get("class", {})
    return (
        str(record.get("project_id", "")),
        str(record.get("bug_id", "")),
        str(class_info.get("file", class_info.get("identifier", ""))),
    )


def method_key(method_info: Dict[str, Any]) -> str:
    return method_signature(method_info)


def strip_first_signature_line(method_body: str) -> str:
    body = normalize_line_endings(method_body)
    brace_index = body.find("{")
    if brace_index == -1:
        return body.strip("\n")

    return body[brace_index + 1 :].lstrip("\n").rstrip("\n")


def indent_lines(lines: Iterable[str], spaces: int = 4) -> List[str]:
    prefix = " " * spaces
    return [f"{prefix}{line}" if line else "" for line in lines]


def with_final_class_brace(target: str) -> str:
    cleaned = target.rstrip("\n")
    if not cleaned:
        return "}"

    return f"{cleaned}\n}}"


def build_source(
    class_info: Dict[str, Any],
    constructors: Iterable[str],
    other_methods: Iterable[str],
    focal_signature: str,
) -> str:
    parts: List[str] = [class_declaration(class_info)]

    fields = field_lines(class_info)
    if fields:
        parts.append("\n".join(indent_lines(fields)))

    ctor_lines = [f"{sig};" for sig in constructors if sig]
    if ctor_lines:
        parts.append("\n".join(indent_lines(ctor_lines)))

    method_lines = [f"{sig};" for sig in other_methods if sig]
    if method_lines:
        parts.append("\n".join(indent_lines(method_lines)))

    parts.append(f"    {focal_signature} {{")
    return "\n\n".join(parts)


def build_examples(records: List[Record]) -> List[Dict[str, Any]]:
    grouped: Dict[Tuple[str, str, str], List[Record]] = defaultdict(list)
    for record in records:
        grouped[class_key(record)].append(record)

    examples: List[Dict[str, Any]] = []

    for record in records:
        method_info = record.get("method", {})
        class_info = record.get("class", {})
        body = method_info.get("body", "")
        focal_signature = method_signature(method_info)

        cls_records = grouped[class_key(record)]

        constructors = sorted(
            {
                method_signature(r.get("method", {}))
                for r in cls_records
                if r.get("method", {}).get("constructor")
            }
        )

        focal_sig_key = method_key(method_info)
        other_method_sigs = sorted(
            {
                method_signature(r.get("method", {}))
                for r in cls_records
                if not r.get("method", {}).get("constructor")
                and method_key(r.get("method", {})) != focal_sig_key
            }
        )

        source = build_source(class_info, constructors, other_method_sigs, focal_signature)
        target = with_final_class_brace(strip_first_signature_line(body))

        examples.append(
            {
                "id": record.get("id"),
                "project_id": record.get("project_id"),
                "bug_id": record.get("bug_id"),
                "class_file": class_info.get("file"),
                "method": method_info.get("identifier"),
                "source": source,
                "target": target,
            }
        )

    return examples


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--split",
        default="train",
        help="Dataset split to load (default: train).",
    )
    parser.add_argument(
        "--hub-repo",
        default="defects4j_fixed_runnable",
        help="Hugging Face dataset repo to upload to.",
    )
    parser.add_argument(
        "--output",
        default=None,
        help="Optional output JSONL file path.",
    )
    parser.add_argument(
        "--max-records",
        type=int,
        default=None,
        help="Optional limit for quick smoke tests.",
    )

    args = parser.parse_args()

    ds = load_dataset("andstor/defects4j_fixed", split=args.split)
    records: List[Record] = list(ds)

    if args.max_records is not None:
        records = records[: args.max_records]

    examples = build_examples(records)

    hf_dataset = Dataset.from_list(examples)
    hf_dataset.push_to_hub(args.hub_repo)
    print(f"Uploaded {len(examples)} examples to {args.hub_repo}")

    if args.output:
        output_path = Path(args.output)
        with output_path.open("w", encoding="utf-8") as f:
            for example in examples:
                f.write(json.dumps(example, ensure_ascii=False) + "\n")
        print(f"Wrote {len(examples)} examples to {output_path}")


if __name__ == "__main__":
    main()