melodium-engine 0.10.0

Mélodium core engine and executor implementation
Documentation
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
use super::{
    Connection, GenericInstanciation, ModelInstanciation, Reference, Scope, TreatmentInstanciation,
    IO,
};
use crate::descriptor::Treatment as TreatmentDescriptor;
use crate::design::{
    Connection as ConnectionDesign, ModelInstanciation as ModelInstanciationDesign,
    Parameter as ParameterDesign, Treatment as TreatmentDesign,
    TreatmentInstanciation as TreatmentInstanciationDesign, IO as IODesign,
};
use crate::error::{LogicError, LogicResult};
use core::fmt::Debug;
use melodium_common::descriptor::{
    Attribuable, Attributes, Collection, DescribedType, Entry, Generics, Identified, Identifier,
    IdentifierRequirement, Parameterized, Treatment as TreatmentTrait,
};
use std::collections::HashMap;
use std::sync::{Arc, RwLock, RwLockReadGuard, Weak};

#[derive(Debug)]
pub struct Treatment {
    collection: Arc<Collection>,
    descriptor: Weak<TreatmentDescriptor>,

    generics: Arc<RwLock<HashMap<String, DescribedType>>>,
    model_instanciations: HashMap<String, Arc<RwLock<ModelInstanciation>>>,
    treatments: HashMap<String, Arc<RwLock<TreatmentInstanciation>>>,
    connections: Vec<Connection>,

    design_reference: Option<Arc<dyn Reference>>,

    auto_reference: Weak<RwLock<Self>>,
}

