-
Notifications
You must be signed in to change notification settings - Fork 28
Add type hints to fluent.syntax & fluent.runtime #180
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
Merged
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5924373
syntax: Add type hints
eemeli 5d6957b
syntax: Fix bugs found by static typing
eemeli cda9de6
syntax: Include py.typed, declare __all__
eemeli 60e7be4
runtime: Split FluentBundle to bundle.py to avoid circular imports
eemeli 9633aec
runtime: Add type hints
eemeli bfcc088
runtime: Fix bugs found by static typing
eemeli a8259dd
runtime: Include py.typed, drop unused six dependency
eemeli 27b9235
ci: Add mypy checks for runtime & syntax
eemeli 49e540a
Fix types for python <3.9 using typing-extensions
eemeli af48d23
Apply suggestions from code review
eemeli 96df2e7
Relax tests due to CLDR 42 changes
eemeli 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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,9 @@ | ||
from setuptools import setup, find_namespace_packages | ||
from setuptools import setup | ||
|
||
setup( | ||
name='fluent.docs', | ||
packages=find_namespace_packages(include=['fluent.*']), | ||
packages=['fluent.docs'], | ||
install_requires=[ | ||
'typing-extensions>=3.7,<5' | ||
], | ||
) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,11 @@ | ||
from .types import fluent_date, fluent_number | ||
from typing import Any, Callable, Dict | ||
from .types import FluentType, fluent_date, fluent_number | ||
|
||
NUMBER = fluent_number | ||
DATETIME = fluent_date | ||
|
||
|
||
BUILTINS = { | ||
BUILTINS: Dict[str, Callable[[Any], FluentType]] = { | ||
'NUMBER': NUMBER, | ||
'DATETIME': DATETIME, | ||
} |
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,113 @@ | ||
import babel | ||
import babel.numbers | ||
import babel.plural | ||
from typing import Any, Callable, Dict, List, TYPE_CHECKING, Tuple, Union, cast | ||
from typing_extensions import Literal | ||
|
||
from fluent.syntax import ast as FTL | ||
|
||
from .builtins import BUILTINS | ||
from .prepare import Compiler | ||
from .resolver import CurrentEnvironment, Message, Pattern, ResolverEnvironment | ||
from .utils import native_to_fluent | ||
|
||
if TYPE_CHECKING: | ||
from .types import FluentNone, FluentType | ||
|
||
PluralCategory = Literal['zero', 'one', 'two', 'few', 'many', 'other'] | ||
|
||
|
||
class FluentBundle: | ||
""" | ||
Bundles are single-language stores of translations. They are | ||
aggregate parsed Fluent resources in the Fluent syntax and can | ||
format translation units (entities) to strings. | ||
|
||
Always use `FluentBundle.get_message` to retrieve translation units from | ||
a bundle. Generate the localized string by using `format_pattern` on | ||
`message.value` or `message.attributes['attr']`. | ||
Translations can contain references to other entities or | ||
external arguments, conditional logic in form of select expressions, traits | ||
which describe their grammatical features, and can use Fluent builtins. | ||
See the documentation of the Fluent syntax for more information. | ||
""" | ||
|
||
def __init__(self, | ||
locales: List[str], | ||
functions: Union[Dict[str, Callable[[Any], 'FluentType']], None] = None, | ||
use_isolating: bool = True): | ||
self.locales = locales | ||
_functions = BUILTINS.copy() | ||
if functions: | ||
_functions.update(functions) | ||
self._functions = _functions | ||
self.use_isolating = use_isolating | ||
self._messages: Dict[str, Union[FTL.Message, FTL.Term]] = {} | ||
self._terms: Dict[str, Union[FTL.Message, FTL.Term]] = {} | ||
self._compiled: Dict[str, Message] = {} | ||
# The compiler is not typed, and this cast is only valid for the public API | ||
self._compiler = cast(Callable[[Union[FTL.Message, FTL.Term]], Message], Compiler()) | ||
self._babel_locale = self._get_babel_locale() | ||
self._plural_form = cast(Callable[[Any], Callable[[Union[int, float]], PluralCategory]], | ||
babel.plural.to_python)(self._babel_locale.plural_form) | ||
|
||
def add_resource(self, resource: FTL.Resource, allow_overrides: bool = False) -> None: | ||
# TODO - warn/error about duplicates | ||
for item in resource.body: | ||
if not isinstance(item, (FTL.Message, FTL.Term)): | ||
continue | ||
map_ = self._messages if isinstance(item, FTL.Message) else self._terms | ||
full_id = item.id.name | ||
if full_id not in map_ or allow_overrides: | ||
map_[full_id] = item | ||
|
||
def has_message(self, message_id: str) -> bool: | ||
return message_id in self._messages | ||
|
||
def get_message(self, message_id: str) -> Message: | ||
return self._lookup(message_id) | ||
|
||
def _lookup(self, entry_id: str, term: bool = False) -> Message: | ||
if term: | ||
compiled_id = '-' + entry_id | ||
else: | ||
compiled_id = entry_id | ||
try: | ||
return self._compiled[compiled_id] | ||
except LookupError: | ||
pass | ||
entry = self._terms[entry_id] if term else self._messages[entry_id] | ||
self._compiled[compiled_id] = self._compiler(entry) | ||
return self._compiled[compiled_id] | ||
|
||
def format_pattern(self, | ||
pattern: Pattern, | ||
args: Union[Dict[str, Any], None] = None | ||
) -> Tuple[Union[str, 'FluentNone'], List[Exception]]: | ||
if args is not None: | ||
fluent_args = { | ||
argname: native_to_fluent(argvalue) | ||
for argname, argvalue in args.items() | ||
} | ||
else: | ||
fluent_args = {} | ||
|
||
errors: List[Exception] = [] | ||
env = ResolverEnvironment(context=self, | ||
current=CurrentEnvironment(args=fluent_args), | ||
errors=errors) | ||
try: | ||
result = pattern(env) | ||
except ValueError as e: | ||
errors.append(e) | ||
result = '{???}' | ||
return (result, errors) | ||
|
||
def _get_babel_locale(self) -> babel.Locale: | ||
for lc in self.locales: | ||
try: | ||
return babel.Locale.parse(lc.replace('-', '_')) | ||
except babel.UnknownLocaleError: | ||
continue | ||
# TODO - log error | ||
return babel.Locale.default() |
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.