harb/tools/push3-transpiler/inject.sh
openhands 34b016a190 fix: Body extraction stops at first shallow closing brace (#809)
Replace the }` heuristic in inject.sh with a brace-depth counter:
start at depth=1 after the opening {, increment on {, decrement on },
stop when depth reaches 0. This correctly handles nested if/else blocks,
loops, and structs that close at 4-space indent inside calculateParams.

Also emit a non-zero exit with a descriptive message if EOF is reached
without finding the matching closing brace.

Add test_inject_extraction.sh covering simple bodies, nested if/else,
multi-level nesting, and the EOF-without-match error case.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 00:21:06 +00:00

67 lines
2.1 KiB
Bash
Executable file

#!/usr/bin/env bash
# inject.sh — Transpile a Push3 file and inject into OptimizerV3.sol
# Usage: bash inject.sh <push3_file> [optimizer_v3_sol]
# Default OptimizerV3.sol: onchain/src/OptimizerV3.sol (relative to repo root)
# Exit codes: 0=success, 1=transpile failed, 2=inject failed
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PUSH3_FILE="${1:?Usage: inject.sh <push3_file> [optimizer_v3_sol]}"
OPTIMIZERV3_SOL="${2:-$REPO_ROOT/onchain/src/OptimizerV3.sol}"
TRANSPILER_OUT="$REPO_ROOT/onchain/src/OptimizerV3Push3.sol"
# Ensure transpiler deps
if [ ! -d "$SCRIPT_DIR/node_modules" ]; then
(cd "$SCRIPT_DIR" && npm install --silent) || exit 1
fi
# 1. Transpile Push3 → OptimizerV3Push3.sol (full contract)
(cd "$SCRIPT_DIR" && npx ts-node src/index.ts "$PUSH3_FILE" "$TRANSPILER_OUT") || exit 1
# 2. Extract function body and inject between BEGIN/END markers in OptimizerV3.sol
python3 - "$TRANSPILER_OUT" "$OPTIMIZERV3_SOL" <<'PYEOF' || exit 2
import sys
push3_path = sys.argv[1]
v3_path = sys.argv[2]
with open(push3_path) as f:
push3 = f.read()
fn_start = push3.find("function calculateParams")
if fn_start == -1:
sys.exit("calculateParams not found in OptimizerV3Push3")
brace_start = push3.find("{", fn_start)
body_start = push3.index("\n", brace_start) + 1
lines = push3[body_start:].split("\n")
body_lines = []
depth = 1
for line in lines:
depth += line.count("{") - line.count("}")
if depth <= 0:
break
body_lines.append(line)
else:
sys.exit("error: calculateParams body: closing brace never found (EOF)")
body = "\n".join(body_lines)
with open(v3_path) as f:
v3 = f.read()
begin_marker = "// ── BEGIN TRANSPILER OUTPUT"
end_marker = "// ── END TRANSPILER OUTPUT"
begin_idx = v3.find(begin_marker)
end_idx = v3.find(end_marker)
if begin_idx == -1 or end_idx == -1:
sys.exit("markers not found in OptimizerV3.sol")
begin_line_end = v3.index("\n", begin_idx) + 1
with open(v3_path, "w") as f:
f.write(v3[:begin_line_end])
f.write(body + "\n")
f.write(v3[end_idx:])
PYEOF