summaryrefslogtreecommitdiffstats
path: root/intl/l10n/rust/l10nregistry-rs/src/registry/synchronous.rs
blob: 097ca68eee9714399f0eb031c2fab57fffc0df2b (plain)
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
use super::{BundleAdapter, L10nRegistry, MetaSources};
use crate::env::ErrorReporter;
use crate::errors::L10nRegistryError;
use crate::fluent::{FluentBundle, FluentError};
use crate::solver::{SerialProblemSolver, SyncTester};
use crate::source::ResourceOption;
use fluent_fallback::{generator::BundleIterator, types::ResourceId};
use unic_langid::LanguageIdentifier;

impl MetaSources {
    pub(crate) fn bundle_from_order<P, B>(
        &self,
        metasource: usize,
        locale: LanguageIdentifier,
        source_order: &[usize],
        resource_ids: &[ResourceId],
        error_reporter: &P,
        bundle_adapter: Option<&B>,
    ) -> Option<Result<FluentBundle, (FluentBundle, Vec<FluentError>)>>
    where
        P: ErrorReporter,
        B: BundleAdapter,
    {
        let mut bundle = FluentBundle::new(vec![locale.clone()]);

        if let Some(bundle_adapter) = bundle_adapter {
            bundle_adapter.adapt_bundle(&mut bundle);
        }

        let mut errors = vec![];

        for (&source_idx, resource_id) in source_order.iter().zip(resource_ids.iter()) {
            let source = self.filesource(metasource, source_idx);
            if let ResourceOption::Some(res) =
                source.fetch_file_sync(&locale, resource_id, /* overload */ true)
            {
                if source.options.allow_override {
                    bundle.add_resource_overriding(res);
                } else if let Err(err) = bundle.add_resource(res) {
                    errors.extend(err.into_iter().map(|error| L10nRegistryError::FluentError {
                        resource_id: resource_id.clone(),
                        loc: None,
                        error,
                    }));
                }
            } else if resource_id.is_required() {
                return None;
            }
        }

        if !errors.is_empty() {
            error_reporter.report_errors(errors);
        }
        Some(Ok(bundle))
    }
}

impl<P, B> L10nRegistry<P, B>
where
    P: Clone,
    B: Clone,
{
    /// A test-only function for easily generating bundles for a single langid.
    #[cfg(feature = "test-fluent")]
    pub fn generate_bundles_for_lang_sync(
        &self,
        langid: LanguageIdentifier,
        resource_ids: Vec<ResourceId>,
    ) -> GenerateBundlesSync<P, B> {
        let lang_ids = vec![langid];

        GenerateBundlesSync::new(self.clone(), lang_ids.into_iter(), resource_ids)
    }

    /// Wiring for hooking up the synchronous bundle generation to the
    /// [BundleGenerator] trait.
    pub fn generate_bundles_sync(
        &self,
        locales: std::vec::IntoIter<LanguageIdentifier>,
        resource_ids: Vec<ResourceId>,
    ) -> GenerateBundlesSync<P, B> {
        GenerateBundlesSync::new(self.clone(), locales, resource_ids)
    }
}

enum State {
    Empty,
    Locale(LanguageIdentifier),
    Solver {
        locale: LanguageIdentifier,
        solver: SerialProblemSolver,
    },
}

impl Default for State {
    fn default() -> Self {
        Self::Empty
    }
}

impl State {
    fn get_locale(&self) -> &LanguageIdentifier {
        match self {
            Self::Locale(locale) => locale,
            Self::Solver { locale, .. } => locale,
            Self::Empty => unreachable!("Attempting to get a locale for an empty state."),
        }
    }

    fn take_solver(&mut self) -> SerialProblemSolver {
        replace_with::replace_with_or_default_and_return(self, |self_| match self_ {
            Self::Solver { locale, solver } => (solver, Self::Locale(locale)),
            _ => unreachable!("Attempting to take a solver in an invalid state."),
        })
    }

    fn put_back_solver(&mut self, solver: SerialProblemSolver) {
        replace_with::replace_with_or_default(self, |self_| match self_ {
            Self::Locale(locale) => Self::Solver { locale, solver },
            _ => unreachable!("Attempting to put back a solver in an invalid state."),
        })
    }
}

pub struct GenerateBundlesSync<P, B> {
    reg: L10nRegistry<P, B>,
    locales: std::vec::IntoIter<LanguageIdentifier>,
    current_metasource: usize,
    resource_ids: Vec<ResourceId>,
    state: State,
}

impl<P, B> GenerateBundlesSync<P, B> {
    fn new(
        reg: L10nRegistry<P, B>,
        locales: std::vec::IntoIter<LanguageIdentifier>,
        resource_ids: Vec<ResourceId>,
    ) -> Self {
        Self {
            reg,
            locales,
            current_metasource: 0,
            resource_ids,
            state: State::Empty,
        }
    }
}

