NAME

Perl::ToPerl6::DEVELOPER - How to make new Perl::ToPerl6::Transformer modules.

DESCRIPTION

For developers who want to create custom coding standards, the following tells how to create a Transformer module for Perl::ToPerl6. Although the Perl::ToPerl6 distribution already includes a number of Policies based on Damian Conway's book Perl Best Practices (which will be referred to via "PBP" from here on), Perl::ToPerl6 is not limited to his guidelines and can be used to enforce any practice, preference, or style that you want to follow. You can even write Policies to enforce contradictory guidelines. All you need to do is write a corresponding Perl::ToPerl6::Transformer subclass, which may require as little as 10 lines of code.

BACKGROUND

The heart of Perl::ToPerl6 is PPI, a parser and lexer for Perl. PPI transforms Perl source code into a Document Object Model (DOM). Each token in the document is represented by a PPI class, such as PPI::Token::Operator or PPI::Token::Word, and then organized into structure classes, like PPI::Statement::Expression and PPI::Structure::Subroutine. The root node of the hierarchy is the PPI::Document.

The Perl::ToPerl6 engine traverses each node in the PPI::Document tree and invokes each of the Perl::ToPerl6::Transformer subclasses at the appropriate node. The Transformer can inspect the node, look at the surrounding nodes, and do whatever else it wants. If the Transformer decides that a coding standard has been violated, it returns one or more Perl::ToPerl6::Transformation objects. If there are no transformations, then the Transformer returns nothing.

Policies are usually written based on existing transformers, so let's look at one to see how it works. The RequireBlockGrep.pm Transformer is relatively simple and demonstrates most of the important issues. The goal of this Transformer is to enforce that every call to grep uses a block for the first argument and not an expression. The reasons for this Transformer are discussed in detail in PBP.

EXAMPLE POLICY

First, the Transformer module needs to have a name. Perl::ToPerl6 uses Module::Pluggable to automatically discover all modules in the Perl::ToPerl6::Transformer namespace. Also, we've adopted the convention of grouping Policies into directories according to the chapters of PBP. Since the goal of this Transformer is to enforce the use of block arguments to grep and it comes from the "Builtin Functions" chapter of PBP, we call it "Perl::ToPerl6::Transformer::BuiltinFunctions::RequireBlockGrep".

package Perl::ToPerl6::Transformer::BuiltinFunctions::RequireBlockGrep;

Next, we set some pragmas and load the modules that we'll need. All Transformer modules inherit from the Perl::ToPerl6::Transformer class, which provides no-op implementations of the basic methods. Our job is to override these methods to make them do something useful.

Technically, use strict and use warnings are optional, but we don't want Perl::ToPerl6 to be a hypocrite, now do we?

use strict;
use warnings;

use Readonly;

use Perl::ToPerl6::Utils qw{ :severities :classification :ppi };
use base 'Perl::ToPerl6::Transformer';

our $VERSION = '1.05';

Next, we'll declare a description and explanation for this Transformer. The description is always just a string that basically says "this is what's wrong." The explanation can be either a string with further details, or a reference to an array of integers that correspond to page numbers in PBP. We make them read-only because they never change. (See Perl::ToPerl6::Transformer::ValuesAndExpressions::ProhibitConstantPragma for why we don't use constant.)

Readonly::Scalar my $DESC => q{Expression form of "grep"};
Readonly::Scalar my $EXPL => [ 169 ];

Most transformers don't need to override the initialize_if_enabled() method provided by Perl::ToPerl6::Transformer. However, if your Transformer is configurable via .perlmogrifyrc, you should implement a supported_parameters() method and need to implement initialize_if_enabled() to examine the $config values. Since this Transformer isn't configurable, we'll declare that by providing an implementation of supported_parameters() that returns an empty list.

sub supported_parameters { return ()                  }

Next, we define the default_severity() method, which must return an integer indicating the severity of violating this Transformer. Severity values range from 1 to 5, where 5 is the "most severe." In general, level 5 is reserved for things that are frequently misused and/or cause bugs. Level 1 is for things that are highly subjective or purely cosmetic. The Perl::ToPerl6::Utils package exports several severity constants that you can use here via the :severities tag.

sub default_severity     { return $SEVERITY_HIGH      }

