Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[API Question] Why FluentBundle::format_pattern takes Option<'bundle FluentArgs> #260

Closed
juliancoffee opened this issue Jul 20, 2022 · 2 comments

Comments

@juliancoffee
Copy link
Contributor

format_pattern has the following signature:

pub fn format_pattern<'bundle>(
       &'bundle self,
       pattern: &'bundle ast::Pattern<&str>,
       args: Option<&'bundle FluentArgs>,
       errors: &mut Vec<FluentError>,
) -> Cow<'bundle, str>

And if I read lifetimes right, it means that args must have the same lifetime as a result. And it's impossible to create args at runtime because their lifetime will be obviously less than the bundle.
I have this code for i18n in my app.

pub struct Locale {
    langs: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
    current_lang: LanguageIdentifier,
}

impl Locale {
    fn bundle(&self) -> &FluentBundle<FluentResource> {
        self.langs
            .get(&self.current_lang)
            .expect("failed to get bundle for current locale")
    }

    pub fn try_msg_ctx(
        &self,
        key: &str,
        args: &[(&str, &str)],
    ) -> Option<String> {
        let bundle = self.bundle();
        let msg = bundle.get_message(key)?;

        let context = wrap(args);

        let mut errs = Vec::new();
        let msg =
            bundle.format_pattern(msg.value()?, Some(&context), &mut errs);
        for err in errs {
            eprintln!("err: {err}")
        }
        
        // notice into_owned here
        Some(msg.into_owned())
    }
}

And because the result of try_msg_ctx borrows lifetime from args, I can't use Cow here and am forced to use String. This means I need to duplicate the code to get message with arguments and without arguments because in the latter case I don't need to create a new string, I can just get it from the bundle, but in the former case, I obviously need to create an owned string. And it seems that I should be ok with just using Cow<'bundle, string>, but because format_pattern links args and result, it doesn't compile (because args will always have a lesser lifetime).
So, my understanding is wrong or things actually can be improved so that args can have their own lifetime?

@juliancoffee
Copy link
Contributor Author

Btw, I think I solved my problem by reordering some lifetimes or just writing better code.
Instead of passing &[(&str, &str)] as args, I used FluentArgs directly and this function just works.
Here are bits of code.

pub struct Locale {
    langs: HashMap<LanguageIdentifier, FluentBundle<FluentResource>>,
    current_lang: LanguageIdentifier,
    fallback: LanguageIdentifier,
}

impl Locale {
    fn bundle(&self) -> &FluentBundle<FluentResource> {
        self.langs
            .get(&self.current_lang)
            .expect("failed to get bundle for current locale")
    }

    fn fallback(&self) -> &FluentBundle<FluentResource> {
        self.langs
            .get(&self.fallback)
            .expect("failed to get bundle for fallback locale")
    }

    fn get_entry(&self, key: &str) -> Option<Entry> {
        let first_bundle = self.bundle();
        let first_msg = first_bundle.get_message(key);
        if let Some(msg) = first_msg {
            Some(Entry {
                bundle: first_bundle,
                msg,
            })
        } else {
            let fallback = self.fallback();
            Some(Entry {
                bundle: fallback,
                msg: fallback.get_message(key)?,
            })
        }
    }

    // Generic way to get message with or without arguments
    pub fn try_msg_cow<'a>(
        &'a self,
        key: &str,
        args: Option<&'a FluentArgs>,
    ) -> Option<Cow<str>> {
        let Entry { bundle, msg } = self.get_entry(key)?;

        let mut errs = Vec::new();
        let msg = bundle.format_pattern(msg.value()?, args, &mut errs);
        for err in errs {
            eprintln!("err: {err}")
        }

        Some(msg)
    }
}

And it doesn't even require calling into_owned() on the call side if I use println right there.

@juliancoffee
Copy link
Contributor Author

And I think I understand now why this is the case (because we may reference args), so closing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant