autosar_data_abstraction/software_component/
mod.rs

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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! Software component types and compositions
//!
//! This module contains the definition of software component types and instances.
//! It also contains the definition of the composition hierarchy, and the connectors between components.

use crate::{
    abstraction_element, datatype, reflist_iterator, AbstractionElement, ArPackage, AutosarAbstractionError, Element,
};
use autosar_data::ElementName;
use datatype::DataTypeMappingSet;

mod connector;
mod interface;
mod port;

pub use connector::*;
pub use interface::*;
pub use port::*;

//##################################################################

/// The `AbstractSwComponentType` is the common interface for all types of software components
pub trait AbstractSwComponentType: AbstractionElement {
    /// iterator over the instances of the component type
    fn instances(&self) -> ComponentPrototypeIterator {
        let model_result = self.element().model();
        let path_result = self.element().path();
        if let (Ok(model), Ok(path)) = (model_result, path_result) {
            let reflist = model.get_references_to(&path);
            ComponentPrototypeIterator::new(reflist)
        } else {
            ComponentPrototypeIterator::new(vec![])
        }
    }

    /// iterator over all compositions containing instances of the component type
    fn parent_compositions(&self) -> impl Iterator<Item = CompositionSwComponentType> {
        self.instances()
            .filter_map(|swcp| swcp.element().named_parent().ok().flatten())
            .filter_map(|elem| CompositionSwComponentType::try_from(elem).ok())
    }

    /// add a data type mapping to the SWC, by referencing an existing `DataTypeMappingSet`
    fn add_data_type_mapping(&self, data_type_mapping_set: &DataTypeMappingSet) -> Result<(), AutosarAbstractionError> {
        // this default implementation applies to component variants that have internal behaviors.
        // specifically, this means that it is NOT valid for the CompositionSwComponentType
        let name = self.name().unwrap();
        let data_type_mapping_refs = self
            .element()
            .get_or_create_sub_element(ElementName::InternalBehaviors)?
            .get_or_create_named_sub_element(ElementName::SwcInternalBehavior, &format!("{name}_InternalBehavior"))?
            .get_or_create_sub_element(ElementName::DataTypeMappingRefs)?;
        data_type_mapping_refs
            .create_sub_element(ElementName::DataTypeMappingRef)?
            .set_reference_target(data_type_mapping_set.element())?;
        Ok(())
    }

    /// create a new required port with the given name and port interface
    fn create_r_port<T: AbstractPortInterface>(
        &self,
        name: &str,
        port_interface: &T,
    ) -> Result<RPortPrototype, AutosarAbstractionError> {
        let ports = self.element().get_or_create_sub_element(ElementName::Ports)?;
        RPortPrototype::new(name, &ports, port_interface)
    }

    /// create a new provided port with the given name and port interface
    fn create_p_port<T: AbstractPortInterface>(
        &self,
        name: &str,
        port_interface: &T,
    ) -> Result<PPortPrototype, AutosarAbstractionError> {
        let ports = self.element().get_or_create_sub_element(ElementName::Ports)?;
        PPortPrototype::new(name, &ports, port_interface)
    }

    /// create a new provided required port with the given name and port interface
    fn create_pr_port<T: AbstractPortInterface>(
        &self,
        name: &str,
        port_interface: &T,
    ) -> Result<PRPortPrototype, AutosarAbstractionError> {
        let ports = self.element().get_or_create_sub_element(ElementName::Ports)?;
        PRPortPrototype::new(name, &ports, port_interface)
    }

    /// get an iterator over the ports of the component
    fn ports(&self) -> impl Iterator<Item = PortPrototype> {
        self.element()
            .get_sub_element(ElementName::Ports)
            .into_iter()
            .flat_map(|ports| ports.sub_elements())
            .filter_map(|elem| PortPrototype::try_from(elem).ok())
    }

    /// create a new port group
    fn create_port_group(&self, name: &str) -> Result<PortGroup, AutosarAbstractionError> {
        let port_groups = self.element().get_or_create_sub_element(ElementName::PortGroups)?;
        PortGroup::new(name, &port_groups)
    }
}

//##################################################################

/// A `CompositionSwComponentType` is a software component that contains other software components
///
/// Use [`ArPackage::create_composition_sw_component_type`] to create a new composition sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CompositionSwComponentType(Element);
abstraction_element!(CompositionSwComponentType, CompositionSwComponentType);

