DateTime::Format::Builder::Parser - Parser creation


DateTime-Format-Builder documentation Contained in the DateTime-Format-Builder distribution.

Index


Code Index:

NAME

Top

DateTime::Format::Builder::Parser - Parser creation

SYNOPSIS

Top

    my $class = 'DateTime::Format::Builder::Parser';
    my $parser = $class->create_single_parser( %specs );

DESCRIPTION

Top

This is a utility class for DateTime::Format::Builder that handles creation of parsers. It is to here that Builder delegates most of its responsibilities.

CONSTRUCTORS

Top

METHODS

Top

There are two sorts of methods in this class. Those used by parser implementations and those used by Builder. It is generally unlikely the user will want to use any of them.

They are presented, grouped according to use.

Parameter Handling (implementations)

These methods allow implementations to have validation of their arguments in a standard manner and due to Parser's impelementation, these methods also allow Parser to determine which implementation to use.

Common parameters

These parameters appear for all parser implementations. These are primarily documented in the main docs.

params

    my $params = $self->params();
    validate( @_, $params );

Returns declared parameters and common parameters in a hashref suitable for handing to Params::Validate's validate function.

params_all

    my $all_params = $self->params_all();

Returns a hash of all the valid options. Not recommended for general use.

valid_params

    __PACKAGE__->valid_params( %params );

Arguments are as per Params::Validate's validate function. This method is used to declare what your valid arguments are in a parser specification.

whose_params

    my $class = whose_params( $key );

Internal function which merely returns to which class a parameter is unique. If not unique, returns undef.

Organising and Creating Parsers

create_single_parser

This takes a single specification and returns a coderef that is a parser that suits that specification. This is the end of the line for all the parser creation methods. It delegates no further.

If a coderef is specified, then that coderef is immediately returned (it is assumed to be appropriate).

The single specification (if not a coderef) can be either a hashref or a hash. The keys and values must be as per the specification.

It is here that any arrays of callbacks are unified. It is also here that any parser implementations are used. With the spec that's given, the keys are looked at and whichever module is the first to have a unique key in the spec is the one to whom the spec is given.

Note: please declare a valid_params argument with an uppercase letter. For example, if you're writing DateTime::Format::Builder::Parser::Fnord, declare a parameter called Fnord. Similarly, DTFBP::Strptime should have Strptime and DTFBP::Regex should have Regex. These latter two don't for backwards compatibility reasons.

The returned parser will return either a DateTime object or undef.

merge_callbacks

Produce either undef or a single coderef from either undef, an empty array, a single coderef or an array of coderefs

create_multiple_parsers

Given the options block (as made from create_parser()) and a list of single parser specifications, this returns a coderef that returns either the resultant DateTime object or undef.

It first sorts the specifications using sort_parsers() and then creates the function based on what that returned.

sort_parsers

This takes the list of specifications and sorts them while turning the specifications into parsers. It returns two values: the first is a hashref containing all the length based parsers. The second is an array containing all the other parsers.

If any of the specs are not code or hash references, then it will call croak().

Code references are put directly into the 'other' array. Any hash references without length keys are run through create_single_parser() and the resultant parser is placed in the 'other' array.

Hash references with length keys are run through create_single_parser(), but the resultant parser is used as the value in the length hashref with the length being the key. If two or more parsers have the same length specified then an error is thrown.

create_parser

create_class() is mostly a wrapper around create_parser() that does loops and stuff and calls create_parser() to create the actual parsers.

create_parser() takes the parser specifications (be they single specifications or multiple specifications) and returns an anonymous coderef that is suitable for use as a method. The coderef will call croak() in the event of being unable to parse the single string it expects as input.

The simplest input is that of a single specification, presented just as a plain hash, not a hashref. This is passed directly to create_single_parser() with the return value from that being wrapped in a function that lets it croak() on failure, with that wrapper being returned.

If the first argument to create_parser() is an arrayref, then that is taken to be an options block (as per the multiple parser specification documented earlier).

Any further arguments should be either hashrefs or coderefs. If the first argument after the optional arrayref is not a hashref or coderef then that argument and all remaining arguments are passed off to create_single_parser() directly. If the first argument is a hashref or coderef, then it and the remaining arguments are passed to create_multiple_parsers().

