-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor resolver into a tree of callable objects, or partially evalu…
…ated (#95)
- Loading branch information
Showing
8 changed files
with
301 additions
and
301 deletions.
There are no files selected for viewing
This file contains 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 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,53 @@ | ||
from __future__ import absolute_import, unicode_literals | ||
from fluent.syntax import ast as FTL | ||
from . import resolver | ||
|
||
|
||
class Compiler(object): | ||
def __init__(self, use_isolating=False): | ||
self.use_isolating = use_isolating | ||
|
||
def __call__(self, item): | ||
if isinstance(item, FTL.BaseNode): | ||
return self.compile(item) | ||
if isinstance(item, (tuple, list)): | ||
return [self(elem) for elem in item] | ||
return item | ||
|
||
def compile(self, node): | ||
nodename = type(node).__name__ | ||
if not hasattr(resolver, nodename): | ||
return node | ||
kwargs = vars(node).copy() | ||
for propname, propvalue in kwargs.items(): | ||
kwargs[propname] = self(propvalue) | ||
handler = getattr(self, 'compile_' + nodename, self.compile_generic) | ||
return handler(nodename, **kwargs) | ||
|
||
def compile_generic(self, nodename, **kwargs): | ||
return getattr(resolver, nodename)(**kwargs) | ||
|
||
def compile_Placeable(self, _, expression, **kwargs): | ||
if self.use_isolating: | ||
return resolver.IsolatingPlaceable(expression=expression, **kwargs) | ||
if isinstance(expression, resolver.Literal): | ||
return expression | ||
return resolver.Placeable(expression=expression, **kwargs) | ||
|
||
def compile_Pattern(self, _, elements, **kwargs): | ||
if ( | ||
len(elements) == 1 and | ||
isinstance(elements[0], resolver.IsolatingPlaceable) | ||
): | ||
# Don't isolate isolated placeables | ||
return elements[0].expression | ||
if any( | ||
not isinstance(child, resolver.Literal) | ||
for child in elements | ||
): | ||
return resolver.Pattern(elements=elements, **kwargs) | ||
if len(elements) == 1: | ||
return elements[0] | ||
return resolver.TextElement( | ||
''.join(child(None) for child in elements) | ||
) |
Oops, something went wrong.