impl CompositionSwComponentType {
    /// create a new composition component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let composition = elements.create_named_sub_element(ElementName::CompositionSwComponentType, name)?;
        Ok(Self(composition))
    }

    /// check if the composition is a parent (or grand-parent, etc.) of the component
    pub fn is_parent_of<T: AbstractSwComponentType>(&self, other: &T) -> bool {
        // the expectation is that in normal cases each component has only one parent
        // additionally there should never be any cycles in the composition hierarchy
        let mut work_items = other.parent_compositions().collect::<Vec<_>>();
        let mut counter = 1000; // just to prevent infinite loops, since I don't trust files generated by other tools
        while !work_items.is_empty() && counter > 0 {
            counter -= 1;
            if work_items.contains(self) {
                return true;
            }
            // the uses of pop here makes this a depth-first search in the case where there are multiple parents
            let item = work_items.pop().unwrap();
            work_items.extend(item.parent_compositions());
        }

        false
    }

    /// create a component of type `component_type` in the composition
    ///
    /// It is not allowed to form cycles in the composition hierarchy, and this will return an error
    pub fn create_component<T: Into<SwComponentType> + Clone>(
        &self,
        name: &str,
        component_type: &T,
    ) -> Result<SwComponentPrototype, AutosarAbstractionError> {
        let component_type = component_type.clone().into();
        if let SwComponentType::Composition(composition_component) = &component_type {
            if composition_component.is_parent_of(self) {
                return Err(AutosarAbstractionError::InvalidParameter(
                    "Creating a cycle in the composition hierarchy".to_string(),
                ));
            }
        }

        let components = self.element().get_or_create_sub_element(ElementName::Components)?;
        SwComponentPrototype::new(name, &components, &component_type)
    }

    /// get an iterator over the components of the composition
    pub fn components(&self) -> impl Iterator<Item = SwComponentPrototype> {
        self.element()
            .get_sub_element(ElementName::Components)
            .into_iter()
            .flat_map(|components| components.sub_elements())
            .filter_map(|elem| SwComponentPrototype::try_from(elem).ok())
    }

    /// create a new delegation connector between an inner port and an outer port
    ///
    /// The two ports must be compatible.
    pub fn create_delegation_connector<T1: Into<PortPrototype> + Clone, T2: Into<PortPrototype> + Clone>(
        &self,
        name: &str,
        inner_port: &T1,
        inner_sw_prototype: &SwComponentPrototype,
        outer_port: &T2,
    ) -> Result<DelegationSwConnector, AutosarAbstractionError> {
        self.create_delegation_connector_internal(
            name,
            &inner_port.clone().into(),
            inner_sw_prototype,
            &outer_port.clone().into(),
        )
    }

    /// create a new delegation connector between an inner port and an outer port
    /// this is the actual implementation of the public method, but without the generic parameters
    fn create_delegation_connector_internal(
        &self,
        name: &str,
        inner_port: &PortPrototype,
        inner_sw_prototype: &SwComponentPrototype,
        outer_port: &PortPrototype,
    ) -> Result<DelegationSwConnector, AutosarAbstractionError> {
        // check the compatibility of the interfaces
        let interface_1 = inner_port.port_interface()?;
        let interface_2 = outer_port.port_interface()?;
        if std::mem::discriminant(&interface_1) != std::mem::discriminant(&interface_2) {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The interfaces of the two ports are not compatible".to_string(),
            ));
        }

        // check that the inner port is part of the inner component
        let inner_swc_from_port = SwComponentType::try_from(inner_port.element().named_parent()?.unwrap())?;
        let inner_swc_from_component =
            inner_sw_prototype
                .component_type()
                .ok_or(AutosarAbstractionError::InvalidParameter(
                    "The inner component is incomplete and lacks a type reference".to_string(),
                ))?;
        if inner_swc_from_port != inner_swc_from_component {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The inner port must be part of the inner component".to_string(),
            ));
        }

        let swc_self = self.clone().into();
        let outer_swc_from_port = SwComponentType::try_from(outer_port.element().named_parent()?.unwrap())?;
        if outer_swc_from_port != swc_self {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The outer port must be part of the composition".to_string(),
            ));
        }

        // create the delegation connector
        let connectors = self.element().get_or_create_sub_element(ElementName::Connectors)?;

        DelegationSwConnector::new(
            name,
            &connectors,
            inner_port, // inner port = port of the contained component
            inner_sw_prototype,
            outer_port, // outer port = port of the composition
        )
    }

    /// create a new assembly connector between two ports of contained software components
    ///
    /// The two ports must be compatible.
    pub fn create_assembly_connector<T1: Into<PortPrototype> + Clone, T2: Into<PortPrototype> + Clone>(
        &self,
        name: &str,
        port_1: &T1,
        sw_prototype_1: &SwComponentPrototype,
        port_2: &T2,
        sw_prototype_2: &SwComponentPrototype,
    ) -> Result<AssemblySwConnector, AutosarAbstractionError> {
        self.create_assembly_connector_internal(
            name,
            &port_1.clone().into(),
            sw_prototype_1,
            &port_2.clone().into(),
            sw_prototype_2,
        )
    }

    fn create_assembly_connector_internal(
        &self,
        name: &str,
        port_1: &PortPrototype,
        sw_prototype_1: &SwComponentPrototype,
        port_2: &PortPrototype,
        sw_prototype_2: &SwComponentPrototype,
    ) -> Result<AssemblySwConnector, AutosarAbstractionError> {
        // check the compatibility of the interfaces
        let interface_1 = port_1.port_interface()?;
        let interface_2 = port_2.port_interface()?;
        if std::mem::discriminant(&interface_1) != std::mem::discriminant(&interface_2) {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The interfaces of the two ports are not compatible".to_string(),
            ));
        }

        // check that the ports are part of the correct components
        let swc_1_from_port = SwComponentType::try_from(port_1.element().named_parent()?.unwrap())?;
        let swc_1_from_component = sw_prototype_1
            .component_type()
            .ok_or(AutosarAbstractionError::InvalidParameter(
                "SW component prototype 1 is incomplete and lacks a type reference".to_string(),
            ))?;
        if swc_1_from_port != swc_1_from_component {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The first port must be part of the first software component".to_string(),
            ));
        }

        let swc_2_from_port = SwComponentType::try_from(port_2.element().named_parent()?.unwrap())?;
        let swc_2_from_component = sw_prototype_2
            .component_type()
            .ok_or(AutosarAbstractionError::InvalidParameter(
                "SW component prototype 2 is incomplete and lacks a type reference".to_string(),
            ))?;
        if swc_2_from_port != swc_2_from_component {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The second port must be part of the second software component".to_string(),
            ));
        }

        // check that both SWCs are part of the composition
        if &sw_prototype_1.parent_composition()? != self {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The first software component must be part of the composition".to_string(),
            ));
        }
        if &sw_prototype_2.parent_composition()? != self {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The second software component must be part of the composition".to_string(),
            ));
        }

        // create the assembly connector
        let connectors = self.element().get_or_create_sub_element(ElementName::Connectors)?;
        AssemblySwConnector::new(name, &connectors, port_1, sw_prototype_1, port_2, sw_prototype_2)
    }

    /// create a new passthrough connector between two outer ports of the composition
    ///
    /// The two ports must be compatible.
    pub fn create_pass_through_connector<T1: Into<PortPrototype> + Clone, T2: Into<PortPrototype> + Clone>(
        &self,
        name: &str,
        port_1: &T1,
        port_2: &T2,
    ) -> Result<PassThroughSwConnector, AutosarAbstractionError> {
        self.create_pass_through_connector_internal(name, &port_1.clone().into(), &port_2.clone().into())
    }

    fn create_pass_through_connector_internal(
        &self,
        name: &str,
        port_1: &PortPrototype,
        port_2: &PortPrototype,
    ) -> Result<PassThroughSwConnector, AutosarAbstractionError> {
        // check the compatibility of the interfaces
        let interface_1 = port_1.port_interface()?;
        let interface_2 = port_2.port_interface()?;
        if std::mem::discriminant(&interface_1) != std::mem::discriminant(&interface_2) {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The interfaces of the two ports are not compatible".to_string(),
            ));
        }

        // decide what kind of connector to create
        let swc_1 = SwComponentType::try_from(port_1.element().named_parent()?.unwrap())?;
        let swc_2 = SwComponentType::try_from(port_2.element().named_parent()?.unwrap())?;
        let swc_self = self.clone().into();

        // both ports must be part of the composition
        if swc_1 != swc_self || swc_2 != swc_self {
            return Err(AutosarAbstractionError::InvalidParameter(
                "The ports must be part of the composition".to_string(),
            ));
        }

        let connectors = self.element().get_or_create_sub_element(ElementName::Connectors)?;
        PassThroughSwConnector::new(name, &connectors, port_1, port_2)
    }

    /// iterate over all connectors
    pub fn connectors(&self) -> impl Iterator<Item = SwConnector> {
        self.element()
            .get_sub_element(ElementName::Connectors)
            .into_iter()
            .flat_map(|connectors| connectors.sub_elements())
            .filter_map(|elem| SwConnector::try_from(elem).ok())
    }
}

