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
//! The `ResolveValue` trait resolves Fluent AST nodes to [`FluentValues`].
//!
//! This is an internal API used by [`FluentBundle`] to evaluate Messages, Attributes and other
//! AST nodes to [`FluentValues`] which can be then formatted to strings.
//!
//! [`FluentValues`]: ../types/enum.FluentValue.html
//! [`FluentBundle`]: ../bundle/struct.FluentBundle.html

use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

use super::bundle::FluentBundle;
use super::entry::GetEntry;
use super::types::FluentValue;
use fluent_syntax::ast;
use fluent_syntax::unicode::unescape_unicode;

#[derive(Debug, PartialEq)]
pub enum ResolverError {
    None,
    Value,
    Cyclic,
}

/// State for a single `ResolveValue::to_value` call.
pub struct Env<'env> {
    /// The current `FluentBundle` instance.
    pub bundle: &'env FluentBundle<'env>,
    /// The current arguments passed by the developer.
    pub args: Option<&'env HashMap<&'env str, FluentValue>>,
    /// Tracks hashes to prevent infinite recursion.
    pub travelled: RefCell<Vec<u64>>,
}

impl<'env> Env<'env> {
    pub fn new(
        bundle: &'env FluentBundle,
        args: Option<&'env HashMap<&'env str, FluentValue>>,
    ) -> Self {
        Env {
            bundle,
            args,
            travelled: RefCell::new(Vec::new()),
        }
    }

    fn track<F>(&self, identifier: &str, action: F) -> Result<FluentValue, ResolverError>
    where
        F: FnMut() -> Result<FluentValue, ResolverError>,
    {
        let mut hasher = DefaultHasher::new();
        identifier.hash(&mut hasher);
        let hash = hasher.finish();

        if self.travelled.borrow().contains(&hash) {
            Err(ResolverError::Cyclic)
        } else {
            self.travelled.borrow_mut().push(hash);
            self.scope(action)
        }
    }

    fn scope<T, F: FnMut() -> T>(&self, mut action: F) -> T {
        let level = self.travelled.borrow().len();
        let output = action();
        self.travelled.borrow_mut().truncate(level);
        output
    }
}

/// Converts an AST node to a `FluentValue`.
pub trait ResolveValue {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError>;
}

impl<'source> ResolveValue for ast::Message<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        env.track(&self.id.name, || {
            self.value
                .as_ref()
                .ok_or(ResolverError::None)?
                .to_value(env)
        })
    }
}

impl<'source> ResolveValue for ast::Term<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        env.track(&self.id.name, || self.value.to_value(env))
    }
}

impl<'source> ResolveValue for ast::Attribute<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        env.track(&self.id.name, || self.value.to_value(env))
    }
}

impl<'source> ResolveValue for ast::Pattern<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        let mut string = String::with_capacity(128);
        for elem in &self.elements {
            let result: Result<String, ()> = env.scope(|| match elem.to_value(env) {
                Err(ResolverError::Cyclic) => Err(()),
                Err(_) => Ok("___".into()),
                Ok(elem) => Ok(elem.format(env.bundle)),
            });

            match result {
                Err(()) => return Ok("___".into()),
                Ok(value) => {
                    string.push_str(&value);
                }
            }
        }
        string.shrink_to_fit();
        Ok(FluentValue::from(string))
    }
}

impl<'source> ResolveValue for ast::PatternElement<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        match self {
            ast::PatternElement::TextElement(s) => Ok(FluentValue::from(*s)),
            ast::PatternElement::Placeable(p) => p.to_value(env),
        }
    }
}

impl<'source> ResolveValue for ast::VariantKey<'source> {
    fn to_value(&self, _env: &Env) -> Result<FluentValue, ResolverError> {
        match self {
            ast::VariantKey::Identifier { name } => Ok(FluentValue::from(*name)),
            ast::VariantKey::NumberLiteral { value } => {
                FluentValue::into_number(value).map_err(|_| ResolverError::Value)
            }
        }
    }
}

