PPI::Element - The abstract Element class, a base for all source objects


PPI documentation Contained in the PPI distribution.

Index


Code Index:

NAME

Top

PPI::Element - The abstract Element class, a base for all source objects

INHERITANCE

Top

  PPI::Element is the root of the PDOM tree

DESCRIPTION

Top

The abstract PPI::Element serves as a base class for all source-related objects, from a single whitespace token to an entire document. It provides a basic set of methods to provide a common interface and basic implementations.

METHODS

Top

significant

Because we treat whitespace and other non-code items as Tokens (in order to be able to "round trip" the PPI::Document back to a file) the significant method allows us to distinguish between tokens that form a part of the code, and tokens that aren't significant, such as whitespace, POD, or the portion of a file after (and including) the __END__ token.

Returns true if the Element is significant, or false it not.

class

The class method is provided as a convenience, and really does nothing more than returning ref($self). However, some people have found that they appreciate the laziness of $Foo->class eq 'whatever', so I have caved to popular demand and included it.

Returns the class of the Element as a string

tokens

The tokens method returns a list of PPI::Token objects for the Element, essentially getting back that part of the document as if it had not been lexed.

This also means there are no Statements and no Structures in the list, just the Token classes.

content

For any PPI::Element, the content method will reconstitute the base code for it as a single string. This method is also the method used for overloading stringification. When an Element is used in a double-quoted string for example, this is the method that is called.

WARNING:

You should be aware that because of the way that here-docs are handled, any here-doc content is not included in content, and as such you should not eval or execute the result if it contains any PPI::Token::HereDoc.

The PPI::Document method serialize should be used to stringify a PDOM document into something that can be executed as expected.

Returns the basic code as a string (excluding here-doc content).

parent

Elements themselves are not intended to contain other Elements, that is left to the PPI::Node abstract class, a subclass of PPI::Element. However, all Elements can be contained within a parent Node.

If an Element is within a parent Node, the parent method returns the Node.

descendant_of $element

Answers whether a PPI::Element is contained within another one.

PPI::Elements are considered to be descendants of themselves.

ancestor_of $element

Answers whether a PPI::Element is contains another one.

PPI::Elements are considered to be ancestors of themselves.

statement

For a PPI::Element that is contained (at some depth) within a PPI::Statment, the statement method will return the first parent Statement object lexically 'above' the Element.

Returns a PPI::Statement object, which may be the same Element if the Element is itself a PPI::Statement object.

Returns false if the Element is not within a Statement and is not itself a Statement.

top

For a PPI::Element that is contained within a PDOM tree, the top method will return the top-level Node in the tree. Most of the time this should be a PPI::Document object, however this will not always be so. For example, if a subroutine has been removed from its Document, to be moved to another Document.

Returns the top-most PDOM object, which may be the same Element, if it is not within any parent PDOM object.

document

For an Element that is contained within a PPI::Document object, the document method will return the top-level Document for the Element.

Returns the PPI::Document for this Element, or false if the Element is not contained within a Document.

next_sibling

All PPI::Node objects (specifically, our parent Node) contain a number of PPI::Element objects. The next_sibling method returns the PPI::Element immediately after the current one, or false if there is no next sibling.

snext_sibling

As per the other 's' methods, the snext_sibling method returns the next significant sibling of the PPI::Element object.

Returns a PPI::Element object, or false if there is no 'next' significant sibling.

previous_sibling

All PPI::Node objects (specifically, our parent Node) contain a number of PPI::Element objects. The previous_sibling method returns the Element immediately before the current one, or false if there is no 'previous' PPI::Element object.

sprevious_sibling

As per the other 's' methods, the sprevious_sibling method returns the previous significant sibling of the PPI::Element object.

Returns a PPI::Element object, or false if there is no 'previous' significant sibling.

first_token

As a support method for higher-order algorithms that deal specifically with tokens and actual Perl content, the first_token method finds the first PPI::Token object within or equal to this one.

That is, if called on a PPI::Node subclass, it will descend until it finds a PPI::Token. If called on a PPI::Token object, it will return the same object.