impl AbstractSwComponentType for CompositionSwComponentType {
    /// add a data type mapping, by referencing an existing `DataTypeMappingSet`
    fn add_data_type_mapping(&self, data_type_mapping_set: &DataTypeMappingSet) -> Result<(), AutosarAbstractionError> {
        let data_type_mapping_refs = self
            .element()
            .get_or_create_sub_element(ElementName::DataTypeMappingRefs)?;
        data_type_mapping_refs
            .create_sub_element(ElementName::DataTypeMappingRef)?
            .set_reference_target(data_type_mapping_set.element())?;
        Ok(())
    }
}

//##################################################################

/// An `ApplicationSwComponentType` is a software component that provides application functionality
///
/// Use [`ArPackage::create_application_sw_component_type`] to create a new application sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ApplicationSwComponentType(Element);
abstraction_element!(ApplicationSwComponentType, ApplicationSwComponentType);

impl ApplicationSwComponentType {
    /// create a new application component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let application = elements.create_named_sub_element(ElementName::ApplicationSwComponentType, name)?;
        Ok(Self(application))
    }
}

impl AbstractSwComponentType for ApplicationSwComponentType {}

//##################################################################

/// A `ComplexDeviceDriverSwComponentType` is a software component that provides complex device driver functionality
///
/// Use [`ArPackage::create_complex_device_driver_sw_component_type`] to create a new complex device driver sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ComplexDeviceDriverSwComponentType(Element);
abstraction_element!(ComplexDeviceDriverSwComponentType, ComplexDeviceDriverSwComponentType);