Likewise, the default_themes() method returns a list of theme names. Themes are intended to be named groups of Policies. All Policies that ship with Perl::ToPerl6 have a "core" theme. Since use of grep without blocks often leads to bugs, we include a "bugs" theme. And since this Transformer comes directly from PBP, this Transformer should be a member of the "pbp" theme.

sub default_themes       { return qw( core bugs pbp ) }

As a Transformer author, you can assign any themes you want to the Transformer. If you're publishing a suite of custom Policies, we suggest that you create a unique theme that covers all the Policies in the distribution. That way, users can easily enable or disable all of your transformers at once. For example, Policies in the Perl::ToPerl6::More distribution all have a "more" theme.

Next, we indicate what elements of the code this Transformer will analyze, like statements or variables or conditionals or POD. These elements are specified as PPI classes such as PPI::Statement, PPI::Token::Symbol, PPI::Structure::Conditional or PPI::Token::Pod respectively. The applies_to() method returns a list of PPI package names. (You can get that list of available package names via perldoc PPI.) As Perl::ToPerl6 traverses the document, it will call the violates() method from this module whenever it encounters one of the PPI types that are given here. In this case, we just want to test calls to grep. Since the token "grep" is a PPI::Token::Word, we return that package name from the applies_to() method.

sub applies_to           { return 'PPI::Token::Word'  }

If your Transformer needs to analyze several different types of elements, the applies_to method may return the name of several PPI packages. If your Transformer needs to examine the file as a whole, then the applies_to method should return PPI::Document. Since there is only one PPI::Document element, your Transformer would only be invoked once per file.

Now comes the interesting part. The violates() method does all the work. It is always called with 2 arguments: a reference to the current PPI element that Perl::ToPerl6 is traversing, and a reference to the entire PPI document. [And since this is an object method, there will be an additional argument that is a reference to this object ($self), but you already knew that!] Since this Transformer does not need access to the document as a whole, we ignore the last parameter by assigning to undef.

sub violates {
    my ( $self, $elem, undef ) = @_;

The violates() method then often performs some tests to make sure we have the right "type" of element. In our example, we know that the element will be a PPI::Token::Word because that's what we declared back in the applies_to() method. However, we didn't specify exactly which "word" we were looking for. Evaluating a PPI element in a string context returns the literal form of the code. (You can also use the content() method.) So we make sure that this PPI::Token::Word is, in fact, "grep". If it's not, then we don't need to bother examining it.

return if $elem ne 'grep';

The PPI::Token::Word class is also used for barewords and methods called on object references. It is possible for someone to declare a bareword hash key as %hash = ( grep => 'foo'). We don't want to test those types of elements because they don't represent function calls to grep. So we use one of handy utility functions from Perl::ToPerl6::Utils to make sure that this "grep" is actually in the right context. (The is_function_call() subroutine is brought in via the :classification tag.)

return if ! is_function_call($elem);

Now that we know this element is a call to the grep function, we can look at the nearby elements to see what kind of arguments are being passed to it. In the following paragraphs, we discuss how to do this manually in order to explore PPI; after that, we'll show how this Transformer actually uses facilities provided by Perl::ToPerl6::Utils to get this done.

Every PPI element is linked to its siblings, parent, and children (if it has any). Since those siblings could just be whitespace, we use the snext_sibling() to get the next code-sibling (the "s" in snext_sibling stands for "significant").

my $sib = $elem->snext_sibling() or return;

In Perl, the parenthesis around argument lists are usually optional, and PPI packs the elements into a PPI::Structure::List object when parentheses are used. So if the sibling is a PPI::Structure::List, we pull out the first (significant) child of that list. This child will be the first argument to grep. If parentheses were not used, then the sibling itself is the first argument.

my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;

In actuality, this sort of function argument lookup is common, so there is a "first_arg" in Perl::ToPerl6::Utils subroutine available via the :ppi tag. So we use that instead.

my $arg = first_arg($elem);

Finally, we now have a reference to the first argument to grep. If that argument is a block (i.e. something in curly braces), then it will be a PPI::Structure::Block, in which case our Transformer is satisfied and we just return nothing.

return if !$arg;
return if $arg->isa('PPI::Structure::Block');

But if it is not a PPI::Structure::Block, then we know that this call to grep must be using the expression form, and that violates our Transformer. So we create and return a new Perl::ToPerl6::Transformation object via the "transformation" in Perl::ToPerl6::Transformer method, passing in the description, explanation, and a reference to the PPI element that caused the transformation. And that's all there is to it!

    return $self->transformation( $DESC, $EXPL, $elem );
}

