]> git.proxmox.com Git - rustc.git/blob - vendor/clap_derive-3.2.18/src/utils/doc_comments.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / vendor / clap_derive-3.2.18 / src / utils / doc_comments.rs
1 //! The preprocessing we apply to doc comments.
2 //!
3 //! #[derive(Parser)] works in terms of "paragraphs". Paragraph is a sequence of
4 //! non-empty adjacent lines, delimited by sequences of blank (whitespace only) lines.
5
6 use crate::attrs::Method;
7
8 use quote::{format_ident, quote};
9 use std::iter;
10
11 pub fn process_doc_comment(lines: Vec<String>, name: &str, preprocess: bool) -> Vec<Method> {
12 // multiline comments (`/** ... */`) may have LFs (`\n`) in them,
13 // we need to split so we could handle the lines correctly
14 //
15 // we also need to remove leading and trailing blank lines
16 let mut lines: Vec<&str> = lines
17 .iter()
18 .skip_while(|s| is_blank(s))
19 .flat_map(|s| s.split('\n'))
20 .collect();
21
22 while let Some(true) = lines.last().map(|s| is_blank(s)) {
23 lines.pop();
24 }
25
26 // remove one leading space no matter what
27 for line in lines.iter_mut() {
28 if line.starts_with(' ') {
29 *line = &line[1..];
30 }
31 }
32
33 if lines.is_empty() {
34 return vec![];
35 }
36
37 let short_name = format_ident!("{}", name);
38 let long_name = format_ident!("long_{}", name);
39
40 if let Some(first_blank) = lines.iter().position(|s| is_blank(s)) {
41 let (short, long) = if preprocess {
42 let paragraphs = split_paragraphs(&lines);
43 let short = paragraphs[0].clone();
44 let long = paragraphs.join("\n\n");
45 (remove_period(short), long)
46 } else {
47 let short = lines[..first_blank].join("\n");
48 let long = lines.join("\n");
49 (short, long)
50 };
51
52 vec![
53 Method::new(short_name, quote!(#short)),
54 Method::new(long_name, quote!(#long)),
55 ]
56 } else {
57 let short = if preprocess {
58 let s = merge_lines(&lines);
59 remove_period(s)
60 } else {
61 lines.join("\n")
62 };
63
64 vec![
65 Method::new(short_name, quote!(#short)),
66 Method::new(long_name, quote!(None)),
67 ]
68 }
69 }
70
71 fn split_paragraphs(lines: &[&str]) -> Vec<String> {
72 let mut last_line = 0;
73 iter::from_fn(|| {
74 let slice = &lines[last_line..];
75 let start = slice.iter().position(|s| !is_blank(s)).unwrap_or(0);
76
77 let slice = &slice[start..];
78 let len = slice
79 .iter()
80 .position(|s| is_blank(s))
81 .unwrap_or(slice.len());
82
83 last_line += start + len;
84
85 if len != 0 {
86 Some(merge_lines(&slice[..len]))
87 } else {
88 None
89 }
90 })
91 .collect()
92 }
93
94 fn remove_period(mut s: String) -> String {
95 if s.ends_with('.') && !s.ends_with("..") {
96 s.pop();
97 }
98 s
99 }
100
101 fn is_blank(s: &str) -> bool {
102 s.trim().is_empty()
103 }
104
105 fn merge_lines(lines: &[&str]) -> String {
106 lines.iter().map(|s| s.trim()).collect::<Vec<_>>().join(" ")
107 }