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 mod 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.
72 /// Comments are not attached to AST nodes; callers can map them by span.
73 pub comments: Vec<Comment<'src>>,
74 /// Parse errors and diagnostics. Empty on a successful parse.
75 pub errors: Vec<ParseError>,
76 /// `true` when the error list was capped at the internal limit and further
77 /// errors were silently dropped. Callers that need a complete error list
78 /// (e.g. linters) should treat this as an incomplete result.
79 pub errors_truncated: bool,
80 /// Pre-computed line index for resolving byte offsets in [`Span`](php_ast::Span)
81 /// to line/column positions. Use [`SourceMap::offset_to_line_col`] or
82 /// [`SourceMap::span_to_line_col`] to convert.
83 pub source_map: SourceMap,
84}
85
86/// Parse PHP `source` using the latest supported PHP version (currently 8.5).
87///
88/// The `arena` is used for all AST allocations, giving callers control over
89/// memory lifetime. The returned [`ParseResult`] borrows from both the arena
90/// and the source string.
91pub fn parse<'arena, 'src>(
92 arena: &'arena bumpalo::Bump,
93 source: &'src str,
94) -> ParseResult<'arena, 'src> {
95 let mut parser = parser::Parser::new(arena, source);
96 let program = parser.parse_program();
97 let errors_truncated = parser.errors_truncated();
98 ParseResult {
99 source,
100 program,
101 comments: parser.take_comments(),
102 errors: parser.into_errors(),
103 errors_truncated,
104 source_map: SourceMap::new(source),
105 }
106}
107
108/// Parse `source` targeting the given PHP `version`.
109///
110/// Syntax that requires a higher version than `version` is still parsed and
111/// included in the AST, but a [`diagnostics::ParseError::VersionTooLow`] error
112/// is also emitted so callers can report it to the user.
113pub fn parse_versioned<'arena, 'src>(
114 arena: &'arena bumpalo::Bump,
115 source: &'src str,
116 version: PhpVersion,
117) -> ParseResult<'arena, 'src> {
118 let mut parser = parser::Parser::with_version(arena, source, version);
119 let program = parser.parse_program();
120 let errors_truncated = parser.errors_truncated();
121 ParseResult {
122 source,
123 program,
124 comments: parser.take_comments(),
125 errors: parser.into_errors(),
126 errors_truncated,
127 source_map: SourceMap::new(source),
128 }
129}
130
131/// A reusable parse context that keeps a `bumpalo::Bump` arena alive between
132/// re-parses, resetting it (O(1)) instead of dropping and reallocating.
133///
134/// This is the preferred entry point for LSP servers or any tool that parses
135/// the same document repeatedly. Once the arena has grown to accommodate the
136/// largest document seen, subsequent parses reuse the backing memory without
137/// any new allocations.
138///
139/// The Rust lifetime system enforces safety: the returned [`ParseResult`]
140/// borrows from `self`, so the borrow checker prevents calling [`reparse`] or
141/// [`reparse_versioned`] again while the previous result is still alive.
142///
143/// [`reparse`]: ParserContext::reparse
144/// [`reparse_versioned`]: ParserContext::reparse_versioned
145///
146/// # Example
147///
148/// ```
149/// let mut ctx = php_rs_parser::ParserContext::new();
150///
151/// let result = ctx.reparse("<?php echo 1;");
152/// assert!(result.errors.is_empty());
153/// drop(result); // must be dropped before the next reparse
154///
155/// let result = ctx.reparse("<?php echo 2;");
156/// assert!(result.errors.is_empty());
157/// ```
158pub struct ParserContext {
159 arena: bumpalo::Bump,
160}
161
162impl ParserContext {
163 /// Create a new context with an empty arena.
164 pub fn new() -> Self {
165 Self {
166 arena: bumpalo::Bump::new(),
167 }
168 }
169
170 /// Reset the arena and parse `source` using PHP 8.5 (the latest version).
171 ///
172 /// The previous [`ParseResult`] **must be dropped** before calling this
173 /// method. The borrow checker enforces this: the returned result borrows
174 /// `self` for the duration of its lifetime, so a second call while the
175 /// first result is still live is a compile-time error.
176 pub fn reparse<'a, 'src>(&'a mut self, source: &'src str) -> ParseResult<'a, 'src> {
177 self.arena.reset();
178 parse(&self.arena, source)
179 }
180
181 /// Reset the arena and parse `source` targeting the given PHP `version`.
182 ///
183 /// See [`reparse`](ParserContext::reparse) for lifetime safety notes.
184 pub fn reparse_versioned<'a, 'src>(
185 &'a mut self,
186 source: &'src str,
187 version: PhpVersion,
188 ) -> ParseResult<'a, 'src> {
189 self.arena.reset();
190 parse_versioned(&self.arena, source, version)
191 }
192}
193
194impl Default for ParserContext {
195 fn default() -> Self {
196 Self::new()
197 }
198}