File size: 15,506 Bytes
da653f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
"""Reusable building blocks: paraphrased conditions, return kinds, identifier
pools, and per-language syntax fragments.

Conditions carry both the literal source expression (Python and JS forms) and a
*plain-English paraphrase* used as the flowchart label, satisfying the strict
"no raw code/operators in labels" constraint.
"""

from __future__ import annotations

from dataclasses import dataclass

from engine import CodeBuilder


# --------------------------------------------------------------------------- #
# Conditions
# --------------------------------------------------------------------------- #


@dataclass(frozen=True)
class Cond:
    label: str          # plain-English paraphrase (flowchart label)
    py: str             # python source template
    js: str             # javascript source template

    def code(self, lang: str, **kw) -> str:
        # The Python form (==, !=, % 2 == 0, &&-free) is valid C/C++ too; only
        # JavaScript needs its === / !== form. So cpp/c map to the py form.
        src = self.js if lang == "javascript" else self.py
        return src.format(**kw)


# placeholder {x}: a numeric scalar
NUM1 = [
    Cond("Number is positive?", "{x} > 0", "{x} > 0"),
    Cond("Number is negative?", "{x} < 0", "{x} < 0"),
    Cond("Value is zero?", "{x} == 0", "{x} === 0"),
    Cond("Value is even?", "{x} % 2 == 0", "{x} % 2 === 0"),
    Cond("Value is odd?", "{x} % 2 != 0", "{x} % 2 !== 0"),
]

# placeholders {x},{t}
NUM_T = [
    Cond("Value above threshold?", "{x} > {t}", "{x} > {t}"),
    Cond("Value meets threshold?", "{x} >= {t}", "{x} >= {t}"),
    Cond("Value below limit?", "{x} < {t}", "{x} < {t}"),
    Cond("Value exceeds maximum?", "{x} > {t}", "{x} > {t}"),
    Cond("Value at or under limit?", "{x} <= {t}", "{x} <= {t}"),
]

# placeholder {c}: a collection
COLL = [
    Cond("Collection is empty?", "len({c}) == 0", "{c}.length === 0"),
    Cond("Collection has items?", "len({c}) > 0", "{c}.length > 0"),
]

# placeholders {c},{t}
COLL_T = [
    Cond("Collection longer than limit?", "len({c}) > {t}", "{c}.length > {t}"),
    Cond("Enough elements gathered?", "len({c}) >= {t}", "{c}.length >= {t}"),
]

# placeholder {v}: maybe-missing value
NULL = [
    Cond("Value is missing?", "{v} is None", "{v} == null"),
    Cond("Value is present?", "{v} is not None", "{v} != null"),
]

# placeholder {s}: a string
STR1 = [
    Cond("Text is empty?", '{s} == ""', '{s} === ""'),
]
# placeholders {s},{t}
STR_T = [
    Cond("Text longer than limit?", "len({s}) > {t}", "{s}.length > {t}"),
]
# placeholders {s},{p}
STR_P = [
    Cond("Text starts with prefix?", "{s}.startswith({p})", "{s}.startsWith({p})"),
]

# placeholders {a},{b}
EQ = [
    Cond("Values are equal?", "{a} == {b}", "{a} === {b}"),
    Cond("Values differ?", "{a} != {b}", "{a} !== {b}"),
    Cond("Matches target?", "{a} == {b}", "{a} === {b}"),
]

# placeholder {f}: a boolean flag
FLAG = [
    Cond("Flag is set?", "{f}", "{f}"),
    Cond("Input is invalid?", "not {f}", "!{f}"),
    Cond("Condition holds?", "{f}", "{f}"),
]

# placeholders {c},{target}
CONTAINS = [
    Cond("Item present in collection?", "{target} in {c}", "{c}.includes({target})"),
]

# placeholders {k},{c}
KEY_IN = [
    Cond("Key exists in map?", "{k} in {c}", "{k} in {c}"),
    Cond("Key is absent?", "{k} not in {c}", "!({k} in {c})"),
]


# --------------------------------------------------------------------------- #
# Return kinds
# --------------------------------------------------------------------------- #


