Skip to main content

Node

Struct Node 

Source
pub struct Node {
    pub kind: NodeKind,
    pub location: ByteSpan,
}
Expand description

Core AST types re-exported for convenience. Re-exported AST node types used during Parse/Index/Analyze stages. Core AST node representing any Perl language construct within parsing workflows.

This is the fundamental building block for representing parsed Perl code. Each node contains both the semantic information (kind) and positional information (location) necessary for comprehensive script analysis.

§LSP Workflow Role

Nodes flow through tooling stages:

  • Parse: Created by the parser as it builds the syntax tree
  • Index: Visited to build symbol and reference tables
  • Navigate: Used to resolve definitions, references, and call hierarchy
  • Complete: Provides contextual information for completion and hover
  • Analyze: Drives semantic analysis and diagnostics

§Memory Optimization

The structure is designed for efficient memory usage during large-scale parsing:

  • SourceLocation uses compact position encoding for large files
  • NodeKind enum variants minimize memory overhead for common constructs
  • Clone operations are optimized for shared analysis workflows

§Examples

Construct a variable declaration node manually:

use perl_ast::{Node, NodeKind, SourceLocation};

let loc = SourceLocation { start: 0, end: 11 };
let var = Node::new(
    NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() },
    loc,
);
let decl = Node::new(
    NodeKind::VariableDeclaration {
        declarator: "my".to_string(),
        variable: Box::new(var),
        attributes: vec![],
        initializer: None,
    },
    loc,
);
assert_eq!(decl.kind.kind_name(), "VariableDeclaration");

Typically you obtain nodes from the parser rather than constructing them by hand:

use perl_parser::Parser;

let mut parser = Parser::new("my $x = 42;");
let ast = parser.parse()?;
println!("AST: {}", ast.to_sexp());

Fields§

§kind: NodeKind

The specific type and semantic content of this AST node

§location: ByteSpan

Source position information for error reporting and code navigation

Implementations§

Source§

impl Node

Source

pub fn new(kind: NodeKind, location: ByteSpan) -> Node

Create a new AST node with the given kind and source location.

§Examples
use perl_ast::{Node, NodeKind, SourceLocation};

let node = Node::new(
    NodeKind::Number { value: "42".to_string() },
    SourceLocation { start: 0, end: 2 },
);
assert_eq!(node.kind.kind_name(), "Number");
assert_eq!(node.location.start, 0);
Source

pub fn to_sexp(&self) -> String

Convert the AST to a tree-sitter compatible S-expression.

Produces a parenthesized representation compatible with tree-sitter’s S-expression format, useful for debugging and snapshot testing.

§Examples
use perl_ast::{Node, NodeKind, SourceLocation};

let loc = SourceLocation { start: 0, end: 2 };
let num = Node::new(NodeKind::Number { value: "42".to_string() }, loc);
let program = Node::new(
    NodeKind::Program { statements: vec![num] },
    loc,
);
let sexp = program.to_sexp();
assert!(sexp.starts_with("(source_file"));
Source

pub fn to_sexp_inner(&self) -> String

Convert the AST to S-expression format that unwraps expression statements in programs

Source

pub fn for_each_child_mut<F>(&mut self, f: F)
where F: FnMut(&mut Node),

Call a function on every direct child node of this node.

This enables depth-first traversal for operations like heredoc content attachment. The closure receives a mutable reference to each child node.

Source

pub fn for_each_child<'a, F>(&'a self, f: F)
where F: FnMut(&'a Node),

Call a function on every direct child node of this node (immutable version).

This enables depth-first traversal for read-only operations like AST analysis. The closure receives an immutable reference to each child node.

Source

pub fn count_nodes(&self) -> usize

Count the total number of nodes in this subtree (inclusive).

§Examples
use perl_ast::{Node, NodeKind, SourceLocation};

let loc = SourceLocation { start: 0, end: 1 };
let leaf = Node::new(NodeKind::Number { value: "1".to_string() }, loc);
assert_eq!(leaf.count_nodes(), 1);

let program = Node::new(
    NodeKind::Program { statements: vec![leaf] },
    loc,
);
assert_eq!(program.count_nodes(), 2);
Source

pub fn children(&self) -> Vec<&Node>

Collect direct child nodes into a vector for convenience APIs.

§Examples
use perl_ast::{Node, NodeKind, SourceLocation};

let loc = SourceLocation { start: 0, end: 1 };
let stmt = Node::new(NodeKind::Number { value: "1".to_string() }, loc);
let program = Node::new(
    NodeKind::Program { statements: vec![stmt] },
    loc,
);
assert_eq!(program.children().len(), 1);
Source

pub fn first_child(&self) -> Option<&Node>

Get the first direct child node, if any.

Optimized to avoid allocating the children vector.

Trait Implementations§

Source§

impl Clone for Node

Source§

fn clone(&self) -> Node

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Node

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Node

Source§

fn eq(&self, other: &Node) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Node

Auto Trait Implementations§

§

impl Freeze for Node

§

impl RefUnwindSafe for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl UnsafeUnpin for Node

§

impl UnwindSafe for Node

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more