#!/usr/bin/perl
# Expand sbt-boilerplate templates (*.scala.template) into Scala sources.
# Reimplements the template language of sbt-boilerplate 0.8.0
# (https://github.com/sbt/sbt-boilerplate), which upstream runs from sbt.
#
# Usage: boilerplate SRCDIR OUTDIR
#
#   [N..M#body#sep]  repeat body for i = N..M (default 1..current), join by sep
#                    (default ", "); inside it 0, 1, 2 print i-1, i, i+1
#   ##1              a literal digit inside a repetition
#   \#               a literal #
# The top level is expanded with current = 22, as the sbt plugin does.

use strict;
use warnings;
use File::Find;
use File::Path qw(make_path);
use File::Basename qw(dirname);

my ($src, $out) = @ARGV;
die "usage: $0 SRCDIR OUTDIR\n" unless defined $out && -d $src;

my ($s, $p);    # template text and position

sub fail { die sprintf("%s: parse error at offset %d: %s\n", $_[0], $p, $_[1]) }

# "[" range "#"; returns [start, end] and advances, or undef and keeps $p.
sub expand_start {
    pos($s) = $p;
    if ($s =~ /\G\[(\d{1,2})?\s*\.\.\s*(\d{1,2})?#/gc
        || $s =~ /\G\[()()#/gc) {
        my @r = map { defined $_ && $_ ne '' ? $_ : undef } ($1, $2);
        $p = pos($s);
        return \@r;
    }
    return undef;
}

sub at_expand_start {
    my $save = $p;
    my $r = expand_start();
    $p = $save;
    return defined $r;
}

# A '#' with a ']' somewhere after it ends a literal inside a repetition.
sub at_expand_end {
    return substr($s, $p, 1) eq '#' && index($s, ']', $p + 1) >= 0;
}

sub parse_expand {
    my ($name) = @_;
    my $range = expand_start() or return undef;
    my @els;
    while ($p < length $s) {
        my $two = substr($s, $p, 2);
        if (substr($s, $p, 1) =~ /[012]/) {
            push @els, ['off', substr($s, $p, 1)];
            $p++;
        } elsif ($two ne '\\#' && $two ne '##' && at_expand_start()) {
            push @els, parse_expand($name);
        } elsif ($two ne '\\#' && $two ne '##' && at_expand_end()) {
            last;
        } else {
            my $lit = '';
            while ($p < length $s) {
                if (substr($s, $p, 2) eq '\\#') {
                    $lit .= '#'; $p += 2;
                } elsif (substr($s, $p, 2) eq '##') {
                    my $d = substr($s, $p + 2, 1);
                    fail($name, "'##' must be followed by 0, 1 or 2") unless $d =~ /[012]/;
                    $lit .= $d; $p += 3;
                } elsif (substr($s, $p, 1) =~ /[012]/ || at_expand_start() || at_expand_end()) {
                    last;
                } else {
                    $lit .= substr($s, $p, 1); $p++;
                }
            }
            push @els, ['lit', $lit];
        }
    }
    fail($name, 'empty repetition') unless @els;
    fail($name, "expected '#'") unless substr($s, $p, 1) eq '#';
    $p++;
    my $end = index($s, ']', $p);
    fail($name, "expected ']'") if $end < 0;
    my $sep = substr($s, $p, $end - $p);
    $sep = ', ' if $sep eq '';
    $p = $end + 1;
    return ['exp', $range->[0], $range->[1], $sep, \@els];
}

sub parse_template {
    my ($name) = @_;
    $p = 0;
    my @els;
    while ($p < length $s) {
        if (at_expand_start()) {
            push @els, parse_expand($name);
            next;
        }
        my $lit = '';
        while ($p < length $s && !at_expand_start()) {
            if (substr($s, $p, 2) eq '\\#') {
                $lit .= '#'; $p += 2;
            } else {
                $lit .= substr($s, $p, 1); $p++;
            }
        }
        push @els, ['lit', $lit];
    }
    return \@els;
}

sub generate {
    my ($els, $idx) = @_;
    my $r = '';
    for my $e (@$els) {
        if ($e->[0] eq 'lit') {
            $r .= $e->[1];
        } elsif ($e->[0] eq 'off') {
            $r .= $idx + $e->[1] - 1;
        } else {
            my ($start, $end) = ($e->[1] // 1, $e->[2] // $idx);
            $r .= join $e->[3], map { generate($e->[4], $_) } $start .. $end;
        }
    }
    return $r;
}

my @templates;
find({ no_chdir => 1, wanted => sub { push @templates, $_ if /\.template\z/ } }, $src);
die "$0: no templates in $src\n" unless @templates;

for my $t (sort @templates) {
    (my $rel = substr($t, length($src))) =~ s{^/+}{};
    $rel =~ s/\.template\z//;
    $rel .= '.scala' unless $rel =~ m{\.[^/]*\z};
    open my $in, '<:raw', $t or die "$t: $!\n";
    $s = do { local $/; <$in> };
    close $in;
    my $code = "// auto-generated by sbt-boilerplate\n" . generate(parse_template($t), 22);
    my $dest = "$out/$rel";
    make_path(dirname($dest));
    open my $o, '>:raw', $dest or die "$dest: $!\n";
    print $o $code;
    close $o or die "$dest: $!\n";
}