@dataclass(frozen=True)
class Ret:
    py: str
    js: str
    label: str

    def code(self, lang: str) -> str:
        return self.py if lang == "python" else self.js


RET = {
    "zero": Ret("return 0", "return 0;", "Return zero"),
    "one": Ret("return 1", "return 1;", "Return one"),
    "neg1": Ret("return -1", "return -1;", "Return not found"),
    "true": Ret("return True", "return true;", "Return true"),
    "false": Ret("return False", "return false;", "Return false"),
    "none": Ret("return None", "return null;", "Return nothing"),
    "total": Ret("return total", "return total;", "Return the total"),
    "count": Ret("return count", "return count;", "Return the count"),
    "result": Ret("return result", "return result;", "Return the result"),
    "results": Ret("return results", "return results;", "Return collected results"),
    "value": Ret("return value", "return value;", "Return the value"),
    "index": Ret("return i", "return i;", "Return the index"),
    "best": Ret("return best", "return best;", "Return the maximum"),
    "current": Ret("return current", "return current;", "Return current value"),
    "empty_list": Ret("return []", "return [];", "Return empty list"),
    "average": Ret("return average", "return average;", "Return the average"),
    "name": Ret("return name", "return name;", "Return the name"),
}


def ret_status(active: bool):
    """A pair of opposite plain-English status returns plus their literals."""
    return active


STATUS_PAIRS = [
    ('"active"', '"inactive"', "Return active status", "Return inactive status"),
    ('"valid"', '"invalid"', "Return valid result", "Return invalid result"),
    ('"granted"', '"denied"', "Return access granted", "Return access denied"),
    ('"pass"', '"fail"', "Return passing grade", "Return failing grade"),
    ('"high"', '"low"', "Return high priority", "Return low priority"),
    ('"ok"', '"error"', "Return ok status", "Return error status"),
]

CLASSIFY_TRIPLES = [
    ('"high"', '"medium"', '"low"', "Return high band", "Return medium band", "Return low band"),
    ('"positive"', '"zero"', '"negative"', "Return positive sign", "Return zero sign", "Return negative sign"),
    ('"gold"', '"silver"', '"bronze"', "Return gold tier", "Return silver tier", "Return bronze tier"),
    ('"adult"', '"teen"', '"child"', "Return adult group", "Return teen group", "Return child group"),
]


# --------------------------------------------------------------------------- #
# Identifier pools
# --------------------------------------------------------------------------- #

FN_VALIDATE = ["validate_input", "check_status", "is_eligible", "verify_token",
               "validate_age", "check_access", "is_valid_user", "validate_score",
               "check_permission", "is_ready"]
FN_MATH = ["compute_total", "calculate_sum", "find_max", "compute_average",
           "factorial", "running_total", "accumulate", "power_of", "clamp_value",
           "tally"]
FN_SEARCH = ["find_item", "search_list", "locate_index", "find_first",
             "contains_value", "lookup", "index_of", "first_match"]
FN_PROCESS = ["process_items", "filter_values", "transform_data", "normalize",
              "aggregate", "summarize", "parse_records", "build_report",
              "collect_valid", "scan_entries"]
FN_STRING = ["format_name", "parse_input", "sanitize", "truncate_text",
             "slugify", "count_words", "trim_value", "label_for"]
FN_GAME = ["update_score", "apply_damage", "check_win", "next_level",
           "move_player", "spawn_enemy", "resolve_turn"]

ALL_FN_GROUPS = {
    "validate": FN_VALIDATE,
    "math": FN_MATH,
    "search": FN_SEARCH,
    "process": FN_PROCESS,
    "string": FN_STRING,
    "game": FN_GAME,
}


def camel(name: str) -> str:
    head, *rest = name.split("_")
    return head + "".join(w.capitalize() for w in rest)


def fn_name(rng, group: str, lang: str) -> str:
    name = rng.choice(ALL_FN_GROUPS[group])
    return camel(name) if lang in ("javascript", "cpp") else name


COLLECTIONS = ["items", "nums", "values", "data", "records", "entries",
               "scores", "elements", "rows", "tokens", "results", "arr"]
