Debian Codegraph @

src/codegen/object.rs

raw
1 use std::{
2 collections::{BTreeMap, HashSet},
3 io::{Result, Write},
4 };
5
6 use super::{
7 child_properties, function, general,
8 general::{cfg_deprecated_string, version_condition_string},
9 properties, signal, trait_impls,
10 };
11 use crate::{
12 analysis::{
13 self, bounds::BoundType, object::has_builder_properties, record_type::RecordType,
14 ref_mode::RefMode, rust_type::RustType, safety_assertion_mode::SafetyAssertionMode,
15 },
16 env::Env,
17 library::{self, Nullable},
18 nameutil,
19 traits::IntoString,
20 };
21
22 pub fn generate(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
23 general::start_comments(w, &env.config)?;
24 if analysis
25 .functions
26 .iter()
27 .any(|f| f.deprecated_version.is_some())
28 {
29 writeln!(w, "#![allow(deprecated)]")?;
30 }
31 general::uses(w, env, &analysis.imports, analysis.version)?;
32
33 let config = &env.config.objects[&analysis.full_name];
34 if config.default_value.is_some() {
35 log::error!(
36 "`default_value` can only be used on flags and enums. {} is neither. Ignoring \
37 `default_value`.",
38 analysis.name,
39 );
40 }
41
42 // Collect all supertypes that were added at a later time. The `glib::wrapper!`
43 // call needs to be done multiple times with different `#[cfg]` directives
44 // if there is a difference.
45 let mut ns_versions: BTreeMap<u16, BTreeMap<_, Vec<_>>> = BTreeMap::new();
46 for p in &analysis.supertypes {
47 use crate::library::*;
48
49 match *env.library.type_(p.type_id) {
50 Type::Interface(Interface { .. }) | Type::Class(Class { .. })
51 if !p.status.ignored() =>
52 {
53 let full_name = p.type_id.full_name(&env.library);
54 if let Some(object) = env.analysis.objects.get(&full_name) {
55 let parent_version = object.version;
56 let namespace_min_version = env
57 .config
58 .min_required_version(env, Some(object.type_id.ns_id));
59 // We should only compare the versions if they come from the
60 // same namespace.
61 let is_same_lib = object.type_id.ns_id == analysis.base.type_id.ns_id;
62 if (parent_version > analysis.version || !is_same_lib)
63 && parent_version > namespace_min_version
64 {
65 ns_versions
66 .entry(object.type_id.ns_id)
67 .or_default()
68 .entry(parent_version)
69 .or_default()
70 .push(p);
71 }
72 }
73 }
74 _ => continue,
75 }
76 }
77 let namespaces: Vec<_> = ns_versions.into_iter().collect();
78
79 if namespaces.is_empty() || analysis.is_fundamental {
80 writeln!(w)?;
81 if analysis.is_fundamental {
82 general::define_fundamental_type(
83 w,
84 env,
85 &analysis.name,
86 &analysis.c_type,
87 &analysis.get_type,
88 analysis.ref_fn.as_deref(),
89 analysis.unref_fn.as_deref(),
90 &analysis.supertypes,
91 analysis.visibility,
92 analysis.type_id,
93 )?;
94 } else {
95 general::define_object_type(
96 w,
97 env,
98 &analysis.name,
99 &analysis.c_type,
100 analysis.c_class_type.as_deref(),
101 &analysis.get_type,
102 analysis.is_interface,
103 &analysis.supertypes,
104 analysis.visibility,
105 analysis.type_id,
106 )?;
107 }
108 } else {
109 // Write the `glib::wrapper!` calls from the highest version to the lowest.
110 // Each block is gated by its version feature and `not` of all higher version
111 // features. The base block is gated by `not(any(all versioned features))`.
112 let mut remove_types: HashSet<library::TypeId> = HashSet::new();
113
114 for (ns_id, versions) in &namespaces {
115 let namespace_name = if *ns_id == analysis::namespaces::MAIN {
116 None
117 } else {
118 Some(env.namespaces[*ns_id].crate_name.clone())
119 };
120
121 let all_version_cfgs: Vec<String> = versions
122 .keys()
123 .filter_map(|v| v.map(|v| v.to_cfg(namespace_name.as_deref())))
124 .collect();
125 let n = all_version_cfgs.len();
126 let mut rev_index = 0usize;
127
128 for (&version, stypes) in versions.iter().rev() {
129 let supertypes = analysis
130 .supertypes
131 .iter()
132 .filter(|t| !remove_types.contains(&t.type_id))
133 .cloned()
134 .collect::<Vec<_>>();
135
136 writeln!(w)?;
137 if version.is_some() {
138 let asc_index = n - 1 - rev_index;
139 let positive = &all_version_cfgs[..=asc_index];
140 let negative = all_version_cfgs.get(asc_index + 1);
141
142 let mut parts: Vec<String> = positive.to_vec();
143 if let Some(neg) = negative {
144 parts.push(format!("not({neg})"));
145 }
146
147 if parts.len() == 1 {
148 writeln!(w, "#[cfg({})]", parts[0])?;
149 } else {
150 writeln!(w, "#[cfg(all({}))]", parts.join(", "))?;
151 }
152
153 if rev_index == 0 {
154 let highest_cfg = &all_version_cfgs[n - 1];
155 writeln!(w, "#[cfg_attr(docsrs, doc(cfg({})))]", highest_cfg)?;
156 }
157
158 rev_index += 1;
159 }
160
161 general::define_object_type(
162 w,
163 env,
164 &analysis.name,
165 &analysis.c_type,
166 analysis.c_class_type.as_deref(),
167 &analysis.get_type,
168 analysis.is_interface,
169 &supertypes,
170 analysis.visibility,
171 analysis.type_id,
172 )?;
173
174 for t in stypes {
175 remove_types.insert(t.type_id);
176 }
177 }
178
179 // Write the base `glib::wrapper!` gated by not(any(all versioned features)).
180 let supertypes = analysis
181 .supertypes
182 .iter()
183 .filter(|t| !remove_types.contains(&t.type_id))
184 .cloned()
185 .collect::<Vec<_>>();
186 writeln!(w)?;
187 if all_version_cfgs.len() == 1 {
188 writeln!(w, "#[cfg(not({}))]", all_version_cfgs[0])?;
189 } else {
190 let all = all_version_cfgs.join(", ");
191 writeln!(w, "#[cfg(not(any({all})))]")?;
192 }
193 general::define_object_type(
194 w,
195 env,
196 &analysis.name,
197 &analysis.c_type,
198 analysis.c_class_type.as_deref(),
199 &analysis.get_type,
200 analysis.is_interface,
201 &supertypes,
202 analysis.visibility,
203 analysis.type_id,
204 )?;
205 }
206 }
207
208 if (analysis.need_generate_inherent() && analysis.should_generate_impl_block())
209 || !analysis.final_type
210 {
211 writeln!(w)?;
212 write!(w, "impl {} {{", analysis.name)?;
213
214 if !analysis.final_type {
215 writeln!(
216 w,
217 "
218 pub const NONE: Option<&'static {}> = None;
219 ",
220 analysis.name
221 )?;
222 }
223
224 for func_analysis in &analysis.constructors() {
225 function::generate(
226 w,
227 env,
228 Some(analysis.type_id),
229 func_analysis,
230 Some(&analysis.specials),
231 analysis.version,
232 false,
233 false,
234 1,
235 )?;
236 }
237
238 if has_builder_properties(&analysis.builder_properties) {
239 // generate builder method that returns the corresponding builder
240 let builder_name = format!("{}Builder", analysis.name);
241 writeln!(
242 w,
243 "
244 // rustdoc-stripper-ignore-next
245 /// Creates a new builder-pattern struct instance to construct [`{name}`] objects.
246 ///
247 /// This method returns an instance of [`{builder_name}`](crate::builders::{builder_name}) which can be used to create [`{name}`] objects.
248 pub fn builder() -> {builder_name} {{
249 {builder_name}::new()
250 }}
251 ",
252 name = analysis.name,
253 builder_name = builder_name
254 )?;
255 }
256
257 if !analysis.need_generate_trait() {
258 for func_analysis in &analysis.methods() {
259 function::generate(
260 w,
261 env,
262 Some(analysis.type_id),
263 func_analysis,
264 Some(&analysis.specials),
265 analysis.version,
266 false,
267 false,
268 1,
269 )?;
270 }
271
272 for property in &analysis.properties {
273 properties::generate(w, env, property, false, false, 1)?;
274 }
275
276 for child_property in &analysis.child_properties {
277 child_properties::generate(w, env, child_property, false, false, 1)?;
278 }
279 }
280
281 for func_analysis in &analysis.functions() {
282 function::generate(
283 w,
284 env,
285 Some(analysis.type_id),
286 func_analysis,
287 Some(&analysis.specials),
288 analysis.version,
289 false,
290 false,
291 1,
292 )?;
293 }
294
295 if !analysis.need_generate_trait() {
296 for signal_analysis in analysis
297 .signals
298 .iter()
299 .chain(analysis.notify_signals.iter())
300 {
301 signal::generate(w, env, signal_analysis, false, false, 1)?;
302 }
303 }
304
305 writeln!(w, "}}")?;
306
307 general::declare_default_from_new(
308 w,
309 env,
310 &analysis.name,
311 &analysis.functions,
312 has_builder_properties(&analysis.builder_properties),
313 )?;
314 }
315
316 trait_impls::generate(
317 w,
318 env,
319 &analysis.name,
320 &analysis.functions,
321 &analysis.specials,
322 if analysis.need_generate_trait() {
323 Some(&analysis.trait_name)
324 } else {
325 None
326 },
327 analysis.version,
328 None, // There is no need for #[cfg()] since it's applied on the whole file.
329 )?;
330
331 if has_builder_properties(&analysis.builder_properties) {
332 writeln!(w)?;
333 generate_builder(w, env, analysis)?;
334 }
335
336 if analysis.concurrency != library::Concurrency::None {
337 writeln!(w)?;
338 }
339
340 match analysis.concurrency {
341 library::Concurrency::Send | library::Concurrency::SendSync => {
342 writeln!(w, "unsafe impl Send for {} {{}}", analysis.name)?;
343 }
344 _ => (),
345 }
346
347 if let library::Concurrency::SendSync = analysis.concurrency {
348 writeln!(w, "unsafe impl Sync for {} {{}}", analysis.name)?;
349 }
350
351 if analysis.need_generate_trait() {
352 writeln!(w)?;
353 generate_trait(w, env, analysis)?;
354 }
355 Ok(())
356 }
357
358 fn generate_builder(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
359 let glib_crate_name = if env.namespaces.is_glib_crate {
360 "crate"
361 } else {
362 "glib"
363 };
364
365 writeln!(
366 w,
367 "// rustdoc-stripper-ignore-next
368 /// A [builder-pattern] type to construct [`{}`] objects.
369 ///
370 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html",
371 analysis.name,
372 )?;
373 writeln!(w, "#[must_use = \"The builder must be built to be used\"]")?;
374 writeln!(
375 w,
376 "pub struct {name}Builder {{
377 builder: {glib_name}::object::ObjectBuilder<'static, {name}>,
378 }}
379
380 impl {name}Builder {{
381 fn new() -> Self {{
382 Self {{ builder: {glib_name}::object::Object::builder() }}
383 }}",
384 name = analysis.name,
385 glib_name = glib_crate_name,
386 )?;
387 for (builder_props, super_tid) in &analysis.builder_properties {
388 for property in builder_props {
389 let direction = if property.is_get {
390 library::ParameterDirection::In
391 } else {
392 library::ParameterDirection::Out
393 };
394 let param_type = RustType::builder(env, property.typ)
395 .direction(direction)
396 .ref_mode(property.set_in_ref_mode)
397 .try_build();
398 let comment_prefix = if param_type.is_err() { "//" } else { "" };
399 let mut param_type_str = param_type.into_string();
400 let (param_type_override, bounds, conversion) = match param_type_str.as_str() {
401 "&str" => (
402 Some(format!("impl Into<{glib_crate_name}::GString>")),
403 String::new(),
404 ".into()",
405 ),
406 "&[&str]" => (
407 Some(format!("impl Into<{glib_crate_name}::StrV>")),
408 String::from(""),
409 ".into()",
410 ),
411 _ if !property.bounds.is_empty() => {
412 let (bounds, _) = function::bounds(&property.bounds, &[], false, false);
413 let param_bound = property.bounds.get_parameter_bound(&property.name);
414 let alias = param_bound.map(|bound| {
415 bound.full_type_parameter_reference(RefMode::ByRef, Nullable(false), false)
416 });
417 let conversion = param_bound.and_then(|bound| match bound.bound_type {
418 BoundType::AsRef(_) => Some(".as_ref().clone()"),
419 _ => None,
420 });
421 (alias, bounds, conversion.unwrap_or(".clone().upcast()"))
422 }
423 typ if typ.starts_with('&') => {
424 let should_clone =
425 if let crate::library::Type::Record(record) = env.type_(property.typ) {
426 match RecordType::of(record) {
427 RecordType::Boxed => "",
428 RecordType::AutoBoxed if !record.has_copy() => "",
429 _ => ".clone()",
430 }
431 } else {
432 ".clone()"
433 };
434
435 (None, String::new(), should_clone)
436 }
437 _ => (None, String::new(), ""),
438 };
439 if let Some(param_type_override) = param_type_override {
440 param_type_str = param_type_override.to_string();
441 }
442 let name = nameutil::mangle_keywords(nameutil::signal_to_snake(&property.name));
443
444 let version_condition_string =
445 version_condition_string(env, Some(super_tid.ns_id), property.version, false, 1);
446 let deprecated_string =
447 cfg_deprecated_string(env, Some(*super_tid), property.deprecated_version, false, 1);
448 let version_prefix = version_condition_string
449 .map(|version| format!("{comment_prefix}{version}\n"))
450 .unwrap_or_default();
451
452 let deprecation_prefix = deprecated_string
453 .map(|version| format!("{comment_prefix}{version}\n"))
454 .unwrap_or_default();
455
456 writeln!(
457 w,
458 "
459 {version_prefix}{deprecation_prefix} {comment_prefix}pub fn {name}{bounds}(self, {name}: {param_type_str}) -> Self {{
460 {comment_prefix} Self {{ builder: self.builder.property(\"{property_name}\", {name}{conversion}), }}
461 {comment_prefix}}}",
462 property_name = property.name,
463 )?;
464 }
465 }
466
467 writeln!(
468 w,
469 "
470 // rustdoc-stripper-ignore-next
471 /// Build the [`{name}`].
472 #[must_use = \"Building the object from the builder is usually expensive and is not expected to have side effects\"]
473 pub fn build(self) -> {name} {{",
474 name = analysis.name,
475 )?;
476
477 // The split allows us to not have clippy::let_and_return lint disabled
478 if let Some(code) = analysis.builder_postprocess.as_ref() {
479 // We don't generate an assertion macro for the case where you have a build post-process
480 // as it is only used to initialize gtk in gtk::ApplicationBuilder which is too early to assert anything
481 writeln!(w, " let ret = self.builder.build();")?;
482 writeln!(w, " {{\n {code}\n }}")?;
483 writeln!(w, " ret\n }}")?;
484 } else {
485 if env.config.generate_safety_asserts {
486 writeln!(w, "{}", SafetyAssertionMode::InMainThread)?;
487 }
488 writeln!(w, " self.builder.build() }}")?;
489 }
490 writeln!(w, "}}")
491 }
492
493 fn generate_trait(w: &mut dyn Write, env: &Env, analysis: &analysis::object::Info) -> Result<()> {
494 write!(
495 w,
496 "pub trait {}: IsA<{}> + 'static {{",
497 analysis.trait_name, analysis.name
498 )?;
499
500 for func_analysis in &analysis.methods() {
501 function::generate(
502 w,
503 env,
504 Some(analysis.type_id),
505 func_analysis,
506 Some(&analysis.specials),
507 analysis.version,
508 true,
509 false,
510 1,
511 )?;
512 }
513 for property in &analysis.properties {
514 properties::generate(w, env, property, true, false, 1)?;
515 }
516 for child_property in &analysis.child_properties {
517 child_properties::generate(w, env, child_property, true, false, 1)?;
518 }
519 for signal_analysis in analysis
520 .signals
521 .iter()
522 .chain(analysis.notify_signals.iter())
523 {
524 signal::generate(w, env, signal_analysis, true, false, 1)?;
525 }
526 writeln!(w, "}}")?;
527
528 writeln!(w)?;
529 writeln!(
530 w,
531 "impl<O: IsA<{}>> {} for O {{}}",
532 analysis.name, analysis.trait_name,
533 )?;
534
535 Ok(())
536 }
537
538 pub fn generate_reexports(
539 env: &Env,
540 analysis: &analysis::object::Info,
541 module_name: &str,
542 contents: &mut Vec<String>,
543 traits: &mut Vec<String>,
544 builders: &mut Vec<String>,
545 ) {
546 let mut cfgs: Vec<String> = Vec::new();
547 if let Some(cfg) = general::cfg_condition_string(analysis.cfg_condition.as_ref(), false, 0) {
548 cfgs.push(cfg);
549 }
550 if let Some(cfg) = general::version_condition_string(env, None, analysis.version, false, 0) {
551 cfgs.push(cfg);
552 }
553 if let Some(cfg) = general::cfg_deprecated_string(
554 env,
555 Some(analysis.type_id),
556 analysis.deprecated_version,
557 false,
558 0,
559 ) {
560 cfgs.push(cfg);
561 }
562
563 contents.push(String::new());
564 contents.extend_from_slice(&cfgs);
565 contents.push(format!("mod {module_name};"));
566 contents.extend_from_slice(&cfgs);
567
568 contents.push(format!(
569 "{} use self::{}::{};",
570 analysis.visibility.export_visibility(),
571 module_name,
572 analysis.name,
573 ));
574
575 if analysis.need_generate_trait() {
576 for cfg in &cfgs {
577 traits.push(format!("\t{cfg}"));
578 }
579 traits.push(format!(
580 "\tpub use super::{}::{};",
581 module_name, analysis.trait_name
582 ));
583 }
584
585 if has_builder_properties(&analysis.builder_properties) {
586 for cfg in &cfgs {
587 builders.push(format!("\t{cfg}"));
588 }
589 builders.push(format!(
590 "\tpub use super::{}::{}Builder;",
591 module_name, analysis.name
592 ));
593 }
594 }