parser
author Tomas Zeman <tzeman@volny.cz>
Tue, 21 Aug 2012 13:01:44 +0200
changeset 41 7a33198be930
parent 35 5a18e00f9ba1
permissions -rw-r--r--
oneaccess.gramar: dial-peers

#!/usr/bin/perl -w

# Copyright (c) 2009, Tomas Zeman <tzeman@volny.cz>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions 
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
$main::VERSION = "1.3-dev";

use strict;
use Parse::RecDescent;
use Data::Dumper;
use Storable;
use Getopt::Std;

my $opts = {};
getopts("do:g:", $opts);

my $grammar_file = $opts->{g};
unless (defined $grammar_file) {
	HELP_MESSAGE();
	exit 1;
}

unless (-f $grammar_file) {
	die "Grammar file $grammar_file does not exit";
}

my $grammar = '';
{
	open G, $grammar_file;
	local $/;
	$grammar = <G>;
	close G;
}

# Enable warnings within the Parse::RecDescent module.
$::RD_ERRORS = 1; # Make sure the parser dies when it encounters an error
$::RD_WARN   = 1; # Enable warnings. This will warn on unused rules &c.
$::RD_HINT   = 1; # Give out hints to help fix problems.

my $parser = Parse::RecDescent->new($grammar);

my $content = '';
{
	local $/;
	$content = <>;
}

$::res = {}; # parse tree result
my $p_res = $parser->file($content);
defined $p_res || die "Parser failed";
my $storable = $opts->{o};
store($::res, $storable) if (defined $storable && length($storable) > 0);
print Dumper $::res if ($opts->{d});


sub main::VERSION_MESSAGE {
	my $fh = shift;
	print $fh "parser version $main::VERSION - Copyright 2009-2012 Tomas Zeman\n";
}

sub main::HELP_MESSAGE {
	print <<EOF;
Usage: parser [ -d ] [ -o data ] -g grammar_file

   -o data	store parse tree into file (using Storable module)
   -d		dump parse tree to stdout
   -g grammar_file
   		file containing parse grammar

EOF
}