File: abstract-syntax-tree.md

package info (click to toggle)
php-league-commonmark 2.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,260 kB
  • sloc: php: 20,378; xml: 1,988; ruby: 45; makefile: 21; javascript: 15
file content (60 lines) | stat: -rw-r--r-- 1,933 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---
layout: default
title: Abstract Syntax Tree
description: Using the Abstract Syntax Tree (AST) to manipulate the parsed content
---

# Abstract Syntax Tree

This library uses a doubly-linked list Abstract Syntax Tree (AST) to represent the parsed block and inline elements.  All such elements extend from the `Node` class.

## `Document`

The root node of the AST will always be a `Document` object.  You can obtain this node a few different ways:

- By calling the `parse()` method on the `DocParser`
- By calling the `getDocument()` method on either the `DocumentPreParsedEvent` or `DocumentParsedEvent` (see the [Event Dispatcher documentation](/1.6/customization/event-dispatcher/))

## Traversal

The following methods can be used to traverse the AST:

- `previous()`
- `next()`
- `parent()`
- `firstChild()`
- `lastChild()`
- `children()`

## Iteration / Walking the Tree

If you'd like to iterate through all the nodes, use the `walker()` method to obtain an instance of `NodeWalker`.  This will walk through the entire tree, emitting `NodeWalkerEvent`s along the way.

```php
use League\CommonMark\Node\NodeWalker;

/** @var NodeWalker $walker */
$walker = $document->walker();
while ($event = $walker->next()) {
    echo 'I am ' . ($event->isEntering() ? 'entering' : 'leaving') . ' a ' . get_class($event->getNode()) . ' node' . "\n";
}
```

This walker doesn't use recursion, so you won't blow the stack when working with deeply-nested nodes.

## Modification

The following methods can be used to modify the AST:

- `insertAfter(Node $sibling)`
- `insertBefore(Node $sibling)`
- `replaceWith(Node $replacement)`
- `detach()`
- `appendChild(Node $child)`
- `prependChild(Node $child)`
- `detachChildren()`
- `replaceChildren(Node[] $children)`

## `DocumentParsedEvent`

The best way to access and manipulate the AST is by adding an [event listener](/1.6/customization/event-dispatcher/) for the `DocumentParsedEvent`.