1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use std::collections::BTreeMap;

use imports::Imports;
use log::error;

use crate::{
    env::Env,
    library::{self, Type, TypeId},
};

pub mod bounds;
pub mod c_type;
pub mod child_properties;
pub mod class_builder;
pub mod class_hierarchy;
pub mod constants;
pub mod conversion_type;
pub mod enums;
pub mod ffi_type;
pub mod flags;
pub mod function_parameters;
pub use function_parameters::Parameter;
pub mod functions;
pub mod general;
pub mod imports;
pub mod info_base;
pub mod namespaces;
pub mod object;
pub mod out_parameters;
mod override_string_type;
pub mod properties;
pub mod record;
pub mod record_type;
pub mod ref_mode;
pub mod return_value;
pub mod rust_type;
pub mod safety_assertion_mode;
pub mod signals;
pub mod signatures;
pub mod special_functions;
pub mod supertypes;
pub mod symbols;
pub mod trampoline_parameters;
pub mod trampolines;
pub mod try_from_glib;
pub mod types;

#[derive(Debug, Default)]
pub struct Analysis {
    pub objects: BTreeMap<String, object::Info>,
    pub records: BTreeMap<String, record::Info>,
    pub global_functions: Option<info_base::InfoBase>,
    pub constants: Vec<constants::Info>,

    pub enumerations: Vec<enums::Info>,
    pub enum_imports: Imports,

    pub flags: Vec<flags::Info>,
    pub flags_imports: Imports,
}

fn find_function<'a>(
    env: &Env,
    mut functions: impl Iterator<Item = &'a functions::Info>,
    search_fn: impl Fn(&functions::Info) -> bool + Copy,
) -> Option<&'a functions::Info> {
    functions.find(|fn_info| fn_info.should_be_doc_linked(env) && search_fn(fn_info))
}

impl Analysis {
    pub fn find_global_function<F: Fn(&functions::Info) -> bool + Copy>(
        &self,
        env: &Env,
        search: F,
    ) -> Option<&functions::Info> {
        self.global_functions
            .as_ref()
            .and_then(move |info| find_function(env, info.functions.iter(), search))
    }

    pub fn find_record_by_function<
        F: Fn(&functions::Info) -> bool + Copy,
        G: Fn(&record::Info) -> bool + Copy,
    >(
        &self,
        env: &Env,
        search_record: G,
        search_fn: F,
    ) -> Option<(&record::Info, &functions::Info)> {
        self.records
            .values()
            .filter(|r| search_record(r))
            .find_map(|record_info| {
                find_function(env, record_info.functions.iter(), search_fn)
                    .map(|fn_info| (record_info, fn_info))
            })
    }

    pub fn find_object_by_virtual_method<
        F: Fn(&functions::Info) -> bool + Copy,
        G: Fn(&object::Info) -> bool + Copy,
    >(
        &self,
        env: &Env,
        search_obj: G,
        search_fn: F,
    ) -> Option<(&object::Info, &functions::Info)> {
        self.objects
            .values()
            .filter(|o| search_obj(o))
            .find_map(|obj_info| {
                find_function(env, obj_info.virtual_methods.iter(), search_fn)
                    .map(|fn_info| (obj_info, fn_info))
            })
    }

    pub fn find_object_by_function<
        F: Fn(&functions::Info) -> bool + Copy,
        G: Fn(&object::Info) -> bool + Copy,
    >(
        &self,
        env: &Env,
        search_obj: G,
        search_fn: F,
    ) -> Option<(&object::Info, &functions::Info)> {
        self.objects
            .values()
            .filter(|o| search_obj(o))
            .find_map(|obj_info| {
                find_function(env, obj_info.functions.iter(), search_fn)
                    .map(|fn_info| (obj_info, fn_info))
            })
    }

    pub fn find_enum_by_function<
        F: Fn(&functions::Info) -> bool + Copy,
        G: Fn(&enums::Info) -> bool + Copy,
    >(
        &self,
        env: &Env,
        search_enum: G,
        search_fn: F,
    ) -> Option<(&enums::Info, &functions::Info)> {
        self.enumerations
            .iter()
            .filter(|o| search_enum(o))
            .find_map(|obj_info| {
                find_function(env, obj_info.functions.iter(), search_fn)
                    .map(|fn_info| (obj_info, fn_info))
            })
    }

    pub fn find_flag_by_function<
        F: Fn(&functions::Info) -> bool + Copy,
        G: Fn(&flags::Info) -> bool + Copy,
    >(
        &self,
        env: &Env,
        search_flag: G,
        search_fn: F,
    ) -> Option<(&flags::Info, &functions::Info)> {
        self.flags
            .iter()
            .filter(|o| search_flag(o))
            .find_map(|obj_info| {
                find_function(env, obj_info.functions.iter(), search_fn)
                    .map(|fn_info| (obj_info, fn_info))
            })
    }
}