Returns a PPI::Token object, or dies on error (which should be extremely rare and only occur if an illegal empty PPI::Statement exists below the current Element somewhere.

last_token

As a support method for higher-order algorithms that deal specifically with tokens and actual Perl content, the last_token method finds the last PPI::Token object within or equal to this one.

That is, if called on a PPI::Node subclass, it will descend until it finds a PPI::Token. If called on a PPI::Token object, it will return the itself.

Returns a PPI::Token object, or dies on error (which should be extremely rare and only occur if an illegal empty PPI::Statement exists below the current Element somewhere.

next_token

As a support method for higher-order algorithms that deal specifically with tokens and actual Perl content, the next_token method finds the PPI::Token object that is immediately after the current Element, even if it is not within the same parent PPI::Node as the one for which the method is being called.

Note that this is not defined as a PPI::Token-specific method, because it can be useful to find the next token that is after, say, a PPI::Statement, although obviously it would be useless to want the next token after a PPI::Document.

Returns a PPI::Token object, or false if there are no more tokens after the Element.

previous_token

As a support method for higher-order algorithms that deal specifically with tokens and actual Perl content, the previous_token method finds the PPI::Token object that is immediately before the current Element, even if it is not within the same parent PPI::Node as this one.

Note that this is not defined as a PPI::Token-only method, because it can be useful to find the token is before, say, a PPI::Statement, although obviously it would be useless to want the next token before a PPI::Document.

Returns a PPI::Token object, or false if there are no more tokens before the Element.

clone

As per the Clone module, the clone method makes a perfect copy of an Element object. In the generic case, the implementation is done using the Clone module's mechanism itself. In higher-order cases, such as for Nodes, there is more work involved to keep the parent-child links intact.

insert_before @Elements

The insert_before method allows you to insert lexical perl content, in the form of PPI::Element objects, before the calling Element. You need to be very careful when modifying perl code, as it's easy to break things.

In its initial incarnation, this method allows you to insert a single Element, and will perform some basic checking to prevent you inserting something that would be structurally wrong (in PDOM terms).

In future, this method may be enhanced to allow the insertion of multiple Elements, inline-parsed code strings or PPI::Document::Fragment objects.

Returns true if the Element was inserted, false if it can not be inserted, or undef if you do not provide a PPI::Element object as a parameter.

insert_after @Elements

The insert_after method allows you to insert lexical perl content, in the form of PPI::Element objects, after the calling Element. You need to be very careful when modifying perl code, as it's easy to break things.

In its initial incarnation, this method allows you to insert a single Element, and will perform some basic checking to prevent you inserting something that would be structurally wrong (in PDOM terms).

In future, this method may be enhanced to allow the insertion of multiple Elements, inline-parsed code strings or PPI::Document::Fragment objects.

Returns true if the Element was inserted, false if it can not be inserted, or undef if you do not provide a PPI::Element object as a parameter.

remove

For a given PPI::Element, the remove method will remove it from its parent intact, along with all of its children.

Returns the Element itself as a convenience, or undef if an error occurs while trying to remove the Element.

delete

For a given PPI::Element, the delete method will remove it from its parent, immediately deleting the Element and all of its children (if it has any).

Returns true if the Element was successfully deleted, or undef if an error occurs while trying to remove the Element.

replace $Element

Although some higher level class support more exotic forms of replace, at the basic level the replace method takes a single Element as an argument and replaces the current Element with it.

To prevent accidental damage to code, in this initial implementation the replacement element must be of the same class (or a subclass) as the one being replaced.

location

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the location method will return the location of the first character of the Element within the Document.

Returns the location as a reference to a five-element array in the form [ $line, $rowchar, $col, $logical_line, $logical_file_name ]. The values are in a human format, with the first character of the file located at [ 1, 1, 1, ?, 'something' ].

The second and third numbers are similar, except that the second is the literal horizontal character, and the third is the visual column, taking into account tabbing (see "tab_width [ $width ]" in PPI::Document).

The fourth number is the line number, taking into account any #line directives. The fifth element is the name of the file that the element was found in, if available, taking into account any #line directives.

Returns undef on error, or if the PPI::Document object has not been indexed.

line_number

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the line_number method will return the line number of the first character of the Element within the Document.

Returns undef on error, or if the PPI::Document object has not been indexed.

column_number

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the column_number method will return the column number of the first character of the Element within the Document.

Returns undef on error, or if the PPI::Document object has not been indexed.

visual_column_number

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the visual_column_number method will return the visual column number of the first character of the Element within the Document, according to the value of "tab_width [ $width ]" in PPI::Document.

Returns undef on error, or if the PPI::Document object has not been indexed.

logical_line_number

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the logical_line_number method will return the line number of the first character of the Element within the Document, taking into account any #line directives.

Returns undef on error, or if the PPI::Document object has not been indexed.

logical_filename

If the Element exists within a PPI::Document that has indexed the Element locations using PPI::Document::index_locations, the logical_filename method will return the logical file name containing the first character of the Element within the Document, taking into account any #line directives.

Returns undef on error, or if the PPI::Document object has not been indexed.

TO DO

Top

It would be nice if location could be used in an ad-hoc manner. That is, if called on an Element within a Document that has not been indexed, it will do a one-off calculation to find the location. It might be very painful if someone started using it a lot, without remembering to index the document, but it would be handy for things that are only likely to use it once, such as error handlers.

SUPPORT

Top

See the support section in the main module.

AUTHOR

Top

Adam Kennedy <adamk@cpan.org>

COPYRIGHT

Top


PPI documentation Contained in the PPI distribution.
package PPI::Element;

use strict;
use Clone           ();
use Scalar::Util    qw{refaddr};
use Params::Util    qw{_INSTANCE _ARRAY};
use List::MoreUtils ();
use PPI::Util       ();
use PPI::Node       ();

use vars qw{$VERSION $errstr %_PARENT};
BEGIN {
	$VERSION = '1.215';
	$errstr  = '';

	# Master Child -> Parent index
	%_PARENT = ();
}

use overload 'bool' => \&PPI::Util::TRUE;
use overload '""'   => 'content';
use overload '=='   => '__equals';
use overload '!='   => '__nequals';
use overload 'eq'   => '__eq';
use overload 'ne'   => '__ne';





#####################################################################
# General Properties

### XS -> PPI/XS.xs:_PPI_Element__significant 0.845+
sub significant { 1 }

sub class { ref($_[0]) }

sub tokens { $_[0] }

### XS -> PPI/XS.xs:_PPI_Element__content 0.900+
sub content { '' }





#####################################################################
# Naigation Methods

sub parent { $_PARENT{refaddr $_[0]} }

sub descendant_of {
	my $cursor = shift;
	my $parent = shift or return undef;
	while ( refaddr $cursor != refaddr $parent ) {
		$cursor = $_PARENT{refaddr $cursor} or return '';
	}
	return 1;
}

sub ancestor_of {
	my $self   = shift;
	my $cursor = shift or return undef;
	while ( refaddr $cursor != refaddr $self ) {
		$cursor = $_PARENT{refaddr $cursor} or return '';
	}
	return 1;
}

sub statement {
	my $cursor = shift;
	while ( ! _INSTANCE($cursor, 'PPI::Statement') ) {
		$cursor = $_PARENT{refaddr $cursor} or return '';
	}
	$cursor;
}

sub top {
	my $cursor = shift;
	while ( my $parent = $_PARENT{refaddr $cursor} ) {
		$cursor = $parent;
	}
	$cursor;
}

sub document {
	my $top = shift->top;
	_INSTANCE($top, 'PPI::Document') and $top;
}

sub next_sibling {
	my $self     = shift;
	my $parent   = $_PARENT{refaddr $self} or return '';
	my $key      = refaddr $self;
	my $elements = $parent->{children};
	my $position = List::MoreUtils::firstidx {
		refaddr $_ == $key
		} @$elements;
	$elements->[$position + 1] || '';
}

sub snext_sibling {
	my $self     = shift;
	my $parent   = $_PARENT{refaddr $self} or return '';
	my $key      = refaddr $self;
	my $elements = $parent->{children};
	my $position = List::MoreUtils::firstidx {
		refaddr $_ == $key
		} @$elements;
	while ( defined(my $it = $elements->[++$position]) ) {
		return $it if $it->significant;
	}
	'';
}

sub previous_sibling {
	my $self     = shift;
	my $parent   = $_PARENT{refaddr $self} or return '';
	my $key      = refaddr $self;
	my $elements = $parent->{children};
	my $position = List::MoreUtils::firstidx {
		refaddr $_ == $key
		} @$elements;
	$position and $elements->[$position - 1] or '';
}

sub sprevious_sibling {
	my $self     = shift;
	my $parent   = $_PARENT{refaddr $self} or return '';
	my $key      = refaddr $self;
	my $elements = $parent->{children};
	my $position = List::MoreUtils::firstidx {
		refaddr $_ == $key
		} @$elements;
	while ( $position-- and defined(my $it = $elements->[$position]) ) {
		return $it if $it->significant;
	}
	'';
}

sub first_token {
	my $cursor = shift;
	while ( $cursor->isa('PPI::Node') ) {
		$cursor = $cursor->first_element
		or die "Found empty PPI::Node while getting first token";
	}
	$cursor;
}


sub last_token {
	my $cursor = shift;
	while ( $cursor->isa('PPI::Node') ) {
		$cursor = $cursor->last_element
		or die "Found empty PPI::Node while getting first token";
	}
	$cursor;
}

sub next_token {
	my $cursor = shift;

	# Find the next element, going upwards as needed
	while ( 1 ) {
		my $element = $cursor->next_sibling;
		if ( $element ) {
			return $element if $element->isa('PPI::Token');
			return $element->first_token;
		}
		$cursor = $cursor->parent or return '';
		if ( $cursor->isa('PPI::Structure') and $cursor->finish ) {
			return $cursor->finish;
		}
	}
}

sub previous_token {
	my $cursor = shift;

	# Find the previous element, going upwards as needed
	while ( 1 ) {
		my $element = $cursor->previous_sibling;
		if ( $element ) {
			return $element if $element->isa('PPI::Token');
			return $element->last_token;
		}
		$cursor = $cursor->parent or return '';
		if ( $cursor->isa('PPI::Structure') and $cursor->start ) {
			return $cursor->start;
		}
	}
}





#####################################################################
# Manipulation

sub clone {
	Clone::clone(shift);
}

sub __insert_before {
	my $self = shift;
	$self->parent->__insert_before_child( $self, @_ );
}

sub __insert_after {
	my $self = shift;
	$self->parent->__insert_after_child( $self, @_ );
}

sub remove {
	my $self   = shift;
	my $parent = $self->parent or return $self;
	$parent->remove_child( $self );
}

sub delete {
	$_[0]->remove or return undef;
	$_[0]->DESTROY;
	1;
}

sub replace {
	my $self    = ref $_[0] ? shift : return undef;
	my $Element = _INSTANCE(shift, ref $self) or return undef;
	die "The ->replace method has not yet been implemented";
}

sub location {
	my $self = shift;

	$self->_ensure_location_present or return undef;

	# Return a copy, not the original
	return [ @{$self->{_location}} ];
}

sub line_number {
	my $self = shift;

	my $location = $self->location() or return undef;
	return $location->[0];
}

sub column_number {
	my $self = shift;

	my $location = $self->location() or return undef;
	return $location->[1];
}

sub visual_column_number {
	my $self = shift;

	my $location = $self->location() or return undef;
	return $location->[2];
}

sub logical_line_number {
	my $self = shift;

	return $self->location()->[3];
}

sub logical_filename {
	my $self = shift;

	my $location = $self->location() or return undef;
	return $location->[4];
}

sub _ensure_location_present {
	my $self = shift;

	unless ( exists $self->{_location} ) {
		# Are we inside a normal document?
		my $Document = $self->document or return undef;
		if ( $Document->isa('PPI::Document::Fragment') ) {
			# Because they can't be serialized, document fragments
			# do not support the concept of location.
			return undef;
		}

		# Generate the locations. If they need one location, then
		# the chances are they'll want more, and it's better that
		# everything is already pre-generated.
		$Document->index_locations or return undef;
		unless ( exists $self->{_location} ) {
			# erm... something went very wrong here
			return undef;
		}
	}

	return 1;
}

# Although flush_locations is only publically a Document-level method,
# we are able to implement it at an Element level, allowing us to
# selectively flush only the part of the document that occurs after the
# element for which the flush is called.
sub _flush_locations {
	my $self  = shift;
	unless ( $self == $self->top ) {
		return $self->top->_flush_locations( $self );
	}

	# Get the full list of all Tokens
	my @Tokens = $self->tokens;

	# Optionally allow starting from an arbitrary element (or rather,
	# the first Token equal-to-or-within an arbitrary element)
	if ( _INSTANCE($_[0], 'PPI::Element') ) {
		my $start = shift->first_token;
		while ( my $Token = shift @Tokens ) {
			return 1 unless $Token->{_location};
			next unless refaddr($Token) == refaddr($start);

			# Found the start. Flush it's location
			delete $$Token->{_location};
			last;
		}
	}

	# Iterate over any remaining Tokens and flush their location
	foreach my $Token ( @Tokens ) {
		delete $Token->{_location};
	}

	1;
}





#####################################################################
# XML Compatibility Methods

sub _xml_name {
	my $class = ref $_[0] || $_[0];
	my $name  = lc join( '_', split /::/, $class );
	substr($name, 4);
}

sub _xml_attr {
	return {};
}

sub _xml_content {
	defined $_[0]->{content} ? $_[0]->{content} : '';
}





#####################################################################
# Internals

# Set the error string
sub _error {
	$errstr = $_[1];
	undef;
}

# Clear the error string
sub _clear {
	$errstr = '';
	$_[0];
}

# Being DESTROYed in this manner, rather than by an explicit
# ->delete means our reference count has probably fallen to zero.
# Therefore we don't need to remove ourselves from our parent,
# just the index ( just in case ).
### XS -> PPI/XS.xs:_PPI_Element__DESTROY 0.900+
sub DESTROY { delete $_PARENT{refaddr $_[0]} }

# Operator overloads
sub __equals  { ref $_[1] and refaddr($_[0]) == refaddr($_[1]) }
sub __nequals { !__equals(@_) }
sub __eq {
	my $self  = _INSTANCE($_[0], 'PPI::Element') ? $_[0]->content : $_[0];
	my $other = _INSTANCE($_[1], 'PPI::Element') ? $_[1]->content : $_[1];
	$self eq $other;
}
sub __ne { !__eq(@_) }

1;