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//! # 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 parser;
53pub use phpdoc_parser as phpdoc;
54pub(crate) mod precedence;
55pub mod source_map;
56pub(crate) mod stmt;
57pub mod version;
58
59use diagnostics::ParseError;
60use php_ast::{Comment, Program};
61use source_map::SourceMap;
62pub use version::PhpVersion;
63
64/// The result of parsing a PHP source string.
65pub struct ParseResult<'arena, 'src> {
66    /// The original source text. Useful for extracting text from spans
67    /// via `&result.source[span.start as usize..span.end as usize]`.
68    pub source: &'src str,
69    /// The parsed AST. Always produced, even when errors are present.
70    pub program: Program<'arena, 'src>,
71    /// All comments found in the source, in source order, **except** `/** */`
72    /// doc-block comments that are immediately attached to a declaration.
73    ///
74    /// When the parser encounters a `/** */` comment directly before a
75    /// function, class, method, property, constant, or enum case, it removes
76    /// that comment from this list and stores it in the declaration node's
77    /// `doc_comment` field instead. The two collections are therefore
78    /// **disjoint**: iterating both without deduplication will double-count
79    /// nothing, but iterating only one will miss the other's entries.
80    ///
81    /// To process every comment in the file, iterate `result.comments` (for
82    /// line, hash, block, and unattached doc comments) and also visit each
83    /// declaration node's `doc_comment` field. Or use
84    /// [`php_ast::visitor::walk_comments`] with a [`Visitor`] that also
85    /// overrides the declaration visit methods.
86    pub comments: Vec<Comment<'src>>,
87    /// Parse errors and diagnostics. Empty on a successful parse.
88    pub errors: Vec<ParseError>,
89    /// `true` when the error list was capped at the internal limit and further
90    /// errors were silently dropped. Callers that need a complete error list
91    /// (e.g. linters) should treat this as an incomplete result.
92    pub errors_truncated: bool,
93    /// Pre-computed line index for resolving byte offsets in [`Span`](php_ast::Span)
94    /// to line/column positions. Use [`SourceMap::offset_to_line_col`] or
95    /// [`SourceMap::span_to_line_col`] to convert.
96    pub source_map: SourceMap,
97}
98
99/// Parse PHP `source` using the latest supported PHP version (currently 8.5).
100///
101/// The `arena` is used for all AST allocations, giving callers control over
102/// memory lifetime. The returned [`ParseResult`] borrows from both the arena
103/// and the source string.
104pub fn parse<'arena, 'src>(
105    arena: &'arena bumpalo::Bump,
106    source: &'src str,
107) -> ParseResult<'arena, 'src> {
108    let mut parser = parser::Parser::new(arena, source);
109    let program = parser.parse_program();
110    let errors_truncated = parser.errors_truncated();
111    ParseResult {
112        source,
113        program,
114        comments: parser.take_comments(),
115        errors: parser.into_errors(),
116        errors_truncated,
117        source_map: SourceMap::new(source),
118    }
119}
120
121/// Parse `source` targeting the given PHP `version`.
122///
123/// Syntax that requires a higher version than `version` is still parsed and
124/// included in the AST, but a [`diagnostics::ParseError::VersionTooLow`] error
125/// is also emitted so callers can report it to the user.
126pub fn parse_versioned<'arena, 'src>(
127    arena: &'arena bumpalo::Bump,
128    source: &'src str,
129    version: PhpVersion,
130) -> ParseResult<'arena, 'src> {
131    let mut parser = parser::Parser::with_version(arena, source, version);
132    let program = parser.parse_program();
133    let errors_truncated = parser.errors_truncated();
134    ParseResult {
135        source,
136        program,
137        comments: parser.take_comments(),
138        errors: parser.into_errors(),
139        errors_truncated,
140        source_map: SourceMap::new(source),
141    }
142}
143
144/// A reusable parse context that keeps a `bumpalo::Bump` arena alive between
145/// re-parses, resetting it (O(1)) instead of dropping and reallocating.
146///
147/// This is the preferred entry point for LSP servers or any tool that parses
148/// the same document repeatedly. Once the arena has grown to accommodate the
149/// largest document seen, subsequent parses reuse the backing memory without
150/// any new allocations.
151///
152/// The Rust lifetime system enforces safety: the returned [`ParseResult`]
153/// borrows from `self`, so the borrow checker prevents calling [`reparse`] or
154/// [`reparse_versioned`] again while the previous result is still alive.
155///
156/// [`reparse`]: ParserContext::reparse
157/// [`reparse_versioned`]: ParserContext::reparse_versioned
158///
159/// # Example
160///
161/// ```
162/// let mut ctx = php_rs_parser::ParserContext::new();
163///
164/// let result = ctx.reparse("<?php echo 1;");
165/// assert!(result.errors.is_empty());
166/// drop(result); // must be dropped before the next reparse
167///
168/// let result = ctx.reparse("<?php echo 2;");
169/// assert!(result.errors.is_empty());
170/// ```
171pub struct ParserContext {
172    arena: bumpalo::Bump,
173}
174
175impl ParserContext {
176    /// Create a new context with an empty arena.
177    pub fn new() -> Self {
178        Self {
179            arena: bumpalo::Bump::new(),
180        }
181    }
182
183    /// Reset the arena and parse `source` using PHP 8.5 (the latest version).
184    ///
185    /// The previous [`ParseResult`] **must be dropped** before calling this
186    /// method. The borrow checker enforces this: the returned result borrows
187    /// `self` for the duration of its lifetime, so a second call while the
188    /// first result is still live is a compile-time error.
189    pub fn reparse<'a, 'src>(&'a mut self, source: &'src str) -> ParseResult<'a, 'src> {
190        self.arena.reset();
191        parse(&self.arena, source)
192    }
193
194    /// Reset the arena and parse `source` targeting the given PHP `version`.
195    ///
196    /// See [`reparse`](ParserContext::reparse) for lifetime safety notes.
197    pub fn reparse_versioned<'a, 'src>(
198        &'a mut self,
199        source: &'src str,
200        version: PhpVersion,
201    ) -> ParseResult<'a, 'src> {
202        self.arena.reset();
203        parse_versioned(&self.arena, source, version)
204    }
205}
206
207impl Default for ParserContext {
208    fn default() -> Self {
209        Self::new()
210    }
211}