1;

One last thing -- people are going to need to understand what is wrong with the code when your Transformer finds a problem. It isn't reasonable to include all the details in your transformation description or explanation. So please include a DESCRIPTION section in the POD for your Transformer. It should succinctly describe the behavior and motivation for your Transformer and include a few examples of both good and bad code. Here's an example:

=pod

=head1 NAME

Perl::ToPerl6::Transformer::BuiltinFunctions::RequireBlockGrep


=head1 DESCRIPTION

The expression forms of C<grep> and C<map> are awkward and hard to read.
Use the block forms instead.

    @matches = grep  /pattern/,    @list;        #not ok
    @matches = grep { /pattern/ }  @list;        #ok

    @mapped = map  transform($_),    @list;      #not ok
    @mapped = map { transform($_) }  @list;      #ok

=cut

When your policy has a section like this, users can invoke perlmogrify with a --verbose parameter of 10 or 11 or with a "%d" escape to see it along with the rest of the output for transformations of your policy.

MAKING YOUR POLICY CONFIGURABLE

Perl::ToPerl6 takes care of gathering configuration information for your Transformer, from whatever source the user specifies. (See "CONFIGURATION" in Perl::ToPerl6 for the details of how a user specifies the values you're going to receive.) What your Transformer ends up receiving for the value of a parameter is a string with leading and trailing whitespace removed. By default, you will need to handle conversion of that string to a useful form yourself. However, if you provide some metadata about your parameters, the parameter handling will be taken care of for you. (Additionally, tools that deal with Policies themselves can use this information to enhance their functionality. See the perlmogrify --profile-proto option for an example.)

You can look at Perl::ToPerl6::Transformer::ControlStructures::ProhibitCascadingIfElse for a simple example of a configurable Transformer and Perl::ToPerl6::Transformer::Documentation::RequirePodSections for a more complex one.

Do It All Yourself

The initialize_if_enabled() method for a Transformer receives one argument: an instance of Perl::ToPerl6::TransformerConfig. This method is only called if the user's configuration has enabled the policy. It returns a boolean stating whether the Transformer should continue to be enabled. Generally, the only reason to return $FALSE is when some external requirement is missing. For example, Perl::ToPerl6::Transformer::CodeLayout::RequireTidyCode used to disable itself if Perl::Tidy was not installed (that is until we made it no longer optional for the Perl-ToPerl6 distribution).

A basic, do-nothing implementation of initialize_if_enabled() would be:

use Perl::ToPerl6::Utils qw< :booleans >;

...

sub initialize_if_enabled {
    my ( $self, $config ) = @_;

    return $TRUE;
}

As stated above, what you get in $config are trimmed strings. For example, if the user's .perlmogrify contains

[Your::Transformer]
foo          = bar baz
factor   =     5.52
selections =   2 78 92

then $config will contain the equivalent of

my $config = {
    foo        => 'bar baz',
    factor     => '5.52',
    selections => '2 78 92',
};

To make this available to the violates() method, the values are usually put into $self under the name of the configuration item prefixed with an underscore. E.g.

sub initialize_if_enabled {
    my ( $self, $config ) = @_;

    $self->{_foo} = $config->get{foo};
    $self->{_factor} = $config->get{factor};
    $self->{_selections} = $config->get{selections};

    return $TRUE;
}

Often, you'll want to convert the configuration values into something more useful. In this example, selections is supposed to be a list of integers. Perl::ToPerl6::Utils contains a number of functions that can help you with this. Assuming that violates() wants to have selections as an array, you'll want to have something like this:

use Perl::ToPerl6::Utils qw{ :booleans :characters :data_conversion };

sub initialize_if_enabled {
    my ( $self, $config ) = @_;

    $self->{_foo} = $config->get{foo};
    $self->{_factor} = $config->get{factor};

    my $selections = $config->get{selections};
    $selections = defined $selections ? $selections : $EMPTY_STRING;
    $self->{_selections} = [ words_from_string($selections) ];

    return $TRUE;
}

Since selections contains numbers, it may be desirable to change the assignment to look like

$self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];

