Debian Codegraph @

src/codegen/doc/mod.rs

raw
1 use std::{
2 borrow::Cow,
3 collections::{BTreeSet, HashSet},
4 io::{Result, Write},
5 sync::OnceLock,
6 };
7
8 use log::{error, info};
9 use regex::{Captures, Regex};
10 use stripper_lib::{Type as SType, TypeStruct, write_file_name, write_item_doc};
11
12 use self::format::reformat_doc;
13 use crate::{
14 analysis::{self, namespaces::MAIN, object::LocationInObject},
15 config::gobjects::GObject,
16 env::Env,
17 file_saver::save_to_file,
18 library::{self, Type as LType, *},
19 nameutil,
20 traits::*,
21 version::Version,
22 };
23
24 mod format;
25 mod gi_docgen;
26
27 // A list of C parameters that are not used directly by the Rust bindings
28 const IGNORED_C_FN_PARAMS: [&str; 6] = [
29 "user_data",
30 "user_destroy",
31 "destroy_func",
32 "dnotify",
33 "destroy",
34 "user_data_free_func",
35 ];
36
37 trait ToStripperType {
38 fn to_stripper_type(&self) -> TypeStruct;
39 }
40
41 macro_rules! impl_to_stripper_type {
42 ($ty:ident, $enum_var:ident, $useless:expr) => {
43 impl ToStripperType for $ty {
44 fn to_stripper_type(&self) -> TypeStruct {
45 TypeStruct::new(
46 SType::$enum_var,
47 &format!(
48 "connect_{}",
49 nameutil::mangle_keywords(nameutil::signal_to_snake(&self.name))
50 ),
51 )
52 }
53 }
54 };
55 ($ty:ident, $enum_var:ident) => {
56 impl ToStripperType for $ty {
57 fn to_stripper_type(&self) -> TypeStruct {
58 TypeStruct::new(SType::$enum_var, &nameutil::mangle_keywords(&self.name))
59 }
60 }
61 };
62 }
63
64 trait FunctionLikeType {
65 fn doc(&self) -> &Option<String>;
66 fn doc_deprecated(&self) -> &Option<String>;
67 fn ret(&self) -> &Parameter;
68 fn parameters(&self) -> &[Parameter];
69 fn deprecated_version(&self) -> &Option<Version>;
70 }
71
72 macro_rules! impl_function_like_type {
73 ($ty:ident) => {
74 impl FunctionLikeType for $ty {
75 fn doc(&self) -> &Option<String> {
76 &self.doc
77 }
78 fn doc_deprecated(&self) -> &Option<String> {
79 &self.doc_deprecated
80 }
81 fn ret(&self) -> &Parameter {
82 &self.ret
83 }
84 fn parameters(&self) -> &[Parameter] {
85 &self.parameters
86 }
87 fn deprecated_version(&self) -> &Option<Version> {
88 &self.deprecated_version
89 }
90 }
91 };
92 }
93
94 impl_to_stripper_type!(Enumeration, Enum);
95 impl_to_stripper_type!(Bitfield, Struct);
96 impl_to_stripper_type!(Record, Struct);
97 impl_to_stripper_type!(Class, Struct);
98 impl_to_stripper_type!(Function, Fn);
99 impl_to_stripper_type!(Signal, Fn, false);
100
101 impl_function_like_type!(Function);
102 impl_function_like_type!(Signal);
103
104 pub fn generate(env: &Env) {
105 info!("Generating documentation {:?}", env.config.doc_target_path);
106 save_to_file(&env.config.doc_target_path, env.config.make_backup, |w| {
107 generate_doc(w, env)
108 });
109 }
110
111 #[allow(clippy::type_complexity)]
112 fn generate_doc(w: &mut dyn Write, env: &Env) -> Result<()> {
113 write_file_name(w, None)?;
114 let mut generators: Vec<(&str, Box<dyn Fn(&mut dyn Write, &Env) -> Result<()>>)> = Vec::new();
115
116 for info in env.analysis.objects.values() {
117 if info.type_id.ns_id == MAIN && !env.is_totally_deprecated(None, info.deprecated_version) {
118 generators.push((
119 &info.name,
120 Box::new(move |w, e| create_object_doc(w, e, info)),
121 ));
122 }
123 }
124
125 for info in env.analysis.records.values() {
126 if info.type_id.ns_id == MAIN && !env.is_totally_deprecated(None, info.deprecated_version) {
127 generators.push((
128 &info.name,
129 Box::new(move |w, e| create_record_doc(w, e, info)),
130 ));
131 }
132 }
133
134 for (tid, type_) in env.library.namespace_types(MAIN) {
135 if let LType::Enumeration(enum_) = type_ {
136 if !env
137 .config
138 .objects
139 .get(&tid.full_name(&env.library))
140 .is_none_or(|obj| obj.status.ignored())
141 && !env.is_totally_deprecated(None, enum_.deprecated_version)
142 {
143 generators.push((
144 enum_.name.as_str(),
145 Box::new(move |w, e| create_enum_doc(w, e, enum_, tid)),
146 ));
147 }
148 } else if let LType::Bitfield(bitfield) = type_
149 && !env
150 .config
151 .objects
152 .get(&tid.full_name(&env.library))
153 .is_none_or(|obj| obj.status.ignored())
154 && !env.is_totally_deprecated(None, bitfield.deprecated_version)
155 {
156 generators.push((
157 bitfield.name.as_str(),
158 Box::new(move |w, e| create_bitfield_doc(w, e, bitfield, tid)),
159 ));
160 }
161 }
162
163 let ns = env.library.namespace(library::MAIN_NAMESPACE);
164
165 if let Some(ref global_functions) = env.analysis.global_functions {
166 let functions = ns
167 .functions
168 .iter()
169 .filter(|f| f.kind == library::FunctionKind::Global);
170
171 for function in functions {
172 if let Some(ref c_identifier) = function.c_identifier {
173 let f_info = global_functions
174 .functions
175 .iter()
176 .find(move |f| &f.glib_name == c_identifier);
177 let fn_new_name = f_info.and_then(|analysed_f| analysed_f.new_name.clone());
178 let doc_trait_name = f_info.and_then(|f| f.doc_trait_name.as_ref());
179 let doc_struct_name = f_info.and_then(|f| f.doc_struct_name.as_ref());
180 assert!(
181 !(doc_trait_name.is_some() && doc_struct_name.is_some()),
182 "Can't use both doc_trait_name and doc_struct_name on the same function"
183 );
184
185 let parent = if doc_trait_name.is_some() {
186 doc_trait_name.map(|p| Box::new(TypeStruct::new(SType::Trait, p)))
187 } else if doc_struct_name.is_some() {
188 doc_struct_name.map(|p| Box::new(TypeStruct::new(SType::Impl, p)))
189 } else {
190 None
191 };
192
193 let doc_ignored_parameters = f_info
194 .map(|analyzed_f| analyzed_f.doc_ignore_parameters.clone())
195 .unwrap_or_default();
196
197 let should_be_documented = f_info.is_some_and(|f| f.should_docs_be_generated(env));
198 if !should_be_documented {
199 continue;
200 }
201
202 create_fn_doc(
203 w,
204 env,
205 function,
206 parent,
207 fn_new_name,
208 &doc_ignored_parameters,
209 None,
210 f_info.is_none_or(|f| f.generate_doc),
211 )?;
212 }
213 }
214 }
215
216 for constant in &ns.constants {
217 // strings are mapped to a static
218 let ty = if constant.c_type == "gchar*" {
219 SType::Static
220 } else {
221 SType::Const
222 };
223 let ty_id = TypeStruct::new(ty, &constant.name);
224 let generate_doc = env
225 .config
226 .objects
227 .get(&constant.typ.full_name(&env.library))
228 .is_none_or(|c| c.generate_doc);
229 if generate_doc {
230 write_item_doc(w, &ty_id, |w| {
231 if let Some(ref doc) = constant.doc {
232 writeln!(w, "{}", reformat_doc(doc, env, Some((&constant.typ, None))))?;
233 }
234 Ok(())
235 })?;
236 }
237 }
238
239 generators.sort_by_key(|&(name, _)| name);
240 for (_, f) in generators {
241 f(w, env)?;
242 }
243
244 Ok(())
245 }
246
247 fn create_object_doc(w: &mut dyn Write, env: &Env, info: &analysis::object::Info) -> Result<()> {
248 let ty = TypeStruct::new(SType::Struct, &info.name);
249 let ty_ext = TypeStruct::new(SType::Trait, &info.trait_name);
250 let has_trait = info.generate_trait;
251 let doc;
252 let doc_deprecated;
253 let functions: &[Function];
254 let virtual_methods: &[Function];
255 let signals: &[Signal];
256 let properties: &[Property];
257 let is_abstract;
258 let has_builder;
259
260 let obj = env
261 .config
262 .objects
263 .get(&info.full_name)
264 .expect("Object not found");
265
266 match env.library.type_(info.type_id) {
267 Type::Class(cl) => {
268 doc = cl.doc.as_ref();
269 doc_deprecated = cl.doc_deprecated.as_ref();
270 functions = &cl.functions;
271 virtual_methods = &cl.virtual_methods;
272 signals = &cl.signals;
273 properties = &cl.properties;
274 is_abstract = env.library.type_(info.type_id).is_abstract();
275 has_builder = obj.generate_builder;
276 }
277 Type::Interface(iface) => {
278 doc = iface.doc.as_ref();
279 doc_deprecated = iface.doc_deprecated.as_ref();
280 functions = &iface.functions;
281 virtual_methods = &iface.virtual_methods;
282 signals = &iface.signals;
283 properties = &iface.properties;
284 is_abstract = false;
285 has_builder = false;
286 }
287 _ => unreachable!(),
288 }
289
290 let manual_traits = get_type_manual_traits_for_implements(env, info);
291
292 write_item_doc(w, &ty, |w| {
293 if let Some(doc) = doc_deprecated {
294 writeln!(
295 w,
296 "{}",
297 reformat_doc(
298 doc,
299 env,
300 Some((&info.type_id, Some(LocationInObject::Impl)))
301 )
302 )?;
303 }
304 if let (Some(doc), true) = (doc, obj.generate_doc) {
305 writeln!(
306 w,
307 "{}",
308 reformat_doc(
309 doc,
310 env,
311 Some((&info.type_id, Some(LocationInObject::Impl)))
312 )
313 )?;
314 } else {
315 writeln!(w)?;
316 }
317 if is_abstract {
318 writeln!(
319 w,
320 "\nThis is an Abstract Base Class, you cannot instantiate it."
321 )?;
322 }
323
324 if !properties.is_empty() {
325 writeln!(w, "\n## Properties")?;
326 document_type_properties(env, w, info, properties, None)?;
327
328 for parent_info in &info.supertypes {
329 match env.library.type_(parent_info.type_id) {
330 Type::Class(cl) if !cl.properties.is_empty() => {
331 document_type_properties(env, w, info, &cl.properties, Some(&cl.name))?;
332 }
333 Type::Interface(iface) if !iface.properties.is_empty() => {
334 document_type_properties(
335 env,
336 w,
337 info,
338 &iface.properties,
339 Some(&iface.name),
340 )?;
341 }
342 _ => (),
343 }
344 }
345 }
346 if !signals.is_empty() {
347 writeln!(w, "\n## Signals")?;
348 document_type_signals(env, w, info, signals, None)?;
349
350 for parent_info in &info.supertypes {
351 match env.library.type_(parent_info.type_id) {
352 Type::Class(cl) if !cl.signals.is_empty() => {
353 document_type_signals(env, w, info, &cl.signals, Some(&cl.name))?;
354 }
355 Type::Interface(iface) if !iface.signals.is_empty() => {
356 document_type_signals(env, w, info, &iface.signals, Some(&iface.name))?;
357 }
358 _ => (),
359 }
360 }
361 }
362
363 let impl_self = if has_trait { Some(info.type_id) } else { None };
364 let mut implements = impl_self
365 .iter()
366 .chain(env.class_hierarchy.supertypes(info.type_id))
367 .filter(|&tid| {
368 !env.type_status(&tid.full_name(&env.library)).ignored()
369 && !env.type_(*tid).is_final_type()
370 && !env.type_(*tid).is_fundamental()
371 })
372 .map(|&tid| get_type_trait_for_implements(env, tid))
373 .collect::<Vec<_>>();
374 implements.extend(manual_traits);
375
376 if !implements.is_empty() {
377 writeln!(w, "\n# Implements\n")?;
378 writeln!(w, "{}", implements.join(", "))?;
379 }
380 Ok(())
381 })?;
382
383 if has_builder {
384 let builder_ty = TypeStruct::new(SType::Impl, &format!("{}Builder", info.name));
385 let mut builder_properties: Vec<_> = properties.iter().collect();
386 for parent_info in &info.supertypes {
387 match env.library.type_(parent_info.type_id) {
388 Type::Class(cl) => {
389 builder_properties.extend(cl.properties.iter().filter(|p| p.writable));
390 }
391 Type::Interface(iface) => {
392 builder_properties.extend(iface.properties.iter().filter(|p| p.writable));
393 }
394 _ => (),
395 }
396 }
397 for property in &builder_properties {
398 if !property.writable {
399 continue;
400 }
401 let ty = TypeStruct {
402 ty: SType::Fn,
403 name: nameutil::signal_to_snake(&property.name),
404 parent: Some(Box::new(builder_ty.clone())),
405 args: vec![],
406 };
407 write_item_doc(w, &ty, |w| {
408 if let Some(ref doc) = property.doc {
409 writeln!(
410 w,
411 "{}",
412 reformat_doc(
413 &fix_param_names(doc, &None),
414 env,
415 Some((&info.type_id, Some(LocationInObject::Builder)))
416 )
417 )?;
418 }
419 if let Some(ref doc) = property.doc_deprecated {
420 writeln!(
421 w,
422 "{}",
423 reformat_doc(
424 &fix_param_names(doc, &None),
425 env,
426 Some((&info.type_id, Some(LocationInObject::Builder)))
427 )
428 )?;
429 }
430 Ok(())
431 })?;
432 }
433 }
434
435 if has_trait {
436 write_item_doc(w, &ty_ext, |w| {
437 writeln!(w, "Trait containing all [`struct@{}`] methods.", ty.name)?;
438
439 let mut implementors = std::iter::once(info.type_id)
440 .chain(env.class_hierarchy.subtypes(info.type_id))
441 .filter(|&tid| !env.type_status(&tid.full_name(&env.library)).ignored())
442 .map(|tid| {
443 format!(
444 "[`{0}`][struct@crate::{0}]",
445 env.library.type_(tid).get_name()
446 )
447 })
448 .collect::<Vec<_>>();
449 implementors.sort();
450
451 writeln!(w, "\n# Implementors\n")?;
452 writeln!(w, "{}", implementors.join(", "))?;
453 Ok(())
454 })?;
455 }
456
457 let ty = TypeStruct {
458 ty: SType::Impl,
459 ..ty
460 };
461
462 for function in functions {
463 let configured_functions = obj.functions.matched(&function.name);
464 let is_manual = configured_functions.iter().any(|f| f.status.manual());
465 let (ty, object_location) = if (has_trait || is_manual)
466 && function.parameters.iter().any(|p| p.instance_parameter)
467 && !info.final_type
468 {
469 if let Some(struct_name) = configured_functions
470 .iter()
471 .find_map(|f| f.doc_struct_name.as_ref())
472 {
473 (
474 TypeStruct::new(SType::Impl, struct_name),
475 Some(LocationInObject::Impl),
476 )
477 }
478 // We use "original_name" here to be sure to get the correct object since the "name"
479 // field could have been renamed.
480 else if let Some(trait_name) = configured_functions
481 .iter()
482 .find_map(|f| f.doc_trait_name.as_ref())
483 {
484 (
485 TypeStruct::new(SType::Trait, trait_name),
486 // Because we cannot sensibly deduce where the docs end up,
487 // assume they're outside the docs so that no `Self::` links
488 // are generated. It is currently quite uncommon to specify
489 // the `{}Manual` trait, which would be ObjectLocation::ExtManual.
490 None,
491 )
492 } else if is_manual {
493 (
494 TypeStruct::new(SType::Trait, &format!("{}ExtManual", info.name)),
495 Some(LocationInObject::ExtManual),
496 )
497 } else {
498 (ty_ext.clone(), Some(LocationInObject::Ext))
499 }
500 } else {
501 (ty.clone(), Some(LocationInObject::Impl))
502 };
503 if let Some(c_identifier) = &function.c_identifier {
504 let f_info = info.functions.iter().find(|f| &f.glib_name == c_identifier);
505 let should_be_documented = f_info.is_some_and(|f| f.should_docs_be_generated(env));
506
507 if !should_be_documented {
508 continue;
509 }
510
511 // Retrieve the new_name computed during analysis, if any
512 let fn_new_name = f_info.and_then(|analysed_f| analysed_f.new_name.clone());
513 let doc_ignored_parameters = f_info
514 .map(|analyzed_f| analyzed_f.doc_ignore_parameters.clone())
515 .unwrap_or_default();
516 create_fn_doc(
517 w,
518 env,
519 function,
520 Some(Box::new(ty)),
521 fn_new_name,
522 &doc_ignored_parameters,
523 Some((&info.type_id, object_location)),
524 f_info.is_none_or(|f| f.generate_doc),
525 )?;
526 }
527 }
528 for signal in signals {
529 let configured_signals = obj.signals.matched(&signal.name);
530 let (ty, object_location) = if has_trait {
531 if let Some(trait_name) = configured_signals
532 .iter()
533 .find_map(|f| f.doc_trait_name.as_ref())
534 {
535 (TypeStruct::new(SType::Trait, trait_name), None)
536 } else {
537 (ty_ext.clone(), Some(LocationInObject::Ext))
538 }
539 } else {
540 (ty.clone(), Some(LocationInObject::Impl))
541 };
542 create_fn_doc(
543 w,
544 env,
545 signal,
546 Some(Box::new(ty)),
547 None,
548 &HashSet::new(),
549 Some((&info.type_id, object_location)),
550 configured_signals.iter().all(|s| s.generate_doc),
551 )?;
552 }
553
554 for function in virtual_methods {
555 let configured_virtual_methods = obj.virtual_methods.matched(&function.name);
556 let (ty, object_location) = if let Some(trait_name) = configured_virtual_methods
557 .iter()
558 .find_map(|f| f.doc_trait_name.as_ref())
559 {
560 (
561 TypeStruct::new(SType::Trait, trait_name),
562 // Because we cannot sensibly deduce where the docs end up,
563 // assume they're outside the docs so that no `Self::` links
564 // are generated. It is currently quite uncommon to specify
565 // the `{}Manual` trait, which would be ObjectLocation::ExtManual.
566 None,
567 )
568 } else {
569 (
570 TypeStruct::new(SType::Trait, &format!("{}Impl", info.name)),
571 Some(LocationInObject::VirtualExt),
572 )
573 };
574
575 if let Some(c_identifier) = &function.c_identifier {
576 let f_info: Option<&analysis::functions::Info> = info
577 .virtual_methods
578 .iter()
579 .find(|f| &f.glib_name == c_identifier);
580 let should_be_documented = f_info.is_some_and(|f| f.should_docs_be_generated(env));
581 if !should_be_documented {
582 continue;
583 }
584
585 // Retrieve the new_name computed during analysis, if any
586 let fn_new_name = f_info.and_then(|analysed_f| analysed_f.new_name.clone());
587 let doc_ignored_parameters = f_info
588 .map(|analyzed_f| analyzed_f.doc_ignore_parameters.clone())
589 .unwrap_or_default();
590 create_fn_doc(
591 w,
592 env,
593 function,
594 Some(Box::new(ty)),
595 fn_new_name,
596 &doc_ignored_parameters,
597 Some((&info.type_id, object_location)),
598 f_info.is_none_or(|f| f.generate_doc),
599 )?;
600 }
601 }
602
603 for property in properties {
604 let getter_name = if property.getter.is_some() {
605 None // Don't generate a getter for the property, there is a getter
606 } else {
607 info.properties
608 .iter()
609 .filter(|p| p.is_get)
610 .find(|p| p.name == property.name)
611 .map(|p| p.func_name.clone())
612 };
613 let setter_name = if property.setter.is_some() {
614 None // don't generate a setter for the property, there is a setter
615 } else {
616 info.properties
617 .iter()
618 .filter(|p| !p.is_get)
619 .find(|p| p.name == property.name)
620 .map(|p| p.func_name.clone())
621 };
622
623 let (ty, object_location) = if has_trait {
624 let configured_properties = obj.properties.matched(&property.name);
625 if let Some(trait_name) = configured_properties
626 .iter()
627 .find_map(|f| f.doc_trait_name.as_ref())
628 {
629 (TypeStruct::new(SType::Trait, trait_name), None)
630 } else {
631 (ty_ext.clone(), Some(LocationInObject::Ext))
632 }
633 } else {
634 (ty.clone(), Some(LocationInObject::Impl))
635 };
636 create_property_doc(
637 w,
638 env,
639 property,
640 Some(Box::new(ty)),
641 (&info.type_id, object_location),
642 getter_name,
643 setter_name,
644 info,
645 )?;
646 }
647 Ok(())
648 }
649
650 fn create_record_doc(w: &mut dyn Write, env: &Env, info: &analysis::record::Info) -> Result<()> {
651 let record: &Record = env.library.type_(info.type_id).to_ref_as();
652 let ty = record.to_stripper_type();
653 let object = env.config.objects.get(&info.full_name);
654 let trait_name = object
655 .and_then(|o| o.trait_name.clone())
656 .unwrap_or_else(|| format!("{}Ext", info.name));
657 let generate_doc = object.is_none_or(|r| r.generate_doc);
658 if generate_doc {
659 write_item_doc(w, &ty, |w| {
660 if let Some(ref doc) = record.doc {
661 writeln!(w, "{}", reformat_doc(doc, env, Some((&info.type_id, None))))?;
662 }
663 if let Some(ver) = info.deprecated_version {
664 writeln!(w, "\n# Deprecated since {ver}\n")?;
665 } else if record.doc_deprecated.is_some() {
666 writeln!(w, "\n# Deprecated\n")?;
667 }
668 if let Some(ref doc) = record.doc_deprecated {
669 writeln!(w, "{}", reformat_doc(doc, env, Some((&info.type_id, None))))?;
670 }
671 Ok(())
672 })?;
673 }
674
675 for function in &record.functions {
676 let function_ty = if function.kind == FunctionKind::ClassMethod {
677 TypeStruct::new(SType::Trait, &trait_name)
678 } else {
679 TypeStruct {
680 ty: SType::Impl,
681 parent: ty.parent.clone(),
682 name: ty.name.clone(),
683 args: ty.args.clone(),
684 }
685 };
686 if let Some(c_identifier) = &function.c_identifier {
687 let f_info = info.functions.iter().find(|f| &f.glib_name == c_identifier);
688 let should_be_documented = f_info.is_some_and(|f| f.should_docs_be_generated(env));
689 if !should_be_documented {
690 continue;
691 }
692 let fn_new_name = f_info.and_then(|analysed_f| analysed_f.new_name.clone());
693
694 create_fn_doc(
695 w,
696 env,
697 function,
698 Some(Box::new(function_ty)),
699 fn_new_name,
700 &HashSet::new(),
701 Some((&info.type_id, None)),
702 f_info.is_none_or(|f| f.generate_doc),
703 )?;
704 }
705 }
706 Ok(())
707 }
708
709 fn create_enum_doc(w: &mut dyn Write, env: &Env, enum_: &Enumeration, tid: TypeId) -> Result<()> {
710 let ty = enum_.to_stripper_type();
711 let config = env.config.objects.get(&tid.full_name(&env.library));
712
713 if config.is_none_or(|c| c.generate_doc) {
714 write_item_doc(w, &ty, |w| {
715 if let Some(ref doc) = enum_.doc {
716 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
717 }
718 if let Some(ver) = enum_.deprecated_version {
719 writeln!(w, "\n# Deprecated since {ver}\n")?;
720 } else if enum_.doc_deprecated.is_some() {
721 writeln!(w, "\n# Deprecated\n")?;
722 }
723 if let Some(ref doc) = enum_.doc_deprecated {
724 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
725 }
726 Ok(())
727 })?;
728 }
729
730 for member in &enum_.members {
731 let generate_doc = config
732 .and_then(|m| {
733 m.members
734 .matched(&member.name)
735 .first()
736 .map(|m| m.generate_doc && !m.status.ignored())
737 })
738 .unwrap_or(true);
739
740 if generate_doc && member.doc.is_some() {
741 let sub_ty = TypeStruct {
742 name: nameutil::enum_member_name(&member.name),
743 parent: Some(Box::new(ty.clone())),
744 ty: SType::Variant,
745 args: Vec::new(),
746 };
747 write_item_doc(w, &sub_ty, |w| {
748 if let Some(ref doc) = member.doc {
749 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
750 }
751 if let Some(ref doc) = member.doc_deprecated {
752 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
753 }
754 Ok(())
755 })?;
756 }
757 }
758
759 Ok(())
760 }
761
762 fn create_bitfield_doc(
763 w: &mut dyn Write,
764 env: &Env,
765 bitfield: &Bitfield,
766 tid: TypeId,
767 ) -> Result<()> {
768 let ty = bitfield.to_stripper_type();
769 let config = env.config.objects.get(&tid.full_name(&env.library));
770
771 write_item_doc(w, &ty, |w| {
772 if config.is_none_or(|c| c.generate_doc)
773 && let Some(ref doc) = bitfield.doc
774 {
775 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
776 }
777 if let Some(ver) = bitfield.deprecated_version {
778 writeln!(w, "\n# Deprecated since {ver}\n")?;
779 } else if bitfield.doc_deprecated.is_some() {
780 writeln!(w, "\n# Deprecated\n")?;
781 }
782 if let Some(ref doc) = bitfield.doc_deprecated {
783 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
784 }
785 Ok(())
786 })?;
787
788 for member in &bitfield.members {
789 let generate_doc = config
790 .and_then(|m| {
791 m.members
792 .matched(&member.name)
793 .first()
794 .map(|m| m.generate_doc)
795 })
796 .unwrap_or(true);
797
798 if generate_doc && member.doc.is_some() {
799 let sub_ty = TypeStruct {
800 name: nameutil::bitfield_member_name(&member.name),
801 parent: Some(Box::new(ty.clone())),
802 ty: SType::Const,
803 args: Vec::new(),
804 };
805 write_item_doc(w, &sub_ty, |w| {
806 if let Some(ref doc) = member.doc {
807 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
808 }
809 if let Some(ref doc) = member.doc_deprecated {
810 writeln!(w, "{}", reformat_doc(doc, env, Some((&tid, None))))?;
811 }
812 Ok(())
813 })?;
814 }
815 }
816
817 Ok(())
818 }
819
820 fn param_name() -> &'static Regex {
821 static REGEX: OnceLock<Regex> = OnceLock::new();
822 REGEX.get_or_init(|| Regex::new(r"@(\w+)\b").unwrap())
823 }
824
825 fn fix_param_names<'a>(doc: &'a str, self_name: &Option<String>) -> Cow<'a, str> {
826 param_name().replace_all(doc, |caps: &Captures<'_>| {
827 if let Some(self_name) = self_name
828 && &caps[1] == self_name
829 {
830 return "@self".into();
831 }
832 format!("@{}", nameutil::mangle_keywords(&caps[1]))
833 })
834 }
835
836 fn create_fn_doc<T>(
837 w: &mut dyn Write,
838 env: &Env,
839 fn_: &T,
840 parent: Option<Box<TypeStruct>>,
841 name_override: Option<String>,
842 doc_ignored_parameters: &HashSet<String>,
843 in_type: Option<(&TypeId, Option<LocationInObject>)>,
844 generate_doc: bool,
845 ) -> Result<()>
846 where
847 T: FunctionLikeType + ToStripperType,
848 {
849 if !generate_doc {
850 return Ok(());
851 }
852 if env.is_totally_deprecated(None, *fn_.deprecated_version()) {
853 return Ok(());
854 }
855 if fn_.doc().is_none()
856 && fn_.doc_deprecated().is_none()
857 && fn_.ret().doc.is_none()
858 && fn_.parameters().iter().all(|p| p.doc.is_none())
859 {
860 return Ok(());
861 }
862
863 let mut st = fn_.to_stripper_type();
864 if let Some(name_override) = name_override {
865 st.name = nameutil::mangle_keywords(name_override).to_string();
866 }
867 let ty = TypeStruct { parent, ..st };
868 let self_name: Option<String> = fn_
869 .parameters()
870 .iter()
871 .find(|p| p.instance_parameter)
872 .map(|p| p.name.clone());
873
874 write_item_doc(w, &ty, |w| {
875 if let Some(doc) = fn_.doc() {
876 writeln!(
877 w,
878 "{}",
879 reformat_doc(&fix_param_names(doc, &self_name), env, in_type)
880 )?;
881 }
882 if let Some(ver) = fn_.deprecated_version() {
883 writeln!(w, "\n# Deprecated since {ver}\n")?;
884 } else if fn_.doc_deprecated().is_some() {
885 writeln!(w, "\n# Deprecated\n")?;
886 }
887 if let Some(doc) = fn_.doc_deprecated() {
888 writeln!(
889 w,
890 "{}",
891 reformat_doc(&fix_param_names(doc, &self_name), env, in_type)
892 )?;
893 }
894
895 // A list of parameter positions to filter out
896 let mut indices_to_ignore: BTreeSet<_> = fn_
897 .parameters()
898 .iter()
899 .filter_map(|param| param.array_length)
900 .collect();
901 if let Some(indice) = fn_.ret().array_length {
902 indices_to_ignore.insert(indice);
903 }
904
905 // The original list of parameters without the ones that specify an array length
906 let no_array_length_params: Vec<_> = fn_
907 .parameters()
908 .iter()
909 .enumerate()
910 .filter_map(|(indice, param)| {
911 (!indices_to_ignore.contains(&(indice as u32))).then_some(param)
912 })
913 .filter(|param| !param.instance_parameter)
914 .collect();
915
916 let in_parameters = no_array_length_params.iter().filter(|param| {
917 let ignore = IGNORED_C_FN_PARAMS.contains(&param.name.as_str())
918 || doc_ignored_parameters.contains(&param.name)
919 || param.direction == ParameterDirection::Out
920 // special case error pointer as it's transformed to a Result
921 || (param.name == "error" && param.c_type == "GError**")
922 // special case `data` with explicit `gpointer` type as it could be something else (unlike `user_data`)
923 || (param.name == "data" && param.c_type == "gpointer");
924 !ignore
925 });
926
927 for parameter in in_parameters {
928 if parameter.name.is_empty() {
929 continue;
930 }
931 if let Some(ref doc) = parameter.doc {
932 writeln!(
933 w,
934 "## `{}`",
935 nameutil::mangle_keywords(parameter.name.as_str())
936 )?;
937 writeln!(
938 w,
939 "{}",
940 reformat_doc(&fix_param_names(doc, &self_name), env, in_type)
941 )?;
942 }
943 }
944
945 let out_parameters: Vec<_> = no_array_length_params
946 .iter()
947 .filter(|param| {
948 param.direction == ParameterDirection::Out
949 && !doc_ignored_parameters.contains(&param.name)
950 && !(param.name == "error" && param.c_type == "GError**")
951 })
952 .collect();
953
954 if fn_.ret().doc.is_some() || !out_parameters.is_empty() {
955 writeln!(w, "\n# Returns\n")?;
956 }
957 // document function's return
958 if let Some(ref doc) = fn_.ret().doc {
959 writeln!(
960 w,
961 "{}",
962 reformat_doc(&fix_param_names(doc, &self_name), env, in_type)
963 )?;
964 }
965 // document OUT parameters as part of the function's Return
966 for parameter in out_parameters {
967 if let Some(ref doc) = parameter.doc {
968 writeln!(
969 w,
970 "\n## `{}`",
971 nameutil::mangle_keywords(parameter.name.as_str())
972 )?;
973 writeln!(
974 w,
975 "{}",
976 reformat_doc(&fix_param_names(doc, &self_name), env, in_type),
977 )?;
978 }
979 }
980 Ok(())
981 })
982 }
983
984 fn create_property_doc(
985 w: &mut dyn Write,
986 env: &Env,
987 property: &Property,
988 parent: Option<Box<TypeStruct>>,
989 in_type: (&TypeId, Option<LocationInObject>),
990 getter_name: Option<String>,
991 setter_name: Option<String>,
992 obj_info: &analysis::object::Info,
993 ) -> Result<()> {
994 if env.is_totally_deprecated(Some(in_type.0.ns_id), property.deprecated_version) {
995 return Ok(());
996 }
997 let generate_doc = env
998 .config
999 .objects
1000 .get(&obj_info.type_id.full_name(&env.library))
1001 .is_none_or(|r| r.generate_doc);
1002 if !generate_doc {
1003 return Ok(());
1004 }
1005 if property.doc.is_none()
1006 && property.doc_deprecated.is_none()
1007 && (property.readable || property.writable)
1008 {
1009 return Ok(());
1010 }
1011 let mut v = Vec::with_capacity(2);
1012
1013 if let Some(getter_name) = getter_name {
1014 v.push(TypeStruct {
1015 parent: parent.clone(),
1016 ..TypeStruct::new(SType::Fn, &getter_name)
1017 });
1018 }
1019 if let Some(setter_name) = setter_name {
1020 v.push(TypeStruct {
1021 parent,
1022 ..TypeStruct::new(SType::Fn, &setter_name)
1023 });
1024 }
1025
1026 for item in &v {
1027 write_item_doc(w, item, |w| {
1028 if let Some(ref doc) = property.doc {
1029 writeln!(
1030 w,
1031 "{}",
1032 reformat_doc(&fix_param_names(doc, &None), env, Some(in_type))
1033 )?;
1034 }
1035 if let Some(ver) = property.deprecated_version {
1036 writeln!(w, "\n# Deprecated since {ver}\n")?;
1037 } else if property.doc_deprecated.is_some() {
1038 writeln!(w, "\n# Deprecated\n")?;
1039 }
1040 if let Some(ref doc) = property.doc_deprecated {
1041 writeln!(
1042 w,
1043 "{}",
1044 reformat_doc(&fix_param_names(doc, &None), env, Some(in_type))
1045 )?;
1046 }
1047 Ok(())
1048 })?;
1049 }
1050 Ok(())
1051 }
1052
1053 fn get_type_trait_for_implements(env: &Env, tid: TypeId) -> String {
1054 let trait_name = if let Some(&GObject {
1055 trait_name: Some(ref trait_name),
1056 ..
1057 }) = env.config.objects.get(&tid.full_name(&env.library))
1058 {
1059 trait_name.clone()
1060 } else {
1061 format!("{}Ext", env.library.type_(tid).get_name())
1062 };
1063 if tid.ns_id == MAIN_NAMESPACE {
1064 format!("[`{trait_name}`][trait@crate::prelude::{trait_name}]")
1065 } else if let Some(symbol) = env.symbols.borrow().by_tid(tid) {
1066 let mut symbol = symbol.clone();
1067 symbol.make_trait(&trait_name);
1068 format!("[`trait@{}`]", symbol.full_rust_name())
1069 } else {
1070 error!("Type {} doesn't have crate", tid.full_name(&env.library));
1071 format!("`{trait_name}`")
1072 }
1073 }
1074
1075 pub fn get_type_manual_traits_for_implements(
1076 env: &Env,
1077 info: &analysis::object::Info,
1078 ) -> Vec<String> {
1079 let mut manual_trait_iters = Vec::new();
1080 for type_id in [info.type_id]
1081 .iter()
1082 .chain(info.supertypes.iter().map(|stid| &stid.type_id))
1083 {
1084 let full_name = type_id.full_name(&env.library);
1085 if let Some(obj) = &env.config.objects.get(&full_name)
1086 && !obj.manual_traits.is_empty()
1087 {
1088 manual_trait_iters.push(obj.manual_traits.iter());
1089 }
1090 }
1091
1092 manual_trait_iters
1093 .into_iter()
1094 .flatten()
1095 .map(|name| format!("[`{name}`][trait@crate::prelude::{name}]"))
1096 .collect()
1097 }
1098
1099 pub fn document_type_properties(
1100 env: &Env,
1101 w: &mut dyn Write,
1102 info: &analysis::object::Info,
1103 properties: &[Property],
1104 subtype: Option<&str>,
1105 ) -> Result<()> {
1106 if let Some(subtype_name) = subtype {
1107 writeln!(w, "<details><summary><h4>{subtype_name}</h4></summary>")?;
1108 }
1109 for property in properties {
1110 let mut details = Vec::new();
1111 if property.readable {
1112 details.push("Readable");
1113 }
1114 if property.writable {
1115 details.push("Writable");
1116 }
1117 if property.construct {
1118 details.push("Construct");
1119 }
1120 if property.construct_only {
1121 details.push("Construct Only");
1122 }
1123 if let Some(doc) = &property.doc {
1124 writeln!(
1125 w,
1126 "\n\n#### `{}`\n {}\n\n{}",
1127 property.name,
1128 reformat_doc(
1129 &fix_param_names(doc, &None),
1130 env,
1131 Some((&info.type_id, None))
1132 ),
1133 details.join(" | "),
1134 )?;
1135 } else {
1136 writeln!(w, "\n\n#### `{}`\n {}", property.name, details.join(" | "),)?;
1137 }
1138 }
1139 if subtype.is_some() {
1140 writeln!(w, "</details>")?;
1141 }
1142 Ok(())
1143 }
1144
1145 pub fn document_type_signals(
1146 env: &Env,
1147 w: &mut dyn Write,
1148 info: &analysis::object::Info,
1149 signals: &[Signal],
1150 subtype: Option<&str>,
1151 ) -> Result<()> {
1152 if let Some(subtype_name) = subtype {
1153 writeln!(w, "<details><summary><h4>{subtype_name}</h4></summary>")?;
1154 }
1155 for signal in signals {
1156 let mut details = Vec::new();
1157 if signal.is_action {
1158 details.push("Action");
1159 }
1160 if signal.is_detailed {
1161 details.push("Detailed");
1162 }
1163 if let Some(doc) = &signal.doc {
1164 writeln!(
1165 w,
1166 "\n\n#### `{}`\n {}\n\n{}",
1167 signal.name,
1168 reformat_doc(
1169 &fix_param_names(doc, &None),
1170 env,
1171 Some((&info.type_id, None))
1172 ),
1173 details.join(" | "),
1174 )?;
1175 } else {
1176 writeln!(w, "\n\n#### `{}`\n {}", signal.name, details.join(" | "),)?;
1177 }
1178 }
1179 if subtype.is_some() {
1180 writeln!(w, "</details>")?;
1181 }
1182 Ok(())
1183 }