impl<'source> ResolveValue for ast::Expression<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        match self {
            ast::Expression::InlineExpression(exp) => exp.to_value(env),
            ast::Expression::SelectExpression { selector, variants } => {
                if let Ok(ref selector) = selector.to_value(env) {
                    for variant in variants {
                        match variant.key {
                            ast::VariantKey::Identifier { name } => {
                                let key = FluentValue::from(name);
                                if key.matches(env.bundle, selector) {
                                    return variant.value.to_value(env);
                                }
                            }
                            ast::VariantKey::NumberLiteral { value } => {
                                if let Ok(key) = FluentValue::into_number(value) {
                                    if key.matches(env.bundle, selector) {
                                        return variant.value.to_value(env);
                                    }
                                } else {
                                    return Err(ResolverError::Value);
                                }
                            }
                        }
                    }
                }

                select_default(variants)
                    .ok_or(ResolverError::None)?
                    .value
                    .to_value(env)
            }
        }
    }
}

impl<'source> ResolveValue for ast::InlineExpression<'source> {
    fn to_value(&self, env: &Env) -> Result<FluentValue, ResolverError> {
        match self {
            ast::InlineExpression::StringLiteral { value } => {
                Ok(FluentValue::from(unescape_unicode(value).into_owned()))
            }
            ast::InlineExpression::NumberLiteral { value } => {
                FluentValue::into_number(*value).map_err(|_| ResolverError::None)
            }
            ast::InlineExpression::FunctionReference { id, arguments } => {
                let (resolved_positional_args, resolved_named_args) = get_arguments(env, arguments);

                let func = env.bundle.entries.get_function(id.name);

                func.ok_or(ResolverError::None).and_then(|func| {
                    func(resolved_positional_args.as_slice(), &resolved_named_args)
                        .ok_or(ResolverError::None)
                })
            }
            ast::InlineExpression::MessageReference { id, attribute } => {
                let msg = env
                    .bundle
                    .entries
                    .get_message(&id.name)
                    .ok_or(ResolverError::None)?;
                if let Some(attribute) = attribute {
                    for attr in msg.attributes.iter() {
                        if attr.id.name == attribute.name {
                            return attr.to_value(env);
                        }
                    }
                    Err(ResolverError::None)
                } else {
                    msg.to_value(env)
                }
            }
            ast::InlineExpression::TermReference {
                id,
                attribute,
                arguments,
            } => {
                let term = env
                    .bundle
                    .entries
                    .get_term(&id.name)
                    .ok_or(ResolverError::None)?;

                let (.., resolved_named_args) = get_arguments(env, arguments);
                let env = Env::new(env.bundle, Some(&resolved_named_args));

                if let Some(attribute) = attribute {
                    for attr in term.attributes.iter() {
                        if attr.id.name == attribute.name {
                            return attr.to_value(&env);
                        }
                    }
                    Err(ResolverError::None)
                } else {
                    term.to_value(&env)
                }
            }
            ast::InlineExpression::VariableReference { id } => env
                .args
                .and_then(|args| args.get(&id.name))
                .cloned()
                .ok_or(ResolverError::None),
            ast::InlineExpression::Placeable { ref expression } => {
                let exp = expression.as_ref();
                exp.to_value(env)
            }
        }
    }
}

fn select_default<'source>(
    variants: &'source [ast::Variant<'source>],
) -> Option<&ast::Variant<'source>> {
    for variant in variants {
        if variant.default {
            return Some(variant);
        }
    }

    None
}

fn get_arguments<'env>(
    env: &Env,
    arguments: &'env Option<ast::CallArguments>,
) -> (Vec<Option<FluentValue>>, HashMap<&'env str, FluentValue>) {
    let mut resolved_positional_args = Vec::new();
    let mut resolved_named_args = HashMap::new();

    if let Some(ast::CallArguments { named, positional }) = arguments {
        for expression in positional {
            resolved_positional_args.push(expression.to_value(env).ok());
        }

        for arg in named {
            if let Ok(arg_value) = arg.value.to_value(env) {
                resolved_named_args.insert(arg.name.name, arg_value);
            }
        }
    }

    (resolved_positional_args, resolved_named_args)
}