If violates() needs to quickly determine whether a particular value is in selections, you would want to use a hash instead of an array, like this:

$self->{_selections} = { hashify( words_from_string($selections) ) };

For an example of a Transformer that has some simple, but non-standard configuration handling, see Perl::ToPerl6::Transformer::CodeLayout::RequireTidyCode.

Note On Constructors

It used to be the case that Policies handled configuration by implementing a constructor. However, there was no requirement to call the base constructor; as long as the Transformer ended up being a blessed hash reference, everything was fine. Unfortunately, this meant that Policies would be loaded and their prerequisites would be used, even if the Transformer wasn't enabled, slowing things down. Also, this severely restricted the core of Perl::ToPerl6's ability to enhance things. Use of constructors is deprecated and is incompatible with supported_parameters() metadata below. Kindly use initialize_if_enabled(), instead, to do any sort of set up that you need.

Providing Basic Configuration Information Via supported_parameters()

As minimum for a well behaved Transformer, you should implement supported_parameters() in order to tell the rest of Perl::ToPerl6 what configuration values the Transformer looks for, even if it is only to say that the Transformer is not configurable. In the simple form, this function returns a list of the names of the parameters the Transformer supports. So, for an non-configurable Transformer, as in the RequireBlockGrep example above, this looked like

sub supported_parameters { return ()                  }

For the example being used in the initialize_if_enabled() section above, this would be

sub supported_parameters { return qw< foo factor selections >; }

Given this information, Perl::ToPerl6 can tell the user when they have specified a parameter for a Transformer which isn't valid, e.g. when they've misspelled the name of the parameter, and can emit the parameter as part of a .perlmogrifyrc prototype.

You can provide even more information about your Transformer's configuration by giving each parameter a description and a string representation of the default value for the parameter. You do this by having the values in the list returned by supported_parameters() be hash references instead of strings, with keys of name, description, and default_string. For example,

sub supported_parameters {
    return (
        {
            name           => 'allowed_values',
            description    =>
                'Individual and ranges of values to allow, and/or "all_integers".',
            default_string => '0 1 2',
        },
        {
            name           => 'allowed_types',
            description    => 'Kind of literals to allow.',
            default_string => 'Float',
        },
    );
}

Note that use of constructors is incompatible with specifying parameters in this way.

Using supported_parameters() to Get It Done For You

The supported_parameters() discussion above showed how you could help others with your Transformer, but didn't do anything to make your life as a Transformer author easier; you still need to implement initialize_if_enabled() to access any configuration that the user has specified. To have the configuration automatically handled for you, you need to declare how your parameters act by specifying a value for their behavior. For example, the following declares that a parameter allows the user to choose from five specific values and that the user can select any combination of them:

sub supported_parameters {
    return (
        {
            name               => 'allowed_types',
            description        => 'Kind of literals to allow.',
            default_string     => 'Float',
            behavior           => 'enumeration',
            enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
            enumeration_allow_multiple_values => 1,
        },
    );
}

When you specify a behavior, parsing and validation of the user-specified and default values is done for you and your violates() method can retrieve the value under the key of the parameter name prefixed with an underscore, e.g., for the above declaration, the parsed and validated value can be accessed via $self->{_allowed_types}.

The behaviors provide additional functionality to Perl::ToPerl6; for more on this, see Perl::ToPerl6::TransformerParameter and Perl::ToPerl6::TransformerParameter::Behavior.

The following discusses each of the supported behaviors and the options they support. For the full details of a behavior, see the documentation for the implementing class.

"string"

Implemented in Perl::ToPerl6::TransformerParameter::Behavior::String.

The most basic of behaviors, the value of the parameter will be stored in the Transformer as a string.

This behavior is not configurable.

supported_parameters() example

sub supported_parameters {
    return (
        {
            name           => 'a_string',
            description    => 'An example string.',
            default_string => 'blah blah blah',
            behavior       => 'string',
        },
    );
}

Access example

