Debian Codegraph @

src/codegen/function.rs

raw
1 use std::{
2 fmt,
3 io::{Result, Write},
4 result::Result as StdResult,
5 };
6
7 use log::warn;
8
9 use super::{
10 function_body_chunk,
11 general::{
12 allow_deprecated, cfg_condition, cfg_deprecated, doc_alias, doc_hidden,
13 not_version_condition, version_condition,
14 },
15 parameter::ToParameter,
16 return_value::{ToReturnValue, out_parameter_types, out_parameters_as_return},
17 special_functions,
18 };
19 use crate::{
20 analysis::{self, bounds::Bounds, try_from_glib::TryFromGlib},
21 chunk::{Chunk, ffi_function_todo},
22 env::Env,
23 library::{self, TypeId},
24 nameutil::use_glib_type,
25 version::Version,
26 writer::{ToCode, primitives::tabs},
27 };
28
29 // We follow the rules of the `return_self_not_must_use` clippy lint:
30 //
31 // If `Self` is returned (so `-> Self`) in a method (whatever the form of the
32 // `self`), then the `#[must_use]` attribute must be added.
33 pub fn get_must_use_if_needed(
34 parent_type_id: Option<TypeId>,
35 analysis: &analysis::functions::Info,
36 comment_prefix: &str,
37 ) -> Option<String> {
38 // If there is no parent, it means it's not a (trait) method so we're not
39 // interested.
40 if let Some(parent_type_id) = parent_type_id {
41 // Check it's a trait declaration or a method declaration (outside of a trait
42 // implementation).
43 if analysis.kind == library::FunctionKind::Method {
44 // We now get the list of the returned types.
45 let outs = out_parameter_types(analysis);
46 // If there is only one type returned, we check if it's the same type as `self`
47 // (stored in `parent_type_id`).
48 if [parent_type_id] == *outs.as_slice() {
49 return Some(format!("{comment_prefix}#[must_use]\n"));
50 }
51 }
52 }
53 None
54 }
55
56 pub fn generate(
57 w: &mut dyn Write,
58 env: &Env,
59 parent_type_id: Option<TypeId>,
60 analysis: &analysis::functions::Info,
61 special_functions: Option<&analysis::special_functions::Infos>,
62 scope_version: Option<Version>,
63 in_trait: bool,
64 only_declaration: bool,
65 indent: usize,
66 ) -> Result<()> {
67 if !analysis.status.need_generate() {
68 return Ok(());
69 }
70
71 if analysis.is_async_finish(env) {
72 return Ok(());
73 }
74
75 if let Some(special_functions) = special_functions
76 && special_functions::generate(w, env, analysis, special_functions, scope_version)?
77 {
78 return Ok(());
79 }
80
81 if analysis.hidden {
82 return Ok(());
83 }
84
85 let commented = analysis.commented;
86 let comment_prefix = if commented { "//" } else { "" };
87 let pub_prefix = if in_trait {
88 String::new()
89 } else {
90 format!("{} ", analysis.visibility)
91 };
92
93 let unsafe_ = if analysis.unsafe_ { "unsafe " } else { "" };
94 let declaration = declaration(env, analysis);
95 let suffix = if only_declaration {
96 ";"
97 } else if analysis.unsafe_ {
98 " { unsafe {"
99 } else {
100 " {"
101 };
102
103 writeln!(w)?;
104 cfg_deprecated(w, env, None, analysis.deprecated_version, commented, indent)?;
105 cfg_condition(w, analysis.cfg_condition.as_ref(), commented, indent)?;
106 let version = Version::if_stricter_than(analysis.version, scope_version);
107 version_condition(w, env, None, version, commented, indent)?;
108 not_version_condition(w, analysis.not_version, commented, indent)?;
109 doc_hidden(w, analysis.doc_hidden, comment_prefix, indent)?;
110 allow_deprecated(w, analysis.deprecated_version, commented, indent)?;
111 doc_alias(w, &analysis.glib_name, comment_prefix, indent)?;
112 if analysis.codegen_name() != analysis.func_name {
113 doc_alias(w, &analysis.func_name, comment_prefix, indent)?;
114 }
115 // TODO Warn the user if both get_property and set_property are set as it is
116 // an error on the gir data.
117 if let Some(get_property) = &analysis.get_property {
118 if get_property != analysis.codegen_name() {
119 doc_alias(w, get_property, comment_prefix, indent)?;
120 }
121 } else if let Some(set_property) = &analysis.set_property
122 && set_property != analysis.codegen_name()
123 {
124 doc_alias(w, set_property, comment_prefix, indent)?;
125 }
126 // Don't add a guard for public or copy/equal functions
127 let dead_code_cfg = if !analysis.visibility.is_public() && !analysis.is_special() {
128 "#[allow(dead_code)]"
129 } else {
130 ""
131 };
132
133 let allow_should_implement_trait = if analysis.codegen_name() == "default" {
134 format!(
135 "{}{}#[allow(clippy::should_implement_trait)]",
136 tabs(indent),
137 comment_prefix
138 )
139 } else {
140 String::new()
141 };
142
143 let allow_new_ret_no_self = if analysis.codegen_name() == "new"
144 && parent_type_id.is_some_and(|tid| {
145 analysis
146 .ret
147 .parameter
148 .as_ref()
149 .is_some_and(|par| par.lib_par.typ != tid)
150 }) {
151 format!(
152 "{}{}#[allow(clippy::new_ret_no_self)]\n",
153 tabs(indent),
154 comment_prefix
155 )
156 } else {
157 String::new()
158 };
159
160 writeln!(
161 w,
162 "{}{}{}{}{}{}{}{}{}{}",
163 allow_should_implement_trait,
164 allow_new_ret_no_self,
165 dead_code_cfg,
166 get_must_use_if_needed(parent_type_id, analysis, comment_prefix).unwrap_or_default(),
167 tabs(indent),
168 comment_prefix,
169 pub_prefix,
170 unsafe_,
171 declaration,
172 suffix,
173 )?;
174
175 if !only_declaration {
176 let body = body_chunk(env, analysis, parent_type_id).to_code(env);
177 for s in body {
178 writeln!(w, "{}{}", tabs(indent), s)?;
179 }
180 if analysis.unsafe_ {
181 writeln!(w, "}}")?;
182 }
183 }
184
185 if analysis.async_future.is_some() {
186 let declaration = declaration_futures(env, analysis);
187 let suffix = if only_declaration { ";" } else { " {" };
188
189 writeln!(w)?;
190 cfg_deprecated(w, env, None, analysis.deprecated_version, commented, indent)?;
191
192 writeln!(w, "{}{}", tabs(indent), comment_prefix)?;
193 cfg_condition(w, analysis.cfg_condition.as_ref(), commented, indent)?;
194 version_condition(w, env, None, version, commented, indent)?;
195 not_version_condition(w, analysis.not_version, commented, indent)?;
196 doc_hidden(w, analysis.doc_hidden, comment_prefix, indent)?;
197 writeln!(
198 w,
199 "{}{}{}{}{}{}",
200 tabs(indent),
201 comment_prefix,
202 pub_prefix,
203 unsafe_,
204 declaration,
205 suffix
206 )?;
207
208 if !only_declaration {
209 let body = body_chunk_futures(env, analysis).unwrap();
210 for s in body.lines() {
211 if !s.is_empty() {
212 writeln!(w, "{}{}{}", tabs(indent + 1), comment_prefix, s)?;
213 } else {
214 writeln!(w)?;
215 }
216 }
217 writeln!(w, "{}{}}}", tabs(indent), comment_prefix)?;
218 }
219 }
220
221 Ok(())
222 }
223
224 pub fn declaration(env: &Env, analysis: &analysis::functions::Info) -> String {
225 let outs_as_return = !analysis.outs.is_empty();
226 let return_str = if outs_as_return {
227 out_parameters_as_return(env, analysis)
228 } else if analysis.ret.bool_return_is_error.is_some() {
229 format!(" -> Result<(), {}>", use_glib_type(env, "error::BoolError"))
230 } else if let Some(return_type) = analysis.ret.to_return_value(
231 env,
232 analysis
233 .ret
234 .parameter
235 .as_ref()
236 .map_or(&TryFromGlib::Default, |par| &par.try_from_glib),
237 false,
238 ) {
239 format!(" -> {return_type}")
240 } else {
241 String::new()
242 };
243 let mut param_str = String::with_capacity(100);
244
245 let (bounds, _) = bounds(&analysis.bounds, &[], false, false);
246
247 for par in &analysis.parameters.rust_parameters {
248 if !param_str.is_empty() {
249 param_str.push_str(", ");
250 }
251 let c_par = &analysis.parameters.c_parameters[par.ind_c];
252 let s = c_par.to_parameter(env, &analysis.bounds, false);
253 param_str.push_str(&s);
254 }
255
256 format!(
257 "fn {}{}({}){}",
258 analysis.codegen_name(),
259 bounds,
260 param_str,
261 return_str,
262 )
263 }
264
265 pub fn declaration_futures(env: &Env, analysis: &analysis::functions::Info) -> String {
266 let async_future = analysis.async_future.as_ref().unwrap();
267
268 let return_str = if let Some(ref error_parameters) = async_future.error_parameters {
269 format!(
270 " -> Pin<Box_<dyn std::future::Future<Output = Result<{}, {}>> + 'static>>",
271 async_future.success_parameters, error_parameters
272 )
273 } else {
274 format!(
275 " -> Pin<Box_<dyn std::future::Future<Output = {}> + 'static>>",
276 async_future.success_parameters
277 )
278 };
279
280 let mut param_str = String::with_capacity(100);
281
282 let mut skipped = 0;
283 let mut skipped_bounds = vec![];
284 for (pos, par) in analysis.parameters.rust_parameters.iter().enumerate() {
285 let c_par = &analysis.parameters.c_parameters[par.ind_c];
286
287 if c_par.name == "callback" || c_par.name == "cancellable" {
288 skipped += 1;
289 if let Some(alias) = analysis
290 .bounds
291 .get_parameter_bound(&c_par.name)
292 .and_then(|bound| bound.type_parameter_reference())
293 {
294 skipped_bounds.push(alias);
295 }
296 continue;
297 }
298
299 if pos - skipped > 0 {
300 param_str.push_str(", ");
301 }
302
303 let s = c_par.to_parameter(env, &analysis.bounds, true);
304 param_str.push_str(&s);
305 }
306
307 let (bounds, _) = bounds(&analysis.bounds, skipped_bounds.as_ref(), true, false);
308
309 format!(
310 "fn {}{}({}){}",
311 async_future.name, bounds, param_str, return_str,
312 )
313 }
314
315 pub fn bounds(
316 bounds: &Bounds,
317 skip: &[char],
318 r#async: bool,
319 filter_callback_modified: bool,
320 ) -> (String, Vec<String>) {
321 use crate::analysis::bounds::BoundType::*;
322
323 if bounds.is_empty() {
324 return (String::new(), Vec::new());
325 }
326
327 let skip_lifetimes = bounds
328 .iter()
329 // TODO: False or true?
330 .filter(|bound| bound.alias.is_some_and(|alias| skip.contains(&alias)))
331 .filter_map(|bound| match bound.bound_type {
332 IsA(lifetime) | AsRef(lifetime) => lifetime,
333 _ => None,
334 })
335 .collect::<Vec<_>>();
336
337 let lifetimes = bounds
338 .iter_lifetimes()
339 .filter(|s| !skip_lifetimes.contains(s))
340 .map(|s| format!("'{s}"))
341 .collect::<Vec<_>>();
342
343 let bounds = bounds.iter().filter(|bound| {
344 bound.alias.is_none_or(|alias| !skip.contains(&alias))
345 && (!filter_callback_modified || !bound.callback_modified)
346 });
347
348 let type_names = lifetimes
349 .iter()
350 .cloned()
351 .chain(
352 bounds
353 .clone()
354 .filter_map(|b| b.type_parameter_definition(r#async)),
355 )
356 .collect::<Vec<_>>();
357
358 let type_names = if type_names.is_empty() {
359 String::new()
360 } else {
361 format!("<{}>", type_names.join(", "))
362 };
363
364 let bounds = lifetimes
365 .into_iter()
366 // TODO: enforce that this is only used on NoWrapper!
367 // TODO: Analyze if alias is used in function, otherwise set to None!
368 .chain(bounds.filter_map(|b| b.alias).map(|a| a.to_string()))
369 .collect::<Vec<_>>();
370
371 (type_names, bounds)
372 }
373
374 pub fn body_chunk(
375 env: &Env,
376 analysis: &analysis::functions::Info,
377 parent_type_id: Option<TypeId>,
378 ) -> Chunk {
379 if analysis.commented {
380 return ffi_function_todo(env, &analysis.glib_name);
381 }
382
383 let outs_as_return = !analysis.outs.is_empty();
384
385 let mut builder = function_body_chunk::Builder::new();
386 let sys_crate_name = if let Some(ty_id) = parent_type_id {
387 env.sys_crate_import(ty_id)
388 } else {
389 env.main_sys_crate_name().to_owned()
390 };
391
392 builder
393 .glib_name(&format!("{}::{}", sys_crate_name, analysis.glib_name))
394 .assertion(analysis.assertion)
395 .ret(&analysis.ret)
396 .transformations(&analysis.parameters.transformations)
397 .in_unsafe(analysis.unsafe_)
398 .outs_mode(analysis.outs.mode);
399
400 if analysis.r#async {
401 if let Some(ref trampoline) = analysis.trampoline {
402 builder.async_trampoline(trampoline);
403 } else {
404 warn!(
405 "Async function {} has no associated _finish function",
406 analysis.codegen_name(),
407 );
408 }
409 } else {
410 for trampoline in &analysis.callbacks {
411 builder.callback(trampoline);
412 }
413 for trampoline in &analysis.destroys {
414 builder.destroy(trampoline);
415 }
416 }
417
418 for par in &analysis.parameters.c_parameters {
419 if outs_as_return && analysis.outs.iter().any(|out| out.lib_par.name == par.name) {
420 builder.out_parameter(env, par);
421 } else {
422 builder.parameter();
423 }
424 }
425
426 let (bounds, bounds_names) = bounds(&analysis.bounds, &[], false, true);
427
428 builder.generate(env, &bounds, &bounds_names.join(", "))
429 }
430
431 pub fn body_chunk_futures(
432 env: &Env,
433 analysis: &analysis::functions::Info,
434 ) -> StdResult<String, fmt::Error> {
435 use std::fmt::Write;
436
437 use crate::analysis::ref_mode::RefMode;
438
439 let async_future = analysis.async_future.as_ref().unwrap();
440
441 let mut body = String::new();
442
443 let gio_future_name = if env.config.library_name != "Gio" {
444 "gio::GioFuture"
445 } else {
446 "crate::GioFuture"
447 };
448 writeln!(body)?;
449
450 if !async_future.assertion.is_none() {
451 writeln!(body, "{}", async_future.assertion)?;
452 }
453 let skip = usize::from(async_future.is_method);
454
455 // Skip the instance parameter
456 for par in analysis.parameters.rust_parameters.iter().skip(skip) {
457 if par.name == "cancellable" || par.name == "callback" {
458 continue;
459 }
460
461 let c_par = &analysis.parameters.c_parameters[par.ind_c];
462
463 let type_ = env.type_(par.typ);
464 let is_str = matches!(type_, library::Type::Basic(library::Basic::Utf8));
465 let is_slice = matches!(type_, library::Type::CArray(_));
466
467 if is_slice {
468 writeln!(body, "let {} = {}.to_vec();", par.name, par.name)?;
469 } else if *c_par.nullable {
470 writeln!(
471 body,
472 "let {} = {}.map(ToOwned::to_owned);",
473 par.name, par.name
474 )?;
475 } else if is_str {
476 writeln!(body, "let {} = String::from({});", par.name, par.name)?;
477 } else if c_par.ref_mode != RefMode::None {
478 writeln!(body, "let {} = {}.clone();", par.name, par.name)?;
479 }
480 }
481
482 let unsafe_block = if analysis.unsafe_ { "unsafe " } else { "" };
483
484 if async_future.is_method {
485 writeln!(
486 body,
487 "Box_::pin({gio_future_name}::new(self, move |obj, cancellable, send| {unsafe_block}{{"
488 )?;
489 } else {
490 writeln!(
491 body,
492 "Box_::pin({gio_future_name}::new(&(), move |_obj, cancellable, send| {unsafe_block}{{"
493 )?;
494 }
495
496 if async_future.is_method {
497 writeln!(body, "\tobj.{}(", analysis.codegen_name())?;
498 } else if analysis.type_name.is_ok() {
499 writeln!(body, "\tSelf::{}(", analysis.codegen_name())?;
500 } else {
501 writeln!(body, "\t{}(", analysis.codegen_name())?;
502 }
503
504 // Skip the instance parameter
505 for par in analysis.parameters.rust_parameters.iter().skip(skip) {
506 if par.name == "cancellable" {
507 writeln!(body, "\t\tSome(cancellable),")?;
508 } else if par.name == "callback" {
509 continue;
510 } else {
511 let c_par = &analysis.parameters.c_parameters[par.ind_c];
512
513 if *c_par.nullable {
514 writeln!(
515 body,
516 "\t\t{}.as_ref().map(::std::borrow::Borrow::borrow),",
517 par.name
518 )?;
519 } else if c_par.ref_mode != RefMode::None {
520 writeln!(body, "\t\t&{},", par.name)?;
521 } else {
522 writeln!(body, "\t\t{},", par.name)?;
523 }
524 }
525 }
526
527 writeln!(body, "\t\tmove |res| {{")?;
528 writeln!(body, "\t\t\tsend.resolve(res);")?;
529 writeln!(body, "\t\t}},")?;
530 writeln!(body, "\t);")?;
531 writeln!(body, "}}))")?;
532
533 Ok(body)
534 }