-
Notifications
You must be signed in to change notification settings - Fork 100
Allow customizing argument resolver #304
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
Open
JasperDeSutter
wants to merge
3
commits into
projectfluent:main
Choose a base branch
from
JasperDeSutter:argument-resolver
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
bdc2c57
refactor(fluent-bundle): Store FluentArg keys as &str instead of Cow
JasperDeSutter 13d5c56
feat(fluent-bundle): Allow passing a custom argument resolver to format
JasperDeSutter 4f67e69
docs(fluent-bundle): Add typesafe message arguments example
JasperDeSutter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
// This is an example of an application which adds a custom argument resolver | ||
// to add type safety. | ||
// See the external_arguments example if you are not yet familiar with fluent arguments. | ||
// | ||
// The goal is that we prevent bugs caused by mixing up arguments that belong | ||
// to different messages. | ||
// We can achieve this by defining structs for each message that encode the | ||
// argument types with the corresponding message ID, and then hooking into | ||
// fluent's resolver using a custom fluent_bundle::ArgumentResolver implementation. | ||
|
||
use std::borrow::Cow; | ||
|
||
use fluent_bundle::{ArgumentResolver, FluentBundle, FluentError, FluentResource, FluentValue}; | ||
use unic_langid::langid; | ||
|
||
fn main() { | ||
let ftl_string = String::from( | ||
" | ||
hello-world = Hello { $name } | ||
ref = The previous message says { hello-world } | ||
unread-emails = | ||
{ $emailCount -> | ||
[one] You have { $emailCount } unread email | ||
*[other] You have { $emailCount } unread emails | ||
} | ||
", | ||
); | ||
let res = FluentResource::try_new(ftl_string).expect("Could not parse an FTL string."); | ||
let langid_en = langid!("en"); | ||
let mut bundle = FluentBundle::new(vec![langid_en]); | ||
bundle | ||
.add_resource(res) | ||
.expect("Failed to add FTL resources to the bundle."); | ||
|
||
let hello_world = messages::HelloWorld { name: "John" }; | ||
let mut errors = vec![]; | ||
let value = bundle.format_message(&hello_world, &mut errors); | ||
println!("{}", value); | ||
|
||
let ref_msg = messages::Ref { hello_world }; | ||
let mut errors = vec![]; | ||
let value = bundle.format_message(&ref_msg, &mut errors); | ||
println!("{}", value); | ||
|
||
let unread_emails = messages::UnreadEmails { | ||
email_count: Some(1), | ||
}; | ||
let mut errors = vec![]; | ||
let value = bundle.format_message(&unread_emails, &mut errors); | ||
println!("{}", value); | ||
} | ||
|
||
// these definitions could be generated by a macro or a code generation tool | ||
mod messages { | ||
use super::*; | ||
|
||
pub struct HelloWorld<'a> { | ||
pub name: &'a str, | ||
} | ||
|
||
impl<'a> Message<'a> for HelloWorld<'a> { | ||
fn id(&self) -> &'static str { | ||
"hello-world" | ||
} | ||
|
||
fn get_arg(&self, name: &str) -> Option<FluentValue<'a>> { | ||
Some(match name { | ||
"name" => self.name.into(), | ||
_ => return None, | ||
}) | ||
} | ||
} | ||
|
||
pub struct Ref<'a> { | ||
pub hello_world: HelloWorld<'a>, | ||
} | ||
|
||
impl<'a> Message<'a> for Ref<'a> { | ||
fn id(&self) -> &'static str { | ||
"ref" | ||
} | ||
|
||
fn get_arg(&self, name: &str) -> Option<FluentValue<'a>> { | ||
self.hello_world.get_arg(name) | ||
} | ||
} | ||
|
||
pub struct UnreadEmails { | ||
pub email_count: Option<u32>, | ||
} | ||
|
||
impl<'a> Message<'a> for UnreadEmails { | ||
fn id(&self) -> &'static str { | ||
"unread-emails" | ||
} | ||
|
||
fn get_arg(&self, name: &str) -> Option<FluentValue<'a>> { | ||
Some(match name { | ||
"emailCount" => self.email_count.into(), | ||
_ => return None, | ||
}) | ||
} | ||
} | ||
} | ||
|
||
trait Message<'a> { | ||
fn id(&self) -> &'static str; | ||
fn get_arg(&self, name: &str) -> Option<FluentValue<'a>>; | ||
} | ||
|
||
// by using &dyn, we prevent monomorphization for each Message struct | ||
// this keeps binary code size in check | ||
impl<'a, 'b> ArgumentResolver<'a> for &'a dyn Message<'b> { | ||
fn resolve(self, name: &str) -> Option<Cow<FluentValue<'a>>> { | ||
let arg = self.get_arg(name)?; | ||
Some(Cow::Owned(arg)) | ||
} | ||
} | ||
|
||
// allows for method syntax, i.e. bundle.format_message(...) | ||
trait CustomizedBundle { | ||
fn format_message<'b>( | ||
&'b self, | ||
message: &dyn Message, | ||
errors: &mut Vec<FluentError>, | ||
) -> Cow<'b, str>; | ||
} | ||
|
||
impl CustomizedBundle for FluentBundle<FluentResource> { | ||
fn format_message<'b>( | ||
&'b self, | ||
message: &dyn Message, | ||
errors: &mut Vec<FluentError>, | ||
) -> Cow<'b, str> { | ||
let msg = self | ||
.get_message(message.id()) | ||
.expect("Message doesn't exist."); | ||
|
||
let pattern = msg.value().expect("Message has no value."); | ||
self.format_pattern_with_argument_resolver(pattern, message, errors) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.