Skip to main content

phpdoc_parser/
lib.rs

1//! Structural PHPDoc comment parser.
2//!
3//! Parses `/** ... */` documentation blocks into a structured AST with accurate
4//! spans and support for inline tags. Designed for type checkers, linters, IDEs,
5//! and documentation generators.
6//!
7//! The crate is **agnostic** — it does not interpret tag semantics or parse type
8//! expressions. Tag bodies are exposed as raw [`PhpDocText`], letting tools apply
9//! their own type parsers and validation rules.
10//!
11//! # Quick start
12//!
13//! ```
14//! use phpdoc_parser::parse;
15//!
16//! let text = "/** @param int $x The value */";
17//! let doc = parse(text);
18//! assert_eq!(doc.tags.len(), 1);
19//! assert_eq!(doc.tags[0].name, "param");
20//! ```
21//!
22//! # Common patterns
23//!
24//! ### Read a tag body
25//!
26//! ```
27//! use phpdoc_parser::{parse, find_tags, body_text};
28//!
29//! let doc = parse("/** @param int $x The mapping */");
30//! for param in find_tags(&doc, "param") {
31//!     let body = body_text(param.body.as_ref()).unwrap_or_default();
32//!     // body is "int $x The mapping" — parse the type yourself
33//! }
34//! ```
35//!
36//! ### Find inline references
37//!
38//! ```
39//! use phpdoc_parser::{parse, inline_tags};
40//!
41//! let doc = parse("/** See {@link User::load()} for details. */");
42//! if let Some(desc) = &doc.description {
43//!     for tag in inline_tags(desc) {
44//!         if tag.name == "link" {
45//!             // Process the reference to User::load()
46//!         }
47//!     }
48//! }
49//! ```
50//!
51//! # Serialization
52//!
53//! The AST implements [`serde::Serialize`]; its serialized shape is not covered by semver.
54
55#![warn(missing_docs)]
56
57pub(crate) mod ast;
58pub(crate) mod parser;
59
60pub use ast::{InlineTag, PhpDoc, PhpDocTag, PhpDocText, TextSegment};
61pub use parser::parse;
62/// Spans are byte offsets into the docblock text passed to [`parse`], not into the PHP file.
63pub use php_ast::Span;
64
65// =============================================================================
66// Utility functions for common tasks
67// =============================================================================
68
69/// Find the first tag with the given name.
70///
71/// # Example
72/// ```
73/// use phpdoc_parser::{parse, find_tag};
74/// let doc = parse("/** @param int $x @return string */");
75/// assert!(find_tag(&doc, "param").is_some());
76/// assert!(find_tag(&doc, "throws").is_none());
77/// ```
78pub fn find_tag<'d>(doc: &'d PhpDoc, name: &str) -> Option<&'d PhpDocTag> {
79    doc.tags.iter().find(|t| t.name == name)
80}
81
82/// Find all tags with the given name.
83///
84/// # Example
85/// ```
86/// use phpdoc_parser::{parse, find_tags};
87/// let doc = parse("/**\n * @param int $x\n * @param string $y\n */");
88/// assert_eq!(find_tags(&doc, "param").count(), 2);
89/// ```
90pub fn find_tags<'d, 'n>(
91    doc: &'d PhpDoc,
92    name: &'n str,
93) -> impl Iterator<Item = &'d PhpDocTag> + use<'d, 'n> {
94    doc.tags.iter().filter(move |t| t.name == name)
95}
96
97/// Reconstruct the text content of a `PhpDocText`, including inline tags.
98///
99/// Inline tags are reconstructed as `{@name body}` format.
100///
101/// # Example
102/// ```
103/// use phpdoc_parser::{parse, text_content};
104/// let doc = parse("/** See {@link Foo} for details. */");
105/// let summary = text_content(doc.summary.as_ref().unwrap());
106/// assert!(summary.contains("@link"));
107/// ```
108pub fn text_content(text: &PhpDocText) -> String {
109    text.segments
110        .iter()
111        .map(|seg| match seg {
112            TextSegment::Text(t) => t.clone(),
113            TextSegment::InlineTag(tag) => {
114                format!(
115                    "{{@{}{}}}",
116                    tag.name,
117                    tag.body
118                        .as_ref()
119                        .map(|b| format!(" {}", b))
120                        .unwrap_or_default()
121                )
122            }
123        })
124        .collect()
125}
126
127/// Get the text content of a tag body, if present.
128///
129/// # Example
130/// ```
131/// use phpdoc_parser::{parse, find_tag, body_text};
132/// let doc = parse("/** @param int $x */");
133/// let param = find_tag(&doc, "param").unwrap();
134/// let text = body_text(param.body.as_ref()).unwrap();
135/// assert!(text.contains("$x"));
136/// ```
137pub fn body_text(body: Option<&PhpDocText>) -> Option<String> {
138    body.map(text_content)
139}
140
141/// Extract all inline tags from a text segment.
142///
143/// # Example
144/// ```
145/// use phpdoc_parser::{parse, inline_tags};
146/// let doc = parse("/** See {@link Foo} and {@link Bar}. */");
147/// let tags = inline_tags(doc.summary.as_ref().unwrap());
148/// assert_eq!(tags.count(), 2);
149/// ```
150pub fn inline_tags(text: &PhpDocText) -> impl Iterator<Item = &InlineTag> {
151    text.segments.iter().filter_map(|seg| match seg {
152        TextSegment::InlineTag(tag) => Some(tag),
153        _ => None,
154    })
155}