Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/benchmark.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ jobs:
find laravel/vendor -depth -type d -name tests -exec rm -rf {} +

- name: Run benchmark (php-parser-in-rust vs php-parser-in-go vs mago-syntax)
# bash with pipefail, so a failing benchmark fails the step
shell: bash
run: |
{
echo "## Corpus benchmark"
Expand Down
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"

[dependencies]
bumpalo = { version = "3", features = ["collections"] }

[profile.release]
codegen-units = 1
Expand Down
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ Parsing the full Laravel framework (`src/` + Composer `vendor/`, 18157 files) on

| Parser | Avg | Peak mem |
|:-------|----:|---------:|
| php-parser-in-rust | 1186 ms | 153 MB |
| [php-parser-in-go](https://github.com/rectorphp/php-parser-in-go) | 2557 ms | 4428 MB |
| [mago-syntax](https://crates.io/crates/mago-syntax) | 536 ms | 151 MB |
| php-parser-in-rust | 300 ms | 96 MB |
| [php-parser-in-go](https://github.com/rectorphp/php-parser-in-go) | 1616 ms | 4429 MB |
| [mago-syntax](https://crates.io/crates/mago-syntax) | 341 ms | 145 MB |

- The Go benchmark runs with the GC disabled, which explains most of its memory.
- mago-syntax allocates each tree in an arena and builds its own CST; it has no PHP version setting. The others parse as PHP 8.3 into the Go AST.
- php-parser-in-rust and mago-syntax allocate each tree in an arena.
- mago-syntax builds its own CST and has no PHP version setting. The others parse as PHP 8.3 into the Go AST.

CI reruns this on every push and every 12 hours, see the **Summary** of the Benchmark workflow. Run it locally on any corpus:

Expand All @@ -24,11 +25,13 @@ bench/compare.sh ./laravel
## Usage

```rust
use php_parser::{parse, Config, version::Version};
use php_parser::{parse, Arena, Config, version::Version};
use php_parser::visitor::dumper::Dumper;

// the arena owns the whole tree and frees it at once
let arena = Arena::new();
let source = b"<?php echo 'hi';";
let result = parse(source, Config { version: Some(Version::new(8, 3)) }).unwrap();
let result = parse(&arena, source, Config { version: Some(Version::new(8, 3)) }).unwrap();

for error in &result.errors {
eprintln!("{error}");
Expand All @@ -41,8 +44,8 @@ if let Some(root) = &result.root {

## Modules

- `parse(source, Config)` - entry point, picks the PHP 5, 7 or 8 grammar by version.
- `ast` - AST nodes, one struct per Go node, wrapped in the `Node` enum.
- `parse(&arena, source, Config)` - entry point, picks the PHP 5, 7 or 8 grammar by version.
- `ast` - AST nodes, one struct per Go node, wrapped in the `Node` enum and allocated in an `Arena`.
- `visitor` - `Visitor` trait, traverser, printer, dumper, formatter, namespace and class resolvers, doc comments.
- `typescope` - static type of value expressions inside a class.
- `token`, `position`, `version`, `errors`.
Expand Down
3 changes: 2 additions & 1 deletion bench/compare.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ cp "$root/target/release/benchmark" "$bin/rust"
cargo build --release --quiet --manifest-path "$root/bench/mago/Cargo.toml"
cp "$root/bench/mago/target/release/bench-mago" "$bin/mago"

if [ ! -d "$bin/php-parser-in-go" ]; then
if [ ! -f "$bin/php-parser-in-go/go.mod" ]; then
rm -rf "$bin/php-parser-in-go"
git clone --quiet --depth 1 https://github.com/rectorphp/php-parser-in-go "$bin/php-parser-in-go"
fi
(cd "$bin/php-parser-in-go" && go build -o "$bin/go" ./benchmark)
Expand Down
49 changes: 32 additions & 17 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::any::Any;
use std::collections::HashMap;
use std::fmt;

mod name;
Expand All @@ -8,40 +6,57 @@ mod nodes;
pub use name::{is_reserved_type, to_string};
pub use nodes::*;

/// Metadata assigned to a node after parsing, such as a resolved type. The map
/// Memory block that owns every node, token and list of the trees parsed into
/// it. Dropping it frees them all at once.
pub type Arena = bumpalo::Bump;

/// List allocated in an [`Arena`].
pub type Vec<'a, T> = bumpalo::collections::Vec<'a, T>;

/// Moves a node struct into the arena and wraps it in its [`Node`] variant.
pub trait IntoNode<'a> {
fn node(self, arena: &'a Arena) -> Node<'a>;
}

/// Metadata assigned to a node after parsing, such as a resolved name. The list
/// is allocated lazily, so a node that never gets one costs a single word.
#[derive(Default)]
#[allow(clippy::box_collection)]
pub struct Attributes(Option<Box<HashMap<String, Box<dyn Any>>>>);
pub struct Attributes<'a>(Option<&'a mut Vec<'a, (&'a str, &'a str)>>);

impl Attributes {
impl<'a> Attributes<'a> {
/// Store `value` under `key`.
pub fn set<T: Any>(&mut self, key: impl Into<String>, value: T) {
self.0
.get_or_insert_with(Default::default)
.insert(key.into(), Box::new(value));
pub fn set(&mut self, arena: &'a Arena, key: &str, value: &str) {
let value = &*arena.alloc_str(value);
let list = self
.0
.get_or_insert_with(|| arena.alloc(Vec::new_in(arena)));
match list.iter_mut().find(|(k, _)| *k == key) {
Some(entry) => entry.1 = value,
None => list.push((arena.alloc_str(key), value)),
}
}

/// Value stored under `key`, if present and of type `T`.
pub fn get<T: Any>(&self, key: &str) -> Option<&T> {
self.0.as_ref()?.get(key)?.downcast_ref()
/// Value stored under `key`.
pub fn get(&self, key: &str) -> Option<&'a str> {
let list = self.0.as_ref()?;
list.iter().find(|(k, _)| *k == key).map(|(_, v)| *v)
}

/// Whether a value is stored under `key`.
pub fn has(&self, key: &str) -> bool {
self.0.as_ref().is_some_and(|map| map.contains_key(key))
self.get(key).is_some()
}

pub fn is_empty(&self) -> bool {
self.0.as_ref().is_none_or(|map| map.is_empty())
self.0.as_ref().is_none_or(|list| list.is_empty())
}
}

impl fmt::Debug for Attributes {
impl fmt::Debug for Attributes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
None => f.write_str("{}"),
Some(map) => f.debug_set().entries(map.keys()).finish(),
Some(list) => f.debug_set().entries(list.iter().map(|(k, _)| k)).finish(),
}
}
}
6 changes: 3 additions & 3 deletions src/ast/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub fn to_string(node: &Node<'_>) -> String {
Node::Name(n) => parts_to_string(n.parts.as_deref()),
Node::NameFullyQualified(n) => parts_to_string(n.parts.as_deref()),
Node::NameRelative(n) => parts_to_string(n.parts.as_deref()),
Node::NamePart(n) => lossy(n.value.as_deref()),
Node::Identifier(n) => lossy(n.value.as_deref()),
Node::NamePart(n) => lossy(n.value),
Node::Identifier(n) => lossy(n.value),
_ => String::new(),
}
}
Expand All @@ -22,7 +22,7 @@ fn parts_to_string(parts: Option<&[Node<'_>]>) -> String {
let mut segments = Vec::new();
for part in parts.unwrap_or_default() {
if let Node::NamePart(name_part) = part {
segments.push(lossy(name_part.value.as_deref()));
segments.push(lossy(name_part.value));
}
}
segments.join("\\")
Expand Down
Loading
Loading