SCALARS = ["value", "n", "x", "amount", "score", "count", "level", "size",
           "weight", "age", "balance", "qty"]
STRINGS = ["text", "name", "word", "line", "title", "label", "code", "key"]
FLAGS = ["valid", "ready", "active", "enabled", "found", "ok", "allowed"]
LOOPVARS = ["i", "idx", "j", "k"]
ITEMVARS = ["item", "entry", "row", "element", "node", "record", "value"]
TARGETS = ["target", "needle", "wanted", "goal", "query"]
KEYS = ["key", "name", "field", "user_id", "code"]

PREFIXES = ['"a"', '"x_"', '"tmp"', '"id_"', '"v"']

# filler text
COMMENTS = [
    "early bail out on bad input",
    "guard against invalid state",
    "main processing path",
    "accumulate the running figure",
    "walk through every element",
    "handle the edge case first",
    "keep scanning until matched",
    "fall through to the default",
    "normalize before comparing",
    "short circuit when possible",
    "TODO revisit this branch",
    "defensive check",
]
DOCSTRINGS = [
    "Return a status for the given input.",
    "Compute and return the aggregate value.",
    "Find and return the matching element.",
    "Validate the arguments and proceed.",
    "Process the collection and report back.",
    "Helper used by the main pipeline.",
]


# --------------------------------------------------------------------------- #
# Language syntax fragments
# --------------------------------------------------------------------------- #


PY_NAME, JS_NAME, CPP_NAME, C_NAME = "python", "javascript", "cpp", "c"

# Abstract parameter/return kinds -> concrete C / C++ types.
_TYPES = {
    CPP_NAME: {"int": "int", "num": "int", "bound": "int", "bool": "bool",
               "str": "std::string", "str_ref": "const std::string&",
               "coll": "std::vector<int>", "coll_ref": "const std::vector<int>&",
               "void": "void"},
    C_NAME: {"int": "int", "num": "int", "bound": "int", "bool": "int",
             "str": "const char*", "str_ref": "const char*",
             "coll": "int*", "coll_ref": "int*", "void": "void"},
}


