|
| 1 | +"""Alternative call/leaf and switch layouts, with bounded work and explicit control-flow guards.""" |
| 2 | +import re |
| 3 | + |
| 4 | +from .integer_repair_support import IDENT, INTEGER, NUMBER, edit, integer, view |
| 5 | +from .pattern_repairs import close |
| 6 | + |
| 7 | + |
| 8 | +def call_statement(text, start): |
| 9 | + """A direct call statement (optionally assigned), with nested argument parentheses kept intact.""" |
| 10 | + hit = re.match(rf'\s*(?:{IDENT}\s*=\s*)?({IDENT})\s*\(', text[start:]) |
| 11 | + if not hit or hit[1] in {'if', 'for', 'while', 'switch', 'sizeof', 'return'}: |
| 12 | + return None |
| 13 | + end = close(text, start+hit.end()-1) |
| 14 | + tail = re.match(r'\s*;', text[end:]) if end else None |
| 15 | + return (start+hit.start(), end+tail.end()) if tail else None |
| 16 | + |
| 17 | + |
| 18 | +def flat_assignments(text): |
| 19 | + return bool(re.fullmatch(rf'(?:\s*{IDENT}\s*=(?!=)[^;{{}}]*;)+\s*', text)) and not re.search( |
| 20 | + r'\b(?:return|goto|break|continue|case|default|for|while|do)\b', text) |
| 21 | + |
| 22 | + |
| 23 | +def terminal_case(text): |
| 24 | + terminal = re.search(r'\b(?:break\s*;|return\b[^;{}]*;|goto\s+'+IDENT+r'\s*;)\s*$', text) |
| 25 | + if not terminal or text[:terminal.start()].count('{') != text[:terminal.start()].count('}'): |
| 26 | + return False |
| 27 | + prefix = text[:terminal.start()].rstrip() |
| 28 | + return not prefix or prefix[-1] in ';}' |
| 29 | + |
| 30 | + |
| 31 | +def controls(part): |
| 32 | + """Braced controls and their ends; an unrecognised scope is a boundary for leaf traversal.""" |
| 33 | + result = {} |
| 34 | + for pos in range(part.opening+1, part.end-1): |
| 35 | + if part.clean[pos] != '{': |
| 36 | + continue |
| 37 | + prefix = part.clean[:pos].rstrip() |
| 38 | + kind = 'else' if re.search(r'\belse$', prefix) else '' |
| 39 | + if prefix.endswith(')'): |
| 40 | + depth = 1 |
| 41 | + start = len(prefix)-2 |
| 42 | + while start >= 0 and depth: |
| 43 | + depth += (prefix[start] == ')')-(prefix[start] == '(') |
| 44 | + start -= 1 |
| 45 | + hit = re.search(r'\b(if|switch|for|while)\s*$', prefix[:start+1]) |
| 46 | + kind = hit[1] if hit else '' |
| 47 | + if re.search(r'\bdo$', prefix): |
| 48 | + kind = 'do' |
| 49 | + end = close(part.clean, pos, '{', '}') |
| 50 | + if end: |
| 51 | + result[end-1] = (pos, kind) |
| 52 | + return result |
| 53 | + |
| 54 | + |
| 55 | +def leaf_transfer(part, start, scopes): |
| 56 | + """Follow closing if arms past their else arms, stopping at one explicit terminal transfer.""" |
| 57 | + pos = start |
| 58 | + while True: |
| 59 | + while pos < part.end and part.clean[pos].isspace(): |
| 60 | + pos += 1 |
| 61 | + if part.clean[pos:pos+1] != '}': |
| 62 | + break |
| 63 | + if pos not in scopes or scopes[pos][1] not in {'if', 'else'}: |
| 64 | + return None |
| 65 | + pos += 1 |
| 66 | + other = re.match(r'\s*else\s*{', part.clean[pos:]) |
| 67 | + if other: |
| 68 | + end = close(part.clean, pos+other.end()-1, '{', '}') |
| 69 | + if not end: |
| 70 | + return None |
| 71 | + pos = end |
| 72 | + elif re.match(r'\s*else\b', part.clean[pos:]): |
| 73 | + return None # shortcut: leave unbraced/else-if continuation to a full CFG parser |
| 74 | + terminal = re.match(rf'\s*(?:goto\s+({IDENT})|return(?:\s+[^;{{}}]+)?|break)\s*;', part.clean[pos:]) |
| 75 | + return (pos, pos+terminal.end(), terminal[1]) if terminal else None |
| 76 | + |
| 77 | + |
| 78 | +def variants(source, name): |
| 79 | + part = view(source, name) |
| 80 | + if not part: |
| 81 | + return [] |
| 82 | + result = [] |
| 83 | + clean = part.clean |
| 84 | + # Distribute a call following an if/else which only selects scalar arguments. Retain assignments: |
| 85 | + # they may still be read afterwards, and evaluating an RHS twice would change its meaning. |
| 86 | + for hit in re.finditer(r'\bif\s*\(', part.body): |
| 87 | + cond_end = close(clean, part.opening+1+hit.end()-1) |
| 88 | + arm = re.match(r'\s*{', clean[cond_end:]) if cond_end else None |
| 89 | + if not arm: |
| 90 | + continue |
| 91 | + left = cond_end+arm.end()-1 |
| 92 | + left_end = close(clean, left, '{', '}') |
| 93 | + other = re.match(r'\s*else\s*{', clean[left_end:]) if left_end else None |
| 94 | + if not other: |
| 95 | + continue |
| 96 | + right = left_end+other.end()-1 |
| 97 | + right_end = close(clean, right, '{', '}') |
| 98 | + if not right_end or not all(flat_assignments(clean[a+1:b-1]) for a, b in [(left, left_end), (right, right_end)]): |
| 99 | + continue |
| 100 | + call = call_statement(clean, right_end) |
| 101 | + if not call: |
| 102 | + continue |
| 103 | + statement = source[call[0]:call[1]] |
| 104 | + result.append(('branch_call', edit(source, [(left_end-1, left_end-1, statement), |
| 105 | + (right_end-1, right_end-1, statement), (*call, '')]))) |
| 106 | + if sum(family == 'branch_call' for family, _ in result) >= 4: |
| 107 | + break |
| 108 | + # Inline a leaf with its terminal transfer, never a label whose following code would fall through. |
| 109 | + # Duplicate local names could change lookup at the new site, so leave those functions alone. |
| 110 | + decls = list(re.finditer(rf'(?:^|[;{{}}])\s*(?!goto\b|return\b|break\b|continue\b)' |
| 111 | + rf'(?:{IDENT}\s+)+\**\s*({IDENT})\s*(?=[;=,\[])', part.body)) |
| 112 | + declarations = [decl[1] for decl in decls] |
| 113 | + nested = any(part.body[:decl.start(1)].count('{') != part.body[:decl.start(1)].count('}') for decl in decls) |
| 114 | + if not nested and len(declarations) == len(set(declarations)): |
| 115 | + scopes = controls(part) |
| 116 | + # Unbraced loops can change a copied break's destination too; don't reason through them. |
| 117 | + unbraced = False |
| 118 | + for loop in re.finditer(r'\b(?:for|while)\s*\(', part.body): |
| 119 | + loop_start = part.opening+1+loop.start() |
| 120 | + if loop[0].startswith('while') and any(kind == 'do' and ending < loop_start |
| 121 | + and not clean[ending+1:loop_start].strip() for ending, (_, kind) in scopes.items()): |
| 122 | + continue # the latch of a braced do/while is not a second, unbraced loop |
| 123 | + loop_end = close(clean, part.opening+1+loop.end()-1) |
| 124 | + if loop_end and not re.match(r'\s*{', clean[loop_end:]): |
| 125 | + unbraced = True |
| 126 | + |
| 127 | + def break_scope(pos): |
| 128 | + enclosing = [(opening, ending) for ending, (opening, kind) in scopes.items() |
| 129 | + if opening < pos < ending and kind in {'switch', 'for', 'while', 'do'}] |
| 130 | + return max(enclosing, default=None) |
| 131 | + |
| 132 | + for label in re.finditer(rf'\b({IDENT})\s*:(?!:)', part.body): |
| 133 | + start = part.opening+1+label.end() |
| 134 | + call = call_statement(clean, start) |
| 135 | + if not call: |
| 136 | + continue |
| 137 | + terminal = leaf_transfer(part, call[1], scopes) |
| 138 | + if not terminal: |
| 139 | + continue |
| 140 | + transfer_start, end, destination = terminal |
| 141 | + leaf = source[start:call[1]]+source[transfer_start:end] |
| 142 | + if destination == label[1]: |
| 143 | + continue |
| 144 | + for jump in re.finditer(rf'\bgoto\s+{re.escape(label[1])}\s*;', part.body): |
| 145 | + pos = part.opening+1+jump.start() |
| 146 | + if start <= pos < end: |
| 147 | + continue |
| 148 | + if re.search(r'\bbreak\b', clean[transfer_start:end]) and ( |
| 149 | + unbraced or break_scope(pos) is None or break_scope(pos) != break_scope(start)): |
| 150 | + continue |
| 151 | + result.append(('goto_leaf', edit(source, [(pos, part.opening+1+jump.end(), '{'+leaf+'}')])) ) |
| 152 | + if sum(family == 'goto_leaf' for family, _ in result) >= 4: |
| 153 | + break |
| 154 | + if sum(family == 'goto_leaf' for family, _ in result) >= 4: |
| 155 | + break |
| 156 | + for switch in re.finditer(r'\bswitch\s*\(', part.body): |
| 157 | + condition = close(clean, part.opening+1+switch.end()-1) |
| 158 | + arm = re.match(r'\s*{', clean[condition:]) if condition else None |
| 159 | + if not arm: |
| 160 | + continue |
| 161 | + opening = condition+arm.end()-1 |
| 162 | + end = close(clean, opening, '{', '}') |
| 163 | + if not end: |
| 164 | + continue |
| 165 | + inside = clean[opening+1:end-1] |
| 166 | + labels = [hit for hit in re.finditer(rf'\b(?:case\s+(-?{NUMBER})|default)\s*:', inside) |
| 167 | + if inside[:hit.start()].count('{') == inside[:hit.start()].count('}')] |
| 168 | + if not labels or inside[:labels[0].start()].strip(): |
| 169 | + continue |
| 170 | + # Reject non-literal/range labels, not merely the subset our regex understands. |
| 171 | + all_labels = [hit for hit in re.finditer(r'\b(?:case\b[^:]*|default)\s*:', inside) |
| 172 | + if inside[:hit.start()].count('{') == inside[:hit.start()].count('}')] |
| 173 | + if len(labels) != len(all_labels): |
| 174 | + continue |
| 175 | + if not any(label[1] is None or integer(label[1].lstrip('-')) == 0 for label in labels): |
| 176 | + result.append(('switch_layout', edit(source, [(opening+1, opening+1, '\ncase 0: break;\n')]))) |
| 177 | + starts = [] |
| 178 | + pending = labels[0].start() |
| 179 | + valid = True |
| 180 | + for index, label in enumerate(labels): |
| 181 | + stop = labels[index+1].start() if index+1 < len(labels) else len(inside) |
| 182 | + code = inside[label.end():stop] |
| 183 | + if not code.strip(): |
| 184 | + continue # grouped labels travel with their one body |
| 185 | + # Only block-scoped declarations can move with a case. No fallthrough or cross-case labels. |
| 186 | + if re.search(rf'\b(?:{INTEGER}|void|float|double)\s*\**\s*{IDENT}', code): |
| 187 | + valid = False |
| 188 | + break |
| 189 | + if not terminal_case(code): |
| 190 | + valid = False |
| 191 | + break |
| 192 | + starts.append((pending, stop)) |
| 193 | + pending = stop |
| 194 | + if not valid or not 2 <= len(starts) <= 6: |
| 195 | + continue |
| 196 | + chunks = [source[opening+1+a:opening+1+b] for a, b in starts] |
| 197 | + orders = [list(range(rotation, len(chunks)))+list(range(rotation)) for rotation in range(1, len(chunks))] |
| 198 | + orders += [list(reversed(range(len(chunks))))] |
| 199 | + for order in orders[:6]: |
| 200 | + result.append(('switch_layout', edit(source, [(opening+1+starts[0][0], opening+1+starts[-1][1], |
| 201 | + ''.join(chunks[index] for index in order))]))) |
| 202 | + break # bounded per function, not factorial permutations of every nested switch |
| 203 | + return list(dict.fromkeys(result)) |
0 commit comments