package RecDescent;

use strict;
use warnings;
use Parse::RecDescent;

sub parse {
   my $file = shift();
   my $text = '';

   open(FILE, $file) or return(undef);
   while(<FILE>) {
      $text .= $_ unless(/^#/);
   }
   close(FILE);
   $text .= "\n";

   my $grammar = <<'EOG';
{
  use locale;
}
main: chrono(s)
{ 
  if($text !~ /^\s*$/) {
      $text =~ /^[ \n\t]*(.+)\n/;
      $return = $1;
  } else {
      $return = undef;
  }
}

chrono: '>>' name id(?) nl metadate(s?) event(s?)

event: date date(?) name(?) id(?) nl metadate(s?) description

name: /[\w\t\/\.()"'<> -]*\w/
nl: /\s*\n/
word: /\w+/

id: '{' word '}'

metadate: "!!" metainfo  nl

metainfo: 'keyword' ':' name(s /[;,]/)
        | 'author' ':' name(s /[;,]/)
        | 'lang' ':' word
        | 'local' ':' name
        | 'ref' ':' ref(s /[;,]/)
        | 'isa' ':' class(s /[;,]/)

class: '[' name '|' name ']'

ref: '[' name '|' ref2 ']'
ref2: url
    | idref

idref: '{' /\w+\:\w+/ '}'

url: 'http://' path
   | 'ftp://' path
   | 'img://' path
   | 'file://' path

path: m![\w~\.\/=\-&]+!

date: '[' approx(?) era(?) /\d{1,4}/ date1 ']'
era: /bc/i
approx: /~/

n2: /\d{1,2}/

sepdate: '/' | '-' | ':'
sephour: ':'
sepdt: 'T'
date1: sepdate n2 date2
     | 
date2: sepdate n2 date3
     |
date3: sepdt(?) n2 sephour n2
     |

description: line(s)

line: "\n"
    | text1 text(s?) "\n"

text1: format
     | /[^!>\[\n\t ][^\n\t ]*/

text: format
    | /[^\n\t ]+/

format: '**' /(?:\\\*|[^\n*])+/ '**'
      | '*' /(?:\\\*|[^\n*])+/ '*'
      | ref
      | class

EOG

   $Parse::RecDescent::skip = '[ \t]*';
   my $parser = new Parse::RecDescent($grammar);
   my $c = $parser->main($text);
   warn "parsing parou em $c\n" if(defined $c);
}

1;
