Skip to main content

libgir/analysis/
functions.rs

1// TODO: better heuristic (https://bugzilla.gnome.org/show_bug.cgi?id=623635#c5)
2// TODO: ProgressCallback types (not specific to async).
3// TODO: add annotation for methods like g_file_replace_contents_bytes_async
4// where the finish method has a different prefix.
5
6use std::{
7    borrow::Borrow,
8    collections::{HashMap, HashSet},
9};
10
11use log::warn;
12
13use super::{namespaces::NsId, special_functions};
14use crate::{
15    analysis::{
16        self,
17        bounds::{Bounds, CallbackInfo},
18        function_parameters::{self, CParameter, Parameters, Transformation, TransformationType},
19        imports::Imports,
20        is_gpointer,
21        out_parameters::{self, use_function_return_for_result},
22        ref_mode::RefMode,
23        return_value,
24        rust_type::*,
25        safety_assertion_mode::SafetyAssertionMode,
26        signatures::{Signature, Signatures},
27        trampolines::Trampoline,
28    },
29    codegen::Visibility,
30    config::{self, gobjects::GStatus},
31    env::Env,
32    library::{self, Function, FunctionKind, MAIN_NAMESPACE, ParameterDirection, Type},
33    nameutil,
34    traits::*,
35    version::Version,
36};
37
38#[derive(Clone, Debug)]
39pub struct AsyncTrampoline {
40    pub is_method: bool,
41    pub has_error_parameter: bool,
42    pub name: String,
43    pub finish_func_name: String,
44    pub callback_type: String,
45    pub bound_name: char,
46    pub output_params: Vec<analysis::Parameter>,
47    pub ffi_ret: Option<analysis::Parameter>,
48}
49
50#[derive(Clone, Debug)]
51pub struct AsyncFuture {
52    pub is_method: bool,
53    pub name: String,
54    pub success_parameters: String,
55    pub error_parameters: Option<String>,
56    pub assertion: SafetyAssertionMode,
57}
58
59#[derive(Debug)]
60pub struct Info {
61    pub name: String,
62    pub func_name: String,
63    pub new_name: Option<String>,
64    pub glib_name: String,
65    pub status: GStatus,
66    pub kind: library::FunctionKind,
67    pub visibility: Visibility,
68    pub type_name: Result,
69    pub parameters: Parameters,
70    pub ret: return_value::Info,
71    pub bounds: Bounds,
72    pub outs: out_parameters::Info,
73    pub version: Option<Version>,
74    pub deprecated_version: Option<Version>,
75    pub not_version: Option<Version>,
76    pub cfg_condition: Option<String>,
77    pub assertion: SafetyAssertionMode,
78    pub doc_hidden: bool,
79    pub doc_trait_name: Option<String>,
80    pub doc_struct_name: Option<String>,
81    pub doc_ignore_parameters: HashSet<String>,
82    pub r#async: bool,
83    pub unsafe_: bool,
84    pub trampoline: Option<AsyncTrampoline>,
85    pub callbacks: Vec<Trampoline>,
86    pub destroys: Vec<Trampoline>,
87    pub remove_params: Vec<usize>,
88    pub async_future: Option<AsyncFuture>,
89    /// Whether the function is hidden (an implementation detail)
90    /// Like the ref/unref/copy/free functions
91    pub hidden: bool,
92    /// Whether the function can't be generated
93    pub commented: bool,
94    /// In order to generate docs links we need to know in which namespace
95    /// this potential global function is defined
96    pub ns_id: NsId,
97    pub generate_doc: bool,
98    pub get_property: Option<String>,
99    pub set_property: Option<String>,
100}
101
102impl Info {
103    pub fn codegen_name(&self) -> &str {
104        self.new_name.as_ref().unwrap_or(&self.name)
105    }
106
107    pub fn is_special(&self) -> bool {
108        self.codegen_name()
109            .trim_end_matches('_')
110            .rsplit('_')
111            .next()
112            .is_some_and(|i| i.parse::<special_functions::Type>().is_ok())
113    }
114
115    // returns whether the method can be linked in the docs
116    pub fn should_be_doc_linked(&self, env: &Env) -> bool {
117        self.should_docs_be_generated(env)
118            && (self.status.manual() || (!self.commented && !self.hidden))
119    }
120
121    pub fn should_docs_be_generated(&self, env: &Env) -> bool {
122        !self.status.ignored() && !self.is_special() && !self.is_async_finish(env)
123    }
124
125    pub fn doc_link(
126        &self,
127        parent: Option<&str>,
128        visible_parent: Option<&str>,
129        is_self: bool,
130    ) -> String {
131        if let Some(p) = parent {
132            if is_self {
133                format!("[`{f}()`][Self::{f}()]", f = self.codegen_name())
134            } else {
135                format!(
136                    "[`{visible_parent}::{f}()`][crate::{p}::{f}()]",
137                    visible_parent = visible_parent.unwrap_or(p),
138                    p = p,
139                    f = self.codegen_name()
140                )
141            }
142        } else {
143            format!(
144                "[`{fn_name}()`][crate::{fn_name}()]",
145                fn_name = self.codegen_name()
146            )
147        }
148    }
149
150    pub fn is_async_finish(&self, env: &Env) -> bool {
151        let has_async_result = self
152            .parameters
153            .rust_parameters
154            .iter()
155            .any(|param| param.typ.full_name(&env.library) == "Gio.AsyncResult");
156        self.name.ends_with("_finish") && has_async_result
157    }
158}
159
160pub fn analyze<F: Borrow<library::Function>>(
161    env: &Env,
162    functions: &[F],
163    type_tid: Option<library::TypeId>,
164    in_trait: bool,
165    is_boxed: bool,
166    obj: &config::gobjects::GObject,
167    imports: &mut Imports,
168    mut signatures: Option<&mut Signatures>,
169    deps: Option<&[library::TypeId]>,
170) -> Vec<Info> {
171    let mut funcs = Vec::new();
172
173    'func: for func in functions {
174        let func = func.borrow();
175        let configured_functions = obj.functions.matched(&func.name);
176        let mut status = obj.status;
177        for f in &configured_functions {
178            match f.status {
179                GStatus::Ignore => continue 'func,
180                GStatus::Manual => {
181                    status = GStatus::Manual;
182                    break;
183                }
184                GStatus::Generate => (),
185            }
186        }
187
188        if env.is_totally_deprecated(
189            Some(type_tid.unwrap_or_default().ns_id),
190            func.deprecated_version,
191        ) {
192            continue;
193        }
194        let name = nameutil::mangle_keywords(&*func.name).into_owned();
195        let signature_params = Signature::new(func);
196        let mut not_version = None;
197        // An inherent method already takes precedence over the parent's trait method.
198        if func.kind == library::FunctionKind::Method
199            && in_trait
200            && let Some(deps) = deps
201        {
202            let (has, version) = signature_params.has_in_deps(env, &name, deps);
203            if has
204                && let Some(v) = version
205                && v > env.config.min_cfg_version
206            {
207                not_version = version;
208            }
209        }
210        if let Some(signatures) = signatures.as_mut() {
211            signatures.insert(name.clone(), signature_params);
212        }
213
214        let mut info = analyze_function(
215            env,
216            obj,
217            &func.name,
218            name,
219            status,
220            func,
221            type_tid,
222            in_trait,
223            is_boxed,
224            &configured_functions,
225            imports,
226        );
227        info.not_version = not_version;
228        funcs.push(info);
229    }
230
231    funcs
232}
233
234fn fixup_gpointer_parameter(
235    env: &Env,
236    type_tid: library::TypeId,
237    is_boxed: bool,
238    in_trait: bool,
239    parameters: &mut Parameters,
240    idx: usize,
241) {
242    use crate::analysis::ffi_type;
243
244    let is_instance_parameter = idx == 0;
245
246    let glib_name = env.library.type_(type_tid).get_glib_name().unwrap();
247    let ffi_name = ffi_type::ffi_type(env, type_tid, glib_name).unwrap();
248    let pointer_type = if is_boxed { "*const" } else { "*mut" };
249    parameters.rust_parameters[idx].typ = type_tid;
250    parameters.c_parameters[idx].typ = type_tid;
251    parameters.c_parameters[idx].is_instance_parameter = is_instance_parameter;
252    parameters.c_parameters[idx].ref_mode = RefMode::ByRef;
253    parameters.c_parameters[idx].transfer = gir_parser::TransferOwnership::None;
254    parameters.transformations[idx] = Transformation {
255        ind_c: idx,
256        ind_rust: Some(idx),
257        transformation_type: TransformationType::ToGlibPointer {
258            name: parameters.rust_parameters[idx].name.clone(),
259            is_instance_parameter,
260            transfer: gir_parser::TransferOwnership::None,
261            ref_mode: RefMode::ByRef,
262            to_glib_extra: Default::default(),
263            explicit_target_type: format!("{} {}", pointer_type, ffi_name.as_str()),
264            pointer_cast: format!(
265                " as {}",
266                nameutil::use_glib_if_needed(env, "ffi::gconstpointer")
267            ),
268            in_trait,
269            nullable: false,
270            move_: false,
271        },
272    };
273}
274
275fn fixup_special_functions(
276    env: &Env,
277    name: &str,
278    type_tid: library::TypeId,
279    is_boxed: bool,
280    in_trait: bool,
281    parameters: &mut Parameters,
282) {
283    // Workaround for some _hash() / _compare() / _equal() functions taking
284    // "gconstpointer" as arguments instead of the actual type
285    if name == "hash"
286        && parameters.c_parameters.len() == 1
287        && parameters.c_parameters[0].c_type == "gconstpointer"
288    {
289        fixup_gpointer_parameter(env, type_tid, is_boxed, in_trait, parameters, 0);
290    }
291
292    if (name == "compare" || name == "equal" || name == "is_equal")
293        && parameters.c_parameters.len() == 2
294        && parameters.c_parameters[0].c_type == "gconstpointer"
295        && parameters.c_parameters[1].c_type == "gconstpointer"
296    {
297        fixup_gpointer_parameter(env, type_tid, is_boxed, in_trait, parameters, 0);
298        fixup_gpointer_parameter(env, type_tid, is_boxed, in_trait, parameters, 1);
299    }
300}
301
302fn find_callback_bound_to_destructor(
303    callbacks: &[Trampoline],
304    destroy: &mut Trampoline,
305    destroy_index: usize,
306) -> bool {
307    for call in callbacks {
308        if call.destroy_index == destroy_index {
309            destroy.nullable = call.nullable;
310            destroy.bound_name = call.bound_name.clone();
311            return true;
312        }
313    }
314    false
315}
316
317fn analyze_callbacks(
318    env: &Env,
319    func: &library::Function,
320    cross_user_data_check: &mut HashMap<usize, usize>,
321    user_data_indexes: &mut HashSet<usize>,
322    parameters: &mut Parameters,
323    used_types: &mut Vec<String>,
324    bounds: &mut Bounds,
325    to_glib_extras: &mut HashMap<usize, String>,
326    imports: &mut Imports,
327    destroys: &mut Vec<Trampoline>,
328    callbacks: &mut Vec<Trampoline>,
329    params: &mut Vec<library::Parameter>,
330    configured_functions: &[&config::functions::Function],
331    disable_length_detect: bool,
332    in_trait: bool,
333    commented: &mut bool,
334    concurrency: library::Concurrency,
335    type_tid: library::TypeId,
336) {
337    let mut to_replace = Vec::new();
338    let mut to_remove = Vec::new();
339
340    {
341        // When closure data and destroy are specified in gir, they don't take into
342        // account the actual closure parameter.
343        let mut c_parameters = Vec::new();
344        for (pos, par) in parameters.c_parameters.iter().enumerate() {
345            if par.is_instance_parameter {
346                continue;
347            }
348            c_parameters.push((par, pos));
349        }
350
351        let func_name = &func.c_identifier;
352        let mut destructors_to_update = Vec::new();
353        for (pos, par) in parameters.c_parameters.iter().enumerate() {
354            // If it is a user data parameter, we ignore it.
355            if cross_user_data_check.values().any(|p| *p == pos) || user_data_indexes.contains(&pos)
356            {
357                continue;
358            }
359            assert!(
360                !par.is_instance_parameter || pos == 0,
361                "Wrong instance parameter in {}",
362                func.c_identifier
363            );
364            if let Ok(rust_type) = RustType::builder(env, par.typ)
365                .direction(par.direction)
366                .try_from_glib(&par.try_from_glib)
367                .try_build()
368            {
369                used_types.extend(rust_type.into_used_types());
370            }
371            let rust_type = env.library.type_(par.typ);
372            let callback_info = if !par.nullable || !rust_type.is_function() {
373                let (to_glib_extra, callback_info) = bounds.add_for_parameter(
374                    env,
375                    func,
376                    par,
377                    false,
378                    concurrency,
379                    configured_functions,
380                );
381                if let Some(to_glib_extra) = to_glib_extra {
382                    let pos_adjusted_for_removed_params =
383                        pos - to_remove.len() - cross_user_data_check.len();
384                    if par.c_type != "GDestroyNotify" {
385                        to_glib_extras.insert(pos_adjusted_for_removed_params, to_glib_extra);
386                    }
387                }
388                callback_info
389            } else {
390                None
391            };
392
393            if rust_type.is_function() {
394                if par.c_type != "GDestroyNotify" {
395                    let callback_parameters_config = configured_functions.iter().find_map(|f| {
396                        f.parameters
397                            .iter()
398                            .find(|p| p.ident.is_match(&par.name))
399                            .map(|p| &p.callback_parameters)
400                    });
401                    if let Some((mut callback, destroy_index)) = analyze_callback(
402                        func_name,
403                        type_tid,
404                        env,
405                        par,
406                        &callback_info,
407                        commented,
408                        imports,
409                        &c_parameters,
410                        rust_type,
411                        callback_parameters_config,
412                    ) {
413                        if let Some(destroy_index) = destroy_index {
414                            let user_data = cross_user_data_check
415                                .entry(destroy_index)
416                                .or_insert_with(|| callback.user_data_index);
417                            if *user_data != callback.user_data_index {
418                                warn_main!(
419                                    type_tid,
420                                    "`{}`: Different destructors cannot share the same user data",
421                                    func_name
422                                );
423                                *commented = true;
424                            }
425                            callback.destroy_index = destroy_index;
426                        } else {
427                            user_data_indexes.insert(callback.user_data_index);
428                            to_remove.push(callback.user_data_index);
429                        }
430                        callbacks.push(callback);
431                        to_replace.push((pos, par.typ));
432                        continue;
433                    }
434                } else if let Some((mut callback, _)) = analyze_callback(
435                    func_name,
436                    type_tid,
437                    env,
438                    par,
439                    &callback_info,
440                    commented,
441                    imports,
442                    &c_parameters,
443                    rust_type,
444                    None,
445                ) {
446                    // We just assume that for API "cleanness", the destroy callback will always
447                    // be |-> *after* <-| the initial callback.
448                    if let Some(user_data_index) = cross_user_data_check.get(&pos) {
449                        callback.user_data_index = *user_data_index;
450                        callback.destroy_index = pos;
451                    } else {
452                        warn_main!(
453                            type_tid,
454                            "`{}`: no user data point to the destroy callback",
455                            func_name,
456                        );
457                        *commented = true;
458                    }
459                    // We check if the user trampoline is there. If so, we change the destroy
460                    // nullable value if needed.
461                    if !find_callback_bound_to_destructor(callbacks, &mut callback, pos) {
462                        // Maybe the linked callback is after so we store it just in case...
463                        destructors_to_update.push((pos, destroys.len()));
464                    }
465                    destroys.push(callback);
466                    to_remove.push(pos);
467                    continue;
468                }
469            }
470            if !*commented {
471                *commented |= RustType::builder(env, par.typ)
472                    .direction(par.direction)
473                    .scope(par.scope)
474                    .try_from_glib(&par.try_from_glib)
475                    .try_build_param()
476                    .is_err();
477            }
478        }
479        for (destroy_index, pos_in_destroys) in destructors_to_update {
480            if !find_callback_bound_to_destructor(
481                callbacks,
482                &mut destroys[pos_in_destroys],
483                destroy_index,
484            ) {
485                warn_main!(
486                    type_tid,
487                    "`{}`: destructor without linked callback",
488                    func_name
489                );
490            }
491        }
492    }
493
494    // Check for cross "user data".
495    if cross_user_data_check
496        .values()
497        .collect::<Vec<_>>()
498        .windows(2)
499        .any(|a| a[0] == a[1])
500    {
501        *commented = true;
502        warn_main!(
503            type_tid,
504            "`{}`: Different user data share the same destructors",
505            func.name
506        );
507    }
508
509    if !destroys.is_empty() || !callbacks.is_empty() {
510        for (pos, typ) in to_replace {
511            let ty = env.library.type_(typ);
512            params[pos].set_tid(typ);
513            params[pos].set_c_type(ty.get_glib_name().unwrap());
514        }
515        let mut s = to_remove
516            .iter()
517            .chain(cross_user_data_check.values())
518            .collect::<HashSet<_>>() // To prevent duplicates.
519            .into_iter()
520            .collect::<Vec<_>>();
521        s.sort(); // We need to sort the array, otherwise the indexes won't be working
522        // anymore.
523        for pos in s.iter().rev() {
524            params.remove(**pos);
525        }
526        *parameters = function_parameters::analyze(
527            env,
528            params,
529            configured_functions,
530            disable_length_detect,
531            false,
532            in_trait,
533        );
534    } else {
535        warn_main!(
536            type_tid,
537            "`{}`: this is supposed to be a callback function but no callback was found...",
538            func.name
539        );
540        *commented = true;
541    }
542}
543
544fn analyze_function(
545    env: &Env,
546    obj: &config::gobjects::GObject,
547    func_name: &str,
548    name: String,
549    status: GStatus,
550    func: &library::Function,
551    type_tid: Option<library::TypeId>,
552    in_trait: bool,
553    is_boxed: bool,
554    configured_functions: &[&config::functions::Function],
555    imports: &mut Imports,
556) -> Info {
557    let ns_id = type_tid.map_or(MAIN_NAMESPACE, |t| t.ns_id);
558    let type_tid = type_tid.unwrap_or_default();
559    let r#async = func.finish_func.is_some()
560        || func.parameters.iter().any(|parameter| {
561            parameter
562                .scope()
563                .is_some_and(|s| s == gir_parser::FunctionScope::Async)
564                && parameter.c_type() == "GAsyncReadyCallback"
565        });
566    let has_callback_parameter = !r#async
567        && func
568            .parameters
569            .iter()
570            .any(|par| env.library.type_(par.typ()).is_function());
571    let concurrency = match env.library.type_(type_tid) {
572        library::Type::Class(_) | library::Type::Interface(_) | library::Type::Record(_) => {
573            obj.concurrency
574        }
575        _ => library::Concurrency::SendSync,
576    };
577
578    let mut commented = false;
579    let mut bounds: Bounds = Default::default();
580    let mut to_glib_extras = HashMap::<usize, String>::new();
581    let mut used_types: Vec<String> = Vec::with_capacity(4);
582    let mut trampoline = None;
583    let mut callbacks = Vec::new();
584    let mut destroys = Vec::new();
585    let mut async_future = None;
586
587    if status.need_generate()
588        && !r#async
589        && !has_callback_parameter
590        && func
591            .parameters
592            .iter()
593            .any(|par| par.c_type() == "GDestroyNotify")
594    {
595        // In here, We have a DestroyNotify callback but no other callback is provided.
596        // A good example of this situation is this function:
597        // https://developer.gnome.org/gio/stable/GTlsPassword.html#g-tls-password-set-value-full
598        warn_main!(
599            type_tid,
600            "Function \"{}\" with destroy callback without callbacks",
601            func.name
602        );
603        commented = true;
604    }
605
606    let mut new_name = configured_functions.iter().find_map(|f| f.rename.clone());
607    let is_constructor = configured_functions.iter().find_map(|f| f.is_constructor);
608
609    let bypass_auto_rename = configured_functions.iter().any(|f| f.bypass_auto_rename);
610    let is_constructor = is_constructor.unwrap_or(false);
611    if !bypass_auto_rename && new_name.is_none() {
612        if func.kind == library::FunctionKind::Constructor || is_constructor {
613            if func.kind == library::FunctionKind::Constructor && is_constructor {
614                warn_main!(
615                    type_tid,
616                    "`{}`: config forces 'constructor' on an already gir-annotated 'constructor'",
617                    func_name
618                );
619            }
620
621            if name.starts_with("new_from")
622                || name.starts_with("new_with")
623                || name.starts_with("new_for")
624            {
625                new_name = Some(name[4..].to_string());
626            }
627        } else {
628            let nb_in_params = func
629                .parameters
630                .iter()
631                .filter(|param| param.direction().is_in())
632                .fold(0, |acc, _| acc + 1);
633            let is_bool_getter = (func.parameters.len() == nb_in_params)
634                && (func.ret.typ() == library::TypeId::tid_bool()
635                    || func.ret.typ() == library::TypeId::tid_c_bool());
636            new_name = getter_rules::try_rename_would_be_getter(&name, is_bool_getter)
637                .ok()
638                .map(getter_rules::NewName::unwrap);
639        }
640    }
641
642    let version = configured_functions
643        .iter()
644        .filter_map(|f| f.version)
645        .min()
646        .or(func.version);
647
648    let version = env.config.filter_version(version);
649    let deprecated_version = func.deprecated_version;
650    let visibility = configured_functions
651        .iter()
652        .find_map(|f| f.visibility)
653        .unwrap_or_default();
654    let cfg_condition = configured_functions
655        .iter()
656        .find_map(|f| f.cfg_condition.clone());
657    let doc_hidden = configured_functions.iter().any(|f| f.doc_hidden);
658    let doc_trait_name = configured_functions
659        .iter()
660        .find_map(|f| f.doc_trait_name.clone());
661    let doc_struct_name = configured_functions
662        .iter()
663        .find_map(|f| f.doc_struct_name.clone());
664    let doc_ignore_parameters = configured_functions
665        .iter()
666        .find(|f| !f.doc_ignore_parameters.is_empty())
667        .map(|f| f.doc_ignore_parameters.clone())
668        .unwrap_or_default();
669    let disable_length_detect = configured_functions.iter().any(|f| f.disable_length_detect);
670    let no_future = configured_functions.iter().any(|f| f.no_future);
671    let unsafe_ = configured_functions.iter().any(|f| f.unsafe_);
672    let assertion = configured_functions.iter().find_map(|f| f.assertion);
673
674    let imports = &mut imports.with_defaults(version, &cfg_condition);
675
676    let ret = return_value::analyze(
677        env,
678        obj,
679        func,
680        type_tid,
681        configured_functions,
682        &mut used_types,
683        imports,
684    );
685    commented |= ret.commented;
686
687    let mut params = func.parameters.clone();
688    let mut parameters = function_parameters::analyze(
689        env,
690        &params,
691        configured_functions,
692        disable_length_detect,
693        r#async,
694        in_trait,
695    );
696    parameters.analyze_return(env, &ret.parameter);
697
698    if status.need_generate()
699        && let Some(ref f) = ret.parameter
700        && let Type::Function(_) = env.library.type_(f.lib_par.typ())
701        && env.config.work_mode.is_normal()
702    {
703        warn!("Function \"{}\" returns callback", func.name);
704        commented = true;
705    }
706
707    fixup_special_functions(
708        env,
709        name.as_str(),
710        type_tid,
711        is_boxed,
712        in_trait,
713        &mut parameters,
714    );
715
716    // Key: destroy callback index
717    // Value: associated user data index
718    let mut cross_user_data_check: HashMap<usize, usize> = HashMap::new();
719    let mut user_data_indexes: HashSet<usize> = HashSet::new();
720
721    if status.need_generate() {
722        if !has_callback_parameter {
723            let mut to_remove = Vec::new();
724            let mut correction_instance = 0;
725            for par in parameters.c_parameters.iter() {
726                if par.scope.is_none() {
727                    continue;
728                }
729                if let Some(index) = par.user_data_index {
730                    to_remove.push(index);
731                }
732                if let Some(index) = par.destroy_index {
733                    to_remove.push(index);
734                }
735            }
736            for (pos, par) in parameters.c_parameters.iter().enumerate() {
737                if par.is_instance_parameter {
738                    correction_instance = 1;
739                }
740
741                if r#async
742                    && pos >= correction_instance
743                    && to_remove.contains(&(pos - correction_instance))
744                {
745                    continue;
746                }
747                assert!(
748                    !par.is_instance_parameter || pos == 0,
749                    "Wrong instance parameter in {}",
750                    func.c_identifier
751                );
752                if let Ok(rust_type) = RustType::builder(env, par.typ)
753                    .direction(par.direction)
754                    .try_from_glib(&par.try_from_glib)
755                    .try_build()
756                    && (!rust_type.as_str().ends_with("GString") || par.c_type == "gchar***")
757                {
758                    used_types.extend(rust_type.into_used_types());
759                }
760                let (to_glib_extra, callback_info) = bounds.add_for_parameter(
761                    env,
762                    func,
763                    par,
764                    r#async,
765                    library::Concurrency::None,
766                    configured_functions,
767                );
768                if let Some(to_glib_extra) = to_glib_extra {
769                    to_glib_extras.insert(pos, to_glib_extra);
770                }
771
772                analyze_async(
773                    env,
774                    func,
775                    type_tid,
776                    new_name.as_ref().unwrap_or(&name),
777                    callback_info,
778                    &mut commented,
779                    &mut trampoline,
780                    no_future,
781                    &mut async_future,
782                    configured_functions,
783                    &parameters,
784                );
785                let type_error = !(r#async
786                    && *env.library.type_(par.typ) == Type::Basic(library::Basic::Pointer))
787                    && RustType::builder(env, par.typ)
788                        .direction(par.direction)
789                        .scope(par.scope)
790                        .try_from_glib(&par.try_from_glib)
791                        .try_build_param()
792                        .is_err();
793                if type_error {
794                    commented = true;
795                }
796            }
797            if r#async && trampoline.is_none() {
798                commented = true;
799            }
800        } else {
801            analyze_callbacks(
802                env,
803                func,
804                &mut cross_user_data_check,
805                &mut user_data_indexes,
806                &mut parameters,
807                &mut used_types,
808                &mut bounds,
809                &mut to_glib_extras,
810                imports,
811                &mut destroys,
812                &mut callbacks,
813                &mut params,
814                configured_functions,
815                disable_length_detect,
816                in_trait,
817                &mut commented,
818                concurrency,
819                type_tid,
820            );
821        }
822    }
823
824    for par in &parameters.rust_parameters {
825        // Disallow basic arrays without length
826        let is_len_for_par = |t: &Transformation| {
827            if let TransformationType::Length { ref array_name, .. } = t.transformation_type {
828                array_name == &par.name
829            } else {
830                false
831            }
832        };
833        if is_carray_with_direct_elements(env, par.typ)
834            && !parameters.transformations.iter().any(is_len_for_par)
835        {
836            commented = true;
837        }
838    }
839
840    let (outs, unsupported_outs) = out_parameters::analyze(
841        env,
842        func,
843        &parameters.c_parameters,
844        &ret,
845        configured_functions,
846    );
847    if unsupported_outs && status.need_generate() {
848        warn_main!(
849            type_tid,
850            "Function {} has unsupported outs",
851            func.c_identifier
852        );
853        commented = true;
854    }
855
856    if r#async && status.need_generate() && !commented {
857        imports.add("std::boxed::Box as Box_");
858        imports.add("std::pin::Pin");
859
860        if let Some(ref trampoline) = trampoline {
861            for out in &trampoline.output_params {
862                if let Ok(rust_type) = RustType::builder(env, out.lib_par.typ())
863                    .direction(ParameterDirection::Out)
864                    .try_build()
865                {
866                    used_types.extend(rust_type.into_used_types());
867                }
868            }
869            if let Some(ref out) = trampoline.ffi_ret
870                && let Ok(rust_type) = RustType::builder(env, out.lib_par.typ())
871                    .direction(ParameterDirection::Return)
872                    .try_build()
873            {
874                used_types.extend(rust_type.into_used_types());
875            }
876        }
877    }
878
879    if status.need_generate() && !commented {
880        if (!destroys.is_empty() || !callbacks.is_empty())
881            && callbacks
882                .iter()
883                .any(|c| !c.scope.is_some_and(|s| s.is_call()))
884        {
885            imports.add("std::boxed::Box as Box_");
886        }
887
888        for transformation in &mut parameters.transformations {
889            if let Some(to_glib_extra) = to_glib_extras.get(&transformation.ind_c) {
890                transformation
891                    .transformation_type
892                    .set_to_glib_extra(to_glib_extra);
893            }
894        }
895
896        imports.add("crate::ffi");
897
898        imports.add_used_types(&used_types);
899        if ret.base_tid.is_some() {
900            imports.add("glib::prelude::*");
901        }
902
903        if func.name.parse::<special_functions::Type>().is_err()
904            || parameters.c_parameters.iter().any(|p| p.move_)
905        {
906            imports.add("glib::translate::*");
907        }
908        bounds.update_imports(imports);
909    }
910
911    let is_method = func.kind == library::FunctionKind::Method;
912    let assertion =
913        assertion.unwrap_or_else(|| SafetyAssertionMode::of(env, is_method, &parameters));
914
915    let generate_doc = configured_functions.iter().all(|f| f.generate_doc);
916
917    Info {
918        name,
919        func_name: func_name.to_string(),
920        new_name,
921        glib_name: func.c_identifier.clone(),
922        status,
923        kind: func.kind,
924        visibility,
925        type_name: RustType::try_new(env, type_tid),
926        parameters,
927        ret,
928        bounds,
929        outs,
930        version,
931        deprecated_version,
932        not_version: None,
933        cfg_condition,
934        assertion,
935        doc_hidden,
936        doc_trait_name,
937        doc_struct_name,
938        doc_ignore_parameters,
939        r#async,
940        unsafe_,
941        trampoline,
942        async_future,
943        callbacks,
944        destroys,
945        remove_params: cross_user_data_check.values().copied().collect::<Vec<_>>(),
946        commented,
947        hidden: false,
948        ns_id,
949        generate_doc,
950        get_property: func.get_property.clone(),
951        set_property: func.set_property.clone(),
952    }
953}
954
955pub fn is_carray_with_direct_elements(env: &Env, typ: library::TypeId) -> bool {
956    match *env.library.type_(typ) {
957        Type::CArray(inner_tid) => {
958            use super::conversion_type::ConversionType;
959            matches!(env.library.type_(inner_tid), Type::Basic(..) if ConversionType::of(env, inner_tid) == ConversionType::Direct)
960        }
961        _ => false,
962    }
963}
964
965fn analyze_async(
966    env: &Env,
967    func: &library::Function,
968    type_tid: library::TypeId,
969    codegen_name: &str,
970    callback_info: Option<CallbackInfo>,
971    commented: &mut bool,
972    trampoline: &mut Option<AsyncTrampoline>,
973    no_future: bool,
974    async_future: &mut Option<AsyncFuture>,
975    configured_functions: &[&config::functions::Function],
976    parameters: &function_parameters::Parameters,
977) -> bool {
978    if let Some(CallbackInfo {
979        callback_type,
980        success_parameters,
981        error_parameters,
982        bound_name,
983    }) = callback_info
984    {
985        // Checks for /*Ignored*/ or other error comments
986        *commented |= callback_type.contains("/*");
987        let func_name = &func.c_identifier;
988        let finish_func_name = if let Some(finish_func_name) = &func.finish_func {
989            finish_func_name.to_string()
990        } else {
991            finish_function_name(func_name)
992        };
993        let mut output_params = vec![];
994        let mut ffi_ret = None;
995        if let Some(function) = find_function(env, &finish_func_name) {
996            if use_function_return_for_result(
997                env,
998                function.ret.typ(),
999                &func.name,
1000                configured_functions,
1001            ) {
1002                ffi_ret = Some(analysis::Parameter::from_return_value(
1003                    env,
1004                    function.ret.clone(),
1005                    configured_functions,
1006                ));
1007            }
1008
1009            for param in &function.parameters {
1010                let mut lib_par = param.clone();
1011                if nameutil::needs_mangling(param.name()) {
1012                    lib_par.set_name(&nameutil::mangle_keywords(param.name()));
1013                }
1014                let configured_parameters = configured_functions.matched_parameters(lib_par.name());
1015                output_params.push(analysis::Parameter::from_parameter(
1016                    env,
1017                    lib_par,
1018                    &configured_parameters,
1019                ));
1020            }
1021        }
1022        if trampoline.is_some() || async_future.is_some() {
1023            warn_main!(
1024                type_tid,
1025                "{}: Cannot handle callbacks and async parameters at the same time for the \
1026                 moment",
1027                func.name
1028            );
1029            *commented = true;
1030            return false;
1031        }
1032        if !*commented && success_parameters.is_empty() {
1033            if success_parameters.is_empty() {
1034                warn_main!(
1035                    type_tid,
1036                    "{}: missing success parameters for async future",
1037                    func.name
1038                );
1039            }
1040            *commented = true;
1041            return false;
1042        }
1043        let is_method = func.kind == FunctionKind::Method;
1044
1045        *trampoline = Some(AsyncTrampoline {
1046            is_method,
1047            has_error_parameter: error_parameters.is_some(),
1048            name: format!("{codegen_name}_trampoline"),
1049            finish_func_name: format!("{}::{}", env.main_sys_crate_name(), finish_func_name),
1050            callback_type,
1051            bound_name,
1052            output_params,
1053            ffi_ret,
1054        });
1055
1056        if !no_future {
1057            *async_future = Some(AsyncFuture {
1058                is_method,
1059                name: format!("{}_future", codegen_name.trim_end_matches("_async")),
1060                success_parameters,
1061                error_parameters,
1062                assertion: match SafetyAssertionMode::of(env, is_method, parameters) {
1063                    SafetyAssertionMode::None => SafetyAssertionMode::None,
1064                    // "_future" functions calls the "async" one which has the init check, so no
1065                    // need to do it twice.
1066                    _ => SafetyAssertionMode::Skip,
1067                },
1068            });
1069        }
1070        true
1071    } else {
1072        false
1073    }
1074}
1075
1076fn analyze_callback(
1077    func_name: &str,
1078    type_tid: library::TypeId,
1079    env: &Env,
1080    par: &CParameter,
1081    callback_info: &Option<CallbackInfo>,
1082    commented: &mut bool,
1083    imports: &mut Imports,
1084    c_parameters: &[(&CParameter, usize)],
1085    rust_type: &Type,
1086    callback_parameters_config: Option<&config::functions::CallbackParameters>,
1087) -> Option<(Trampoline, Option<usize>)> {
1088    let mut imports_to_add = Vec::new();
1089
1090    if let Type::Function(func) = rust_type {
1091        if par.c_type != "GDestroyNotify" {
1092            if let Some(user_data) = par.user_data_index {
1093                if user_data >= c_parameters.len() {
1094                    warn_main!(
1095                        type_tid,
1096                        "function `{}` has an invalid user data index of {} when there are {} parameters",
1097                        func_name,
1098                        user_data,
1099                        c_parameters.len()
1100                    );
1101                    return None;
1102                } else if !is_gpointer(&c_parameters[user_data].0.c_type) {
1103                    *commented = true;
1104                    warn_main!(
1105                        type_tid,
1106                        "function `{}`'s callback `{}` has invalid user data",
1107                        func_name,
1108                        par.name
1109                    );
1110                    return None;
1111                }
1112            } else {
1113                *commented = true;
1114                warn_main!(
1115                    type_tid,
1116                    "function `{}`'s callback `{}` without associated user data",
1117                    func_name,
1118                    par.name
1119                );
1120                return None;
1121            }
1122            if let Some(destroy_index) = par.destroy_index {
1123                if destroy_index >= c_parameters.len() {
1124                    warn_main!(
1125                        type_tid,
1126                        "function `{}` has an invalid destroy index of {} when there are {} \
1127                         parameters",
1128                        func_name,
1129                        destroy_index,
1130                        c_parameters.len()
1131                    );
1132                    return None;
1133                }
1134                if c_parameters[destroy_index].0.c_type != "GDestroyNotify" {
1135                    *commented = true;
1136                    warn_main!(
1137                        type_tid,
1138                        "function `{}`'s callback `{}` has invalid destroy callback",
1139                        func_name,
1140                        par.name
1141                    );
1142                    return None;
1143                }
1144            }
1145        }
1146
1147        // If we don't have a "user data" parameter, we can't get the closure so there's
1148        // nothing we can do...
1149        if par.c_type != "GDestroyNotify"
1150            && (func.parameters.is_empty()
1151                || !func.parameters.iter().any(|c| c.closure().is_some()))
1152        {
1153            *commented = true;
1154            warn_main!(
1155                type_tid,
1156                "Closure type `{}` doesn't provide user data for function {}",
1157                par.c_type,
1158                func_name,
1159            );
1160            return None;
1161        }
1162
1163        let parameters = crate::analysis::trampoline_parameters::analyze(
1164            env,
1165            &func.parameters,
1166            par.typ,
1167            &[],
1168            callback_parameters_config,
1169        );
1170        if par.c_type != "GDestroyNotify" && !*commented {
1171            *commented |= func.parameters.iter().any(|p| {
1172                if p.closure().is_none() {
1173                    crate::analysis::trampolines::type_error(env, p).is_some()
1174                } else {
1175                    false
1176                }
1177            });
1178        }
1179        for p in &parameters.rust_parameters {
1180            if let Ok(rust_type) = RustType::builder(env, p.typ)
1181                .direction(p.direction)
1182                .nullable(p.nullable)
1183                .try_from_glib(&p.try_from_glib)
1184                .try_build()
1185            {
1186                imports_to_add.extend(rust_type.into_used_types());
1187            }
1188        }
1189        if let Ok(rust_type) = RustType::builder(env, func.ret.typ())
1190            .direction(ParameterDirection::Return)
1191            .try_build()
1192            && !rust_type.as_str().ends_with("GString")
1193            && !rust_type.as_str().ends_with("GAsyncResult")
1194        {
1195            imports_to_add.extend(rust_type.into_used_types());
1196        }
1197        let user_data_index = par.user_data_index.unwrap_or(0);
1198        if par.c_type != "GDestroyNotify" && c_parameters.len() <= user_data_index {
1199            warn_main!(
1200                type_tid,
1201                "`{}`: Invalid user data index of `{}`",
1202                func.name,
1203                user_data_index
1204            );
1205            *commented = true;
1206            None
1207        } else if match par.destroy_index {
1208            Some(destroy_index) => c_parameters.len() <= destroy_index,
1209            None => false,
1210        } {
1211            warn_main!(
1212                type_tid,
1213                "`{}`: Invalid destroy index of `{}`",
1214                func.name,
1215                par.destroy_index.unwrap()
1216            );
1217            *commented = true;
1218            None
1219        } else {
1220            if !*commented {
1221                for import in imports_to_add {
1222                    imports.add_used_type(&import);
1223                }
1224            }
1225            Some((
1226                Trampoline {
1227                    name: par.name.to_string(),
1228                    parameters,
1229                    ret: func.ret.clone(),
1230                    bound_name: match callback_info {
1231                        Some(x) => x.bound_name.to_string(),
1232                        None => match RustType::builder(env, par.typ)
1233                            .direction(par.direction)
1234                            .nullable(par.nullable)
1235                            .scope(par.scope)
1236                            .try_build()
1237                        {
1238                            Ok(rust_type) => rust_type.into_string(),
1239                            Err(_) => {
1240                                warn_main!(type_tid, "`{}`: unknown type", func.name);
1241                                return None;
1242                            }
1243                        },
1244                    },
1245                    bounds: Bounds::default(),
1246                    version: None,
1247                    inhibit: false,
1248                    concurrency: library::Concurrency::None,
1249                    is_notify: false,
1250                    scope: par.scope,
1251                    // If destroy callback, id doesn't matter.
1252                    user_data_index: if par.c_type != "GDestroyNotify" {
1253                        c_parameters[user_data_index].1
1254                    } else {
1255                        0
1256                    },
1257                    destroy_index: 0,
1258                    nullable: par.nullable,
1259                    type_name: env.library.type_(type_tid).get_name(),
1260                },
1261                par.destroy_index
1262                    .map(|destroy_index| c_parameters[destroy_index].1),
1263            ))
1264        }
1265    } else {
1266        None
1267    }
1268}
1269
1270pub fn find_function<'a>(env: &'a Env, c_identifier: &str) -> Option<&'a Function> {
1271    let find = |functions: &'a [Function]| -> Option<&'a Function> {
1272        functions
1273            .iter()
1274            .find(|&function| function.c_identifier == c_identifier)
1275    };
1276
1277    if let Some((index, _)) = env.library.find_namespace(&env.config.library_name) {
1278        let namespace = env.library.namespace(index);
1279        if let Some(f) = find(&namespace.functions) {
1280            return Some(f);
1281        }
1282        for typ in &namespace.types {
1283            if let Some(Type::Class(class)) = typ {
1284                if let Some(f) = find(&class.functions) {
1285                    return Some(f);
1286                }
1287            } else if let Some(Type::Interface(interface)) = typ
1288                && let Some(f) = find(&interface.functions)
1289            {
1290                return Some(f);
1291            }
1292        }
1293    }
1294    None
1295}
1296
1297/// Given async function name tries to guess the name of finish function.
1298pub fn finish_function_name(mut func_name: &str) -> String {
1299    if func_name.ends_with("_async") {
1300        let len = func_name.len() - "_async".len();
1301        func_name = &func_name[0..len];
1302    }
1303    format!("{}_finish", func_name)
1304}
1305
1306pub fn find_index_to_ignore<'a>(
1307    parameters: impl IntoIterator<Item = &'a library::Parameter>,
1308    ret: Option<&'a library::Parameter>,
1309) -> Option<usize> {
1310    parameters
1311        .into_iter()
1312        .chain(ret)
1313        .find(|param| param.array_length().is_some())
1314        .and_then(|param| param.array_length().map(|length| length as usize))
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320
1321    #[test]
1322    fn test_finish_function_name() {
1323        assert_eq!(
1324            "g_file_copy_finish",
1325            &finish_function_name("g_file_copy_async")
1326        );
1327        assert_eq!("g_bus_get_finish", &finish_function_name("g_bus_get"));
1328    }
1329}