#!/usr/bin/perl
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2024 Jan Engelhardt
#
# Usage: selective-preprocess -a 15 -b 15 <x.cpp g++ -E -x c++ -
# 1-based line numbers! a..b is inclusive!
# So for expanding a single line, a=b.
# Because of "-" to gcc, you need "-x c++".

use Getopt::Long;
use strict;
use warnings;
use IPC::Open2;

&Getopt::Long::Configure(qw(bundling posix_default pass_through));
my($from, $to, $fromexp) = (0, 0, 0);
&GetOptions("a=i" => \$from, "b=i" => \$to);
my @lines = <STDIN>;

my($cld_out, $cld_in);
my $pid = open2($cld_out, $cld_in, @ARGV);
# g++-15/clang++-18 is known to suppress output until input is complete,
# might be different for other preprocessors, and thus might need
# nonblocking IO.
--$from;
for (my $i = 0; $i < $from; ++$i) {
	print $cld_in $lines[$i];
	print $lines[$i];
}
close($cld_in);
while (<$cld_out>) {
	++$fromexp;
}
close($cld_out);

$pid = open2($cld_out, $cld_in, @ARGV);
for (my $i = 0; $i < $to; ++$i) {
	print $cld_in $lines[$i];
}
close($cld_in);
for (my $i = 0; $i < $fromexp; ++$i) {
	<$cld_out>;
}
while (<$cld_out>) {
	print;
}

for (my $i = $to; $i < scalar(@lines); ++$i) {
	print $lines[$i];
}
