1use crate::{
2 CONTRACT_INHERITANCE_ID, CommentTag, Comments, CommentsRef, DEPLOYMENTS_ID, Document,
3 GIT_SOURCE_ID, INHERITDOC_ID, Markdown, PreprocessorOutput,
4 document::{DocumentContent, read_context},
5 helpers::function_signature,
6 parser::ParseSource,
7 solang_ext::SafeUnwrap,
8 writer::BufWriter,
9};
10use itertools::Itertools;
11use solang_parser::pt::{Base, FunctionDefinition};
12use std::path::{Path, PathBuf};
13
14pub type AsDocResult = Result<String, std::fmt::Error>;
16
17pub trait AsDoc {
19 fn as_doc(&self) -> AsDocResult;
21}
22
23impl AsDoc for String {
24 fn as_doc(&self) -> AsDocResult {
25 Ok(self.to_owned())
26 }
27}
28
29impl AsDoc for Comments {
30 fn as_doc(&self) -> AsDocResult {
31 CommentsRef::from(self).as_doc()
32 }
33}
34
35impl AsDoc for CommentsRef<'_> {
36 fn as_doc(&self) -> AsDocResult {
38 let mut writer = BufWriter::default();
39
40 let titles = self.include_tag(CommentTag::Title);
42 if !titles.is_empty() {
43 writer.write_bold(&format!("Title{}:", if titles.len() == 1 { "" } else { "s" }))?;
44 writer.writeln_raw(titles.iter().map(|t| &t.value).join(", "))?;
45 writer.writeln()?;
46 }
47
48 let authors = self.include_tag(CommentTag::Author);
50 if !authors.is_empty() {
51 writer.write_bold(&format!("Author{}:", if authors.len() == 1 { "" } else { "s" }))?;
52 writer.writeln_raw(authors.iter().map(|a| &a.value).join(", "))?;
53 writer.writeln()?;
54 }
55
56 let notices = self.include_tag(CommentTag::Notice);
58 for n in notices.iter() {
59 writer.writeln_raw(&n.value)?;
60 writer.writeln()?;
61 }
62
63 let devs = self.include_tag(CommentTag::Dev);
65 for d in devs.iter() {
66 writer.write_dev_content(&d.value)?;
67 writer.writeln()?;
68 }
69
70 let customs = self.get_custom_tags();
72 if !customs.is_empty() {
73 writer.write_bold(&format!("Note{}:", if customs.len() == 1 { "" } else { "s" }))?;
74 for c in customs.iter() {
75 writer.writeln_raw(format!(
76 "{}{}: {}",
77 if customs.len() == 1 { "" } else { "- " },
78 &c.tag,
79 &c.value
80 ))?;
81 writer.writeln()?;
82 }
83 }
84
85 Ok(writer.finish())
86 }
87}
88
89impl AsDoc for Base {
90 fn as_doc(&self) -> AsDocResult {
91 Ok(self.name.identifiers.iter().map(|ident| ident.name.to_owned()).join("."))
92 }
93}
94
95impl AsDoc for Document {
96 fn as_doc(&self) -> AsDocResult {
97 let mut writer = BufWriter::default();
98
99 match &self.content {
100 DocumentContent::OverloadedFunctions(items) => {
101 writer
102 .write_title(&format!("function {}", items.first().unwrap().source.ident()))?;
103 if let Some(git_source) = read_context!(self, GIT_SOURCE_ID, GitSource) {
104 writer.write_link("Git Source", &git_source)?;
105 writer.writeln()?;
106 }
107
108 for item in items {
109 let func = item.as_function().unwrap();
110 let heading = function_signature(func).replace(',', ", ");
111 writer.write_heading(&heading)?;
112 writer.write_section(&item.comments, &item.code)?;
113 }
114 }
115 DocumentContent::Constants(items) => {
116 writer.write_title("Constants")?;
117 if let Some(git_source) = read_context!(self, GIT_SOURCE_ID, GitSource) {
118 writer.write_link("Git Source", &git_source)?;
119 writer.writeln()?;
120 }
121
122 for item in items {
123 let var = item.as_variable().unwrap();
124 writer.write_heading(&var.name.safe_unwrap().name)?;
125 writer.write_section(&item.comments, &item.code)?;
126 }
127 }
128 DocumentContent::Single(item) => {
129 writer.write_title(&item.source.ident())?;
130 if let Some(git_source) = read_context!(self, GIT_SOURCE_ID, GitSource) {
131 writer.write_link("Git Source", &git_source)?;
132 writer.writeln()?;
133 }
134
135 if let Some(deployments) = read_context!(self, DEPLOYMENTS_ID, Deployments) {
136 writer.write_deployments_table(deployments)?;
137 }
138
139 match &item.source {
140 ParseSource::Contract(contract) => {
141 if !contract.base.is_empty() {
142 writer.write_bold("Inherits:")?;
143
144 let src_target_dir = self.target_src_dir();
146
147 let mut bases = vec![];
148 let linked =
149 read_context!(self, CONTRACT_INHERITANCE_ID, ContractInheritance);
150 for base in &contract.base {
151 let base_doc = base.as_doc()?;
152 let base_ident = &base.name.identifiers.last().unwrap().name;
153
154 let link = linked
155 .as_ref()
156 .and_then(|link| {
157 link.get(base_ident).map(|path| {
158 let path = Path::new("/").join(
159 path.strip_prefix(&src_target_dir)
160 .ok()
161 .unwrap_or(path),
162 );
163 Markdown::Link(&base_doc, &path.display().to_string())
164 .as_doc()
165 })
166 })
167 .transpose()?
168 .unwrap_or(base_doc);
169
170 bases.push(link);
171 }
172
173 writer.writeln_raw(bases.join(", "))?;
174 writer.writeln()?;
175 }
176
177 writer.writeln_doc(&item.comments)?;
178
179 if let Some(state_vars) = item.variables() {
180 writer.write_subtitle("State Variables")?;
181 state_vars.into_iter().try_for_each(|(item, comments, code)| {
182 let comments = comments.merge_inheritdoc(
183 &item.name.safe_unwrap().name,
184 read_context!(self, INHERITDOC_ID, Inheritdoc),
185 );
186
187 writer.write_heading(&item.name.safe_unwrap().name)?;
188 writer.write_section(&comments, code)?;
189 writer.writeln()
190 })?;
191 }
192
193 if let Some(funcs) = item.functions() {
194 writer.write_subtitle("Functions")?;
195
196 for (func, comments, code) in &funcs {
197 self.write_function(&mut writer, func, comments, code)?;
198 }
199 }
200
201 if let Some(events) = item.events() {
202 writer.write_subtitle("Events")?;
203 events.into_iter().try_for_each(|(item, comments, code)| {
204 writer.write_heading(&item.name.safe_unwrap().name)?;
205 writer.write_section(comments, code)?;
206 writer.try_write_events_table(&item.fields, comments)
207 })?;
208 }
209
210 if let Some(errors) = item.errors() {
211 writer.write_subtitle("Errors")?;
212 errors.into_iter().try_for_each(|(item, comments, code)| {
213 writer.write_heading(&item.name.safe_unwrap().name)?;
214 writer.write_section(comments, code)?;
215 writer.try_write_errors_table(&item.fields, comments)
216 })?;
217 }
218
219 if let Some(structs) = item.structs() {
220 writer.write_subtitle("Structs")?;
221 structs.into_iter().try_for_each(|(item, comments, code)| {
222 writer.write_heading(&item.name.safe_unwrap().name)?;
223 writer.write_section(comments, code)?;
224 writer.try_write_properties_table(&item.fields, comments)
225 })?;
226 }
227
228 if let Some(enums) = item.enums() {
229 writer.write_subtitle("Enums")?;
230 enums.into_iter().try_for_each(|(item, comments, code)| {
231 writer.write_heading(&item.name.safe_unwrap().name)?;
232 writer.write_section(comments, code)?;
233 writer.try_write_variant_table(item, comments)
234 })?;
235 }
236 }
237
238 ParseSource::Function(func) => {
239 writer.writeln_doc(
242 &item.comments.exclude_tags(&[CommentTag::Param, CommentTag::Return]),
243 )?;
244
245 writer.write_code(&item.code)?;
247
248 let params =
250 func.params.iter().filter_map(|p| p.1.as_ref()).collect::<Vec<_>>();
251 writer.try_write_param_table(CommentTag::Param, ¶ms, &item.comments)?;
252
253 let returns =
255 func.returns.iter().filter_map(|p| p.1.as_ref()).collect::<Vec<_>>();
256 writer.try_write_param_table(
257 CommentTag::Return,
258 &returns,
259 &item.comments,
260 )?;
261
262 writer.writeln()?;
263 }
264
265 ParseSource::Struct(ty) => {
266 writer.write_section(&item.comments, &item.code)?;
267 writer.try_write_properties_table(&ty.fields, &item.comments)?;
268 }
269 ParseSource::Event(ev) => {
270 writer.write_section(&item.comments, &item.code)?;
271 writer.try_write_events_table(&ev.fields, &item.comments)?;
272 }
273 ParseSource::Error(err) => {
274 writer.write_section(&item.comments, &item.code)?;
275 writer.try_write_errors_table(&err.fields, &item.comments)?;
276 }
277 ParseSource::Variable(_) | ParseSource::Enum(_) | ParseSource::Type(_) => {
278 writer.write_section(&item.comments, &item.code)?;
279 }
280 }
281 }
282 DocumentContent::Empty => (),
283 };
284
285 Ok(writer.finish())
286 }
287}
288
289impl Document {
290 fn target_src_dir(&self) -> PathBuf {
292 self.out_target_dir.join("src")
293 }
294
295 fn write_function(
297 &self,
298 writer: &mut BufWriter,
299 func: &FunctionDefinition,
300 comments: &Comments,
301 code: &str,
302 ) -> Result<(), std::fmt::Error> {
303 let func_sign = function_signature(func);
304 let func_name = func.name.as_ref().map_or(func.ty.to_string(), |n| n.name.to_owned());
305 let comments =
306 comments.merge_inheritdoc(&func_sign, read_context!(self, INHERITDOC_ID, Inheritdoc));
307
308 writer.write_heading(&func_name)?;
310
311 writer.writeln()?;
312
313 writer.writeln_doc(&comments.exclude_tags(&[CommentTag::Param, CommentTag::Return]))?;
315
316 writer.write_code(code)?;
318
319 let params = func.params.iter().filter_map(|p| p.1.as_ref()).collect::<Vec<_>>();
321 writer.try_write_param_table(CommentTag::Param, ¶ms, &comments)?;
322
323 let returns = func.returns.iter().filter_map(|p| p.1.as_ref()).collect::<Vec<_>>();
325 writer.try_write_param_table(CommentTag::Return, &returns, &comments)?;
326
327 writer.writeln()?;
328 Ok(())
329 }
330}