-
Notifications
You must be signed in to change notification settings - Fork 221
/
parser.rs
2752 lines (2538 loc) · 90.4 KB
/
parser.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 std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::{
error::{FMLError, Result},
intermediate_representation::{
EnumDef, FeatureDef, FeatureManifest, ModuleId, ObjectDef, PropDef, TargetLanguage,
TypeRef, VariantDef,
},
util::loaders::{FileLoader, FilePath},
};
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct EnumVariantBody {
description: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct EnumBody {
description: String,
variants: HashMap<String, EnumVariantBody>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct FieldBody {
description: String,
#[serde(default)]
required: bool,
#[serde(rename = "type")]
variable_type: String,
default: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct ObjectBody {
description: String,
failable: Option<bool>,
// We need these in a deterministic order, so they are stable across multiple
// runs of the same manifests.
fields: BTreeMap<String, FieldBody>,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct Types {
#[serde(default)]
enums: HashMap<String, EnumBody>,
#[serde(default)]
objects: HashMap<String, ObjectBody>,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct AboutBlock {
pub(crate) description: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "kotlin", alias = "android")]
pub(crate) kotlin_about: Option<KotlinAboutBlock>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "swift", alias = "ios")]
pub(crate) swift_about: Option<SwiftAboutBlock>,
}
impl AboutBlock {
pub(crate) fn is_includable(&self) -> bool {
self.kotlin_about.is_none() && self.swift_about.is_none()
}
#[allow(unused)]
pub(crate) fn supports(&self, lang: &TargetLanguage) -> bool {
match lang {
TargetLanguage::Kotlin => self.kotlin_about.is_some(),
TargetLanguage::Swift => self.swift_about.is_some(),
TargetLanguage::IR => true,
TargetLanguage::ExperimenterYAML => true,
TargetLanguage::ExperimenterJSON => true,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, Eq)]
pub(crate) struct SwiftAboutBlock {
pub(crate) module: String,
pub(crate) class: String,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, Eq)]
pub(crate) struct KotlinAboutBlock {
pub(crate) package: String,
pub(crate) class: String,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub(crate) struct ImportBlock {
pub(crate) path: String,
pub(crate) channel: String,
#[serde(default)]
pub(crate) features: HashMap<String, Vec<DefaultBlock>>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct FeatureBody {
description: String,
// We need these in a deterministic order, so they are stable across multiple
// runs of the same manifests:
// 1. Swift insists on args in the same order they were declared.
// 2. imported features are declared and constructed in different runs of the tool.
variables: BTreeMap<String, FieldBody>,
#[serde(alias = "defaults")]
default: Option<Vec<DefaultBlock>>,
}
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct ManifestFrontEnd {
#[serde(default)]
version: String,
#[serde(default)]
about: Option<AboutBlock>,
// We'd like to get rid of the `types` property,
// but we need to keep supporting it.
#[serde(default)]
#[serde(rename = "types")]
legacy_types: Option<Types>,
#[serde(default)]
features: HashMap<String, FeatureBody>,
#[serde(default)]
#[serde(alias = "include")]
includes: Vec<String>,
#[serde(default)]
#[serde(alias = "import")]
imports: Vec<ImportBlock>,
#[serde(default)]
channels: Vec<String>,
// If a types attribute isn't explicitly expressed,
// then we should assume that we use the flattened version.
#[serde(default)]
#[serde(flatten)]
types: Types,
}
impl ManifestFrontEnd {
/// Retrieves all the types represented in the Manifest
///
/// # Returns
/// Returns a [`std::collections::HashMap<String,TypeRef>`] where
/// the key is the name of the type, and the TypeRef represents the type itself
fn get_types(&self) -> HashMap<String, TypeRef> {
let types = self.legacy_types.as_ref().unwrap_or(&self.types);
types
.enums
.keys()
.map(|s| (s.clone(), TypeRef::Enum(s.clone())))
.chain(
types
.objects
.keys()
.map(|s| (s.clone(), TypeRef::Object(s.clone()))),
)
.collect()
}
/// Transforms a front-end field definition, a tuple of [`String`] and [`FieldBody`],
/// into a [`PropDef`]
///
/// # Arguments
/// - `field`: The [`(&String, &FieldBody)`] tuple to get the propdef from
///
/// # Returns
/// return the IR [`PropDef`]
fn get_prop_def_from_field(&self, field: (&String, &FieldBody)) -> PropDef {
let types = self.get_types();
PropDef {
name: field.0.into(),
doc: field.1.description.clone(),
typ: match get_typeref_from_string(
field.1.variable_type.to_owned(),
Some(types.clone()),
) {
Ok(type_ref) => type_ref,
Err(e) => {
// Try matching against the user defined types
match types.get(&field.1.variable_type) {
Some(type_ref) => type_ref.to_owned(),
None => panic!(
"{}\n{} is not a valid FML type or user defined type",
e, field.1.variable_type
),
}
}
},
default: json!(field.1.default),
}
}
/// Retrieves all the feature definitions represented in the manifest
///
/// # Returns
/// Returns a [`std::vec::Vec<FeatureDef>`]
fn get_feature_defs(&self, merger: &DefaultsMerger) -> Result<Vec<FeatureDef>> {
self.features
.iter()
.map(|(name, body)| {
let mut def = FeatureDef {
name: name.clone(),
doc: body.description.clone(),
props: body
.variables
.iter()
.map(|v| self.get_prop_def_from_field(v))
.collect(),
};
merger.merge_feature_defaults(&mut def, &body.default)?;
Ok(def)
})
.collect()
}
/// Retrieves all the Object type definitions represented in the manifest
///
/// # Returns
/// Returns a [`std::vec::Vec<ObjectDef>`]
fn get_objects(&self) -> Vec<ObjectDef> {
let types = self.legacy_types.as_ref().unwrap_or(&self.types);
types
.objects
.iter()
.map(|t| ObjectDef {
name: t.0.clone(),
doc: t.1.description.clone(),
props: t
.1
.fields
.iter()
.map(|v| self.get_prop_def_from_field(v))
.collect(),
})
.collect()
}
/// Retrieves all the Enum type definitions represented in the manifest
///
/// # Returns
/// Returns a [`std::vec::Vec<EnumDef>`]
fn get_enums(&self) -> Vec<EnumDef> {
let types = self.legacy_types.as_ref().unwrap_or(&self.types);
types
.enums
.clone()
.into_iter()
.map(|t| EnumDef {
name: t.0,
doc: t.1.description,
variants: t
.1
.variants
.iter()
.map(|v| VariantDef {
name: v.0.clone(),
doc: v.1.description.clone(),
})
.collect(),
})
.collect()
}
fn get_intermediate_representation(
&self,
id: &ModuleId,
channel: &str,
) -> Result<FeatureManifest> {
let enums = self.get_enums();
let objects = self.get_objects();
let object_map: HashMap<String, &ObjectDef> =
objects.iter().map(|o| (o.name(), o)).collect();
let merger = DefaultsMerger::new(object_map, self.channels.clone(), channel.to_owned());
let features = self.get_feature_defs(&merger)?;
let about = match &self.about {
Some(a) => a.clone(),
None => Default::default(),
};
Ok(FeatureManifest {
id: id.clone(),
about,
enum_defs: enums,
obj_defs: objects,
hints: HashMap::new(),
feature_defs: features,
..Default::default()
})
}
}
fn parse_typeref_string(input: String) -> Result<(String, Option<String>)> {
// Split the string into the TypeRef and the name
let mut object_type_iter = input.split(&['<', '>'][..]);
// This should be the TypeRef type (except for )
let type_ref_name = object_type_iter.next().unwrap().trim();
if ["String", "Int", "Boolean"].contains(&type_ref_name) {
return Ok((type_ref_name.to_string(), None));
}
// This should be the name or type of the Object
match object_type_iter.next() {
Some(object_type_name) => Ok((
type_ref_name.to_string(),
Some(object_type_name.to_string()),
)),
None => Ok((type_ref_name.to_string(), None)),
}
}
/// Collects the channel defaults of the feature manifest
/// and merges them by channel
///
/// **NOTE**: defaults with no channel apply to **all** channels
///
/// # Arguments
/// - `defaults`: a [`serde_json::Value`] representing the array of defaults
///
/// # Returns
/// Returns a [`std::collections::HashMap<String, serde_json::Value>`] representing
/// the merged defaults. The key is the name of the channel and the value is the
/// merged json.
///
/// # Errors
/// Will return errors in the following cases (not exhaustive):
/// - The `defaults` argument is not an array
/// - There is a `channel` in the `defaults` argument that doesn't
/// exist in the `channels` argument
fn collect_channel_defaults(
defaults: &[DefaultBlock],
channels: &[String],
) -> Result<HashMap<String, serde_json::Value>> {
// We initialize the map to have an entry for every valid channel
let mut channel_map = channels
.iter()
.map(|channel_name| (channel_name.clone(), json!({})))
.collect::<HashMap<_, _>>();
for default in defaults {
if let Some(channels_for_default) = &default.merge_channels() {
for channel in channels_for_default {
if let Some(old_default) = channel_map.get(channel).cloned() {
if default.targeting.is_none() {
// TODO: we currently ignore any defaults with targeting involved
let merged = merge_two_defaults(&old_default, &default.value);
channel_map.insert(channel.clone(), merged);
}
} else {
return Err(FMLError::InvalidChannelError(
channel.into(),
channels.into(),
));
}
}
// This is a default with no channel, so it applies to all channels
} else {
channel_map = channel_map
.into_iter()
.map(|(channel, old_default)| {
(channel, merge_two_defaults(&old_default, &default.value))
})
.collect();
}
}
Ok(channel_map)
}
pub struct DefaultsMerger<'object> {
objects: HashMap<String, &'object ObjectDef>,
supported_channels: Vec<String>,
channel: String,
}
impl<'object> DefaultsMerger<'object> {
pub fn new(
objects: HashMap<String, &'object ObjectDef>,
supported_channels: Vec<String>,
channel: String,
) -> Self {
Self {
objects,
supported_channels,
channel,
}
}
fn collect_feature_defaults(&self, feature: &FeatureDef) -> Result<serde_json::Value> {
let mut res = serde_json::value::Map::new();
for p in feature.props() {
let collected = self
.collect_prop_defaults(&p.typ, &p.default)?
.unwrap_or_else(|| p.default());
res.insert(p.name(), collected);
}
Ok(serde_json::to_value(res)?)
}
fn collect_object_defaults(&self, nm: &str) -> Result<serde_json::Value> {
if !self.objects.contains_key(nm) {
return Err(FMLError::ValidationError(
format!("objects/{}", nm),
format!("Object named {} is not defined", nm),
));
}
let obj = self.objects.get(nm).unwrap();
let mut res = serde_json::value::Map::new();
for p in obj.props() {
if let Some(collected) = self.collect_prop_defaults(&p.typ, &p.default)? {
res.insert(p.name(), collected);
}
}
Ok(serde_json::to_value(res)?)
}
fn collect_prop_defaults(
&self,
typ: &TypeRef,
v: &serde_json::Value,
) -> Result<Option<serde_json::Value>> {
Ok(match typ {
TypeRef::Object(nm) => Some(merge_two_defaults(&self.collect_object_defaults(nm)?, v)),
TypeRef::EnumMap(_, v_type) => Some(self.collect_map_defaults(v_type, v)?),
TypeRef::StringMap(v_type) => Some(self.collect_map_defaults(v_type, v)?),
_ => None,
})
}
fn collect_map_defaults(
&self,
v_type: &TypeRef,
obj: &serde_json::Value,
) -> Result<serde_json::Value> {
let map = obj
.as_object()
.unwrap_or_else(|| panic!("Expected a JSON object as a default"));
let mut res = serde_json::value::Map::new();
for (k, v) in map {
let collected = self
.collect_prop_defaults(v_type, v)?
.unwrap_or_else(|| v.clone());
res.insert(k.clone(), collected);
}
Ok(serde_json::to_value(res)?)
}
/// Transforms a feature definition with unmerged defaults into a feature
/// definition with its defaults merged.
///
/// # How the algorithm works:
/// There are two types of defaults:
/// 1. Field level defaults
/// 1. Feature level defaults, that are listed by channel
///
/// The algorithm gathers the field level defaults first, they are the base
/// defaults. Then, it gathers the feature level defaults and merges them by
/// calling [`collect_channel_defaults`]. Finally, it overwrites any common
/// defaults between the merged feature level defaults and the field level defaults
///
/// # Example:
/// Assume we have the following feature manifest
/// ```yaml
/// variables:
/// positive:
/// description: This is a positive button
/// type: Button
/// default:
/// {
/// "label": "Ok then",
/// "color": "blue"
/// }
/// default:
/// - channel: release
/// value: {
/// "positive": {
/// "color": "green"
/// }
/// }
/// - value: {
/// "positive": {
/// "alt-text": "Go Ahead!"
/// }
/// }
/// ```
///
/// The result of the algorithm would be a default that looks like:
/// ```yaml
/// variables:
/// positive:
/// default:
/// {
/// "label": "Ok then",
/// "color": "green",
/// "alt-text": "Go Ahead!"
/// }
///
/// ```
///
/// - The `label` comes from the original field level default
/// - The `color` comes from the `release` channel feature level default
/// - The `alt-text` comes from the feature level default with no channel (that applies to all channels)
///
/// # Arguments
/// - `feature_def`: a [`FeatureDef`] representing the feature definition to transform
/// - `channel`: a [`Option<&String>`] representing the channel to merge back into the field variables
/// - `supported_channels`: a [`&[String]`] representing the channels that are supported by the manifest
/// If the `channel` is `None` we default to using the `release` channel
///
/// # Returns
/// Returns a transformed [`FeatureDef`] with its defaults merged
pub fn merge_feature_defaults(
&self,
feature_def: &mut FeatureDef,
defaults: &Option<Vec<DefaultBlock>>,
) -> Result<(), FMLError> {
let supported_channels = self.supported_channels.as_slice();
let channel = &self.channel;
if !supported_channels.iter().any(|c| c == channel) {
return Err(FMLError::InvalidChannelError(
channel.into(),
supported_channels.into(),
));
}
let variable_defaults = self.collect_feature_defaults(feature_def)?;
let mut res = feature_def;
if let Some(defaults) = defaults {
let merged_defaults = collect_channel_defaults(defaults, supported_channels)?;
if let Some(default_to_merged) = merged_defaults.get(channel) {
let merged = merge_two_defaults(&variable_defaults, default_to_merged);
let map = merged.as_object().ok_or(FMLError::InternalError(
"Map was merged into a different type",
))?;
res.props = map
.iter()
.map(|(k, v)| -> Result<PropDef> {
if let Some(prop) = res.props.iter().find(|p| &p.name == k) {
let mut res = prop.clone();
res.default = v.clone();
Ok(res)
} else {
Err(FMLError::InvalidPropertyError(k.clone(), res.name.clone()))
}
})
.collect::<Result<Vec<_>>>()?;
}
}
Ok(())
}
}
/// Merges two [`serde_json::Value`]s into one
///
/// # Arguments:
/// - `old_default`: a reference to a [`serde_json::Value`], that represents the old default
/// - `new_default`: a reference to a [`serde_json::Value`], that represents the new default, this takes
/// precedence over the `old_default` if they have conflicting fields
///
/// # Returns
/// A merged [`serde_json::Value`] that contains all fields from `old_default` and `new_default`, merging
/// where there is a conflict. If the `old_default` and `new_default` are not both objects, this function
/// returns the `new_default`
fn merge_two_defaults(
old_default: &serde_json::Value,
new_default: &serde_json::Value,
) -> serde_json::Value {
use serde_json::Value::Object;
match (old_default.clone(), new_default.clone()) {
(Object(old), Object(new)) => {
let mut merged = serde_json::Map::new();
for (key, val) in old {
merged.insert(key, val);
}
for (key, val) in new {
if let Some(old_val) = merged.get(&key).cloned() {
merged.insert(key, merge_two_defaults(&old_val, &val));
} else {
merged.insert(key, val);
}
}
Object(merged)
}
(_, new) => new,
}
}
fn get_typeref_from_string(
input: String,
types: Option<HashMap<String, TypeRef>>,
) -> Result<TypeRef, FMLError> {
let (type_ref, type_name) = parse_typeref_string(input)?;
return match type_ref.as_str() {
"String" => Ok(TypeRef::String),
"Int" => Ok(TypeRef::Int),
"Boolean" => Ok(TypeRef::Boolean),
"BundleText" | "Text" => Ok(TypeRef::BundleText(
type_name.unwrap_or_else(|| "unnamed".to_string()),
)),
"BundleImage" | "Drawable" | "Image" => Ok(TypeRef::BundleImage(
type_name.unwrap_or_else(|| "unnamed".to_string()),
)),
"Enum" => Ok(TypeRef::Enum(type_name.unwrap())),
"Object" => Ok(TypeRef::Object(type_name.unwrap())),
"List" => Ok(TypeRef::List(Box::new(get_typeref_from_string(
type_name.unwrap(),
types,
)?))),
"Option" => Ok(TypeRef::Option(Box::new(get_typeref_from_string(
type_name.unwrap(),
types,
)?))),
"Map" => {
// Maps take a little extra massaging to get the key and value types
let type_name = type_name.unwrap();
let mut map_type_info_iter = type_name.split(',');
let key_type = map_type_info_iter.next().unwrap().to_string();
let value_type = map_type_info_iter.next().unwrap().trim().to_string();
if key_type.eq("String") {
Ok(TypeRef::StringMap(Box::new(get_typeref_from_string(
value_type, types,
)?)))
} else {
Ok(TypeRef::EnumMap(
Box::new(get_typeref_from_string(key_type, types.clone())?),
Box::new(get_typeref_from_string(value_type, types)?),
))
}
}
type_name => {
if types.is_none() {
return Err(FMLError::TypeParsingError(format!(
"{} is not a recognized FML type",
type_ref
)));
}
match types.unwrap().get(type_name) {
Some(type_ref) => Ok(type_ref.clone()),
None => {
return Err(FMLError::TypeParsingError(format!(
"{} is not a recognized FML type",
type_ref
)));
}
}
}
};
}
#[derive(Debug)]
pub struct Parser {
files: FileLoader,
source: FilePath,
}
impl Parser {
pub fn new(files: FileLoader, source: FilePath) -> Result<Parser> {
Ok(Parser { source, files })
}
// This method loads a manifest, including resolving the includes and merging the included files
// into this top level one.
// It recursively calls itself and then calls `merge_manifest`.
fn load_manifest(
&self,
path: &FilePath,
loading: &mut HashSet<ModuleId>,
) -> Result<ManifestFrontEnd> {
let id: ModuleId = path.try_into()?;
let files = &self.files;
let s = files
.read_to_string(path)
.map_err(|e| FMLError::FMLModuleError(id.clone(), e.to_string()))?;
let mut parent = serde_yaml::from_str::<ManifestFrontEnd>(&s)
.map_err(|e| FMLError::FMLModuleError(id.clone(), e.to_string()))?;
// We canonicalize the paths to the import files really soon after the loading so when we merge
// other included files, we cam match up the files that _they_ import, the concatenate the default
// blocks for their features.
self.canonicalize_import_paths(path, &mut parent.imports)
.map_err(|e| FMLError::FMLModuleError(id.clone(), e.to_string()))?;
loading.insert(id.clone());
parent
.includes
.clone()
.iter()
.fold(Ok(parent), |parent: Result<ManifestFrontEnd>, f| {
let src_path = files.join(path, f)?;
let parent = parent?;
let child_id = ModuleId::try_from(&src_path)?;
Ok(if !loading.contains(&child_id) {
let manifest = self.load_manifest(&src_path, loading)?;
self.merge_manifest(&src_path, parent, &src_path, manifest)
.map_err(|e| FMLError::FMLModuleError(id.clone(), e.to_string()))?
} else {
parent
})
})
}
// Attempts to merge two manifests: a child into a parent.
// The `child_path` is needed to report errors.
fn merge_manifest(
&self,
parent_path: &FilePath,
parent: ManifestFrontEnd,
child_path: &FilePath,
child: ManifestFrontEnd,
) -> Result<ManifestFrontEnd> {
self.check_can_merge_manifest(parent_path, &parent, child_path, &child)?;
// Child must not specify any features, objects or enums that the parent has.
let features = merge_map(
&parent.features,
&child.features,
"Features",
"features",
child_path,
)?;
let p_types = &parent.legacy_types.unwrap_or(parent.types);
let c_types = &child.legacy_types.unwrap_or(child.types);
let objects = merge_map(
&c_types.objects,
&p_types.objects,
"Objects",
"objects",
child_path,
)?;
let enums = merge_map(&c_types.enums, &p_types.enums, "Enums", "enums", child_path)?;
let imports = self.merge_import_block_list(&parent.imports, &child.imports)?;
let merged = ManifestFrontEnd {
features,
types: Types { enums, objects },
legacy_types: None,
imports,
..parent
};
Ok(merged)
}
/// Load a manifest and all its imports, recursively if necessary.
///
/// We populate a map of `FileId` to `FeatureManifest`s, so to avoid unnecessary clones,
/// we return a `FileId` even when the file has already been imported.
fn load_imports(
&self,
current: &FilePath,
channel: &str,
imports: &mut HashMap<ModuleId, FeatureManifest>,
) -> Result<ModuleId> {
let id = current.try_into()?;
if imports.contains_key(&id) {
return Ok(id);
}
// We put a terminus in here, to make sure we don't try and load more than once.
imports.insert(id.clone(), Default::default());
// This loads the manifest in its frontend format (i.e. direct from YAML via serde), including
// all the `includes` for this manifest.
let frontend = self.load_manifest(current, &mut HashSet::new())?;
// Aside: tiny quality of life improvement. In the case where only one channel is supported,
// we use it. This helps with globbing directories where the app wants to keep the feature definition
// away from the feature configuration.
let channel = if frontend.channels.len() == 1 {
frontend.channels.first().unwrap()
} else {
channel
};
let mut manifest = frontend.get_intermediate_representation(&id, channel)?;
// We're now going to go through all the imports in the manifest YAML.
// Each of the import blocks will have a path, and a Map<FeatureId, List<DefaultBlock>>
// This loop does the work of merging the default blocks back into the imported manifests.
// We'll then attach all the manifests to the root (i.e. the one we're generating code for today), in `imports`.
// We associate only the feature ids with the manifest we're loading in this method.
let mut imported_feature_id_map = HashMap::new();
for block in &frontend.imports {
// 1. Load the imported manifests in to the hash map.
let path = self.files.join(current, &block.path)?;
// The channel comes from the importer, rather than the command or the imported file.
let child_id = self.load_imports(&path, &block.channel, imports)?;
let child_manifest = imports.get_mut(&child_id).expect("just loaded this file");
// We detect that there are no name collisions after the loading has finished, with `check_can_import_manifest`.
// We can't do it greedily, because of transitive imports may cause collisions, but we'll check here for better error
// messages.
check_can_import_manifest(&manifest, child_manifest)?;
// We detect that the imported files have language specific files in `validate_manifest_for_lang()`.
// We can't do it now because we don't yet know what this run is going to generate.
// 2. We'll build a set of feature names that this manifest imports from the child manifest.
// This will be the only thing we add directly to the manifest we load in this method.
let mut feature_ids = BTreeSet::new();
// 3. For each of the features in each of the imported files, the user can specify new defaults that should
// merge into/overwrite the defaults specified in the imported file. Let's do that now:
// a. Prepare a DefaultsMerger, with an object map.
let object_map: HashMap<String, &ObjectDef> = child_manifest
.obj_defs
.iter()
.map(|o| (o.name(), o))
.collect();
let merger = DefaultsMerger::new(object_map, frontend.channels.clone(), channel.into());
// b. Prepare a feature map that we'll alter in place.
// EXP- 2540 If we want to support re-exporting/encapsulating features then we will need to change
// this to be a more recursive look up. e.g. change `FeatureManifest.feature_defs` to be a `BTreeMap`.
let mut feature_map: HashMap<String, &mut FeatureDef> = child_manifest
.feature_defs
.iter_mut()
.map(|o| (o.name(), o))
.collect();
// c. Iterate over the features we want to override
for (f, default_blocks) in &block.features {
let feature_def = feature_map.get_mut(f).ok_or_else(|| {
FMLError::FMLModuleError(
id.clone(),
format!(
"Cannot override defaults for `{}` feature from {}",
f, &child_id
),
)
})?;
// d. And merge the overrides in place into the FeatureDefs
merger
.merge_feature_defaults(feature_def, &Some(default_blocks).cloned())
.map_err(|e| FMLError::FMLModuleError(child_id.clone(), e.to_string()))?;
feature_ids.insert(f.clone());
}
// 4. Associate the imports as children of this manifest.
imported_feature_id_map.insert(child_id.clone(), feature_ids);
}
manifest.imported_features = imported_feature_id_map;
imports.insert(id.clone(), manifest);
Ok(id)
}
pub fn get_intermediate_representation(
&self,
channel: &str,
) -> Result<FeatureManifest, FMLError> {
let mut manifests = HashMap::new();
let id = self.load_imports(&self.source, channel, &mut manifests)?;
let mut fm = manifests
.remove(&id)
.expect("Top level manifest should always be present");
for child in manifests.values() {
check_can_import_manifest(&fm, child)?;
}
fm.all_imports = manifests;
Ok(fm)
}
}
impl Parser {
fn check_can_merge_manifest(
&self,
parent_path: &FilePath,
parent: &ManifestFrontEnd,
child_path: &FilePath,
child: &ManifestFrontEnd,
) -> Result<()> {
if !child.channels.is_empty() {
let child = &child.channels;
let child = child.iter().collect::<HashSet<&String>>();
let parent = &parent.channels;
let parent = parent.iter().collect::<HashSet<&String>>();
if !child.is_subset(&parent) {
return Err(FMLError::ValidationError(
"channels".to_string(),
format!(
"Included manifest should not define its own channels: {}",
child_path
),
));
}
}
if let Some(about) = &child.about {
if !about.is_includable() {
return Err(FMLError::ValidationError(
"about".to_string(),
format!("Only files that don't already correspond to generated files may be included: file has a `class` and `package`/`module` name: {}", child_path),
));
}
}
let mut map = Default::default();
self.check_can_merge_imports(parent_path, &parent.imports, &mut map)?;
self.check_can_merge_imports(child_path, &child.imports, &mut map)?;
Ok(())
}
fn canonicalize_import_paths(
&self,
path: &FilePath,
blocks: &mut Vec<ImportBlock>,
) -> Result<()> {
for ib in blocks {
let p = &self.files.join(path, &ib.path)?;
ib.path = p.canonicalize()?.to_string();
}
Ok(())
}
fn check_can_merge_imports(
&self,
path: &FilePath,
blocks: &Vec<ImportBlock>,
map: &mut HashMap<String, String>,
) -> Result<()> {
for b in blocks {
let id = &b.path;
let channel = &b.channel;
let existing = map.insert(id.clone(), channel.clone());
if let Some(v) = existing {
if &v != channel {
return Err(FMLError::FMLModuleError(
path.try_into()?,
format!(
"File {} is imported with two different channels: {} and {}",
id, v, &channel
),
));
}
}
}
Ok(())
}
fn merge_import_block_list(
&self,
parent: &[ImportBlock],
child: &[ImportBlock],
) -> Result<Vec<ImportBlock>> {
let mut map = parent
.iter()
.map(|im| (im.path.clone(), im.clone()))
.collect::<HashMap<_, _>>();
for cib in child {
let path = &cib.path;
if let Some(pib) = map.get(path) {
// We'll define an ordering here: the parent will come after the child
// so the top-level one will override the lower level ones.
// In practice, this shouldn't make a difference.
let merged = merge_import_block(cib, pib)?;