class Lang:
    def __init__(self, name: str):
        self.name = name
        self.py = name == PY_NAME
        self.braces = name in (JS_NAME, CPP_NAME, C_NAME)
        self.semi = ";" if self.braces else ""
        self.indent_unit = "    " if self.py else "  "
        self.comment_prefix = "# " if self.py else "// "

    def builder(self) -> CodeBuilder:
        return CodeBuilder(self.indent_unit, self.comment_prefix)

    # types & signatures ----------------------------------------------------- #
    def _type(self, kind: str, by_ref: bool = False) -> str:
        if by_ref and kind in ("str", "coll"):
            kind = kind + "_ref"
        return _TYPES[self.name][kind]

    def sig(self, params) -> str:
        """params: list of name (=> int) or (kind, name). C collections gain a
        companion length parameter."""
        norm = [(p if isinstance(p, tuple) else ("int", p)) for p in params]
        if self.name in (PY_NAME, JS_NAME):
            return ", ".join(n for _, n in norm)
        out = []
        for kind, name in norm:
            out.append(f"{self._type(kind, by_ref=True)} {name}")
            if self.name == C_NAME and kind == "coll":
                out.append(f"int {name}_len")
        return ", ".join(out)

    # headers ---------------------------------------------------------------- #
    def def_header(self, fn: str, params, ret: str = "int") -> str:
        s = self.sig(params)
        if self.py:
            return f"def {fn}({s}):"
        if self.name == JS_NAME:
            return f"function {fn}({s}) {{"
        return f"{self._type(ret)} {fn}({s}) {{"  # cpp / c

    def if_header(self, cond: str) -> str:
        return f"if {cond}:" if self.py else f"if ({cond}) {{"

    def elif_header(self, cond: str) -> str:
        return f"elif {cond}:" if self.py else f"}} else if ({cond}) {{"

    def else_header(self) -> str:
        return "else:" if self.py else "} else {"

    def while_header(self, cond: str) -> str:
        return f"while {cond}:" if self.py else f"while ({cond}) {{"

    def forrange(self, cb: CodeBuilder, indent: int, ivar: str, n) -> int:
        if self.py:
            return cb.add(f"for {ivar} in range({n}):", indent)
        decl = "let" if self.name == JS_NAME else "int"
        return cb.add(f"for ({decl} {ivar} = 0; {ivar} < {n}; {ivar}++) {{", indent)

    def foreach(self, cb: CodeBuilder, indent: int, item: str, coll: str, ivar: str = "i"):
        """Emit a for-each loop; return (line_no, element_expression)."""
        if self.py:
            return cb.add(f"for {item} in {coll}:", indent), item
        if self.name == JS_NAME:
            return cb.add(f"for (const {item} of {coll}) {{", indent), item
        if self.name == CPP_NAME:
            return cb.add(f"for (int {item} : {coll}) {{", indent), item
        ln = cb.add(f"for (int {ivar} = 0; {ivar} < {coll}_len; {ivar}++) {{", indent)
        return ln, f"{coll}[{ivar}]"

    # length & lang-specific conditions ------------------------------------- #
    def length(self, c: str) -> str:
        return {PY_NAME: f"len({c})", JS_NAME: f"{c}.length",
                CPP_NAME: f"{c}.size()", C_NAME: f"{c}_len"}[self.name]

    def cond_empty(self, c: str) -> str:
        return {PY_NAME: f"len({c}) == 0", JS_NAME: f"{c}.length === 0",
                CPP_NAME: f"{c}.empty()", C_NAME: f"{c}_len == 0"}[self.name]

    def cond_nonempty(self, c: str) -> str:
        return {PY_NAME: f"len({c}) > 0", JS_NAME: f"{c}.length > 0",
                CPP_NAME: f"!{c}.empty()", C_NAME: f"{c}_len > 0"}[self.name]

    def cond_null(self, v: str) -> str:
        return {PY_NAME: f"{v} is None", JS_NAME: f"{v} == null",
                CPP_NAME: f"{v} == nullptr", C_NAME: f"{v} == NULL"}[self.name]

    def cond_notnull(self, v: str) -> str:
        return {PY_NAME: f"{v} is not None", JS_NAME: f"{v} != null",
                CPP_NAME: f"{v} != nullptr", C_NAME: f"{v} != NULL"}[self.name]

    def cond_flag(self, f: str) -> str:
        return f

    def cond_notflag(self, f: str) -> str:
        return f"not {f}" if self.py else f"!{f}"

    # literals --------------------------------------------------------------- #
    def true(self) -> str:
        return "True" if self.py else ("1" if self.name == C_NAME else "true")

    def false(self) -> str:
        return "False" if self.py else ("0" if self.name == C_NAME else "false")

    def null(self) -> str:
        return {PY_NAME: "None", JS_NAME: "null",
                CPP_NAME: "nullptr", C_NAME: "NULL"}[self.name]

    def and_op(self) -> str:
        return "and" if self.py else "&&"

    def eq(self) -> str:
        return "===" if self.name == JS_NAME else "=="

    # statements ------------------------------------------------------------- #
    def declare(self, name: str, value: str, kind: str = "int") -> str:
        if self.py:
            return f"{name} = {value}"
        if self.name == JS_NAME:
            return f"let {name} = {value};"
        return f"{self._type(kind)} {name} = {value};"  # cpp / c

    def reassign(self, name: str, value: str) -> str:
        return f"{name} = {value}{self.semi}"

    def aug(self, a: str, op: str, b: str) -> str:
        return f"{a} {op}= {b}{self.semi}"

    def stmt(self, expr: str) -> str:
        return f"{expr}{self.semi}"

    def ret(self, expr: str) -> str:
        return f"return {expr}{self.semi}"

    def break_(self) -> str:
        return f"break{self.semi}"

    def continue_(self) -> str:
        return f"continue{self.semi}"

    # block close (python uses indentation, no brace) ----------------------- #
    def close(self, cb: CodeBuilder, indent: int) -> None:
        if self.braces:
            cb.add("}", indent)