The resultant coderef from calling either of the creation methods is then wrapped in a function that calls croak() in event of failure or the DateTime object in event of success.

FINDING IMPLEMENTATIONS

Top

Parser automatically loads any parser classes in @INC.

To be loaded automatically, you must be a DateTime::Format::Builder::Parser::XXX module.

To be invisible, and not loaded, start your class with a lower class letter. These are ignored.

WRITING A PARSER IMPLEMENTATION

Top

Naming your parser

Create a module and name it in the form DateTime::Format::Builder::Parser::XXX where XXX is whatever you like, so long as it doesn't start with a lower case letter.

Alternatively, call it something completely different if you don't mind the users explicitly loading your module.

I'd recommend keeping within the DateTime::Format::Builder namespace though --- at the time of writing I've not given thought to what non-auto loaded ones should be called. Any ideas, please email me.

Declaring specification arguments

Call <DateTime::Format::Builder::Parser-valid_params()>> with Params::Validate style arguments. For example:

   DateTime::Format::Builder::Parser->valid_params(
       params => { type => ARRAYREF },
       Regex  => { type => SCALARREF, callbacks => {
          'is a regex' => sub { ref(shift) eq 'Regexp' }
       }}
   );

Start one of the key names with a capital letter. Ideally that key should match the XXX from earlier. This will be used to help identify which module a parser specification should be given to.

The key names on_match, on_fail, postprocess, preprocess, label and length are predefined. You are recommended to make use of them. You may ignore length as sort_parsers takes care of that.

Define create_parser

A class method of the name create_parser that does the following:

Its arguments are as for a normal method (i.e. class as first argument). The other arguments are the result from a call to Params::Validate according to your specification (the valid_params earlier), i.e. a hash of argument name and value.

The return value should be a coderef that takes a date string as its first argument and returns either a DateTime object or undef.

Callbacks

It is preferred that you support some callbacks to your parsers. In particular, preprocess, on_match, on_fail and postprocess. See the main Builder docs for the appropriate placing of calls to the callbacks.

SUPPORT

Top

Support for this module is provided via the datetime@perl.org email list. See http://lists.perl.org/ for more details.

Alternatively, log them via the CPAN RT system via the web or email:

    http://perl.dellah.org/rt/dtbuilder
    bug-datetime-format-builder@rt.cpan.org

This makes it much easier for me to track things and thus means your problem is less likely to be neglected.

THANKS

Top

See DateTime::Format::Builder.

LICENCE AND COPYRIGHT

Top

AUTHOR

Top

Iain Truskett <spoon@cpan.org>

SEE ALSO

Top

datetime@perl.org mailing list.

http://datetime.perl.org/

perl, DateTime, DateTime::Format::Builder.

Params::Validate.

DateTime::Format::Builder::Parser::generic, DateTime::Format::Builder::Parser::Dispatch, DateTime::Format::Builder::Parser::Quick, DateTime::Format::Builder::Parser::Regex, DateTime::Format::Builder::Parser::Strptime.


DateTime-Format-Builder documentation Contained in the DateTime-Format-Builder distribution.
package DateTime::Format::Builder::Parser;
use strict;
use vars qw( $VERSION );
use Carp qw( croak );
use Params::Validate qw(
    validate SCALAR CODEREF UNDEF ARRAYREF
);
use Scalar::Util qw( weaken );

$VERSION = '0.77';

sub on_fail
{
    my ($self, $input, $parent) = @_;
    my $maker = $self->maker;
    if ( $maker and $maker->can( 'on_fail' ) ) {
        $maker->on_fail( $input );
    } else {
        croak __PACKAGE__.": Invalid date format: $input";
    }
}

sub no_parser
{
    croak "No parser set for this parser object.";
}

sub new
{
    my $class = shift;
    $class = ref($class)||$class;
    my $i = 0;
    my $self = bless {
        on_fail => \&on_fail,
        parser => \&no_parser,
    }, $class;

    return $self;
}

sub maker { $_[0]->{maker} }

sub set_maker
{
    my $self  = shift;
    my $maker = shift;

    $self->{maker} = $maker;
    weaken $self->{maker}
        if ref $self->{maker};

    return $self;
}

