#!/usr/bin/env perl

use English;

our $interp;       # current interpreter
our $loader;       # current loader

$match_blank   = qr /^\s*$/o;
$match_comment = qr/^\s*#/o;

$match_interp  = qr/\[(\w+)\]/o;
$match_loader  = qr/^\s* loader \s+ (\S+) \s* $/xo;
$match_fspath  = qr/^\s* (install|build) \s+ (\S+) \s* $/xo;
$match_phase   = qr/^\s* (\w+) \s+ compile \s+ (\w+) \s* $/xo;

my %loaders = (
  arch     => 'PARROT_RUNTIME_FT_ARCH',
  bytecode => 'PARROT_RUNTIME_FT_BYTECODE',
  source   => 'PARROT_RUNTIME_FT_SOURCE',
);

print STDOUT <<BASE_TOP;
/* auto-generated by $PROGRAM_NAME. do not modify this file directly or changes
 * will be lost on the next re-build.
 */

static void
populate_builtin_library_paths( Interp* interp, PMC* lib_paths ) {
    STRING *ns, *entry;
    PMC *loader_table;

BASE_TOP


sub start_new_namespace {
  my $interp = shift();

  print STDERR "$PROGRAM_NAME: translating paths for: $interp\n";

  print STDOUT <<NEW_INTERP;

    /* starting namespace $interp */

    ns = CONST_STRING(interp, "$interp");
    loader_table = get_load_table_for_populate(interp, lib_paths, ns );

NEW_INTERP
}

sub add_search_entry {
  my ( $search_space , $entry ) = @_;
  print STDOUT <<ADD_ENTRY;

    entry = CONST_STRING(interp, "$entry");
    populate_search_table(interp, loader_table, $loader, $search_space, entry );

ADD_ENTRY
}

my $line = 1;

while (<STDIN>) {
  next if ( /$match_blank/ || /$match_comment/ );

  if ( /$match_interp/ ) {
    my ( $interp ) = /$match_interp/;
    start_new_namespace( $interp );
    next;
  }

  if ( /$match_loader/ ) {
    our ( $loader ) = /$match_loader/;

    unless ( exists $loaders{ $loader } ) {
      print "line #$line invalid loader $loader, valid values are: ",
            join('|', keys( %loader )), "\n";

    }

    $loader = $loaders{ $loader };
    next;
  }

  if ( /$match_fspath/ ) {
    my ( undef , $entry ) = /$match_fspath/;
    add_search_entry( 'SEARCH_TABLE_PATH' , $entry );
    next;
  }

  if ( /$match_phase/ ) {
    my ( undef , $phase ) = /$match_phase/;
    add_search_entry( 'SEARCH_TABLE_EXT' , ".$phase" );
    next;
  }

  print STDERR "skipped line #$line, either not recognized or implemented\n";
}
continue {
  $line++;
}

print STDOUT "}\n";