impl<P, B> SyncTester for GenerateBundlesSync<P, B> {
    fn test_sync(&self, res_idx: usize, source_idx: usize) -> bool {
        let locale = self.state.get_locale();
        let resource_id = &self.resource_ids[res_idx];
        !self
            .reg
            .try_borrow_metasources()
            .expect("Unable to get the MetaSources.")
            .filesource(self.current_metasource, source_idx)
            .fetch_file_sync(locale, resource_id, /* overload */ true)
            .is_required_and_missing()
    }
}

impl<P, B> BundleIterator for GenerateBundlesSync<P, B>
where
    P: ErrorReporter,
{
    fn prefetch_sync(&mut self) {
        if let State::Solver { .. } = self.state {
            let mut solver = self.state.take_solver();
            if let Err(idx) = solver.try_next(self, true) {
                self.reg
                    .shared
                    .provider
                    .report_errors(vec![L10nRegistryError::MissingResource {
                        locale: self.state.get_locale().clone(),
                        resource_id: self.resource_ids[idx].clone(),
                    }]);
            }
            self.state.put_back_solver(solver);
            return;
        }

        if let Some(locale) = self.locales.next() {
            let mut solver = SerialProblemSolver::new(
                self.resource_ids.len(),
                self.reg
                    .try_borrow_metasources()
                    .expect("Unable to get the MetaSources.")
                    .get(self.current_metasource)
                    .len(),
            );
            self.state = State::Locale(locale.clone());
            if let Err(idx) = solver.try_next(self, true) {
                self.reg
                    .shared
                    .provider
                    .report_errors(vec![L10nRegistryError::MissingResource {
                        locale,
                        resource_id: self.resource_ids[idx].clone(),
                    }]);
            }
            self.state.put_back_solver(solver);
        }
    }
}

impl<P, B> Iterator for GenerateBundlesSync<P, B>
where
    P: ErrorReporter,
    B: BundleAdapter,
{
    type Item = Result<FluentBundle, (FluentBundle, Vec<FluentError>)>;

    /// Synchronously generate a bundle based on a solver.
    fn next(&mut self) -> Option<Self::Item> {
        let metasources = self
            .reg
            .try_borrow_metasources()
            .expect("Unable to get the MetaSources.");

        if metasources.is_empty() {
            // There are no metasources available, so no bundles can be generated.
            return None;
        }

        loop {
            if let State::Solver { .. } = self.state {
                // A solver has already been set up, continue iterating through the
                // resources and generating a bundle.
                let mut solver = self.state.take_solver();
                let solver_result = solver.try_next(self, false);

                if let Ok(Some(order)) = solver_result {
                    // The solver resolved an ordering, and a bundle may be able
                    // to be generated.

                    let bundle = metasources.bundle_from_order(
                        self.current_metasource,
                        self.state.get_locale().clone(),
                        &order,
                        &self.resource_ids,
                        &self.reg.shared.provider,
                        self.reg.shared.bundle_adapter.as_ref(),
                    );

                    self.state.put_back_solver(solver);

                    if bundle.is_some() {
                        // The bundle was successfully generated.
                        return bundle;
                    }

                    // No bundle was generated, continue on.
                    continue;
                }

                // There is no bundle ordering available.

                if self.current_metasource > 0 {
                    // There are more metasources, create a new solver and try the
                    // next metasource. If there is an error in the solver_result
                    // ignore it for now, since there are more metasources.
                    self.current_metasource -= 1;
                    let solver = SerialProblemSolver::new(
                        self.resource_ids.len(),
                        metasources.get(self.current_metasource).len(),
                    );
                    self.state = State::Solver {
                        locale: self.state.get_locale().clone(),
                        solver,
                    };
                    continue;
                }

                if let Err(idx) = solver_result {
                    // Since there are no more metasources, and there is an error,
                    // report it instead of ignoring it.
                    self.reg.shared.provider.report_errors(vec![
                        L10nRegistryError::MissingResource {
                            locale: self.state.get_locale().clone(),
                            resource_id: self.resource_ids[idx].clone(),
                        },
                    ]);
                }

                self.state = State::Empty;
                continue;
            }

            // Try the next locale, or break out of the loop if there are none left.
            let locale = self.locales.next()?;

            // Restart at the end of the metasources for this locale, and iterate
            // backwards.
            let last_metasource_idx = metasources.len() - 1;
            self.current_metasource = last_metasource_idx;

            let solver = SerialProblemSolver::new(
                self.resource_ids.len(),
                metasources.get(self.current_metasource).len(),
            );

            // Continue iterating on the next solver.
            self.state = State::Solver { locale, solver };
        }
    }
}