-
Notifications
You must be signed in to change notification settings - Fork 25
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
Add support for parsing dotted names into tags #57
Open
kaushikcfd
wants to merge
13
commits into
inducer:main
Choose a base branch
from
kaushikcfd:parse_tag
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 8 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
c1085fb
add support for parsing dotted names into tags
kaushikcfd 016d50b
add mako, lark to dependencies
kaushikcfd e3196ef
typo fix
kaushikcfd f585143
testlib.py -> testlib_tags.py
kaushikcfd 838592a
static tags parsing grammar
kaushikcfd 52599f8
removes dep:Mako; makes 'lark' a soft dependency
kaushikcfd db50fb9
formatting
kaushikcfd 29ec0c3
Merge branch 'master' into parse_tag
inducer 6583c32
moves grammar to tags.lark
kaushikcfd ff625d9
memoize parser construction; remove pytools.tag's hard dep on lark
kaushikcfd 6fb2eb3
moves the args flattening inside the mixin
kaushikcfd 4189294
Merge branch 'master' into parse_tag
kaushikcfd 9501b80
Merge branch 'main' into parse_tag
inducer 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 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
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 |
---|---|---|
@@ -1,5 +1,8 @@ | ||
from dataclasses import dataclass | ||
from typing import Tuple, Any, FrozenSet, Union, Iterable, TypeVar | ||
import importlib | ||
|
||
from lark import Lark, Transformer | ||
kaushikcfd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from pytools import memoize | ||
|
||
__copyright__ = """ | ||
|
@@ -40,6 +43,8 @@ | |
.. autoclass:: Taggable | ||
.. autoclass:: Tag | ||
.. autoclass:: UniqueTag | ||
.. autoclass:: ToPythonObjectMapper | ||
.. autofunction:: parse_tag | ||
|
||
Supporting Functionality | ||
------------------------ | ||
|
@@ -257,4 +262,152 @@ def without_tags(self: T_co, | |
|
||
# }}} | ||
|
||
|
||
# {{{ parse | ||
|
||
TAG_GRAMMAR = """ | ||
tag: tag_class "(" params ")" -> map_tag_from_python_class | ||
| SHORTCUT -> map_tag_from_shortcut | ||
|
||
params: -> map_empty_args_params | ||
| args -> map_args_only_params | ||
| kwargs -> map_kwargs_only_params | ||
| args "," kwargs -> map_args_kwargs_params | ||
|
||
?kwargs: kwarg | ||
| kwargs "," kwarg -> map_kwargs | ||
|
||
args: arg -> map_singleton_args | ||
| args "," arg -> map_args | ||
|
||
kwarg: name "=" arg -> map_kwarg | ||
|
||
?arg: tag | ||
| INT -> map_int | ||
| ESCAPED_STRING -> map_string | ||
|
||
tag_class: module "." name -> map_tag_class | ||
|
||
module: name -> map_top_level_module | ||
| module "." name -> map_nested_module | ||
|
||
name: CNAME -> map_name | ||
SHORTCUT: "." ("_"|LETTER) ("_"|LETTER|DIGIT|".")* | ||
|
||
%import common.INT | ||
%import common.ESCAPED_STRING | ||
%import common.DIGIT | ||
%import common.LETTER | ||
%import common.CNAME | ||
%import common.WS | ||
%ignore WS | ||
""" | ||
kaushikcfd marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looked over the grammar, looks OK. (Please leave this for me to resolve at final review.) |
||
|
||
|
||
class CallParams: | ||
""" | ||
Intermediate data structure for :class:`ToPythonObjectMapper`. | ||
""" | ||
def __init__(self, args, kwargs): | ||
self.args = args | ||
self.kwargs = kwargs | ||
|
||
|
||
class ToPythonObjectMapper(Transformer): | ||
""" | ||
Map a parsed tree to pythonic objects. | ||
""" | ||
def __init__(self, shortcuts, caller_globals): | ||
super().__init__() | ||
self.shortcuts = shortcuts | ||
self.caller_globals = caller_globals | ||
|
||
def _call_userfunc(self, tree, new_children=None): | ||
# Assumes tree is already transformed | ||
children = new_children if new_children is not None else tree.children | ||
try: | ||
f = getattr(self, tree.data) | ||
except AttributeError: | ||
return self.__default__(tree.data, children, tree.meta) | ||
else: | ||
# flatten the args | ||
return f(*children) | ||
|
||
def map_tag_from_python_class(self, cls, params): | ||
try: | ||
return cls(*params.args, **params.kwargs) | ||
except TypeError as e: | ||
raise TypeError(f"Error while instantiating '{cls.__name__}': {e}") | ||
|
||
def map_empty_args_params(self): | ||
return CallParams((), {}) | ||
|
||
def map_args_only_params(self, args): | ||
return CallParams(args, {}) | ||
|
||
def map_kwargs_only_params(self, kwargs): | ||
return CallParams((), kwargs) | ||
|
||
def map_args_kwargs_params(self, args, kwargs): | ||
return CallParams(args, kwargs) | ||
|
||
def map_name(self, tok): | ||
return tok.value | ||
|
||
def map_top_level_module(self, modulename): | ||
try: | ||
return self.caller_globals[modulename] | ||
except KeyError: | ||
return importlib.import_module(modulename) | ||
|
||
def map_nested_module(self, module, child): | ||
return getattr(module, child) | ||
|
||
def map_tag_class(self, module, classname): | ||
return getattr(module, classname) | ||
|
||
def map_string(self, text): | ||
return str(text) | ||
|
||
def map_int(self, text): | ||
return int(text) | ||
|
||
def map_singleton_args(self, arg): | ||
return (arg,) | ||
|
||
def map_args(self, args, arg): | ||
return args + (arg,) | ||
|
||
def map_kwarg(self, name, arg): | ||
return {name: arg} | ||
|
||
def map_kwargs(self, kwargs, kwarg): | ||
assert len(kwarg) == 1 | ||
(key, val), = kwarg.items() | ||
if key in kwargs: | ||
raise ValueError(f"keyword argument '{key}' repeated") | ||
|
||
updated_kwargs = kwargs.copy() | ||
updated_kwargs[key] = val | ||
return updated_kwargs | ||
|
||
def map_tag_from_shortcut(self, name): | ||
name = name[1:] # remove the starting "." | ||
return self.shortcuts[name] | ||
|
||
|
||
def parse_tag(tag_text, shortcuts={}): | ||
""" | ||
Parses a :class:`Tag` from a provided dotted name. | ||
""" | ||
import inspect | ||
caller_globals = inspect.currentframe().f_back.f_globals | ||
parser = Lark(TAG_GRAMMAR, start="tag") | ||
kaushikcfd marked this conversation as resolved.
Show resolved
Hide resolved
kaushikcfd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tag = ToPythonObjectMapper(shortcuts, caller_globals).transform( | ||
parser.parse(tag_text)) | ||
|
||
return tag | ||
|
||
# }}} | ||
|
||
# vim: foldmethod=marker |
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,43 @@ | ||
import sys | ||
import pytest | ||
import testlib_tags as testlib # noqa | ||
|
||
|
||
def test_parse_tags(): | ||
from pytools.tag import parse_tag | ||
|
||
def assert_same_as_python(tag_text): | ||
assert parse_tag(tag_text) == eval(tag_text) | ||
|
||
assert_same_as_python("testlib.FruitNameTag(testlib.MangoTag())") | ||
assert_same_as_python("testlib.LocalAxisTag(0)") | ||
assert_same_as_python('testlib.ColorTag("blue")') | ||
assert_same_as_python('testlib.ColorTag(color="blue")') | ||
assert_same_as_python("testlib.LocalAxisTag(axis=0)") | ||
|
||
assert (parse_tag("testlib.FruitNameTag(.mango)", | ||
shortcuts={"mango": testlib.MangoTag(), | ||
"apple": testlib.AppleTag()}) | ||
== testlib.FruitNameTag(testlib.MangoTag())) | ||
|
||
assert (parse_tag(".l.0", | ||
shortcuts={"l.0": testlib.LocalAxisTag(0)}) | ||
== testlib.LocalAxisTag(axis=0)) | ||
|
||
|
||
def test_parse_tag_raises(): | ||
from pytools.tag import parse_tag | ||
|
||
with pytest.raises(ValueError): | ||
parse_tag('testlib.ColorTag(color="green",color="blue")') | ||
|
||
with pytest.raises(TypeError): | ||
parse_tag('testlib.ColorTag(typoed_kwarg_name="typo",color="blue")') | ||
|
||
|
||
if __name__ == "__main__": | ||
if len(sys.argv) > 1: | ||
exec(sys.argv[1]) | ||
else: | ||
from pytest import main | ||
main([__file__]) |
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,26 @@ | ||
from pytools.tag import Tag, UniqueTag | ||
|
||
|
||
class FruitNameTag(UniqueTag): | ||
def __init__(self, tag): | ||
self.tag = tag | ||
|
||
|
||
class MangoTag(Tag): | ||
def __str__(self): | ||
return "mango" | ||
|
||
|
||
class AppleTag(Tag): | ||
def __str__(self): | ||
return "apple" | ||
|
||
|
||
class ColorTag(Tag): | ||
def __init__(self, color): | ||
self.color = color | ||
|
||
|
||
class LocalAxisTag(Tag): | ||
def __init__(self, axis): | ||
self.axis = axis |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you push a sister MR to Gitlab (add the link to the PR description) to ensure that passes, too?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://gitlab.tiker.net/inducer/pytools/-/merge_requests/52