#! perl -w
#
# jakoc - compile a Jako source file Parrot assembly file.
#
# by Gregor N. Purdy <gregor@focusresearch.com>
#
# Copyright (C) 2001-2005, The Perl Foundation.
# This program is free software. It is subject to the same license
# as Perl itself.
#
# $Id: jakoc 26450 2008-03-17 20:02:51Z bernhard $
#

use strict;

# perl5.005 complains:
# Can't locate object method "block" via package
# "Jako::Construct::Block::File" at lib/Jako/Construct/Block.pm line 243.

use Carp;
use Data::Dumper;

$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 1;
$Data::Dumper::Quotekeys = 0;

use Jako::Lexer;
use Jako::Parser;
use Jako::Compiler;

use FileHandle;

my $lexer    = Jako::Lexer->new;
my $parser   = Jako::Parser->new;
my $compiler = Jako::Compiler->new;

$lexer->debug(1);
$parser->debug(1);
$compiler->debug(1);

use Getopt::Std;

my %opts;
getopts('ctTx', \%opts);

die "$0: usage: $0 <source>\n" unless @ARGV == 1;
$compiler->file(shift @ARGV);

#
# Tokenize the input, and possibly dump the tokens.
#

$lexer->scan_file($compiler->file);

if ($opts{t}) {
  $lexer->dump;
  exit 0;
}

$parser->tokens($lexer->tokens);
my $root = $parser->parse();

if ($opts{T}) {
  print Dumper $root;
  exit 0;
}

if ($opts{x}) { # -x means "XML"
  eval "use XML::Handler::YAWriter";
  die "Could not find XML::Handler::YAWriter!" if $@;
  my $handler = XML::Handler::YAWriter->new(
    Output => IO::File->new('>-'),
    Pretty => {
      PrettyWhiteIndent  => 1,
      PrettyWhiteNewline => 1,
      CatchEmptyElement  => 1,
      CompactAttrIndent  => 1
    }
  );

  $handler->start_document;
  $root->sax($handler);
  $handler->end_document;
}
elsif ($opts{c}) { # -c means "Check", like with Perl.
  # DO NOTHING
}
else {
  my $fh = FileHandle->new('>-');
  $compiler->compile($root, $fh);
}

exit 0;

#
# End of file.
#