impl ComplexDeviceDriverSwComponentType {
    /// create a new complex device driver component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let cdd = elements.create_named_sub_element(ElementName::ComplexDeviceDriverSwComponentType, name)?;
        Ok(Self(cdd))
    }
}

impl AbstractSwComponentType for ComplexDeviceDriverSwComponentType {}

//##################################################################

/// `ServiceSwComponentType` is used for configuring services for a given ECU. Instances of this class should only
/// be created in ECU Configuration phase for the specific purpose of the service configuration.
///
/// Use [`ArPackage::create_service_sw_component_type`] to create a new service sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServiceSwComponentType(Element);
abstraction_element!(ServiceSwComponentType, ServiceSwComponentType);

impl ServiceSwComponentType {
    /// create a new service component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let service = elements.create_named_sub_element(ElementName::ServiceSwComponentType, name)?;
        Ok(Self(service))
    }
}

impl AbstractSwComponentType for ServiceSwComponentType {}

//##################################################################

/// `SensorActuatorSwComponentType` is used to connect sensor/acutator devices to the ECU configuration
///
/// Use [`ArPackage::create_sensor_actuator_sw_component_type`] to create a new sensor/actuator sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SensorActuatorSwComponentType(Element);
abstraction_element!(SensorActuatorSwComponentType, SensorActuatorSwComponentType);

impl SensorActuatorSwComponentType {
    /// create a new sensor/actuator component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let sensor_actuator = elements.create_named_sub_element(ElementName::SensorActuatorSwComponentType, name)?;
        Ok(Self(sensor_actuator))
    }
}

impl AbstractSwComponentType for SensorActuatorSwComponentType {}

//##################################################################

/// The `ECUAbstraction` is a special `AtomicSwComponentType` that resides between a software-component
/// that wants to access ECU periphery and the Microcontroller Abstraction
///
/// Use [`ArPackage::create_ecu_abstraction_sw_component_type`] to create a new ECU abstraction sw component type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EcuAbstractionSwComponentType(Element);
abstraction_element!(EcuAbstractionSwComponentType, EcuAbstractionSwComponentType);

impl EcuAbstractionSwComponentType {
    /// create a new ECU abstraction component with the given name
    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
        let ecu_abstraction = elements.create_named_sub_element(ElementName::EcuAbstractionSwComponentType, name)?;
        Ok(Self(ecu_abstraction))
    }
}

impl AbstractSwComponentType for EcuAbstractionSwComponentType {}

//##################################################################

/// The `SwComponentType` enum represents all possible types of software components
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SwComponentType {
    /// the component is `CompositionSwComponentType`
    Composition(CompositionSwComponentType),
    /// the component is `ApplicationSwComponentType`
    Application(ApplicationSwComponentType),
    /// the component is `ComplexDeviceDriverSwComponentType`
    ComplexDeviceDriver(ComplexDeviceDriverSwComponentType),
    /// the component is `ServiceSwComponentType`
    Service(ServiceSwComponentType),
    /// the component is `SensorActuatorSwComponentType`
    SensorActuator(SensorActuatorSwComponentType),
    /// the component is `EcuAbstractionSwComponentType`
    EcuAbstraction(EcuAbstractionSwComponentType),
}

