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
use std::collections::BTreeSet;

use convert_case::{Case, Casing};
use fluent_syntax::ast;
use proc_macro2::Literal;
use quote::format_ident;
use syn::Ident;

use crate::Error;

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Var {
    pub(crate) name: String,
}

impl Var {
    pub fn new(name: String) -> Self {
        Self { name }
    }
    pub fn ident(&self) -> Ident {
        format_ident!("{}", self.name.to_case(Case::Snake))
    }

    pub fn literal(&self) -> Literal {
        Literal::string(&self.name)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Message {
    pub(crate) name: String,
    pub(crate) vars: BTreeSet<Var>,
}

impl Message {
    pub fn parse<T: AsRef<str>>(message: &ast::Message<T>) -> Result<Self, Error> {
        let name = message.id.name.as_ref().to_string();
        let vars = extract_variables(message.value.as_ref())?;
        Ok(Self { name, vars })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn function_ident(&self) -> Ident {
        format_ident!("{}", self.name.to_case(Case::Snake))
    }

    pub fn message_name_literal(&self) -> Literal {
        Literal::string(&self.name)
    }

    pub fn vars(&self) -> BTreeSet<&Var> {
        self.vars.iter().collect()
    }
}

impl<T: AsRef<str>> TryFrom<&ast::Message<T>> for Message {
    type Error = Error;

    fn try_from(value: &ast::Message<T>) -> Result<Self, Self::Error> {
        Message::parse(value)
    }
}

fn extract_variables<T: AsRef<str>>(
    value: Option<&ast::Pattern<T>>,
) -> Result<BTreeSet<Var>, Error> {
    let mut result = BTreeSet::new();
    if let Some(pattern) = value {
        for element in pattern.elements.iter() {
            if let ast::PatternElement::Placeable { expression } = element {
                match expression {
                    ast::Expression::Select { selector, variants } => {
                        if let Some(var) = parse_expression(selector)? {
                            result.insert(Var::new(var));
                        }
                        for variant in variants {
                            result.extend(extract_variables(Some(&variant.value))?.into_iter())
                        }
                    }
                    ast::Expression::Inline(e) => {
                        if let Some(var) = parse_expression(e)? {
                            result.insert(Var::new(var));
                        }
                    }
                }
            }
        }
    }
    Ok(result)
}

fn parse_expression<T: AsRef<str>>(
    inline_expression: &ast::InlineExpression<T>,
) -> Result<Option<String>, Error> {
    match inline_expression {
        ast::InlineExpression::StringLiteral { .. } => Ok(None),
        ast::InlineExpression::NumberLiteral { .. } => Ok(None),
        ast::InlineExpression::FunctionReference { id, .. } => Err(Error::UnsupportedFeature {
            feature: "function reference".to_string(),
            id: id.name.as_ref().to_string(),
        }),
        ast::InlineExpression::MessageReference { id, .. } => Err(Error::UnsupportedFeature {
            feature: "message reference".to_string(),
            id: id.name.as_ref().to_string(),
        }),
        ast::InlineExpression::TermReference { id, .. } => Err(Error::UnsupportedFeature {
            feature: "term reference".to_string(),
            id: id.name.as_ref().to_string(),
        }),

        ast::InlineExpression::VariableReference { id } => Ok(Some(id.name.as_ref().to_string())),
        ast::InlineExpression::Placeable { .. } => Err(Error::UnsupportedFeature {
            feature: "nested expression".to_string(),
            // TODO better diagnostics
            id: "".to_string(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use fluent_syntax::{ast, parser};

    use super::Message;

    fn parse(content: &'static str) -> Vec<ast::Message<&'static str>> {
        let resource = parser::parse(content).unwrap();

        resource
            .body
            .into_iter()
            .filter_map(|entry| {
                if let ast::Entry::Message(message) = entry {
                    Some(message)
                } else {
                    None
                }
            })
            .collect::<Vec<ast::Message<_>>>()
    }

    #[test]
    fn multiline_message() {
        let resource = "test = foo\n    bar\n\ntest1 = foo bar";
        let msg = parse(resource).into_iter().next().unwrap();

        let msg = Message::parse(&msg).unwrap();

        assert_eq!("test", msg.name())
    }
}