pub fn run(env: &mut Env) {
    let mut to_analyze: Vec<(TypeId, Vec<TypeId>)> = Vec::with_capacity(env.config.objects.len());
    for obj in env.config.objects.values() {
        if obj.status.ignored() {
            continue;
        }
        let Some(tid) = env.library.find_type(0, &obj.name) else {
            continue;
        };
        let deps = supertypes::dependencies(env, tid);
        to_analyze.push((tid, deps));
    }

    let mut analyzed = 1;
    while analyzed > 0 {
        analyzed = 0;
        let mut new_to_analyze: Vec<(TypeId, Vec<TypeId>)> = Vec::with_capacity(to_analyze.len());
        for (tid, ref deps) in to_analyze {
            if !is_all_deps_analyzed(env, deps) {
                new_to_analyze.push((tid, deps.clone()));
                continue;
            }
            analyze(env, tid, deps);
            analyzed += 1;
        }

        to_analyze = new_to_analyze;
    }

    if !to_analyze.is_empty() {
        error!(
            "Not analyzed {} objects due unfinished dependencies",
            to_analyze.len()
        );
        return;
    }

    analyze_enums(env);

    analyze_flags(env);

    analyze_constants(env);

    // Analyze free functions as the last step once all types are analyzed
    analyze_global_functions(env);
}

fn analyze_enums(env: &mut Env) {
    let mut imports = Imports::new(&env.library);

    for obj in env.config.objects.values() {
        if obj.status.ignored() {
            continue;
        }
        let Some(tid) = env.library.find_type(0, &obj.name) else {
            continue;
        };

        if let Type::Enumeration(_) = env.library.type_(tid) {
            if let Some(info) = enums::new(env, obj, &mut imports) {
                env.analysis.enumerations.push(info);
            }
        }
    }

    env.analysis.enum_imports = imports;
}

fn analyze_flags(env: &mut Env) {
    let mut imports = Imports::new(&env.library);

    for obj in env.config.objects.values() {
        if obj.status.ignored() {
            continue;
        }
        let Some(tid) = env.library.find_type(0, &obj.name) else {
            continue;
        };

        if let Type::Bitfield(_) = env.library.type_(tid) {
            if let Some(info) = flags::new(env, obj, &mut imports) {
                env.analysis.flags.push(info);
            }
        }
    }

    env.analysis.flags_imports = imports;
}

fn analyze_global_functions(env: &mut Env) {
    let ns = env.library.namespace(library::MAIN_NAMESPACE);

    let full_name = format!("{}.*", ns.name);

    let obj = match env.config.objects.get(&*full_name) {
        Some(obj) if obj.status.need_generate() => obj,
        _ => return,
    };

    let functions: Vec<_> = ns
        .functions
        .iter()
        .filter(|f| f.kind == library::FunctionKind::Global)
        .collect();
    if functions.is_empty() {
        return;
    }

    let mut imports = imports::Imports::new(&env.library);
    imports.add("glib::translate::*");
    imports.add("crate:ffi");

    let functions = functions::analyze(
        env,
        &functions,
        None,
        false,
        false,
        obj,
        &mut imports,
        None,
        None,
    );

    env.analysis.global_functions = Some(info_base::InfoBase {
        full_name,
        type_id: TypeId::tid_none(),
        name: "*".into(),
        functions,
        imports,
        ..Default::default()
    });
}

fn analyze_constants(env: &mut Env) {
    let ns = env.library.namespace(library::MAIN_NAMESPACE);

    let full_name = format!("{}.*", ns.name);

    let obj = match env.config.objects.get(&*full_name) {
        Some(obj) if obj.status.need_generate() => obj,
        _ => return,
    };

    let constants: Vec<_> = ns.constants.iter().collect();
    if constants.is_empty() {
        return;
    }

    env.analysis.constants = constants::analyze(env, &constants, obj);
}

fn analyze(env: &mut Env, tid: TypeId, deps: &[TypeId]) {
    let full_name = tid.full_name(&env.library);
    let Some(obj) = env.config.objects.get(&*full_name) else {
        return;
    };
    match env.library.type_(tid) {
        Type::Class(_) => {
            if let Some(info) = object::class(env, obj, deps) {
                env.analysis.objects.insert(full_name, info);
            }
        }
        Type::Interface(_) => {
            if let Some(info) = object::interface(env, obj, deps) {
                env.analysis.objects.insert(full_name, info);
            }
        }
        Type::Record(_) => {
            if let Some(info) = record::new(env, obj) {
                env.analysis.records.insert(full_name, info);
            }
        }
        _ => {}
    }
}

fn is_all_deps_analyzed(env: &Env, deps: &[TypeId]) -> bool {
    for tid in deps {
        let full_name = tid.full_name(&env.library);
        if !env.analysis.objects.contains_key(&full_name) {
            return false;
        }
    }
    true
}

pub fn is_gpointer(s: &str) -> bool {
    s == "gpointer" || s == "void*"
}