impl Treatment {
    pub fn new(
        descriptor: &Arc<TreatmentDescriptor>,
        collection: Arc<Collection>,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> Arc<RwLock<Self>> {
        Arc::<RwLock<Self>>::new_cyclic(|me| {
            RwLock::new(Self {
                descriptor: Arc::downgrade(descriptor),
                collection,
                generics: Arc::new(RwLock::new(
                    // This is required to satisfy type/generics comparison for inner instanciantions.
                    descriptor
                        .generics()
                        .iter()
                        .map(|generic| {
                            (
                                generic.name.clone(),
                                DescribedType::Generic(Box::new(generic.clone())),
                            )
                        })
                        .collect(),
                )),
                model_instanciations: HashMap::new(),
                treatments: HashMap::new(),
                connections: Vec::new(),
                design_reference,
                auto_reference: me.clone(),
            })
        })
    }

    pub fn collection(&self) -> &Arc<Collection> {
        &self.collection
    }

    pub fn descriptor(&self) -> Arc<TreatmentDescriptor> {
        self.descriptor.upgrade().unwrap()
    }

    pub fn design_reference(&self) -> &Option<Arc<dyn Reference>> {
        &self.design_reference
    }

    pub fn import_design(
        &mut self,
        design: &TreatmentDesign,
        replace: &HashMap<Identifier, Identifier>,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        for (name, model_instanciation_design) in &design.model_instanciations {
            let model_identifier = model_instanciation_design
                .descriptor
                .upgrade()
                .unwrap()
                .identifier()
                .clone();
            let model_identifier = replace.get(&model_identifier).unwrap_or(&model_identifier);
            if let Some(model_instanciation) =
                result.merge_degrade_failure(self.add_model_instanciation(
                    &model_identifier.into(),
                    name,
                    design_reference.clone(),
                ))
            {
                result.merge_degrade_failure(model_instanciation.write().unwrap().import_design(
                    model_instanciation_design,
                    &self.collection,
                    replace,
                ));
            }
        }

        for (name, treatment_instanciation_design) in &design.treatments {
            let treatment_identifier = treatment_instanciation_design
                .descriptor
                .upgrade()
                .unwrap()
                .identifier()
                .clone();
            let treatment_identifier = replace
                .get(&treatment_identifier)
                .unwrap_or(&treatment_identifier);
            if let Some(treatment_instanciation) = result.merge_degrade_failure(self.add_treatment(
                &treatment_identifier.into(),
                name,
                design_reference.clone(),
            )) {
                result.merge_degrade_failure(
                    treatment_instanciation.write().unwrap().import_design(
                        treatment_instanciation_design,
                        &self.collection,
                        replace,
                    ),
                );
            }
        }

        for connection in &design.connections {
            match (&connection.output_treatment, &connection.input_treatment) {
                (IODesign::Sequence(), IODesign::Sequence()) => {
                    result.merge_degrade_failure(self.add_self_connection(
                        &connection.output_name,
                        &connection.input_name,
                        connection.attributes().clone(),
                        design_reference.clone(),
                    ))
                }
                (IODesign::Sequence(), IODesign::Treatment(input_treatment)) => result
                    .merge_degrade_failure(self.add_input_connection(
                        &connection.output_name,
                        input_treatment,
                        &connection.input_name,
                        connection.attributes().clone(),
                        design_reference.clone(),
                    )),
                (IODesign::Treatment(output_treatment), IODesign::Sequence()) => result
                    .merge_degrade_failure(self.add_output_connection(
                        &connection.input_name,
                        output_treatment,
                        &connection.output_name,
                        connection.attributes().clone(),
                        design_reference.clone(),
                    )),
                (IODesign::Treatment(output_treatment), IODesign::Treatment(input_treatment)) => {
                    result.merge_degrade_failure(self.add_connection(
                        output_treatment,
                        &connection.output_name,
                        input_treatment,
                        &connection.input_name,
                        connection.attributes().clone(),
                        design_reference.clone(),
                    ))
                }
            };
        }

        result
    }

    pub fn add_model_instanciation(
        &mut self,
        model_identifier: &IdentifierRequirement,
        name: &str,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<Arc<RwLock<ModelInstanciation>>> {
        if self.model_instanciations.contains_key(name) {
            return Err(LogicError::already_declared_model(
                209,
                self.descriptor().identifier().clone(),
                name.to_string(),
                design_reference.clone(),
            ))
            .into();
        }
        if let Some(Entry::Model(model_descriptor)) = self.collection.get(model_identifier) {
            let model = ModelInstanciation::new(
                &(self.descriptor() as Arc<dyn TreatmentTrait>),
                &self.auto_reference.upgrade().unwrap(),
                self.identifier(),
                model_descriptor,
                name,
                design_reference.clone(),
            );
            self.model_instanciations
                .insert(name.to_string(), Arc::clone(&model));
            Ok(model).into()
        } else {
            Err(LogicError::unexisting_model(
                41,
                self.descriptor().identifier().clone(),
                model_identifier.clone(),
                design_reference.clone(),
            ))
            .into()
        }
    }

    pub fn rename_model_instanciation(
        &mut self,
        actual_name: &str,
        new_name: &str,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());
        if self.model_instanciations.contains_key(new_name) {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::already_declared_model(
                    211,
                    self.descriptor().identifier().clone(),
                    new_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }
        if let Some(model_instanciation) = self.model_instanciations.remove(actual_name) {
            model_instanciation
                .write()
                .unwrap()
                .set_name(new_name.to_string());
            self.model_instanciations
                .insert(new_name.to_string(), model_instanciation);

            for (_, treatment) in &self.treatments {
                let mut treatment = treatment.write().unwrap();
                let to_replace = treatment
                    .models()
                    .iter()
                    .filter_map(|(parametric_name, local_name)| {
                        if local_name == actual_name {
                            Some(parametric_name.clone())
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>();
                for name in to_replace {
                    let _ = treatment.add_model(&name, new_name);
                }
            }
            result
        } else {
            result.and_degrade_failure(LogicResult::new_failure(LogicError::undeclared_model(
                212,
                self.descriptor().identifier().clone(),
                actual_name.to_string(),
                design_reference.clone(),
            )))
        }
    }

    pub fn remove_model_instanciation(&mut self, name: &str) -> LogicResult<bool> {
        Ok(if let Some(_) = self.model_instanciations.remove(name) {
            for (_, treatment) in &self.treatments {
                let mut treatment = treatment.write().unwrap();
                let to_remove = treatment
                    .models()
                    .iter()
                    .filter_map(|(parametric_name, local_name)| {
                        if local_name == name {
                            Some(parametric_name.clone())
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>();
                for name in to_remove {
                    let _ = treatment.remove_model(&name);
                }
            }

            true
        } else {
            false
        })
        .into()
    }

    pub fn add_treatment(
        &mut self,
        treatment_identifier: &IdentifierRequirement,
        name: &str,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<Arc<RwLock<TreatmentInstanciation>>> {
        if self.treatments.contains_key(name) {
            return Err(LogicError::already_declared_treatment(
                210,
                self.descriptor().identifier().clone(),
                name.to_string(),
                design_reference.clone(),
            ))
            .into();
        }
        if let Some(Entry::Treatment(treatment_descriptor)) =
            self.collection.get(treatment_identifier)
        {
            let rc_treatment = TreatmentInstanciation::new(
                &(self.descriptor() as Arc<dyn TreatmentTrait>),
                &self.auto_reference.upgrade().unwrap(),
                &self.generics,
                self.identifier(),
                &treatment_descriptor,
                name,
                design_reference.clone(),
            );
            self.treatments
                .insert(name.to_string(), Arc::clone(&rc_treatment));
            Ok(rc_treatment).into()
        } else {
            Err(LogicError::unexisting_treatment(
                40,
                self.descriptor().identifier().clone(),
                treatment_identifier.clone(),
                design_reference.clone(),
            ))
            .into()
        }
    }

    pub fn rename_treatment(
        &mut self,
        actual_name: &str,
        new_name: &str,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());
        if self.treatments.contains_key(new_name) {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::already_declared_treatment(
                    212,
                    self.descriptor().identifier().clone(),
                    new_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }
        if let Some(treatment) = self.treatments.remove(actual_name) {
            treatment.write().unwrap().set_name(new_name.to_string());
            self.treatments.insert(new_name.to_string(), treatment);

            result
        } else {
            result.and_degrade_failure(LogicResult::new_failure(LogicError::undeclared_treatment(
                213,
                self.descriptor().identifier().clone(),
                actual_name.to_string(),
                design_reference.clone(),
            )))
        }
    }

    pub fn remove_treatment(&mut self, name: &str) -> LogicResult<bool> {
        Ok(if let Some(ref treatment) = self.treatments.remove(name) {
            self.connections.retain(|conn| {
                let mut result = true;
                if let IO::Treatment(input_treatment) = &conn.input_treatment {
                    result &= !input_treatment.ptr_eq(&Arc::downgrade(treatment));
                }
                if let IO::Treatment(output_treatment) = &conn.output_treatment {
                    result &= !output_treatment.ptr_eq(&Arc::downgrade(treatment));
                }

                result
            });

            true
        } else {
            false
        })
        .into()
    }

    pub fn add_connection(
        &mut self,
        output_treatment: &str,
        output_name: &str,
        input_treatment: &str,
        input_name: &str,
        attributes: Attributes,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        let mut rc_output_treatment = None;
        let mut output = None;
        let mut output_treatment_generics = None;
        if let Some(pos_rc_output_treatment) = self.treatments.get(output_treatment) {
            rc_output_treatment = Some(pos_rc_output_treatment);

            let output_treatment = pos_rc_output_treatment.read().unwrap();
            let output_treatment_descriptor = output_treatment.descriptor();
            output_treatment_generics = Some(Arc::clone(output_treatment.access_generics()));

            if let Some(pos_output) = output_treatment_descriptor.outputs().get(output_name) {
                output = Some(pos_output.clone());
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::connection_output_not_found(
                        36,
                        self.descriptor().identifier().clone(),
                        output_treatment_descriptor.identifier().clone(),
                        output_name.to_string(),
                        design_reference.clone(),
                    ),
                ));
            }
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::undeclared_treatment(
                    43,
                    self.descriptor().identifier().clone(),
                    output_treatment.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        let mut rc_input_treatment = None;
        let mut input = None;
        let mut input_treatment_generics = None;
        if let Some(pos_rc_input_treatment) = self.treatments.get(input_treatment) {
            rc_input_treatment = Some(pos_rc_input_treatment);

            let input_treatment = pos_rc_input_treatment.read().unwrap();
            let input_treatment_descriptor = input_treatment.descriptor();
            input_treatment_generics = Some(Arc::clone(input_treatment.access_generics()));

            if let Some(pos_input) = input_treatment_descriptor.inputs().get(input_name) {
                input = Some(pos_input.clone());
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::connection_input_not_found(
                        32,
                        self.descriptor().identifier().clone(),
                        input_treatment_descriptor.identifier().clone(),
                        input_name.to_string(),
                        design_reference.clone(),
                    ),
                ));
            }
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::undeclared_treatment(
                    44,
                    self.descriptor().identifier().clone(),
                    input_treatment.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        if let (Some(rc_output_treatment), Some(output), Some(rc_input_treatment), Some(input)) =
            (rc_output_treatment, output, rc_input_treatment, input)
        {
            if input.matches_output(
                &input_treatment_generics.unwrap().read().unwrap(),
                &output,
                &output_treatment_generics.unwrap().read().unwrap(),
            ) {
                self.connections.push(Connection::new_internal(
                    output_name,
                    rc_output_treatment,
                    input_name,
                    rc_input_treatment,
                    attributes,
                    design_reference.clone(),
                ));
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::unexisting_connexion_type(
                        47,
                        self.descriptor().identifier().clone(),
                        output_treatment.to_string(),
                        output_name.to_string(),
                        input_treatment.to_string(),
                        input_name.to_string(),
                        *output.flow(),
                        output.described_type().clone(),
                        *input.flow(),
                        input.described_type().clone(),
                        design_reference,
                    ),
                ));
            }
        }

        result
    }

    pub fn remove_connection(
        &mut self,
        output_treatment: &str,
        output_name: &str,
        input_treatment: &str,
        input_name: &str,
    ) -> LogicResult<bool> {
        let mut found = false;
        self.connections.retain(|connection| {
            if connection.output_name == output_name
                && connection.input_name == input_name
                && match &connection.output_treatment {
                    IO::Treatment(t) => {
                        t.upgrade().unwrap().read().unwrap().name() == output_treatment
                    }
                    _ => false,
                }
                && match &connection.input_treatment {
                    IO::Treatment(t) => {
                        t.upgrade().unwrap().read().unwrap().name() == input_treatment
                    }
                    _ => false,
                }
            {
                found = true;
                false
            } else {
                true
            }
        });

        Ok(found).into()
    }

    pub fn add_self_connection(
        &mut self,
        self_input_name: &str,
        self_output_name: &str,
        attributes: Attributes,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        let mut input_self = None;
        if let Some(pos_input) = self.descriptor().inputs().get(self_input_name) {
            input_self = Some(pos_input.clone());
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::connection_self_input_not_found(
                    34,
                    self.descriptor().identifier().clone(),
                    self_input_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        let mut output_self = None;
        if let Some(pos_output) = self.descriptor().outputs().get(self_output_name) {
            output_self = Some(pos_output.clone());
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::connection_self_output_not_found(
                    38,
                    self.descriptor().identifier().clone(),
                    self_output_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        if let (Some(input_self), Some(output_self)) = (input_self, output_self) {
            if input_self.matches_output(&self.generics(), &output_self, &self.generics()) {
                self.connections.push(Connection::new_self(
                    input_self.name(),
                    output_self.name(),
                    attributes,
                    design_reference.clone(),
                ));
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::unexisting_connexion_type(
                        48,
                        self.descriptor().identifier().clone(),
                        "Self".to_string(),
                        self_input_name.to_string(),
                        "Self".to_string(),
                        self_output_name.to_string(),
                        *input_self.flow(),
                        input_self.described_type().clone(),
                        *output_self.flow(),
                        output_self.described_type().clone(),
                        design_reference,
                    ),
                ));
            }
        }

        result
    }

    pub fn remove_self_connection(
        &mut self,
        self_input_name: &str,
        self_output_name: &str,
    ) -> LogicResult<bool> {
        let mut found = false;
        self.connections.retain(|connection| {
            if connection.output_name == self_input_name
                && connection.input_name == self_output_name
                && match connection.output_treatment {
                    IO::Sequence() => true,
                    _ => false,
                }
                && match connection.input_treatment {
                    IO::Sequence() => true,
                    _ => false,
                }
            {
                found = true;
                false
            } else {
                true
            }
        });

        Ok(found).into()
    }

    pub fn add_input_connection(
        &mut self,
        self_input_name: &str,
        input_treatment: &str,
        input_name: &str,
        attributes: Attributes,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        let mut input_self = None;
        if let Some(pos_input) = self.descriptor().inputs().get(self_input_name) {
            input_self = Some(pos_input.clone());
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::connection_self_input_not_found(
                    35,
                    self.descriptor().identifier().clone(),
                    self_input_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        let mut rc_input_treatment = None;
        let mut input = None;
        let mut input_treatment_generics = None;
        if let Some(pos_rc_input_treatment) = self.treatments.get(input_treatment) {
            rc_input_treatment = Some(pos_rc_input_treatment);

            let input_treatment = pos_rc_input_treatment.read().unwrap();
            let input_treatment_descriptor = input_treatment.descriptor();
            input_treatment_generics = Some(Arc::clone(input_treatment.access_generics()));

            if let Some(pos_input) = input_treatment_descriptor.inputs().get(input_name) {
                input = Some(pos_input.clone());
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::connection_input_not_found(
                        33,
                        self.descriptor().identifier().clone(),
                        input_treatment_descriptor.identifier().clone(),
                        input_name.to_string(),
                        design_reference.clone(),
                    ),
                ));
            }
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::undeclared_treatment(
                    45,
                    self.descriptor().identifier().clone(),
                    input_treatment.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        if let (Some(input_self), Some(rc_input_treatment), Some(input)) =
            (input_self, rc_input_treatment, input)
        {
            if input_self.matches_input(
                &self.generics(),
                &input,
                &input_treatment_generics.unwrap().read().unwrap(),
            ) {
                self.connections.push(Connection::new_self_to_internal(
                    input_self.name(),
                    input.name(),
                    rc_input_treatment,
                    attributes,
                    design_reference.clone(),
                ));
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::unexisting_connexion_type(
                        49,
                        self.descriptor().identifier().clone(),
                        "Self".to_string(),
                        self_input_name.to_string(),
                        input_treatment.to_string(),
                        input_name.to_string(),
                        *input_self.flow(),
                        input_self.described_type().clone(),
                        *input.flow(),
                        input.described_type().clone(),
                        design_reference,
                    ),
                ));
            }
        }
        result
    }

    pub fn remove_input_connection(
        &mut self,
        self_input_name: &str,
        input_treatment: &str,
        input_name: &str,
    ) -> LogicResult<bool> {
        let mut found = false;
        self.connections.retain(|connection| {
            if connection.output_name == self_input_name
                && connection.input_name == input_name
                && match connection.output_treatment {
                    IO::Sequence() => true,
                    _ => false,
                }
                && match &connection.input_treatment {
                    IO::Treatment(t) => {
                        t.upgrade().unwrap().read().unwrap().name() == input_treatment
                    }
                    _ => false,
                }
            {
                found = true;
                false
            } else {
                true
            }
        });

        Ok(found).into()
    }

    pub fn add_output_connection(
        &mut self,
        self_output_name: &str,
        output_treatment: &str,
        output_name: &str,
        attributes: Attributes,
        design_reference: Option<Arc<dyn Reference>>,
    ) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        let mut output_self = None;
        if let Some(pos_output) = self.descriptor().outputs().get(self_output_name) {
            output_self = Some(pos_output.clone());
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::connection_self_output_not_found(
                    39,
                    self.descriptor().identifier().clone(),
                    self_output_name.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        let mut rc_output_treatment = None;
        let mut output = None;
        let mut output_treatment_generics = None;
        if let Some(pos_rc_output_treatment) = self.treatments.get(output_treatment) {
            rc_output_treatment = Some(pos_rc_output_treatment);

            let output_treatment = pos_rc_output_treatment.read().unwrap();
            let output_treatment_descriptor = output_treatment.descriptor();
            output_treatment_generics = Some(Arc::clone(output_treatment.access_generics()));

            if let Some(pos_output) = output_treatment_descriptor.outputs().get(output_name) {
                output = Some(pos_output.clone());
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::connection_output_not_found(
                        37,
                        self.descriptor().identifier().clone(),
                        output_treatment_descriptor.identifier().clone(),
                        output_name.to_string(),
                        design_reference.clone(),
                    ),
                ));
            }
        } else {
            result = result.and_degrade_failure(LogicResult::new_failure(
                LogicError::undeclared_treatment(
                    46,
                    self.descriptor().identifier().clone(),
                    output_treatment.to_string(),
                    design_reference.clone(),
                ),
            ));
        }

        if let (Some(output_self), Some(rc_output_treatment), Some(output)) =
            (output_self, rc_output_treatment, output)
        {
            if output_self.matches_output(
                &self.generics(),
                &output,
                &output_treatment_generics.unwrap().read().unwrap(),
            ) {
                self.connections.push(Connection::new_internal_to_self(
                    output.name(),
                    rc_output_treatment,
                    output_self.name(),
                    attributes,
                    design_reference.clone(),
                ));
            } else {
                result = result.and_degrade_failure(LogicResult::new_failure(
                    LogicError::unexisting_connexion_type(
                        50,
                        self.descriptor().identifier().clone(),
                        output_treatment.to_string(),
                        output_name.to_string(),
                        "Self".to_string(),
                        self_output_name.to_string(),
                        *output.flow(),
                        output.described_type().clone(),
                        *output_self.flow(),
                        output_self.described_type().clone(),
                        design_reference,
                    ),
                ));
            }
        }

        result
    }

    pub fn remove_output_connection(
        &mut self,
        self_output_name: &str,
        output_treatment: &str,
        output_name: &str,
    ) -> LogicResult<bool> {
        let mut found = false;
        self.connections.retain(|connection| {
            if connection.output_name == output_name
                && connection.input_name == self_output_name
                && match &connection.output_treatment {
                    IO::Treatment(t) => {
                        t.upgrade().unwrap().read().unwrap().name() == output_treatment
                    }
                    _ => false,
                }
                && match connection.input_treatment {
                    IO::Sequence() => true,
                    _ => false,
                }
            {
                found = true;
                false
            } else {
                true
            }
        });

        Ok(found).into()
    }

    pub fn model_instanciations(&self) -> &HashMap<String, Arc<RwLock<ModelInstanciation>>> {
        &self.model_instanciations
    }

    pub fn treatments(&self) -> &HashMap<String, Arc<RwLock<TreatmentInstanciation>>> {
        &self.treatments
    }

    pub fn connections(&self) -> &Vec<Connection> {
        &self.connections
    }

    pub fn validate(&self) -> LogicResult<()> {
        let mut result = LogicResult::new_success(());

        result = self
            .model_instanciations
            .iter()
            .fold(result, |result, (_, model)| {
                result.and_degrade_failure(model.read().unwrap().validate())
            });
        result = self
            .treatments
            .iter()
            .fold(result, |result, (_, treatment)| {
                result.and_degrade_failure(treatment.read().unwrap().validate())
            });

        // TODO Maybe should we check if no circular
        // references in connections there

        // Checking all inputs are satisfied.
        for (treatment_name, arc_treatment) in &self.treatments {
            let treatment = arc_treatment.read().unwrap();
            for (input_name, _) in treatment.descriptor().inputs() {
                let mut satisfaction = 0;
                for connection in &self.connections {
                    if let IO::Treatment(treatment_ref) = &connection.input_treatment {
                        if Arc::<_>::downgrade(&arc_treatment).ptr_eq(treatment_ref)
                            && input_name == &connection.input_name
                        {
                            satisfaction += 1;
                        }
                    }
                }

                if satisfaction == 0 {
                    result = result.and_degrade_failure(LogicResult::new_failure(
                        LogicError::unsatisfied_input(
                            243,
                            Some(self.descriptor().identifier().clone()),
                            treatment_name.clone(),
                            input_name.clone(),
                            self.design_reference.clone(),
                        ),
                    ));
                } else if satisfaction > 1 {
                    result = result.and_degrade_failure(LogicResult::new_failure(
                        LogicError::overloaded_input(
                            244,
                            self.descriptor().identifier().clone(),
                            treatment_name.clone(),
                            input_name.clone(),
                            self.design_reference.clone(),
                        ),
                    ));
                }
            }
        }

        // Counting number of outputs connected to self outputs.
        let mut outputs_satisfaction = self
            .descriptor()
            .outputs()
            .iter()
            .map(|(name, _output)| -> (String, usize) { (name.to_string(), 0) })
            .collect::<HashMap<String, usize>>();

        for connection in &self.connections {
            match connection.input_treatment {
                IO::Sequence() => {
                    *(outputs_satisfaction
                        .get_mut(&connection.input_name)
                        .unwrap()) += 1;
                }
                _ => {}
            }
        }

        // Check self outputs are connected to exactly one treatment output.
        for (output, count) in outputs_satisfaction {
            if count < 1 {
                result.errors_mut().push(LogicError::unsatisfied_output(
                    51,
                    self.descriptor().identifier().clone(),
                    output,
                    self.design_reference.clone(),
                ));
            } else if count > 1 {
                result.errors_mut().push(LogicError::overloaded_output(
                    52,
                    self.descriptor().identifier().clone(),
                    output,
                    self.design_reference.clone(),
                ));
            }
        }

        result
    }

    pub fn make_use(&self, identifier: &Identifier) -> bool {
        self.unvalidated_design()
            .success()
            .map(|design| design.make_use(identifier))
            .unwrap_or(false)
    }

    pub fn uses(&self) -> Vec<Identifier> {
        self.unvalidated_design()
            .success()
            .map(|design| design.uses())
            .unwrap_or_default()
    }

    pub fn unvalidated_design(&self) -> LogicResult<TreatmentDesign> {
        let result = LogicResult::new_success(());

        result.and_then(|_| {
            LogicResult::new_success(TreatmentDesign {
                descriptor: self.descriptor.clone(),
                model_instanciations: self
                    .model_instanciations
                    .iter()
                    .map(|(name, model_instanciation)| {
                        let model_instanciation = model_instanciation.read().unwrap();
                        (
                            name.clone(),
                            ModelInstanciationDesign {
                                name: name.clone(),
                                attributes: model_instanciation.attributes().clone(),
                                descriptor: Arc::downgrade(&model_instanciation.descriptor()),
                                parameters: model_instanciation
                                    .parameters()
                                    .iter()
                                    .filter_map(|(name, param)| {
                                        if let Some(value) = param.read().unwrap().value().as_ref()
                                        {
                                            Some((
                                                name.clone(),
                                                ParameterDesign {
                                                    name: name.clone(),
                                                    value: value.clone(),
                                                },
                                            ))
                                        } else {
                                            None
                                        }
                                    })
                                    .collect(),
                            },
                        )
                    })
                    .collect(),
                treatments: self
                    .treatments
                    .iter()
                    .map(|(name, treatment_instanciation)| {
                        let treatment_instanciation = treatment_instanciation.read().unwrap();
                        (
                            name.clone(),
                            TreatmentInstanciationDesign {
                                name: name.clone(),
                                attributes: treatment_instanciation.attributes().clone(),
                                descriptor: Arc::downgrade(&treatment_instanciation.descriptor()),
                                generics: {
                                    let clone = treatment_instanciation.generics().clone();
                                    clone
                                },
                                models: treatment_instanciation.models().clone(),
                                parameters: treatment_instanciation
                                    .parameters()
                                    .iter()
                                    .filter_map(|(name, param)| {
                                        if let Some(value) = param.read().unwrap().value().as_ref()
                                        {
                                            Some((
                                                name.clone(),
                                                ParameterDesign {
                                                    name: name.clone(),
                                                    value: value.clone(),
                                                },
                                            ))
                                        } else {
                                            None
                                        }
                                    })
                                    .collect(),
                            },
                        )
                    })
                    .collect(),
                connections: self
                    .connections
                    .iter()
                    .filter_map(|connection| {
                        Some(ConnectionDesign {
                            attributes: connection.attributes().clone(),
                            output_treatment: match &connection.output_treatment {
                                IO::Sequence() => IODesign::Sequence(),
                                IO::Treatment(t) => IODesign::Treatment(
                                    t.upgrade()?.read().unwrap().name().to_string(),
                                ),
                            },
                            output_name: connection.output_name.clone(),
                            input_treatment: match &connection.input_treatment {
                                IO::Sequence() => IODesign::Sequence(),
                                IO::Treatment(t) => IODesign::Treatment(
                                    t.upgrade()?.read().unwrap().name().to_string(),
                                ),
                            },
                            input_name: connection.input_name.clone(),
                        })
                    })
                    .collect(),
            })
        })
    }

    pub fn design(&self) -> LogicResult<TreatmentDesign> {
        self.validate().and_then(|_| self.unvalidated_design())
    }
}

impl Scope for Treatment {
    fn descriptor(&self) -> Arc<dyn Parameterized> {
        Arc::clone(&self.descriptor()) as Arc<dyn Parameterized>
    }

    fn collection(&self) -> Arc<Collection> {
        Arc::clone(&self.collection)
    }

    fn identifier(&self) -> Identifier {
        self.descriptor().identifier().clone()
    }
}

impl GenericInstanciation for Treatment {
    fn generics(&'_ self) -> RwLockReadGuard<'_, HashMap<String, DescribedType>> {
        self.generics.read().unwrap()
    }

    fn set_generic(&mut self, _generic_name: String, _type: DescribedType) -> LogicResult<()> {
        LogicResult::new_success(())
    }
}