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(¶m.body).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#![warn(missing_docs)]
52
53pub(crate) mod ast;
54pub(crate) mod parser;
55pub(crate) mod span;
56
57pub use ast::{InlineTag, PhpDoc, PhpDocTag, PhpDocText, TextSegment};
58pub use parser::parse;
59pub use span::Span;
60
61// =============================================================================
62// Utility functions for common tasks
63// =============================================================================
64
65/// Find the first tag with the given name.
66///
67/// # Example
68/// ```
69/// use phpdoc_parser::{parse, find_tag};
70/// let doc = parse("/** @param int $x @return string */");
71/// assert!(find_tag(&doc, "param").is_some());
72/// assert!(find_tag(&doc, "throws").is_none());
73/// ```
74pub fn find_tag<'d>(doc: &'d PhpDoc, name: &str) -> Option<&'d PhpDocTag> {
75 doc.tags.iter().find(|t| t.name == name)
76}
77
78/// Find all tags with the given name.
79///
80/// # Example
81/// ```
82/// use phpdoc_parser::{parse, find_tags};
83/// let doc = parse("/**\n * @param int $x\n * @param string $y\n */");
84/// assert_eq!(find_tags(&doc, "param").len(), 2);
85/// ```
86pub fn find_tags<'d>(doc: &'d PhpDoc, name: &str) -> Vec<&'d PhpDocTag> {
87 doc.tags.iter().filter(|t| t.name == name).collect()
88}
89
90/// Reconstruct the text content of a `PhpDocText`, including inline tags.
91///
92/// Inline tags are reconstructed as `{@name body}` format.
93///
94/// # Example
95/// ```
96/// use phpdoc_parser::{parse, text_content};
97/// let doc = parse("/** See {@link Foo} for details. */");
98/// let summary = text_content(doc.summary.as_ref().unwrap());
99/// assert!(summary.contains("@link"));
100/// ```
101pub fn text_content(text: &PhpDocText) -> String {
102 text.segments
103 .iter()
104 .map(|seg| match seg {
105 TextSegment::Text(t) => t.clone(),
106 TextSegment::InlineTag(tag) => {
107 format!(
108 "{{@{}{}}}",
109 tag.name,
110 tag.body
111 .as_ref()
112 .map(|b| format!(" {}", b))
113 .unwrap_or_default()
114 )
115 }
116 })
117 .collect()
118}
119
120/// Get the text content of a tag body, if present.
121///
122/// # Example
123/// ```
124/// use phpdoc_parser::{parse, find_tag, body_text};
125/// let doc = parse("/** @param int $x */");
126/// let param = find_tag(&doc, "param").unwrap();
127/// let text = body_text(¶m.body).unwrap();
128/// assert!(text.contains("$x"));
129/// ```
130pub fn body_text(body: &Option<PhpDocText>) -> Option<String> {
131 body.as_ref().map(text_content)
132}
133
134/// Extract all inline tags from a text segment.
135///
136/// # Example
137/// ```
138/// use phpdoc_parser::{parse, inline_tags};
139/// let doc = parse("/** See {@link Foo} and {@link Bar}. */");
140/// let tags = inline_tags(doc.summary.as_ref().unwrap());
141/// assert_eq!(tags.len(), 2);
142/// ```
143pub fn inline_tags(text: &PhpDocText) -> Vec<&InlineTag> {
144 text.segments
145 .iter()
146 .filter_map(|seg| match seg {
147 TextSegment::InlineTag(tag) => Some(tag),
148 _ => None,
149 })
150 .collect()
151}