Debian Codegraph @

src/config/gobjects.rs

raw
1 use std::{
2 collections::{BTreeMap, HashSet},
3 str::FromStr,
4 sync::Arc,
5 };
6
7 use log::{error, warn};
8 use toml::Value;
9
10 use super::{
11 child_properties::ChildProperties,
12 constants::Constants,
13 derives::Derives,
14 functions::Functions,
15 ident::Ident,
16 members::Members,
17 properties::Properties,
18 signals::{Signal, Signals},
19 virtual_methods::VirtualMethods,
20 };
21 use crate::{
22 analysis::{conversion_type::ConversionType, ref_mode},
23 codegen::Visibility,
24 config::{
25 error::TomlHelper,
26 parsable::{Parsable, Parse},
27 },
28 library::{self, Library, MAIN_NAMESPACE, TypeId},
29 version::Version,
30 };
31
32 #[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
33 pub enum GStatus {
34 Manual,
35 Generate,
36 #[default]
37 Ignore,
38 }
39
40 impl GStatus {
41 pub fn ignored(self) -> bool {
42 self == Self::Ignore
43 }
44 pub fn manual(self) -> bool {
45 self == Self::Manual
46 }
47 pub fn need_generate(self) -> bool {
48 self == Self::Generate
49 }
50 }
51
52 impl FromStr for GStatus {
53 type Err = String;
54 fn from_str(s: &str) -> Result<Self, Self::Err> {
55 match s {
56 "manual" => Ok(Self::Manual),
57 "generate" => Ok(Self::Generate),
58 "ignore" => Ok(Self::Ignore),
59 e => Err(format!("Wrong object status: \"{e}\"")),
60 }
61 }
62 }
63
64 /// Info about `GObject` descendant
65 #[derive(Clone, Debug)]
66 pub struct GObject {
67 pub name: String,
68 pub functions: Functions,
69 pub virtual_methods: VirtualMethods,
70 pub constants: Constants,
71 pub signals: Signals,
72 pub members: Members,
73 pub properties: Properties,
74 pub derives: Option<Derives>,
75 pub status: GStatus,
76 pub module_name: Option<String>,
77 pub version: Option<Version>,
78 pub cfg_condition: Option<String>,
79 pub type_id: Option<TypeId>,
80 pub final_type: Option<bool>,
81 pub fundamental_type: Option<bool>,
82 pub exhaustive: bool,
83 pub trait_name: Option<String>,
84 pub child_properties: Option<ChildProperties>,
85 pub concurrency: library::Concurrency,
86 pub ref_mode: Option<ref_mode::RefMode>,
87 pub must_use: bool,
88 pub conversion_type: Option<ConversionType>,
89 pub trust_return_value_nullability: bool,
90 pub manual_traits: Vec<String>,
91 pub align: Option<u32>,
92 pub generate_builder: bool,
93 pub builder_postprocess: Option<String>,
94 pub boxed_inline: bool,
95 pub init_function_expression: Option<String>,
96 pub copy_into_function_expression: Option<String>,
97 pub clear_function_expression: Option<String>,
98 pub visibility: Visibility,
99 pub default_value: Option<String>,
100 pub generate_doc: bool,
101 }
102
103 impl Default for GObject {
104 fn default() -> GObject {
105 GObject {
106 name: "Default".into(),
107 functions: Functions::new(),
108 virtual_methods: VirtualMethods::new(),
109 constants: Constants::new(),
110 signals: Signals::new(),
111 members: Members::new(),
112 properties: Properties::new(),
113 derives: None,
114 status: Default::default(),
115 module_name: None,
116 version: None,
117 cfg_condition: None,
118 type_id: None,
119 final_type: None,
120 fundamental_type: None,
121 exhaustive: false,
122 trait_name: None,
123 child_properties: None,
124 concurrency: Default::default(),
125 ref_mode: None,
126 must_use: false,
127 conversion_type: None,
128 trust_return_value_nullability: false,
129 manual_traits: Vec::default(),
130 align: None,
131 generate_builder: false,
132 builder_postprocess: None,
133 boxed_inline: false,
134 init_function_expression: None,
135 copy_into_function_expression: None,
136 clear_function_expression: None,
137 visibility: Default::default(),
138 default_value: None,
139 generate_doc: true,
140 }
141 }
142 }
143
144 // TODO: ?change to HashMap<String, GStatus>
145 pub type GObjects = BTreeMap<String, GObject>;
146
147 pub fn parse_toml(
148 toml_objects: &Value,
149 concurrency: library::Concurrency,
150 generate_builder: bool,
151 trust_return_value_nullability: bool,
152 ) -> GObjects {
153 let mut objects = GObjects::new();
154 for toml_object in toml_objects.as_array().unwrap() {
155 let gobject = parse_object(
156 toml_object,
157 concurrency,
158 generate_builder,
159 trust_return_value_nullability,
160 );
161 objects.insert(gobject.name.clone(), gobject);
162 }
163 objects
164 }
165
166 pub fn parse_conversion_type(toml: Option<&Value>, object_name: &str) -> Option<ConversionType> {
167 use crate::analysis::conversion_type::ConversionType::*;
168
169 let v = toml?;
170 v.check_unwanted(&["variant", "ok_type", "err_type"], "conversion_type");
171
172 let (conversion_type, ok_type, err_type) = match &v {
173 Value::Table(table) => {
174 let conversion_type = table.get("variant").and_then(Value::as_str);
175 if conversion_type.is_none() {
176 error!("Missing `variant` for {object_name}.conversion_type");
177 return None;
178 }
179
180 let ok_type = Some(Arc::from(
181 table
182 .get("ok_type")
183 .and_then(Value::as_str)
184 .unwrap_or(object_name),
185 ));
186 let err_type = table.get("err_type").and_then(Value::as_str);
187
188 (conversion_type.unwrap(), ok_type, err_type)
189 }
190 Value::String(conversion_type) => (conversion_type.as_str(), None, None),
191 _ => {
192 error!("Unexpected toml item for {object_name}.conversion_type");
193 return None;
194 }
195 };
196
197 let get_err_type = || -> Arc<str> {
198 err_type.map_or_else(
199 || {
200 error!("Missing `err_type` for {object_name}.conversion_type");
201 Arc::from("MissingErrorType")
202 },
203 Arc::from,
204 )
205 };
206
207 match conversion_type {
208 "direct" => Some(Direct),
209 "scalar" => Some(Scalar),
210 "Option" => Some(Option),
211 "Result" => Some(Result {
212 ok_type: ok_type.expect("Missing `ok_type`"),
213 err_type: get_err_type(),
214 }),
215 "pointer" => Some(Pointer),
216 "borrow" => Some(Borrow),
217 "unknown" => Some(Unknown),
218 unexpected => {
219 error!("Unexpected {unexpected} for {object_name}.conversion_type");
220 None
221 }
222 }
223 }
224
225 fn parse_object(
226 toml_object: &Value,
227 concurrency: library::Concurrency,
228 generate_builder: bool,
229 trust_return_value_nullability: bool,
230 ) -> GObject {
231 let name: String = toml_object
232 .lookup("name")
233 .expect("Object name not defined")
234 .as_str()
235 .unwrap()
236 .into();
237 // Also checks for ChildProperties
238 toml_object.check_unwanted(
239 &[
240 "name",
241 "status",
242 "function",
243 "constant",
244 "signal",
245 "member",
246 "property",
247 "derive",
248 "module_name",
249 "version",
250 "concurrency",
251 "ref_mode",
252 "conversion_type",
253 "child_prop",
254 "child_name",
255 "child_type",
256 "final_type",
257 "fundamental_type",
258 "exhaustive",
259 "trait",
260 "trait_name",
261 "cfg_condition",
262 "must_use",
263 "trust_return_value_nullability",
264 "manual_traits",
265 "align",
266 "generate_builder",
267 "builder_postprocess",
268 "boxed_inline",
269 "init_function_expression",
270 "copy_into_function_expression",
271 "clear_function_expression",
272 "visibility",
273 "default_value",
274 "generate_doc",
275 ],
276 &format!("object {name}"),
277 );
278
279 let status = match toml_object.lookup("status") {
280 Some(value) => {
281 GStatus::from_str(value.as_str().unwrap()).unwrap_or_else(|_| Default::default())
282 }
283 None => Default::default(),
284 };
285
286 let constants = Constants::parse(toml_object.lookup("constant"), &name);
287 let functions = Functions::parse(toml_object.lookup("function"), &name);
288 let mut function_names = HashSet::new();
289 for f in &functions {
290 if let Ident::Name(name) = &f.ident {
291 assert!(function_names.insert(name), "{name} already defined!");
292 }
293 }
294 let virtual_methods = VirtualMethods::parse(toml_object.lookup("virtual_method"), &name);
295 let mut virtual_methods_names = HashSet::new();
296 for f in &virtual_methods {
297 if let Ident::Name(name) = &f.ident {
298 assert!(
299 virtual_methods_names.insert(name),
300 "{name} already defined!"
301 );
302 }
303 }
304
305 let signals = {
306 let mut v = Vec::new();
307 if let Some(configs) = toml_object.lookup("signal").and_then(Value::as_array) {
308 for config in configs {
309 if let Some(item) = Signal::parse(config, &name, concurrency) {
310 v.push(item);
311 }
312 }
313 }
314
315 v
316 };
317 let members = Members::parse(toml_object.lookup("member"), &name);
318 let properties = Properties::parse(toml_object.lookup("property"), &name);
319 let derives = toml_object
320 .lookup("derive")
321 .map(|derives| Derives::parse(Some(derives), &name));
322 let module_name = toml_object
323 .lookup("module_name")
324 .and_then(Value::as_str)
325 .map(ToOwned::to_owned);
326 let version = toml_object
327 .lookup("version")
328 .and_then(Value::as_str)
329 .and_then(|s| s.parse().ok());
330 let cfg_condition = toml_object
331 .lookup("cfg_condition")
332 .and_then(Value::as_str)
333 .map(ToOwned::to_owned);
334 let generate_trait = toml_object.lookup("trait").and_then(Value::as_bool);
335 let final_type = toml_object
336 .lookup("final_type")
337 .and_then(Value::as_bool)
338 .or_else(|| generate_trait.map(|t| !t));
339 let fundamental_type = toml_object
340 .lookup("fundamental_type")
341 .and_then(Value::as_bool);
342 let exhaustive = toml_object
343 .lookup("exhaustive")
344 .and_then(Value::as_bool)
345 .unwrap_or(false);
346 let trait_name = toml_object
347 .lookup("trait_name")
348 .and_then(Value::as_str)
349 .map(ToOwned::to_owned);
350 let concurrency = toml_object
351 .lookup("concurrency")
352 .and_then(Value::as_str)
353 .and_then(|v| v.parse().ok())
354 .unwrap_or(concurrency);
355 let ref_mode = toml_object
356 .lookup("ref_mode")
357 .and_then(Value::as_str)
358 .and_then(|v| v.parse().ok());
359 let conversion_type = parse_conversion_type(toml_object.lookup("conversion_type"), &name);
360 let child_properties = ChildProperties::parse(toml_object, &name);
361 let must_use = toml_object
362 .lookup("must_use")
363 .and_then(Value::as_bool)
364 .unwrap_or(false);
365 let trust_return_value_nullability = toml_object
366 .lookup("trust_return_value_nullability")
367 .and_then(Value::as_bool)
368 .unwrap_or(trust_return_value_nullability);
369 let manual_traits = toml_object
370 .lookup_vec("manual_traits", "IGNORED ERROR")
371 .into_iter()
372 .flatten()
373 .filter_map(|v| v.as_str().map(String::from))
374 .collect();
375 let align = toml_object
376 .lookup("align")
377 .and_then(Value::as_integer)
378 .and_then(|v| {
379 if v.count_ones() != 1 || v > i64::from(u32::MAX) || v < 0 {
380 warn!("`align` configuration must be a power of two of type u32, found {v}");
381 None
382 } else {
383 Some(v as u32)
384 }
385 });
386 let generate_builder = toml_object
387 .lookup("generate_builder")
388 .and_then(Value::as_bool)
389 .unwrap_or(generate_builder);
390
391 let boxed_inline = toml_object
392 .lookup("boxed_inline")
393 .and_then(Value::as_bool)
394 .unwrap_or(false);
395
396 let builder_postprocess = toml_object
397 .lookup("builder_postprocess")
398 .and_then(Value::as_str)
399 .map(String::from);
400 let init_function_expression = toml_object
401 .lookup("init_function_expression")
402 .and_then(Value::as_str)
403 .map(ToOwned::to_owned);
404 let copy_into_function_expression = toml_object
405 .lookup("copy_into_function_expression")
406 .and_then(Value::as_str)
407 .map(ToOwned::to_owned);
408 let clear_function_expression = toml_object
409 .lookup("clear_function_expression")
410 .and_then(Value::as_str)
411 .map(ToOwned::to_owned);
412 let default_value = toml_object
413 .lookup("default_value")
414 .and_then(Value::as_str)
415 .map(ToOwned::to_owned);
416
417 let visibility = toml_object
418 .lookup("visibility")
419 .and_then(Value::as_str)
420 .map(|v| v.parse())
421 .transpose();
422 if let Err(ref err) = visibility {
423 error!("{err}");
424 }
425 let visibility = visibility.ok().flatten().unwrap_or_default();
426 if boxed_inline
427 && !((init_function_expression.is_none()
428 && copy_into_function_expression.is_none()
429 && clear_function_expression.is_none())
430 || (init_function_expression.is_some()
431 && copy_into_function_expression.is_some()
432 && clear_function_expression.is_some()))
433 {
434 panic!(
435 "`init_function_expression`, `copy_into_function_expression` and `clear_function_expression` all have to be provided or neither"
436 );
437 }
438
439 if !boxed_inline
440 && (init_function_expression.is_some()
441 || copy_into_function_expression.is_some()
442 || clear_function_expression.is_some())
443 {
444 panic!(
445 "`init_function_expression`, `copy_into_function_expression` and `clear_function_expression` can only be provided for BoxedInline types"
446 );
447 }
448
449 if status != GStatus::Manual && ref_mode.is_some() {
450 warn!("ref_mode configuration used for non-manual object {name}");
451 }
452
453 if status != GStatus::Manual
454 && !conversion_type
455 .as_ref()
456 .is_none_or(ConversionType::can_use_to_generate)
457 {
458 warn!(
459 "unexpected conversion_type {conversion_type:?} configuration used for non-manual object {name}"
460 );
461 }
462
463 let generate_doc = toml_object
464 .lookup("generate_doc")
465 .and_then(Value::as_bool)
466 .unwrap_or(true);
467
468 if generate_trait.is_some() {
469 warn!("`trait` configuration is deprecated and replaced by `final_type` for object {name}");
470 }
471
472 GObject {
473 name,
474 functions,
475 virtual_methods,
476 constants,
477 signals,
478 members,
479 properties,
480 derives,
481 status,
482 module_name,
483 version,
484 cfg_condition,
485 type_id: None,
486 final_type,
487 fundamental_type,
488 exhaustive,
489 trait_name,
490 child_properties,
491 concurrency,
492 ref_mode,
493 must_use,
494 conversion_type,
495 trust_return_value_nullability,
496 manual_traits,
497 align,
498 generate_builder,
499 builder_postprocess,
500 boxed_inline,
501 init_function_expression,
502 copy_into_function_expression,
503 clear_function_expression,
504 visibility,
505 default_value,
506 generate_doc,
507 }
508 }
509
510 pub fn parse_status_shorthands(
511 objects: &mut GObjects,
512 toml: &Value,
513 concurrency: library::Concurrency,
514 generate_builder: bool,
515 trust_return_value_nullability: bool,
516 ) {
517 use self::GStatus::*;
518 for &status in &[Manual, Generate, Ignore] {
519 parse_status_shorthand(
520 objects,
521 status,
522 toml,
523 concurrency,
524 generate_builder,
525 trust_return_value_nullability,
526 );
527 }
528 }
529
530 fn parse_status_shorthand(
531 objects: &mut GObjects,
532 status: GStatus,
533 toml: &Value,
534 concurrency: library::Concurrency,
535 generate_builder: bool,
536 trust_return_value_nullability: bool,
537 ) {
538 let option_name = format!("options.{status:?}").to_ascii_lowercase();
539 if let Some(a) = toml.lookup(&option_name).map(|a| a.as_array().unwrap()) {
540 for name in a.iter().map(|s| s.as_str().unwrap()) {
541 match objects.get(name) {
542 None => {
543 objects.insert(
544 name.into(),
545 GObject {
546 name: name.into(),
547 status,
548 concurrency,
549 trust_return_value_nullability,
550 generate_builder,
551 ..Default::default()
552 },
553 );
554 }
555 Some(_) => panic!("Bad name in {option_name}: {name} already defined"),
556 }
557 }
558 }
559 }
560
561 pub fn resolve_type_ids(objects: &mut GObjects, library: &Library) {
562 let ns = library.namespace(MAIN_NAMESPACE);
563 let global_functions_name = format!("{}.*", ns.name);
564
565 for (name, object) in objects.iter_mut() {
566 let type_id = library.find_type(0, name);
567 if type_id.is_none() && name != &global_functions_name && object.status != GStatus::Ignore {
568 warn!("Configured object `{name}` missing from the library");
569 } else if object.generate_builder
570 && let Some(type_id) = type_id
571 && library.type_(type_id).is_abstract()
572 {
573 warn!("Cannot generate builder for `{name}` because it's a base class");
574 // We set this to `false` to avoid having the "not_bound" mode saying that this
575 // builder should be generated.
576 object.generate_builder = false;
577 }
578 object.type_id = type_id;
579 }
580 }
581
582 #[cfg(test)]
583 mod tests {
584 use super::*;
585 use crate::{analysis::conversion_type::ConversionType, library::Concurrency};
586
587 fn toml(input: &str) -> ::toml::Value {
588 let value = ::toml::from_str(input);
589 assert!(value.is_ok());
590 value.unwrap()
591 }
592
593 #[test]
594 fn conversion_type_default() {
595 let toml = &toml(
596 r#"
597 name = "Test"
598 status = "generate"
599 "#,
600 );
601
602 let object = parse_object(toml, Concurrency::default(), false, false);
603 assert_eq!(object.conversion_type, None);
604 }
605
606 #[test]
607 fn conversion_type_option_str() {
608 let toml = toml(
609 r#"
610 name = "Test"
611 status = "generate"
612 conversion_type = "Option"
613 "#,
614 );
615
616 let object = parse_object(&toml, Concurrency::default(), false, false);
617 assert_eq!(object.conversion_type, Some(ConversionType::Option));
618 }
619
620 #[test]
621 fn conversion_type_option_table() {
622 let toml = &toml(
623 r#"
624 name = "Test"
625 status = "generate"
626 [conversion_type]
627 variant = "Option"
628 "#,
629 );
630
631 let object = parse_object(toml, Concurrency::default(), false, false);
632 assert_eq!(object.conversion_type, Some(ConversionType::Option));
633 }
634
635 #[test]
636 fn conversion_type_result_table_missing_err() {
637 let toml = &toml(
638 r#"
639 name = "Test"
640 status = "generate"
641 [conversion_type]
642 variant = "Result"
643 "#,
644 );
645
646 let object = parse_object(toml, Concurrency::default(), false, false);
647 assert_eq!(
648 object.conversion_type,
649 Some(ConversionType::Result {
650 ok_type: Arc::from("Test"),
651 err_type: Arc::from("MissingErrorType"),
652 }),
653 );
654 }
655
656 #[test]
657 fn conversion_type_result_table_with_err() {
658 let toml = &toml(
659 r#"
660 name = "Test"
661 status = "generate"
662 [conversion_type]
663 variant = "Result"
664 err_type = "TryFromIntError"
665 "#,
666 );
667
668 let object = parse_object(toml, Concurrency::default(), false, false);
669 assert_eq!(
670 object.conversion_type,
671 Some(ConversionType::Result {
672 ok_type: Arc::from("Test"),
673 err_type: Arc::from("TryFromIntError"),
674 }),
675 );
676 }
677
678 #[test]
679 fn conversion_type_result_table_with_ok_err() {
680 let toml = &toml(
681 r#"
682 name = "Test"
683 status = "generate"
684 [conversion_type]
685 variant = "Result"
686 ok_type = "TestSuccess"
687 err_type = "TryFromIntError"
688 "#,
689 );
690
691 let object = parse_object(toml, Concurrency::default(), false, false);
692 assert_eq!(
693 object.conversion_type,
694 Some(ConversionType::Result {
695 ok_type: Arc::from("TestSuccess"),
696 err_type: Arc::from("TryFromIntError"),
697 }),
698 );
699 }
700
701 #[test]
702 fn conversion_type_fields() {
703 let toml = &toml(
704 r#"
705 [[object]]
706 name = "Test"
707 status = "generate"
708 [[object.constant]]
709 name = "Const"
710 [[object.function]]
711 name = "Func"
712 manual = true
713
714 "#,
715 );
716
717 let object = toml
718 .lookup("object")
719 .map(|t| parse_toml(t, Concurrency::default(), false, false))
720 .expect("parsing failed");
721 assert_eq!(
722 object["Test"].constants,
723 vec![crate::config::constants::Constant {
724 ident: Ident::Name("Const".to_owned()),
725 status: GStatus::Generate,
726 version: None,
727 cfg_condition: None,
728 generate_doc: true,
729 }],
730 );
731 assert_eq!(object["Test"].functions.len(), 1);
732 assert_eq!(
733 object["Test"].functions[0].ident,
734 Ident::Name("Func".to_owned()),
735 );
736 }
737
738 #[test]
739 fn conversion_type_generate_doc() {
740 let r = &toml(
741 r#"
742 name = "Test"
743 status = "generate"
744 generate_doc = false
745 "#,
746 );
747
748 let object = parse_object(r, Concurrency::default(), false, false);
749 assert!(!object.generate_doc);
750
751 // Ensure that the default value is "true".
752 let r = &toml(
753 r#"
754 name = "Test"
755 status = "generate"
756 "#,
757 );
758 let object = parse_object(r, Concurrency::default(), false, false);
759 assert!(object.generate_doc);
760 }
761 }