Skip to main content

php_rs_parser/
lib.rs

1//! Fast, fault-tolerant PHP parser that produces a fully typed AST.
2//!
3//! This crate parses PHP source code (PHP 8.0–8.5) into a [`php_ast::Program`]
4//! tree, recovering from syntax errors so that downstream tools always receive
5//! a complete AST.
6//!
7//! # Quick start
8//!
9//! ```
10//! let arena = bumpalo::Bump::new();
11//! let result = php_rs_parser::parse(&arena, "<?php echo 'hello';");
12//! assert!(result.errors.is_empty());
13//! ```
14//!
15//! # Version-aware parsing
16//!
17//! Use [`parse_versioned`] to target a specific PHP version. Syntax that
18//! requires a higher version is still parsed into the AST, but a
19//! [`diagnostics::ParseError::VersionTooLow`] diagnostic is emitted.
20//!
21//! ```
22//! let arena = bumpalo::Bump::new();
23//! let result = php_rs_parser::parse_versioned(
24//!     &arena,
25//!     "<?php enum Status { case Active; }",
26//!     php_rs_parser::PhpVersion::Php80,
27//! );
28//! assert!(!result.errors.is_empty()); // enums require PHP 8.1
29//! ```
30//!
31//! # Reusing arenas across re-parses (LSP usage)
32//!
33//! Use [`ParserContext`] to avoid allocator churn when the same document is
34//! re-parsed on every edit. The context owns a `bumpalo::Bump` arena and resets
35//! it in O(1) before each parse, reusing the backing memory once it has grown
36//! to a stable size.
37//!
38//! ```
39//! let mut ctx = php_rs_parser::ParserContext::new();
40//!
41//! let result = ctx.reparse("<?php echo 1;");
42//! assert!(result.errors.is_empty());
43//! drop(result); // must be dropped before the next reparse
44//!
45//! let result = ctx.reparse("<?php echo 2;");
46//! assert!(result.errors.is_empty());
47//! ```
48
49pub mod diagnostics;
50pub(crate) mod expr;
51pub mod instrument;
52pub(crate) mod interpolation;
53pub(crate) mod parser;
54pub mod phpdoc;
55pub(crate) mod precedence;
56pub mod source_map;
57pub(crate) mod stmt;
58pub mod version;
59
60use diagnostics::ParseError;
61use php_ast::{Comment, Program};
62use source_map::SourceMap;
63pub use version::PhpVersion;
64
65/// The result of parsing a PHP source string.
66pub struct ParseResult<'arena, 'src> {
67    /// The original source text. Useful for extracting text from spans
68    /// via `&result.source[span.start as usize..span.end as usize]`.
69    pub source: &'src str,
70    /// The parsed AST. Always produced, even when errors are present.
71    pub program: Program<'arena, 'src>,
72    /// All comments found in the source, in source order.
73    /// Comments are not attached to AST nodes; callers can map them by span.
74    pub comments: Vec<Comment<'src>>,
75    /// Parse errors and diagnostics. Empty on a successful parse.
76    pub errors: Vec<ParseError>,
77    /// Pre-computed line index for resolving byte offsets in [`Span`](php_ast::Span)
78    /// to line/column positions. Use [`SourceMap::offset_to_line_col`] or
79    /// [`SourceMap::span_to_line_col`] to convert.
80    pub source_map: SourceMap,
81}
82
83/// Parse PHP `source` using the latest supported PHP version (currently 8.5).
84///
85/// The `arena` is used for all AST allocations, giving callers control over
86/// memory lifetime. The returned [`ParseResult`] borrows from both the arena
87/// and the source string.
88pub fn parse<'arena, 'src>(
89    arena: &'arena bumpalo::Bump,
90    source: &'src str,
91) -> ParseResult<'arena, 'src> {
92    let mut parser = parser::Parser::new(arena, source);
93    let program = parser.parse_program();
94    ParseResult {
95        source,
96        program,
97        comments: parser.take_comments(),
98        errors: parser.into_errors(),
99        source_map: SourceMap::new(source),
100    }
101}
102
103/// Parse `source` targeting the given PHP `version`.
104///
105/// Syntax that requires a higher version than `version` is still parsed and
106/// included in the AST, but a [`diagnostics::ParseError::VersionTooLow`] error
107/// is also emitted so callers can report it to the user.
108pub fn parse_versioned<'arena, 'src>(
109    arena: &'arena bumpalo::Bump,
110    source: &'src str,
111    version: PhpVersion,
112) -> ParseResult<'arena, 'src> {
113    let mut parser = parser::Parser::with_version(arena, source, version);
114    let program = parser.parse_program();
115    ParseResult {
116        source,
117        program,
118        comments: parser.take_comments(),
119        errors: parser.into_errors(),
120        source_map: SourceMap::new(source),
121    }
122}
123
124/// A reusable parse context that keeps a `bumpalo::Bump` arena alive between
125/// re-parses, resetting it (O(1)) instead of dropping and reallocating.
126///
127/// This is the preferred entry point for LSP servers or any tool that parses
128/// the same document repeatedly. Once the arena has grown to accommodate the
129/// largest document seen, subsequent parses reuse the backing memory without
130/// any new allocations.
131///
132/// The Rust lifetime system enforces safety: the returned [`ParseResult`]
133/// borrows from `self`, so the borrow checker prevents calling [`reparse`] or
134/// [`reparse_versioned`] again while the previous result is still alive.
135///
136/// [`reparse`]: ParserContext::reparse
137/// [`reparse_versioned`]: ParserContext::reparse_versioned
138///
139/// # Example
140///
141/// ```
142/// let mut ctx = php_rs_parser::ParserContext::new();
143///
144/// let result = ctx.reparse("<?php echo 1;");
145/// assert!(result.errors.is_empty());
146/// drop(result); // must be dropped before the next reparse
147///
148/// let result = ctx.reparse("<?php echo 2;");
149/// assert!(result.errors.is_empty());
150/// ```
151pub struct ParserContext {
152    arena: bumpalo::Bump,
153}
154
155impl ParserContext {
156    /// Create a new context with an empty arena.
157    pub fn new() -> Self {
158        Self {
159            arena: bumpalo::Bump::new(),
160        }
161    }
162
163    /// Reset the arena and parse `source` using PHP 8.5 (the latest version).
164    ///
165    /// The previous [`ParseResult`] **must be dropped** before calling this
166    /// method. The borrow checker enforces this: the returned result borrows
167    /// `self` for the duration of its lifetime, so a second call while the
168    /// first result is still live is a compile-time error.
169    pub fn reparse<'a, 'src>(&'a mut self, source: &'src str) -> ParseResult<'a, 'src> {
170        self.arena.reset();
171        parse(&self.arena, source)
172    }
173
174    /// Reset the arena and parse `source` targeting the given PHP `version`.
175    ///
176    /// See [`reparse`](ParserContext::reparse) for lifetime safety notes.
177    pub fn reparse_versioned<'a, 'src>(
178        &'a mut self,
179        source: &'src str,
180        version: PhpVersion,
181    ) -> ParseResult<'a, 'src> {
182        self.arena.reset();
183        parse_versioned(&self.arena, source, version)
184    }
185}
186
187impl Default for ParserContext {
188    fn default() -> Self {
189        Self::new()
190    }
191}