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 7.4–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//! # Semantic-rejection responsibility
8//!
9//! The parser is fault-tolerant: it always produces an AST and reports every
10//! error it can identify before recovering. Its semantic-rejection
11//! responsibility is defined externally:
12//!
13//! > **For any input, the parser emits at least one diagnostic iff `php -l`
14//! > would reject that input at the configured target PHP version.**
15//!
16//! Flow-sensitive checks — cross-file resolution, unused variables, dead code,
17//! type-mismatched returns — are out of scope and belong in a later semantic
18//! layer. Checks decidable from one declaration, one parameter list, one
19//! modifier set, or one declaration loop are in scope and use
20//! [`diagnostics::ParseError::Forbidden`].
21//!
22//! The `===php_error===` section in `tests/fixtures/**/*.phpt` records `php -l`
23//! output; the fixture runner enforces the rule above by failing CI when PHP
24//! rejects an input that the parser silently accepts.
25//!
26//! # Quick start
27//!
28//! ```
29//! let result = php_rs_parser::parse("<?php echo 'hello';");
30//! assert!(result.errors.is_empty());
31//! ```
32//!
33//! # Version-aware parsing
34//!
35//! Use [`parse_versioned`] to target a specific PHP version. Syntax that
36//! requires a higher version is still parsed into the AST, but a
37//! [`diagnostics::ParseError::VersionTooLow`] diagnostic is emitted.
38//!
39//! ```
40//! let result = php_rs_parser::parse_versioned(
41//!     "<?php enum Status { case Active; }",
42//!     php_rs_parser::PhpVersion::Php80,
43//! );
44//! assert!(!result.errors.is_empty()); // enums require PHP 8.1
45//! ```
46//!
47//! # Multi-file cache
48//!
49//! [`parse`] returns a [`ParseResult`] with no lifetime parameters — fully
50//! owned, storable in a `HashMap`, sendable across threads.
51//!
52//! ```
53//! use std::collections::HashMap;
54//! use std::path::PathBuf;
55//!
56//! let mut cache: HashMap<PathBuf, php_rs_parser::ParseResult> = HashMap::new();
57//! cache.insert(PathBuf::from("a.php"), php_rs_parser::parse("<?php echo 1;"));
58//! ```
59//!
60//! # Arena API (LSP / hot-path usage)
61//!
62//! Use [`parse_arena`] / [`ParserContext`] when you need maximum throughput
63//! and can manage the arena lifetime yourself. The returned
64//! [`ArenaParseResult`] borrows from both the arena and the source string —
65//! no allocation copying occurs.
66//!
67//! ```
68//! let mut ctx = php_rs_parser::ParserContext::new();
69//!
70//! let result = ctx.reparse("<?php echo 1;");
71//! assert!(result.errors.is_empty());
72//! drop(result); // must be dropped before the next reparse
73//!
74//! let result = ctx.reparse("<?php echo 2;");
75//! assert!(result.errors.is_empty());
76//! ```
77
78pub mod diagnostics;
79pub(crate) mod expr;
80pub mod instrument;
81pub(crate) mod parser;
82pub use phpdoc_parser as phpdoc;
83pub(crate) mod precedence;
84pub mod source_map;
85pub(crate) mod stmt;
86pub mod version;
87
88use diagnostics::ParseError;
89use php_ast::owned::Comment as OwnedComment;
90use php_ast::{owned::to_owned_program, Comment, Program};
91use source_map::SourceMap;
92pub use version::PhpVersion;
93
94/// Lifetime-free result of parsing a PHP source string.
95///
96/// This is the primary return type of [`parse`] and [`parse_versioned`]. The
97/// AST is fully owned (`Box<str>`, `Box<[T]>`) so it can be stored in a
98/// `HashMap`, sent across threads, or cached alongside other data without
99/// fighting the borrow checker.
100///
101/// Use [`parse_arena`] or [`ParserContext`] when you need the arena-allocated
102/// form for maximum throughput in tight loops or LSP re-parse scenarios.
103pub struct ParseResult {
104    /// The original source text, owned.
105    pub source: String,
106    /// The parsed AST, fully owned with no lifetime parameters.
107    pub program: php_ast::owned::Program,
108    /// All comments found in the source, in source order. Doc-block comments
109    /// attached to a declaration are stored in the declaration node's
110    /// `doc_comment` field, not here.
111    pub comments: Vec<php_ast::owned::Comment>,
112    /// Parse errors and diagnostics. Empty on a successful parse.
113    pub errors: Vec<ParseError>,
114    /// `true` when the error list was capped and further errors were dropped.
115    pub errors_truncated: bool,
116    /// Pre-computed line index for span-to-line/column resolution.
117    pub source_map: SourceMap,
118}
119
120impl ParseResult {
121    fn from_arena_result(result: ArenaParseResult<'_, '_>) -> Self {
122        let program = to_owned_program(&result.program);
123        let comments = result
124            .comments
125            .iter()
126            .map(|c| OwnedComment {
127                kind: c.kind,
128                text: c.text.into(),
129                span: c.span,
130            })
131            .collect();
132        Self {
133            source: result.source.to_owned(),
134            program,
135            comments,
136            errors: result.errors,
137            errors_truncated: result.errors_truncated,
138            source_map: result.source_map,
139        }
140    }
141}
142
143/// Arena-allocated result of parsing a PHP source string.
144///
145/// Returned by [`parse_arena`], [`parse_arena_versioned`], and
146/// [`ParserContext::reparse`]. Both the AST and the source text are borrowed,
147/// so this type has two lifetime parameters. Use [`ParseResult`] (from
148/// [`parse`]) when you need an owned, lifetime-free result.
149pub struct ArenaParseResult<'arena, 'src> {
150    /// The original source text. Useful for extracting text from spans
151    /// via `&result.source[span.start as usize..span.end as usize]`.
152    pub source: &'src str,
153    /// The parsed AST. Always produced, even when errors are present.
154    pub program: Program<'arena, 'src>,
155    /// All comments found in the source, in source order, **except** `/** */`
156    /// doc-block comments that are immediately attached to a declaration.
157    ///
158    /// When the parser encounters a `/** */` comment directly before a
159    /// function, class, method, property, constant, or enum case, it removes
160    /// that comment from this list and stores it in the declaration node's
161    /// `doc_comment` field instead. The two collections are therefore
162    /// **disjoint**: iterating both without deduplication will double-count
163    /// nothing, but iterating only one will miss the other's entries.
164    ///
165    /// To process every comment in the file, iterate `result.comments` (for
166    /// line, hash, block, and unattached doc comments) and also visit each
167    /// declaration node's `doc_comment` field. Or use
168    /// [`php_ast::visitor::walk_comments`] with a [`Visitor`] that also
169    /// overrides the declaration visit methods.
170    pub comments: Vec<Comment<'src>>,
171    /// Parse errors and diagnostics. Empty on a successful parse.
172    pub errors: Vec<ParseError>,
173    /// `true` when the error list was capped at the internal limit and further
174    /// errors were silently dropped. Callers that need a complete error list
175    /// (e.g. linters) should treat this as an incomplete result.
176    pub errors_truncated: bool,
177    /// Pre-computed line index for resolving byte offsets in [`Span`](php_ast::Span)
178    /// to line/column positions. Use [`SourceMap::offset_to_line_col`] or
179    /// [`SourceMap::span_to_line_col`] to convert.
180    pub source_map: SourceMap,
181}
182
183/// Parse PHP `source` using the latest supported PHP version (currently 8.5).
184///
185/// Returns a fully-owned [`ParseResult`] with no lifetime parameters. The
186/// internal arena is created, used, and converted within this call.
187///
188/// Use [`parse_arena`] when you need the raw arena-allocated AST for maximum
189/// throughput (no allocation copying).
190pub fn parse(source: &str) -> ParseResult {
191    let arena = bumpalo::Bump::new();
192    ParseResult::from_arena_result(parse_arena(&arena, source))
193}
194
195/// Parse `source` targeting the given PHP `version`.
196///
197/// Syntax that requires a higher version than `version` is still parsed and
198/// included in the AST, but a [`diagnostics::ParseError::VersionTooLow`] error
199/// is also emitted so callers can report it to the user.
200///
201/// Returns a fully-owned [`ParseResult`]. Use [`parse_arena_versioned`] for the
202/// arena form.
203pub fn parse_versioned(source: &str, version: PhpVersion) -> ParseResult {
204    let arena = bumpalo::Bump::new();
205    ParseResult::from_arena_result(parse_arena_versioned(&arena, source, version))
206}
207
208/// Parse PHP `source` using the latest supported PHP version, returning an
209/// arena-allocated [`ArenaParseResult`].
210///
211/// The `arena` is used for all AST allocations, giving callers control over
212/// memory lifetime. The returned result borrows from both the arena and the
213/// source string.
214///
215/// Prefer [`parse`] unless you are managing the arena yourself for performance
216/// reasons (e.g. LSP re-parsing with [`ParserContext`]).
217pub fn parse_arena<'arena, 'src>(
218    arena: &'arena bumpalo::Bump,
219    source: &'src str,
220) -> ArenaParseResult<'arena, 'src> {
221    let mut parser = parser::Parser::new(arena, source);
222    let program = parser.parse_program();
223    let errors_truncated = parser.errors_truncated();
224    ArenaParseResult {
225        source,
226        program,
227        comments: parser.take_comments(),
228        errors: parser.into_errors(),
229        errors_truncated,
230        source_map: SourceMap::new(source),
231    }
232}
233
234/// Parse `source` targeting the given PHP `version`, returning an
235/// arena-allocated [`ArenaParseResult`].
236///
237/// See [`parse_arena`] for arena lifetime semantics and [`parse_versioned`] for
238/// version-gating behaviour.
239pub fn parse_arena_versioned<'arena, 'src>(
240    arena: &'arena bumpalo::Bump,
241    source: &'src str,
242    version: PhpVersion,
243) -> ArenaParseResult<'arena, 'src> {
244    let mut parser = parser::Parser::with_version(arena, source, version);
245    let program = parser.parse_program();
246    let errors_truncated = parser.errors_truncated();
247    ArenaParseResult {
248        source,
249        program,
250        comments: parser.take_comments(),
251        errors: parser.into_errors(),
252        errors_truncated,
253        source_map: SourceMap::new(source),
254    }
255}
256
257/// A reusable parse context that keeps a `bumpalo::Bump` arena alive between
258/// re-parses, resetting it (O(1)) instead of dropping and reallocating.
259///
260/// This is the preferred entry point for LSP servers or any tool that parses
261/// the same document repeatedly. Once the arena has grown to accommodate the
262/// largest document seen, subsequent parses reuse the backing memory without
263/// any new allocations.
264///
265/// The Rust lifetime system enforces safety: the returned [`ArenaParseResult`]
266/// borrows from `self`, so the borrow checker prevents calling [`reparse`] or
267/// [`reparse_versioned`] again while the previous result is still alive.
268///
269/// [`reparse`]: ParserContext::reparse
270/// [`reparse_versioned`]: ParserContext::reparse_versioned
271///
272/// # Example
273///
274/// ```
275/// let mut ctx = php_rs_parser::ParserContext::new();
276///
277/// let result = ctx.reparse("<?php echo 1;");
278/// assert!(result.errors.is_empty());
279/// drop(result); // must be dropped before the next reparse
280///
281/// let result = ctx.reparse("<?php echo 2;");
282/// assert!(result.errors.is_empty());
283/// ```
284pub struct ParserContext {
285    arena: bumpalo::Bump,
286}
287
288impl ParserContext {
289    /// Create a new context with an empty arena.
290    pub fn new() -> Self {
291        Self {
292            arena: bumpalo::Bump::new(),
293        }
294    }
295
296    /// Reset the arena and parse `source` using PHP 8.5 (the latest version).
297    ///
298    /// The previous [`ArenaParseResult`] **must be dropped** before calling
299    /// this method. The borrow checker enforces this: the returned result
300    /// borrows `self` for the duration of its lifetime, so a second call while
301    /// the first result is still live is a compile-time error.
302    pub fn reparse<'a, 'src>(&'a mut self, source: &'src str) -> ArenaParseResult<'a, 'src> {
303        self.arena.reset();
304        parse_arena(&self.arena, source)
305    }
306
307    /// Reset the arena and parse `source` targeting the given PHP `version`.
308    ///
309    /// See [`reparse`](ParserContext::reparse) for lifetime safety notes.
310    pub fn reparse_versioned<'a, 'src>(
311        &'a mut self,
312        source: &'src str,
313        version: PhpVersion,
314    ) -> ArenaParseResult<'a, 'src> {
315        self.arena.reset();
316        parse_arena_versioned(&self.arena, source, version)
317    }
318
319    /// Reset the arena and parse `source`, returning a fully-owned [`ParseResult`].
320    ///
321    /// Unlike [`reparse`](ParserContext::reparse), the returned result has no
322    /// lifetime parameters and can be stored anywhere. The arena is reused for
323    /// the parse but the output is immediately converted to owned types, so
324    /// there is no borrow on `self` after this call returns.
325    pub fn reparse_owned(&mut self, source: &str) -> ParseResult {
326        self.arena.reset();
327        ParseResult::from_arena_result(parse_arena(&self.arena, source))
328    }
329
330    /// Reset the arena and parse `source` targeting the given PHP `version`,
331    /// returning a fully-owned [`ParseResult`].
332    ///
333    /// See [`reparse_owned`](ParserContext::reparse_owned) for ownership notes
334    /// and [`reparse_versioned`](ParserContext::reparse_versioned) for version
335    /// semantics.
336    pub fn reparse_owned_versioned(&mut self, source: &str, version: PhpVersion) -> ParseResult {
337        self.arena.reset();
338        ParseResult::from_arena_result(parse_arena_versioned(&self.arena, source, version))
339    }
340}
341
342impl Default for ParserContext {
343    fn default() -> Self {
344        Self::new()
345    }
346}