impl AbstractionElement for SwComponentType {
    fn element(&self) -> &Element {
        match self {
            SwComponentType::Composition(comp) => comp.element(),
            SwComponentType::Application(app) => app.element(),
            SwComponentType::ComplexDeviceDriver(cdd) => cdd.element(),
            SwComponentType::Service(service) => service.element(),
            SwComponentType::SensorActuator(sensor_actuator) => sensor_actuator.element(),
            SwComponentType::EcuAbstraction(ecu_abstraction) => ecu_abstraction.element(),
        }
    }
}

impl TryFrom<Element> for SwComponentType {
    type Error = AutosarAbstractionError;

    fn try_from(element: Element) -> Result<Self, Self::Error> {
        match element.element_name() {
            ElementName::CompositionSwComponentType => {
                Ok(SwComponentType::Composition(CompositionSwComponentType(element)))
            }
            ElementName::ApplicationSwComponentType => {
                Ok(SwComponentType::Application(ApplicationSwComponentType(element)))
            }
            ElementName::ComplexDeviceDriverSwComponentType => Ok(SwComponentType::ComplexDeviceDriver(
                ComplexDeviceDriverSwComponentType(element),
            )),
            ElementName::ServiceSwComponentType => Ok(SwComponentType::Service(ServiceSwComponentType(element))),
            ElementName::SensorActuatorSwComponentType => {
                Ok(SwComponentType::SensorActuator(SensorActuatorSwComponentType(element)))
            }
            ElementName::EcuAbstractionSwComponentType => {
                Ok(SwComponentType::EcuAbstraction(EcuAbstractionSwComponentType(element)))
            }
            _ => Err(AutosarAbstractionError::ConversionError {
                element,
                dest: "SwComponentType".to_string(),
            }),
        }
    }
}

impl From<CompositionSwComponentType> for SwComponentType {
    fn from(comp: CompositionSwComponentType) -> Self {
        SwComponentType::Composition(comp)
    }
}

impl From<ApplicationSwComponentType> for SwComponentType {
    fn from(app: ApplicationSwComponentType) -> Self {
        SwComponentType::Application(app)
    }
}

impl From<ComplexDeviceDriverSwComponentType> for SwComponentType {
    fn from(cdd: ComplexDeviceDriverSwComponentType) -> Self {
        SwComponentType::ComplexDeviceDriver(cdd)
    }
}

impl From<ServiceSwComponentType> for SwComponentType {
    fn from(service: ServiceSwComponentType) -> Self {
        SwComponentType::Service(service)
    }
}

impl From<SensorActuatorSwComponentType> for SwComponentType {
    fn from(sensor_actuator: SensorActuatorSwComponentType) -> Self {
        SwComponentType::SensorActuator(sensor_actuator)
    }
}

impl From<EcuAbstractionSwComponentType> for SwComponentType {
    fn from(ecu_abstraction: EcuAbstractionSwComponentType) -> Self {
        SwComponentType::EcuAbstraction(ecu_abstraction)
    }
}

impl AbstractSwComponentType for SwComponentType {
    fn add_data_type_mapping(&self, data_type_mapping_set: &DataTypeMappingSet) -> Result<(), AutosarAbstractionError> {
        match self {
            SwComponentType::Composition(comp) => comp.add_data_type_mapping(data_type_mapping_set),
            SwComponentType::Application(app) => app.add_data_type_mapping(data_type_mapping_set),
            SwComponentType::ComplexDeviceDriver(cdd) => cdd.add_data_type_mapping(data_type_mapping_set),
            SwComponentType::Service(service) => service.add_data_type_mapping(data_type_mapping_set),
            SwComponentType::SensorActuator(sensor_actuator) => {
                sensor_actuator.add_data_type_mapping(data_type_mapping_set)
            }
            SwComponentType::EcuAbstraction(ecu_abstraction) => {
                ecu_abstraction.add_data_type_mapping(data_type_mapping_set)
            }
        }
    }
}

//##################################################################

/// A `SwComponentPrototype` is an instance of a software component type
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SwComponentPrototype(Element);
abstraction_element!(SwComponentPrototype, SwComponentPrototype);

impl SwComponentPrototype {
    fn new(
        name: &str,
        components: &Element,
        component_type: &SwComponentType,
    ) -> Result<Self, AutosarAbstractionError> {
        let component = components.create_named_sub_element(ElementName::SwComponentPrototype, name)?;
        component
            .create_sub_element(ElementName::TypeTref)?
            .set_reference_target(component_type.element())?;

        Ok(Self(component))
    }

    /// get the sw component type that this prototype is based on
    #[must_use]
    pub fn component_type(&self) -> Option<SwComponentType> {
        let component_elem = self
            .element()
            .get_sub_element(ElementName::TypeTref)?
            .get_reference_target()
            .ok()?;
        SwComponentType::try_from(component_elem).ok()
    }