sub violates {
    my ($self, $element, $document) = @_;

    ...
    my $string = $self->{_a_string};
    ...
}

"boolean"

Implemented in Perl::ToPerl6::TransformerParameter::Behavior::Boolean.

The value of the parameter will be either $TRUE or $FALSE.

This behavior is not configurable.

supported_parameters() example

sub supported_parameters {
    return (
        {
            name           => 'a_boolean',
            description    => 'An example boolean.',
            default_string => '1',
            behavior       => 'boolean',
        },
    );
}

Access example

sub violates {
    my ($self, $element, $document) = @_;

    ...
    my $is_whatever = $self->{_a_boolean};
    if ($is_whatever) {
        ...
    }
    ...
}

"integer"

Implemented in Perl::ToPerl6::TransformerParameter::Behavior::Integer.

The value is validated against m/ \A [-+]? [1-9] [\d_]* \z /xms (with an special check for "0"). Notice that this means that underscores are allowed in input values as with Perl numeric literals.

This takes two options, integer_minimum and integer_maximum, which specify endpoints of an inclusive range to restrict the value to. Either, neither, or both may be specified.

supported_parameters() example

sub supported_parameters {
    return (
        {
            name            => 'an_integer',
            description     => 'An example integer.',
            default_string  => '5',
            behavior        => 'integer',
            integer_minimum => 0,
            integer_maximum => 10,
        },
    );
}

Access example

sub violates {
    my ($self, $element, $document) = @_;

    ...
    my $integer = $self->{_an_integer};
    if ($integer > $TURNING_POINT) {
        ...
    }
    ...
}

"string list"

Implemented in Perl::ToPerl6::TransformerParameter::Behavior::StringList.

The values will be derived by splitting the input string on blanks. (See "words_from_string" in Perl::ToPerl6::Utils.) The parameter will be stored as a reference to a hash, with the values being the keys.

This takes one optional option, list_always_present_values, of a reference to an array of strings that will always be included in the parameter value, e.g. if the value of this option is [ qw{ a b c } ] and the user specifies a value of 'c d e', then the value of the parameter will contain 'a', 'b', 'c', 'd', and 'e'.

supported_parameters() example

sub supported_parameters {
    return (
        {
            name                  => 'a_string_list',
            description           => 'An example list.',
            default_string        => 'red pink blue',
            behavior              => 'string list',
            list_always_present_values => [ qw{ green purple} ],
        },
    );
}

Access example

sub violates {
    my ($self, $element, $document) = @_;

    ...
    my $list = $self->{_a_string_list};
    my @list = keys %{$list};
    ...
    return if not $list->{ $element->content() };
    ...
}

"enumeration"

Implemented in Perl::ToPerl6::TransformerParameter::Behavior::Enumeration.

The values will be derived by splitting the input string on blanks. (See "words_from_string" in Perl::ToPerl6::Utils.) Depending upon the value of the enumeration_allow_multiple_values option, the parameter will be stored as a string or a reference to a hash, with the values being the keys.

This behavior takes one required option and one optional one. A value for enumeration_values of a reference to an array of valid strings is required. A true value can be specified for enumeration_allow_multiple_values to allow the user to pick more than one value, but this defaults to false.

supported_parameters() example

use Perl::ToPerl6::Utils qw{ :characters };

sub supported_parameters {
    return (
        {
            name               => 'a_single_valued_enumeration',
            description        =>
                'An example enumeration that can only have a single value.',
            default_string     => $EMPTY,
            behavior           => 'enumeration',
            enumeration_values => [ qw{ block statement pod operator } ],
            enumeration_allow_multiple_values => 0,
        },
        {
            name               => 'a_multi_valued_enumeration',
            description        =>
                'An example enumeration that can have multiple values.',
            default_string     => 'fe',
            behavior           => 'enumeration',
            enumeration_values => [ qw{ fe fi fo fum } ],
            enumeration_allow_multiple_values => 1,
        },
    );
}

Access example

sub violates {
    my ($self, $element, $document) = @_;

    ...
    my $single_value = $self->{_a_single_valued_enumeration};
    ...
    my $multi_value = $self->{_a_multi_valued_enumeration};
    if ( $multi_value->{fum} ) {
        ...
    }
    ...
}

Using a Custom Parser