sub fail
{
    my ($self, $parent, $input) = @_;
    $self->{on_fail}->( $self, $input, $parent );
}

sub parse
{
    my ( $self, $parent, $input, @args ) = @_;
    my $r = $self->{parser}->( $parent, $input, @args );
    $self->fail( $parent, $input ) unless defined $r;
    $r;
}

sub set_parser
{
    my ($self, $parser) = @_;
    $self->{parser} = $parser;
    $self;
}

sub set_fail
{
    my ($self, $fail) = @_;
    $self->{on_fail} = $fail;
    $self;
}

my @callbacks = qw( on_match on_fail postprocess preprocess );

{

    my %params = (
	common => {
	    length	=> {
		type      => SCALAR|ARRAYREF,
		optional  => 1,
		callbacks => {
		    'is an int' => sub { ref $_[0] ? 1 : $_[0] !~ /\D/ },
		    'not empty' => sub { ref $_[0] ? @{$_[0]} >= 1 : 1 },
		}
	    },

	    # Stuff used by callbacks
	    label	=> { type => SCALAR,	optional => 1 },
	    ( map { $_ => { type => CODEREF|ARRAYREF, optional => 1 } } @callbacks ),
	},
    );

    sub params
    {
	my $self = shift;
	my $caller = ref $self || $self;
	return { map { %$_ } @params{ $caller, 'common' } }
    }

    my $all_params;
    sub params_all
    {
	return $all_params if defined $all_params;
	my %all_params = map { %$_ } values %params;
	$_->{optional} = 1 for values %all_params;
	$all_params = \%all_params;
    }

    my %inverse;
    sub valid_params
    {
	my $self = shift;
	my $from = (caller)[0];
	my %args = @_;
	$params{ $from } = \%args;
	for (keys %args)
	{
	    # %inverse contains keys matching all the
	    # possible params; values are the class if and
	    # only if that class is the only one that uses
	    # the given param.
	    $inverse{$_} = exists $inverse{$_} ? undef : $from;
	}
	undef $all_params;
	1;
    }

    sub whose_params
    {
	my $param = shift;
	return $inverse{$param};
    }
}

sub create_single_object
{
    my ( $self ) = shift;
    my $obj = $self->new;
    my $parser = $self->create_single_parser( @_ );

    $obj->set_parser( $parser );
}

sub create_single_parser
{
    my $class = shift;
    return $_[0] if ref $_[0] eq 'CODE'; # already code
    @_ = %{ $_[0] } if ref $_[0] eq 'HASH'; # turn hashref into hash
    # ordinary boring sort
    my %args = validate( @_, params_all() );

    # Determine variables for ease of reference.
    for (@callbacks)
    {
	$args{$_} = $class->merge_callbacks( $args{$_} ) if $args{$_};
    }

    # Determine parser class
    my $from;
    for ( keys %args )
    {
	$from = whose_params( $_ );
	next if (not defined $from) or ($from eq 'common');
	last;
    }
    croak "Could not identify a parsing module to use." unless $from;

    # Find and call parser creation method
    my $method = $from->can( "create_parser" )
	or croak "Can't create a $_ parser (no appropriate create_parser method)";
    my @args = %args;
    %args = validate( @args, $from->params() );
    $from->$method( %args );
}

sub merge_callbacks
{
    my $self = shift;

    return unless @_; # No arguments
    return unless $_[0]; # Irrelevant argument
    my @callbacks = @_;
    if (@_ == 1)
    {
	return $_[0] if ref $_[0] eq 'CODE';
	@callbacks = @{ $_[0] } if ref $_[0] eq 'ARRAY';
    }
    return unless @callbacks;

    for (@callbacks)
    {
	croak "All callbacks must be coderefs!" unless ref $_ eq 'CODE';
    }

    return sub {
	my $rv;
	my %args = @_;
	for my $cb (@callbacks)
	{
	    $rv = $cb->( %args );
	    return $rv unless $rv;
	    # Ugh. Symbiotic. All but postprocessor return the date.
	    $args{input} = $rv unless $args{parsed};
	}
	$rv;
    };
}