    /// get the composition containing this component
    pub fn parent_composition(&self) -> Result<CompositionSwComponentType, AutosarAbstractionError> {
        let parent = self.element().named_parent()?.unwrap();
        CompositionSwComponentType::try_from(parent)
    }
}

//##################################################################

/// The `RootSwCompositionPrototype` is a special kind of `SwComponentPrototype` that represents the root of the composition hierarchy
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RootSwCompositionPrototype(Element);
abstraction_element!(RootSwCompositionPrototype, RootSwCompositionPrototype);

impl RootSwCompositionPrototype {
    pub(crate) fn new(
        name: &str,
        root_compositions: &Element,
        composition_type: &CompositionSwComponentType,
    ) -> Result<Self, AutosarAbstractionError> {
        let root_composition =
            root_compositions.create_named_sub_element(ElementName::RootSwCompositionPrototype, name)?;
        root_composition
            .create_sub_element(ElementName::SoftwareCompositionTref)?
            .set_reference_target(composition_type.element())?;

        Ok(Self(root_composition))
    }

    /// get the composition that this root component is based on
    #[must_use]
    pub fn composition(&self) -> Option<CompositionSwComponentType> {
        let composition_elem = self
            .element()
            .get_sub_element(ElementName::SoftwareCompositionTref)?
            .get_reference_target()
            .ok()?;
        CompositionSwComponentType::try_from(composition_elem).ok()
    }
}

//##################################################################

/// The `ComponentPrototype` enum represents all possible types of software component prototypes
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ComponentPrototype {
    /// the component prototype is a `SwComponentPrototype`
    SwComponent(SwComponentPrototype),
    /// the component prototype is a `RootSwCompositionPrototype`
    RootComposition(RootSwCompositionPrototype),
}

impl AbstractionElement for ComponentPrototype {
    fn element(&self) -> &Element {
        match self {
            ComponentPrototype::SwComponent(swcp) => swcp.element(),
            ComponentPrototype::RootComposition(root) => root.element(),
        }
    }
}

impl TryFrom<Element> for ComponentPrototype {
    type Error = AutosarAbstractionError;

    fn try_from(element: Element) -> Result<Self, Self::Error> {
        match element.element_name() {
            ElementName::SwComponentPrototype => Ok(ComponentPrototype::SwComponent(SwComponentPrototype(element))),
            ElementName::RootSwCompositionPrototype => {
                Ok(ComponentPrototype::RootComposition(RootSwCompositionPrototype(element)))
            }
            _ => Err(AutosarAbstractionError::ConversionError {
                element,
                dest: "ComponentPrototype".to_string(),
            }),
        }
    }
}

impl ComponentPrototype {
    #[must_use]
    /// get the sw component type that this prototype is based on
    pub fn component_type(&self) -> Option<SwComponentType> {
        match self {
            ComponentPrototype::SwComponent(swcp) => swcp.component_type(),
            ComponentPrototype::RootComposition(rc) => rc.composition().map(std::convert::Into::into),
        }
    }

    /// get the composition containing this component
    ///
    /// if the component is a root composition, this will always return None
    pub fn parent_composition(&self) -> Result<Option<CompositionSwComponentType>, AutosarAbstractionError> {
        match self {
            ComponentPrototype::SwComponent(swcp) => swcp.parent_composition().map(Some),
            ComponentPrototype::RootComposition(_) => Ok(None),
        }
    }
}

//##################################################################

reflist_iterator!(ComponentPrototypeIterator, ComponentPrototype);

//##################################################################

#[cfg(test)]
mod test {
    use super::*;
    use crate::SystemCategory;
    use autosar_data::{AutosarModel, AutosarVersion};

    #[test]
    fn software_compositions() {
        let model = AutosarModel::new();
        let _file = model.create_file("filename", AutosarVersion::LATEST).unwrap();
        let package = ArPackage::get_or_create(&model, "/package").unwrap();

        let comp1 = CompositionSwComponentType::new("comp1", &package).unwrap();
        let comp2 = CompositionSwComponentType::new("comp2", &package).unwrap();
        let comp3 = CompositionSwComponentType::new("comp3", &package).unwrap();
        let comp4 = CompositionSwComponentType::new("comp4", &package).unwrap();

        comp1.create_component("comp2", &comp2.clone()).unwrap();
        comp2.create_component("comp3", &comp3.clone()).unwrap();
        comp3.create_component("comp4", &comp4.clone()).unwrap();

        assert_eq!(comp1.instances().count(), 0);
        assert_eq!(comp2.instances().count(), 1);
        assert_eq!(comp3.instances().count(), 1);
        assert_eq!(comp4.instances().count(), 1);

        assert!(comp1.is_parent_of(&comp2));
        assert!(comp1.is_parent_of(&comp3));
        assert!(comp1.is_parent_of(&comp4));

        assert!(!comp2.is_parent_of(&comp1));
        assert!(comp2.is_parent_of(&comp3));
        assert!(comp2.is_parent_of(&comp4));

        assert!(!comp3.is_parent_of(&comp1));
        assert!(!comp3.is_parent_of(&comp2));
        assert!(comp3.is_parent_of(&comp4));

        assert!(!comp4.is_parent_of(&comp1));
        assert!(!comp4.is_parent_of(&comp2));
        assert!(!comp4.is_parent_of(&comp3));
    }

