-
Notifications
You must be signed in to change notification settings - Fork 221
/
intermediate_representation.rs
2029 lines (1882 loc) · 67.3 KB
/
intermediate_representation.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::error::FMLError::InvalidFeatureError;
use crate::error::{FMLError, Result};
use crate::parser::{AboutBlock, DefaultsMerger};
use crate::util::loaders::FilePath;
use anyhow::{bail, Error, Result as AnyhowResult};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Display;
use std::slice::Iter;
#[derive(Eq, PartialEq, Hash, Debug, Clone)]
pub enum TargetLanguage {
Kotlin,
Swift,
IR,
ExperimenterYAML,
ExperimenterJSON,
}
impl TargetLanguage {
pub fn extension(&self) -> &str {
match self {
TargetLanguage::Kotlin => "kt",
TargetLanguage::Swift => "swift",
TargetLanguage::IR => "fml.json",
TargetLanguage::ExperimenterJSON => "json",
TargetLanguage::ExperimenterYAML => "yaml",
}
}
pub fn from_extension(path: &str) -> AnyhowResult<TargetLanguage> {
if let Some((_, extension)) = path.rsplit_once('.') {
extension.try_into()
} else {
bail!("Unknown or unsupported target language: \"{}\"", path)
}
}
}
impl TryFrom<&str> for TargetLanguage {
type Error = Error;
fn try_from(value: &str) -> AnyhowResult<Self> {
Ok(match value.to_ascii_lowercase().as_str() {
"kotlin" | "kt" | "kts" => TargetLanguage::Kotlin,
"swift" => TargetLanguage::Swift,
"fml.json" => TargetLanguage::IR,
"yaml" => TargetLanguage::ExperimenterYAML,
"json" => TargetLanguage::ExperimenterJSON,
_ => bail!("Unknown or unsupported target language: \"{}\"", value),
})
}
}
/// The `TypeRef` enum defines a reference to a type.
///
/// Other types will be defined in terms of these enum values.
///
/// They represent the types available via the current `Variables` API—
/// some primitives and structural types— and can be represented by
/// Kotlin, Swift and JSON Schema.
///
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Hash, Eq)]
pub enum TypeRef {
// Current primitives.
String,
Int,
Boolean,
// Strings can be coerced into a few types.
// The types here will require the app's bundle or context to look up the final value.
// They will likely have
BundleText(StringId),
BundleImage(StringId),
Enum(String),
// JSON objects can represent a data class.
Object(String),
// JSON objects can also represent a `Map<String, V>` or a `Map` with
// keys that can be derived from a string.
StringMap(Box<TypeRef>),
// We can coerce the String keys into Enums, so this represents that.
EnumMap(Box<TypeRef>, Box<TypeRef>),
List(Box<TypeRef>),
Option(Box<TypeRef>),
}
/**
* An identifier derived from a `FilePath` of a top-level or importable FML file.
*
* An FML module is the conceptual FML file (and included FML files) that a single
* Kotlin or Swift file. It can be imported by other FML modules.
*
* It is somewhat distinct from the `FilePath` enum for three reasons:
*
* - a file path can specify a non-canonical representation of the path
* - a file path is difficult to serialize/deserialize
* - a module identifies the cluster of FML files that map to a single generated
* Kotlin or Swift file; this difference can be seen as: files can be included,
* modules can be imported.
*/
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone, Serialize, Deserialize)]
pub enum ModuleId {
Local(String),
Remote(String),
}
impl Default for ModuleId {
fn default() -> Self {
Self::Local("none".to_string())
}
}
impl TryFrom<&FilePath> for ModuleId {
type Error = FMLError;
fn try_from(path: &FilePath) -> Result<Self> {
Ok(match path {
FilePath::Local(p) => {
// We do this map_err here because the IO Error message that comes out of `canonicalize`
// doesn't include the problematic file path.
let p = p.canonicalize().map_err(|e| {
FMLError::InvalidPath(format!("{}: {}", e, p.as_path().display()))
})?;
ModuleId::Local(p.display().to_string())
}
FilePath::Remote(u) => ModuleId::Remote(u.to_string()),
})
}
}
impl Display for ModuleId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
ModuleId::Local(s) | ModuleId::Remote(s) => s,
})
}
}
pub trait TypeFinder {
fn all_types(&self) -> HashSet<TypeRef> {
let mut types = HashSet::new();
self.find_types(&mut types);
types
}
fn find_types(&self, types: &mut HashSet<TypeRef>);
}
impl TypeFinder for TypeRef {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
if types.insert(self.clone()) {
match self {
TypeRef::List(v) | TypeRef::Option(v) | TypeRef::StringMap(v) => {
v.find_types(types)
}
TypeRef::EnumMap(k, v) => {
k.find_types(types);
v.find_types(types);
}
_ => {}
}
}
}
}
pub(crate) type StringId = String;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct FeatureManifest {
#[serde(skip)]
pub(crate) id: ModuleId,
#[serde(rename = "enums")]
#[serde(default)]
pub enum_defs: Vec<EnumDef>,
#[serde(rename = "objects")]
#[serde(default)]
pub obj_defs: Vec<ObjectDef>,
// `hints` are useful for things that will be constructed from strings
// such as images and display text.
pub hints: HashMap<StringId, FromStringDef>,
#[serde(rename = "features")]
pub feature_defs: Vec<FeatureDef>,
#[serde(default)]
pub(crate) about: AboutBlock,
#[serde(default)]
pub(crate) imported_features: HashMap<ModuleId, BTreeSet<String>>,
#[serde(default)]
pub(crate) all_imports: HashMap<ModuleId, FeatureManifest>,
}
impl TypeFinder for FeatureManifest {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
for e in &self.enum_defs {
e.find_types(types);
}
for o in &self.obj_defs {
o.find_types(types);
}
for f in &self.feature_defs {
f.find_types(types);
}
}
}
impl FeatureManifest {
#[allow(unused)]
pub(crate) fn validate_manifest_for_lang(&self, lang: &TargetLanguage) -> Result<()> {
if !&self.about.supports(lang) {
return Err(FMLError::ValidationError(
"about".to_string(),
format!(
"Manifest file {file} is unable to generate {lang} files",
file = &self.id,
lang = &lang.extension(),
),
));
}
for child in self.all_imports.values() {
child.validate_manifest_for_lang(lang)?;
}
Ok(())
}
pub fn validate_manifest(&self) -> Result<()> {
// We first validate that each enum_def has a unique name.
// TODO: We repeat this check three times, it should be its
// own generic helper
let mut enum_names = HashSet::new();
self.validate_enum_defs(&mut enum_names)?;
// We then validate that each obj_defs also has a unique name.
let mut obj_names = HashSet::new();
self.validate_obj_defs(&mut obj_names)?;
// We then validate that each feature_def has a unique name.
let mut feature_names = HashSet::new();
self.validate_feature_defs(&mut feature_names)?;
// We then validate that each type_ref is valid
for feature_def in &self.feature_defs {
for prop in &feature_def.props {
let path = format!("features/{}.{}", &feature_def.name, &prop.name);
Self::validate_type_ref(&path, &prop.typ, &enum_names, &obj_names)?;
}
}
self.validate_defaults()?;
// Validating the imported manifests.
// This is not only validating the well formed-ness of the imported manifests
// but also the defaults that are sent into the child manifests.
for child in self.all_imports.values() {
child.validate_manifest()?;
}
Ok(())
}
fn validate_type_ref(
path: &str,
type_ref: &TypeRef,
enum_names: &HashSet<String>,
obj_names: &HashSet<String>,
) -> Result<()> {
match type_ref {
TypeRef::Enum(name) => {
if !enum_names.contains(name) {
return Err(FMLError::ValidationError(
path.to_string(),
format!(
"Found enum reference with name: {}, but no definition",
name
),
));
}
Ok(())
}
TypeRef::Object(name) => {
if !obj_names.contains(name) {
return Err(FMLError::ValidationError(
path.to_string(),
format!(
"Found object reference with name: {}, but no definition",
name
),
));
}
Ok(())
}
TypeRef::EnumMap(key_type, value_type) => {
if let TypeRef::Enum(_) = key_type.as_ref() {
Self::validate_type_ref(path, key_type, enum_names, obj_names)?;
Self::validate_type_ref(path, value_type, enum_names, obj_names)
} else {
Err(FMLError::ValidationError(
path.to_string(),
format!("EnumMap key has be an enum, found: {:?}", key_type),
))
}
}
TypeRef::List(list_type) => {
Self::validate_type_ref(path, list_type, enum_names, obj_names)
}
TypeRef::StringMap(value_type) => {
Self::validate_type_ref(path, value_type, enum_names, obj_names)
}
TypeRef::Option(option_type) => {
if let TypeRef::Option(_) = option_type.as_ref() {
Err(FMLError::ValidationError(
path.to_string(),
"Found nested optional types".into(),
))
} else {
Self::validate_type_ref(path, option_type, enum_names, obj_names)
}
}
_ => Ok(()),
}
}
fn validate_enum_defs(&self, enum_names: &mut HashSet<String>) -> Result<()> {
for enum_def in &self.enum_defs {
if !enum_names.insert(enum_def.name.clone()) {
return Err(FMLError::ValidationError(
format!("enums/{}", enum_def.name),
format!(
"EnumDef names must be unique. Found two EnumDefs with the same name: {}",
enum_def.name
),
));
}
}
Ok(())
}
fn validate_obj_defs(&self, obj_names: &mut HashSet<String>) -> Result<()> {
for obj_def in &self.obj_defs {
if !obj_names.insert(obj_def.name.clone()) {
return Err(FMLError::ValidationError(
format!("objects/{}", obj_def.name),
format!(
"ObjectDef names must be unique. Found two ObjectDefs with the same name: {}",
obj_def.name
),
));
}
}
Ok(())
}
fn validate_feature_defs(&self, feature_names: &mut HashSet<String>) -> Result<()> {
for feature_def in &self.feature_defs {
if !feature_names.insert(feature_def.name.clone()) {
return Err(FMLError::ValidationError(
feature_def.name(),
format!(
"FeatureDef names must be unique. Found two FeatureDefs with the same name: {}",
feature_def.name
),
));
}
// while checking the feature, we also check that each prop is unique within a feature
let mut prop_names = HashSet::new();
self.validate_props(feature_def, &mut prop_names)?;
}
Ok(())
}
fn validate_props(
&self,
feature_def: &FeatureDef,
prop_names: &mut HashSet<String>,
) -> Result<()> {
let path = format!("features/{}", &feature_def.name);
for prop in &feature_def.props {
if !prop_names.insert(prop.name.clone()) {
return Err(FMLError::ValidationError(
format!("{}.{}", path, prop.name),
format!(
"PropDef names must be unique. Found two PropDefs with the same name: {} in the same feature_def: {}",
prop.name, feature_def.name
)));
}
}
Ok(())
}
fn validate_defaults(&self) -> Result<()> {
for object in &self.obj_defs {
for prop in &object.props {
let path = format!("objects/{}.{}", object.name, prop.name);
self.validate_prop_defaults(&path, prop)?;
}
}
for feature in &self.feature_defs {
self.validate_feature_def(feature)?;
}
Ok(())
}
fn validate_feature_def(&self, feature_def: &FeatureDef) -> Result<()> {
for prop in &feature_def.props {
let path = format!("features/{}.{}", feature_def.name, prop.name);
self.validate_prop_defaults(&path, prop)?;
}
Ok(())
}
fn validate_prop_defaults(&self, path: &str, prop: &PropDef) -> Result<()> {
self.validate_default_by_typ(path, &prop.typ, &prop.default)
}
pub fn validate_default_by_typ(
&self,
path: &str,
type_ref: &TypeRef,
default: &Value,
) -> Result<()> {
match (type_ref, default) {
(TypeRef::Boolean, Value::Bool(_))
| (TypeRef::BundleImage(_), Value::String(_))
| (TypeRef::BundleText(_), Value::String(_))
| (TypeRef::String, Value::String(_))
| (TypeRef::Int, Value::Number(_))
| (TypeRef::Option(_), Value::Null) => Ok(()),
(TypeRef::Option(inner), v) => {
if let TypeRef::Option(_) = inner.as_ref() {
return Err(FMLError::ValidationError(
path.to_string(),
"Nested options".into(),
));
}
self.validate_default_by_typ(path, inner, v)
}
(TypeRef::Enum(enum_name), Value::String(s)) => {
let enum_def = self.find_enum(enum_name).ok_or_else(|| {
FMLError::ValidationError(
path.to_string(),
format!("Type `{}` is not a type. Perhaps you need to declare an enum of that name.", enum_name)
)
})?;
for variant in enum_def.variants() {
if *s == variant.name() {
return Ok(());
}
}
Err(FMLError::ValidationError(
path.to_string(),
format!(
"Default value `{value}` is not declared a variant of {enum_type}",
value = s,
enum_type = enum_name
),
))
}
(TypeRef::EnumMap(enum_type, map_type), Value::Object(map)) => {
let enum_name = if let TypeRef::Enum(name) = enum_type.as_ref() {
name.clone()
} else {
unreachable!()
};
// We first validate that the keys of the map cover all all the enum variants, and no more or less
let enum_def = self.find_enum(&enum_name).ok_or_else(|| {
FMLError::ValidationError(
path.to_string(),
format!("Type `{}` is not a type. Perhaps you need to declare an enum of that name.", enum_name)
)
})?;
let mut seen = HashSet::new();
let mut unseen = HashSet::new();
for variant in enum_def.variants() {
let map_value = map.get(&variant.name());
match (map_type.as_ref(), map_value) {
(TypeRef::Option(_), None) => (),
(_, None) => {
unseen.insert(variant.name());
}
(_, Some(inner)) => {
let path = format!("{}[{}#{}]", path, enum_def.name, variant.name);
self.validate_default_by_typ(&path, map_type, inner)?;
seen.insert(variant.name());
}
}
}
if !unseen.is_empty() {
return Err(FMLError::ValidationError(
path.to_string(),
format!(
"Default for enum map {} doesn't contain variant(s) {:?}",
enum_name, unseen
),
));
}
for map_key in map.keys() {
if !seen.contains(map_key) {
return Err(FMLError::ValidationError(path.to_string(), format!("Enum map default contains key {} that doesn't exist in the enum definition", map_key)));
}
}
Ok(())
}
(TypeRef::StringMap(map_type), Value::Object(map)) => {
for (key, value) in map {
let path = format!("{}['{}']", path, key);
self.validate_default_by_typ(&path, map_type, value)?;
}
Ok(())
}
(TypeRef::List(list_type), Value::Array(arr)) => {
for (index, value) in arr.iter().enumerate() {
let path = format!("{}['{}']", path, index);
self.validate_default_by_typ(&path, list_type, value)?;
}
Ok(())
}
(TypeRef::Object(obj_name), Value::Object(map)) => {
let obj_def = self.find_object(obj_name).ok_or_else(|| {
FMLError::ValidationError(
path.to_string(),
format!("Object {} is not defined in the manifest", obj_name),
)
})?;
let mut seen = HashSet::new();
let path = format!("{}#{}", path, obj_name);
for prop in &obj_def.props {
// We only check the defaults overriding the property defaults
// from the object's own property defaults.
// We check the object property defaults previously.
if let Some(map_val) = map.get(&prop.name) {
let path = format!("{}.{}", path, prop.name);
self.validate_default_by_typ(&path, &prop.typ, map_val)?;
}
seen.insert(prop.name());
}
for map_key in map.keys() {
if !seen.contains(map_key) {
return Err(FMLError::ValidationError(
path,
format!(
"Default includes key {} that doesn't exist in {}'s object definition",
map_key, obj_name
),
));
}
}
Ok(())
}
_ => Err(FMLError::ValidationError(
path.to_string(),
format!(
"Mismatch between type {:?} and default {}",
type_ref, default
),
)),
}
}
pub fn iter_enum_defs(&self) -> Iter<EnumDef> {
self.enum_defs.iter()
}
pub fn iter_object_defs(&self) -> Iter<ObjectDef> {
self.obj_defs.iter()
}
pub fn iter_all_object_defs(&self) -> impl Iterator<Item = (&FeatureManifest, &ObjectDef)> {
let objects = self.obj_defs.iter().map(move |o| (self, o));
let imported_objects: Vec<(&FeatureManifest, &ObjectDef)> = self
.all_imports
.iter()
.flat_map(|(_, fm)| fm.iter_all_object_defs())
.collect();
objects.chain(imported_objects)
}
pub fn iter_feature_defs(&self) -> Iter<FeatureDef> {
self.feature_defs.iter()
}
pub fn iter_all_feature_defs(&self) -> impl Iterator<Item = (&FeatureManifest, &FeatureDef)> {
let features = self.feature_defs.iter().map(move |f| (self, f));
let imported_features: Vec<(&FeatureManifest, &FeatureDef)> = self
.all_imports
.iter()
.flat_map(|(_, fm)| fm.iter_all_feature_defs())
.collect();
features.chain(imported_features)
}
#[allow(unused)]
pub(crate) fn iter_imported_files(&self) -> Vec<ImportedModule> {
let map = &self.all_imports;
self.imported_features
.iter()
.filter_map(|(id, features)| {
let fm = map.get(id).to_owned()?;
Some(ImportedModule::new(id.clone(), fm, features))
})
.collect()
}
pub fn find_object(&self, nm: &str) -> Option<&ObjectDef> {
self.iter_object_defs().find(|o| o.name() == nm)
}
pub fn find_enum(&self, nm: &str) -> Option<&EnumDef> {
self.iter_enum_defs().find(|e| e.name() == nm)
}
pub fn get_feature(&self, nm: &str) -> Option<&FeatureDef> {
self.iter_feature_defs().find(|f| f.name() == nm)
}
pub fn find_feature(&self, nm: &str) -> Option<(&FeatureManifest, &FeatureDef)> {
self.iter_all_feature_defs().find(|(_, f)| f.name() == nm)
}
pub fn find_import(&self, id: &ModuleId) -> Option<&FeatureManifest> {
self.all_imports.get(id)
}
pub fn default_json(&self) -> Value {
Value::Object(
self.iter_all_feature_defs()
.map(|(_, f)| (f.name(), f.default_json()))
.collect(),
)
}
/// This function is used to validate a new value for a feature. It accepts a feature name and
/// a feature value, and returns a Result containing a FeatureDef.
///
/// If the value is invalid for the feature, it will return an Err result.
///
/// If the value is valid for the feature, it will return an Ok result with a new FeatureDef
/// with the supplied feature value applied to the feature's property defaults.
#[allow(unused)]
pub(crate) fn validate_feature_config(
&self,
feature_name: &str,
feature_value: Value,
) -> Result<FeatureDef> {
let dummy_channel = "dummy".to_string();
let objects: HashMap<String, &ObjectDef> = self
.iter_all_object_defs()
.map(|(_, o)| (o.name(), o))
.collect();
let merger = DefaultsMerger::new(
objects.into_iter().map(|(k, o)| (k, o)).collect(),
vec![dummy_channel.clone()],
dummy_channel,
);
if let Some((manifest, feature_def)) = self.find_feature(feature_name) {
let mut feature_def = feature_def.clone();
merger.merge_feature_defaults(&mut feature_def, &Some(vec![feature_value.into()]))?;
manifest.validate_feature_def(&feature_def)?;
Ok(feature_def.clone())
} else {
Err(InvalidFeatureError(feature_name.to_string()))
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct FeatureDef {
pub(crate) name: String,
pub(crate) doc: String,
pub(crate) props: Vec<PropDef>,
}
impl FeatureDef {
#[allow(dead_code)]
pub fn new(name: &str, doc: &str, props: Vec<PropDef>) -> Self {
Self {
name: name.into(),
doc: doc.into(),
props,
}
}
pub fn name(&self) -> String {
self.name.clone()
}
pub fn doc(&self) -> String {
self.doc.clone()
}
pub fn props(&self) -> Vec<PropDef> {
self.props.clone()
}
pub fn default_json(&self) -> Value {
let mut props = Map::new();
for prop in self.props().iter() {
props.insert(prop.name(), prop.default());
}
Value::Object(props)
}
}
impl TypeFinder for FeatureDef {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
for p in self.props() {
p.find_types(types);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct EnumDef {
pub name: String,
pub doc: String,
pub variants: Vec<VariantDef>,
}
impl EnumDef {
pub fn name(&self) -> String {
self.name.clone()
}
pub fn doc(&self) -> String {
self.doc.clone()
}
pub fn variants(&self) -> Vec<VariantDef> {
self.variants.clone()
}
}
impl TypeFinder for EnumDef {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
types.insert(TypeRef::Enum(self.name()));
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FromStringDef {
pub name: String,
pub doc: String,
pub variants: Vec<VariantDef>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct VariantDef {
pub(crate) name: String,
pub(crate) doc: String,
}
impl VariantDef {
#[allow(dead_code)]
pub fn new(name: &str, doc: &str) -> Self {
Self {
name: name.into(),
doc: doc.into(),
}
}
pub fn name(&self) -> String {
self.name.clone()
}
pub fn doc(&self) -> String {
self.doc.clone()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ObjectDef {
pub(crate) name: String,
pub(crate) doc: String,
pub(crate) props: Vec<PropDef>,
}
#[allow(unused)]
impl ObjectDef {
pub fn new(name: &str, doc: &str, props: Vec<PropDef>) -> Self {
Self {
name: name.into(),
doc: doc.into(),
props,
}
}
pub(crate) fn name(&self) -> String {
self.name.clone()
}
pub(crate) fn doc(&self) -> String {
self.doc.clone()
}
pub fn props(&self) -> Vec<PropDef> {
self.props.clone()
}
pub(crate) fn find_prop(&self, nm: &str) -> PropDef {
self.props
.iter()
.find(|p| p.name == nm)
.unwrap_or_else(|| unreachable!("Can't find {}. This is a bug in FML", nm))
.clone()
}
}
impl TypeFinder for ObjectDef {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
for p in self.props() {
p.find_types(types);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PropDef {
pub name: String,
pub doc: String,
#[serde(rename = "type")]
pub typ: TypeRef,
pub default: Literal,
}
impl PropDef {
pub fn name(&self) -> String {
self.name.clone()
}
pub fn doc(&self) -> String {
self.doc.clone()
}
pub fn typ(&self) -> TypeRef {
self.typ.clone()
}
pub fn default(&self) -> Literal {
self.default.clone()
}
}
impl TypeFinder for PropDef {
fn find_types(&self, types: &mut HashSet<TypeRef>) {
types.insert(self.typ());
}
}
pub type Literal = Value;
#[allow(unused)]
#[derive(Debug, Clone)]
pub(crate) struct ImportedModule<'a> {
pub(crate) id: ModuleId,
pub(crate) fm: &'a FeatureManifest,
features: &'a BTreeSet<String>,
}
#[allow(unused)]
impl<'a> ImportedModule<'a> {
pub(crate) fn new(
id: ModuleId,
fm: &'a FeatureManifest,
features: &'a BTreeSet<String>,
) -> Self {
Self { id, fm, features }
}
pub(crate) fn about(&self) -> &AboutBlock {
&self.fm.about
}
pub(crate) fn features(&self) -> Vec<&'a FeatureDef> {
let fm = self.fm;
self.features
.iter()
.filter_map(|f| fm.get_feature(f))
.collect()
}
}
#[cfg(test)]
pub mod unit_tests {
use serde_json::{json, Number};
use super::*;
use crate::error::Result;
use crate::fixtures::intermediate_representation::get_simple_homescreen_feature;
#[test]
fn can_ir_represent_smoke_test() -> Result<()> {
let reference_manifest = get_simple_homescreen_feature();
let json_string = serde_json::to_string(&reference_manifest)?;
let manifest_from_json: FeatureManifest = serde_json::from_str(&json_string)?;
assert_eq!(reference_manifest, manifest_from_json);
Ok(())
}
#[test]
fn validate_good_feature_manifest() -> Result<()> {
let fm = get_simple_homescreen_feature();
fm.validate_manifest()
}
#[test]
fn validate_duplicate_enum_defs_fail() -> Result<()> {
let mut fm = get_simple_homescreen_feature();
fm.enum_defs.push(EnumDef {
name: "HomeScreenSection".into(),
doc: "The sections of the homescreen".into(),
variants: vec![
VariantDef::new("top-sites", "The original frecency sorted sites"),
VariantDef::new("jump-back-in", "Jump back in section"),
VariantDef::new("recently-saved", "Tabs that have been bookmarked recently"),
],
});
fm.validate_manifest()
.expect_err("Should fail on duplicate enum_defs");
Ok(())
}
#[test]
fn validate_duplicate_obj_defs_fails() -> Result<()> {
let mut fm = get_simple_homescreen_feature();
fm.obj_defs = vec![
ObjectDef {
name: "SimpleObjDef".into(),
doc: "Simpel doc".into(),
props: vec![],
},
ObjectDef {
name: "SimpleObjDef".into(),
doc: "Simpel doc".into(),
props: vec![],
},
];
fm.validate_manifest()
.expect_err("Should fail on duplicate obj_defs");
Ok(())
}
#[test]
fn validate_duplicate_feature_defs_fails() -> Result<()> {
let mut fm = get_simple_homescreen_feature();
fm.feature_defs.push(FeatureDef::new(
"homescreen",
"Represents the homescreen feature",
vec![PropDef {
name: "sections-enabled".into(),
doc: "A map of booleans".into(),
typ: TypeRef::EnumMap(
Box::new(TypeRef::Enum("SectionId".into())),
Box::new(TypeRef::String),
),
default: json!({
"top-sites": true,
"jump-back-in": false,
"recently-saved": false,
}),
}],
));
fm.validate_manifest()
.expect_err("Should fail on duplicate feature defs");
Ok(())
}
#[test]
fn validate_duplicate_props_in_same_feature_fails() -> Result<()> {
let mut fm = get_simple_homescreen_feature();
fm.feature_defs.push(FeatureDef::new(
"otherhomescreen",
"Represents the homescreen feature",
vec![
PropDef {
name: "duplicate-prop".into(),
doc: "A map of booleans".into(),
typ: TypeRef::EnumMap(
Box::new(TypeRef::Enum("SectionId".into())),
Box::new(TypeRef::String),
),
default: json!({
"top-sites": true,
"jump-back-in": false,
"recently-saved": false,
}),
},
PropDef {
name: "duplicate-prop".into(),
doc: "A map of booleans".into(),
typ: TypeRef::EnumMap(
Box::new(TypeRef::Enum("SectionId".into())),
Box::new(TypeRef::String),
),
default: json!({
"top-sites": true,
"jump-back-in": false,
"recently-saved": false,
}),
},
],
));
fm.validate_manifest()
.expect_err("Should fail on duplicate props in the same feature");
Ok(())
}