sub create_multiple_parsers
{
    my $class = shift;
    my ($options, @specs) = @_;

    my $obj = $class->new;

    # Organise the specs, and transform them into parsers.
    my ($lengths, $others) = $class->sort_parsers( $options, \@specs );

    # Merge callbacks if any.
    for ( 'preprocess' ) {
	$options->{$_} = $class->merge_callbacks(
	    $options->{$_}
	) if $options->{$_};
    }
    # Custom fail method?
    $obj->set_fail( $options->{on_fail} ) if exists $options->{on_fail};
    # Who's our maker?
    $obj->set_maker( $options->{maker} ) if exists $options->{maker};

    # We don't want to save the whole options hash as a closure, since
    # that can cause a circular reference when $options->{maker} is
    # set.
    my $preprocess = $options->{preprocess};

    # These are the innards of a multi-parser.
    my $parser = sub {
	my ($self, $date, @args) = @_;
	return unless defined $date;

	# Parameters common to the callbacks. Pre-prepared.
	my %param = (
	    self => $self,
	    ( @args ? (args => \@args) : () ),
	);

	my %p;
	# Preprocess and potentially fill %p
	if ($preprocess)
	{
	    $date = $preprocess->(
		input => $date, parsed => \%p, %param
	    );
	}

	# Find length parser
	if (%$lengths)
	{
	    my $length = length $date;
	    my $parser = $lengths->{$length};
	    if ($parser)
	    {
		# Found one, call it with _copy_ of %p
		my $dt = $parser->( $self, $date, { %p }, @args );
		return $dt if defined $dt;
	    }
	}
	# Or calls all others, with _copy_ of %p
	for my $parser (@$others)
	{
	    my $dt = $parser->( $self, $date, { %p }, @args );
	    return $dt if defined $dt;
	}
	# Failed, return undef.
	return;
    };
    $obj->set_parser( $parser );
}

sub sort_parsers
{
    my $class = shift;
    my ($options, $specs) = @_;
    my (%lengths, @others);

    for my $spec (@$specs)
    {
	# Put coderefs straight into the 'other' heap.
	if (ref $spec eq 'CODE')
	{
	    push @others, $spec;
	}
	# Specifications...
	elsif (ref $spec eq 'HASH')
	{
	    if (exists $spec->{length})
	    {
		my $code = $class->create_single_parser( %$spec );
		my @lengths = ref $spec->{length}
		    ? @{ $spec->{length} }
		    : ( $spec->{length} );
		for my $length ( @lengths )
		{
		    push @{ $lengths{$length} }, $code;
		}
	    }
	    else
	    {
		push @others, $class->create_single_parser( %$spec );
	    }
	}
	# Something else
	else
	{
	    croak "Invalid specification in list.";
	}
    }

    while (my ($length, $parsers) = each %lengths)
    {
	$lengths{$length} = $class->chain_parsers( $parsers );
    }

    return ( \%lengths, \@others );
}

sub chain_parsers
{
    my ($self, $parsers) = @_;
    return $parsers->[0] if @$parsers == 1;
    return sub {
	my $self = shift;
	for my $parser (@$parsers)
	{
	    my $rv = $self->$parser( @_ );
	    return $rv if defined $rv;
	}
	return undef;
    };
}

sub create_parser
{
    my $class = shift;
    if (not ref $_[0])
    {
	# Simple case of single specification as a hash
	return $class->create_single_object( @_ )
    }

    # Let's see if we were given an options block
    my %options;
    while ( ref $_[0] eq 'ARRAY' )
    {
	my $options = shift;
	%options = ( %options, @$options );
    }

    # Now, can we create a multi-parser out of the remaining arguments?
    if (ref $_[0] eq 'HASH' or ref $_[0] eq 'CODE')
    {
	return $class->create_multiple_parsers( \%options, @_ );
    }
    else
    {
	# If it wasn't a HASH or CODE, then it was (ideally)
        # a list of pairs describing a single specification.
        return $class->create_multiple_parsers( \%options, { @_ } );
    }
}

# Find all our workers
{
    use Class::Factory::Util;

    foreach my $worker ( __PACKAGE__->subclasses )
    {
        eval "use DateTime::Format::Builder::Parser::$worker;";
        die $@ if $@;
    }
}

1;

__END__