    #[test]
    fn root_composition() {
        let model = AutosarModel::new();
        let _file = model.create_file("filename", AutosarVersion::LATEST).unwrap();
        let package = ArPackage::get_or_create(&model, "/package").unwrap();

        let system = package.create_system("system", SystemCategory::EcuExtract).unwrap();
        let comp = CompositionSwComponentType::new("comp", &package).unwrap();
        let root_sw_component_prototype = system.set_root_sw_composition("root", &comp).unwrap();

        assert_eq!(
            ComponentPrototype::RootComposition(root_sw_component_prototype),
            comp.instances().next().unwrap()
        );
        assert_eq!(comp.instances().count(), 1);
    }

    #[test]
    fn data_type_mapping() {
        let model = AutosarModel::new();
        let _file = model.create_file("filename", AutosarVersion::LATEST).unwrap();
        let package = ArPackage::get_or_create(&model, "/package").unwrap();

        let mapping_set = DataTypeMappingSet::new("mapping_set", &package).unwrap();
        let composition = CompositionSwComponentType::new("comp", &package).unwrap();
        composition.add_data_type_mapping(&mapping_set).unwrap();

        let app = ApplicationSwComponentType::new("app", &package).unwrap();
        app.add_data_type_mapping(&mapping_set).unwrap();

        let cdd = ComplexDeviceDriverSwComponentType::new("cdd", &package).unwrap();
        cdd.add_data_type_mapping(&mapping_set).unwrap();

        let service = ServiceSwComponentType::new("service", &package).unwrap();
        service.add_data_type_mapping(&mapping_set).unwrap();

        let sensor_actuator = SensorActuatorSwComponentType::new("sensor_actuator", &package).unwrap();
        sensor_actuator.add_data_type_mapping(&mapping_set).unwrap();

        let ecu_abstraction = EcuAbstractionSwComponentType::new("ecu_abstraction", &package).unwrap();
        ecu_abstraction.add_data_type_mapping(&mapping_set).unwrap();

        let sw_component_type = SwComponentType::Composition(composition);
        sw_component_type.add_data_type_mapping(&mapping_set).unwrap();
    }