If none of the behaviors does exactly what you want it to, you can provide your own parser for a parameter. The reason for doing this as opposed to using an implementation of initialize_if_enabled() is that it allows you to use a behavior to provide its extra functionality and it provides a means for a Perl::ToPerl6 configuration program, e.g. an IDE that integrates Perl::ToPerl6, to validate your parameter as the user modifies its value.

The way you declare that you have a custom parser is to include a reference to it in the parameter specification with the parser key. For example:

sub supported_parameters {
    return (
        {
            name           => 'file_name',
            description    => 'A file for to read a list of values from.',
            default_string => undef,
            behavior       => 'string',
            parser         => \&_parse_file_name,
        },
    );
}

A parser is a method on a subclass of Perl::ToPerl6::Transformer that takes two parameters: the Perl::ToPerl6::TransformerParameter that is being specified and the value string provided by the user. The method is responsible for dealing with any default value and for saving the parsed value for later use by the violates() method.

An example parser (without enough error handling) for the above example declaration:

use File::Slurp qw< slurp >;

use Perl::ToPerl6::Exception::Configuration::Option::Transformer::ParameterValue
    qw{ throw_policy_value };

sub _parse_file_name {
    my ($self, $parameter, $config_string) = @_;

    my @thingies;

    if ($config_string) {
        if (not -r $config_string) {
            throw_policy_value
                policy         => $self->get_short_name(),
                option_name    => $parameter->get_name(),
                option_value   => $config_string,
                message_suffix => 'is not readable.';
        }

        @thingies = slurp $config_string;
    }

    $self->{_thingies} = \@thingies;

    return;
}

Note that, if the value for the parameter is not valid, an instance of Perl::ToPerl6::Exception::Configuration::Option::Transformer::ParameterValue is thrown. This allows Perl::ToPerl6 to include that problem along with any other problems found with the user's configuration in a single error message.

Using Both supported_parameters() and initialize_if_enabled()

There are cases where a Transformer needs additional initialization beyond configuration or where the way it acts depends upon the combination of multiple parameters. In such situations, you will need to create an implementation of initialize_if_enabled(). If you want to take advantage of the supplied parameter handling from within implementation of initialize_if_enabled(), note that the information from supported_parameters() will already have been used, with user-supplied parameter values validated and placed into the Transformer by the time initialize_if_enabled() has been called. It is likely that you will not need to refer the contents of the $config parameter; just pull the information you need out of $self. In fact, any value for the parameter values will be gone.

Summary of permitted hash keys in supported_parameters().

All types

- "name" (mandatory)
- "description" (optional)
- "behavior" (optional)

Currently, one of:

"boolean"
"enumeration"
"integer"
"string"
"string list"
- "default_string" (optional)

A string representation of the default value of the parameter.

- "parser" (optional)

A code ref to a custom parser for the parameter.

Enumerations

- "enumeration_values" (mandatory)

A mandatory reference to an array of strings.

- "enumeration_allow_multiple_values" (optional)

Boolean indicating whether or not the user is restricted to a single value.

Integers

- "integer_minimum" (optional)

Minimum allowed value, inclusive.

- "integer_maximum" (optional)

Maximum allowed value, inclusive.

String lists

- "list_always_present_values" (optional)

A reference to an array of values that should always be included in the value of the parameter.

ADDITIONAL FEATURES

default_maximum_transformations_per_document()

Certain problems that a Transformer detects can be endemic to a particular file; if there's one transformation, there's likely to be many. A good example of this is Perl::ToPerl6::Transformer::TestingAndDebugging::RequireUseStrict; if there's one line before "use strict", there's a good chance that the entire file is missing "use strict". In such cases, it's not much help to the user to report every single transformation. If you've got such a policy, you should override default_maximum_transformations_per_document() method to provide a limit. The user can override this value with a value for "maximum_transformations_per_document" in their .perlmogrifyrc.

See the source code for Perl::ToPerl6::Transformer::ValuesAndExpressions::ProhibitMagicNumbers and Perl::ToPerl6::Transformer::TestingAndDebugging::RequireUseWarnings for examples.

is_safe()