    #[test]
    fn components() {
        let model = AutosarModel::new();
        let _file = model.create_file("filename", AutosarVersion::LATEST).unwrap();
        let package = ArPackage::get_or_create(&model, "/package").unwrap();

        let comp = CompositionSwComponentType::new("comp", &package).unwrap();
        let app = ApplicationSwComponentType::new("app", &package).unwrap();
        let cdd = ComplexDeviceDriverSwComponentType::new("cdd", &package).unwrap();
        let service = ServiceSwComponentType::new("service", &package).unwrap();
        let sensor_actuator = SensorActuatorSwComponentType::new("sensor_actuator", &package).unwrap();
        let ecu_abstraction = EcuAbstractionSwComponentType::new("ecu_abstraction", &package).unwrap();

        let container_comp = CompositionSwComponentType::new("container_comp", &package).unwrap();
        let comp_prototype = container_comp.create_component("comp", &comp.clone()).unwrap();
        let _app_prototype = container_comp.create_component("app", &app.clone()).unwrap();
        let _cdd_prototype = container_comp.create_component("cdd", &cdd.clone()).unwrap();
        let _service_prototype = container_comp.create_component("service", &service.clone()).unwrap();
        let _sensor_actuator_prototype = container_comp
            .create_component("sensor_actuator", &sensor_actuator.clone())
            .unwrap();
        let _ecu_abstraction_prototype = container_comp
            .create_component("ecu_abstraction", &ecu_abstraction.clone())
            .unwrap();

        assert_eq!(container_comp.components().count(), 6);
        let mut comp_prototype_iter = container_comp.components();
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            comp.clone().into()
        );
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            app.into()
        );
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            cdd.into()
        );
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            service.into()
        );
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            sensor_actuator.into()
        );
        assert_eq!(
            comp_prototype_iter.next().unwrap().component_type().unwrap(),
            ecu_abstraction.into()
        );
        assert!(comp_prototype_iter.next().is_none());

        let component_prototype = ComponentPrototype::SwComponent(comp_prototype);
        assert_eq!(component_prototype.component_type().unwrap(), comp.into());
    }

    #[test]
    fn ports_and_connectors() {
        let model = AutosarModel::new();
        let _file = model.create_file("filename", AutosarVersion::LATEST).unwrap();
        let package = ArPackage::get_or_create(&model, "/package").unwrap();

        // create some components:
        // comp_parent contains comp_child, swc1, swc2
        let comp_parent_type = package.create_composition_sw_component_type("comp_parent").unwrap();
        let comp_child_type = package.create_composition_sw_component_type("comp_child").unwrap();
        let swc_type = package.create_application_sw_component_type("swc_type1").unwrap();

        let comp_child_proto = comp_parent_type.create_component("comp2", &comp_child_type).unwrap();
        let swc_proto = comp_parent_type.create_component("swc1", &swc_type).unwrap();

        // create port interfaces: S/R and C/S
        let port_interface_sr = package.create_sender_receiver_interface("sr").unwrap();
        let port_interface_cs = package.create_client_server_interface("cs").unwrap();

        // connect S/R ports:
        // - comp_parent R port to swc R port (delegation)
        // - swc P port to comp_child R port (assembly)
        // - comp_child R port to comp_child p port (passthrough)
        let comp_parent_r_port = comp_parent_type.create_r_port("port_r", &port_interface_sr).unwrap();
        let swc_r_port = swc_type.create_r_port("port_r", &port_interface_sr).unwrap();
        let swc_p_port = swc_type.create_p_port("port_p", &port_interface_sr).unwrap();
        let comp_child_r_port = comp_child_type.create_r_port("port_r", &port_interface_sr).unwrap();
        let comp_child_p_port = comp_child_type.create_p_port("port_p", &port_interface_sr).unwrap();

        comp_parent_type
            .create_delegation_connector("sr_delegation", &swc_r_port, &swc_proto, &comp_parent_r_port)
            .unwrap();
        comp_parent_type
            .create_assembly_connector(
                "sr_assembly",
                &swc_p_port,
                &swc_proto,
                &comp_child_r_port,
                &comp_child_proto,
            )
            .unwrap();
        comp_child_type
            .create_pass_through_connector("sr_passthrough", &comp_child_r_port, &comp_child_p_port)
            .unwrap();

        // connect C/S ports:
        // - comp_parent S port to swc S port (delegation)
        // - swc C port to comp_child S port (assembly)
        // - comp_child S port to comp_child C port (passthrough)
        let comp_parent_s_port = comp_parent_type.create_p_port("port_s", &port_interface_cs).unwrap();
        let swc_s_port = swc_type.create_p_port("port_s", &port_interface_cs).unwrap();
        let swc_c_port = swc_type.create_r_port("port_c", &port_interface_cs).unwrap();
        let comp_child_s_port = comp_child_type.create_p_port("port_s", &port_interface_cs).unwrap();
        let comp_child_c_port = comp_child_type.create_r_port("port_c", &port_interface_cs).unwrap();

        comp_parent_type
            .create_delegation_connector("cs_delegation", &swc_s_port, &swc_proto, &comp_parent_s_port)
            .unwrap();
        comp_parent_type
            .create_assembly_connector(
                "cs_assembly",
                &swc_c_port,
                &swc_proto,
                &comp_child_s_port,
                &comp_child_proto,
            )
            .unwrap();
        comp_child_type
            .create_pass_through_connector("cs_passthrough", &comp_child_s_port, &comp_child_c_port)
            .unwrap();

        // check the connectors
        let mut parent_connectors = comp_parent_type.connectors();
        assert_eq!(parent_connectors.next().unwrap().name().unwrap(), "sr_delegation");
        assert_eq!(parent_connectors.next().unwrap().name().unwrap(), "sr_assembly");
        assert_eq!(parent_connectors.next().unwrap().name().unwrap(), "cs_delegation");
        assert_eq!(parent_connectors.next().unwrap().name().unwrap(), "cs_assembly");
        assert!(parent_connectors.next().is_none());

        let mut child_connectors = comp_child_type.connectors();
        assert_eq!(child_connectors.next().unwrap().name().unwrap(), "sr_passthrough");
        assert_eq!(child_connectors.next().unwrap().name().unwrap(), "cs_passthrough");
        assert!(child_connectors.next().is_none());

        // create a port group
        comp_parent_type.create_port_group("group").unwrap();
    }
}