Most Perl::ToPerl6 Policies are purely static. In other words, they never compile or execute any of the source code that they analyze. However it is possible to write dynamic Policies that do compile or execute code, which may result in unsafe operations (see Perl::ToPerl6::Dynamic for an example). So the is_safe() method is used to indicate whether a Transformer can be trusted to not cause mischief. By default, is_safe() returns true. But if you are writing a Transformer that will compile or execute any of the source code that it analyzes, then you should override the is_safe() method to return false.

DISTRIBUTING YOUR POLICIES

Create a Distribution

You need to come up with a name for your set of transformers. Sets of add-on transformers are generally named Perl::ToPerl6::something, e.g. Perl::ToPerl6::More.

The module representing the distribution will not actually have any functionality; it's just documentation and a name for users to use when installing via CPAN/CPANPLUS. The important part is that this will include a list of the included transformers, with descriptions of each.

A typical implementation will look like:

package Perl::ToPerl6::Example;

use strict;
use warnings;

our $VERSION = '1.000000';

1; # Magic true value required at end of module

__END__

=head1 NAME

Perl::ToPerl6::Example - Policies for Perl::ToPerl6 that act as an example.

=head1 AFFILIATION

This module has no functionality, but instead contains documentation
for this distribution and acts as a means of pulling other modules
into a bundle.  All of the Transformer modules contained herein will have
an "AFFILIATION" section announcing their participation in this
grouping.


=head1 SYNOPSIS

Some L<Perl::ToPerl6|Perl::ToPerl6> transformers that will help you keep your
code nice and compliant.


=head1 DESCRIPTION

The included transformers are:

=over

=item L<Perl::ToPerl6::Transformer::Documentation::Example|Perl::ToPerl6::Transformer::Documentation::Example>

Complains about some example documentation issues.  [Default severity: 3]


=item L<Perl::ToPerl6::Transformer::Variables::Example|Perl::ToPerl6::Transformer::Variables::Example>

All modules must have at least one variable.  [Default severity: 3]


=back


=head1 CONFIGURATION AND ENVIRONMENT

All transformers included are in the "example" theme.  See the
L<Perl::ToPerl6|Perl::ToPerl6> documentation for how to make use of this.

Themes

Users can choose which transformers to enable using themes. You should implement default_themes() so that users can take advantage of this. In particular, you should use a theme named after your distribution in all your transformers; this should match the value listed in the CONFIGURATION AND ENVIRONMENT POD section as shown above.

default_themes { return qw< example math > }

If you're looking for ideas of what themes to use, have a look at the output of perlmogrify --list-themes.

Documentation

AFFILIATION

Since all transformers have to go somewhere under the Perl::ToPerl6::Transformer:: namespace, it isn't always clear what distribution a policy came from when browsing through their documentation. For this reason, you should include an AFFILIATION section in the POD for all of your transformers that state where the policy comes from. For example:

=head1 AFFILIATION

This policy is part of L<Perl::ToPerl6::Example|Perl::ToPerl6::Example>.

CONFIGURATION

In order to make it clear what can be done with a policy, you should always include a CONFIGURATION section in your POD, even if it's only to say:

=head1 CONFIGURATION

This Transformer is not configurable except for the standard options.

TESTING YOUR POLICY

The Perl::ToPerl6 distribution also contains a framework for testing your Transformer. See Test::Perl::ToPerl6::Transformer for the details.

HINT

When you're trying to figure out what PPI is going to hand you for a chunk of code, there is a tools/ppidump program in the Perl::ToPerl6 distribution that will help you. For example, when developing the above RequireBlockGrep example, you might want to try

tools/ppidump '@matches = grep /pattern/, @list;'

and

tools/ppidump '@matches = grep { /pattern/ } @list;'

to see the differences between the two cases.

Alternatively, see the ppi_dumper documentation at http://search.cpan.org/dist/App-PPI-Dumper/script/ppi_dumper and the PPI::Tester documentation at http://search.cpan.org/dist/PPI-Tester/lib/PPI/Tester.pm.

VERSION

This is part of Perl::ToPerl6 version 1.116.

SEE ALSO

Chas. Owens has a blog post about developing in-house transformers at http://svok.blogspot.com/2009/09/adding-house-transformers-to-perlmogrify.html.

AUTHOR

Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>

COPYRIGHT

Copyright (c) 2005-2011 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.