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

Allow deepcopy of fparser tree #453

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*.pyc
*~
src/**/*.mod
arporter marked this conversation as resolved.
Show resolved Hide resolved
*.log
_build/
htmlcov/
Expand Down
19 changes: 17 additions & 2 deletions src/fparser/two/Fortran2003.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,19 +252,22 @@ class Program(BlockBase): # R201
use_names = ["Program_Unit"]

@show_result
def __new__(cls, string):
def __new__(cls, string, _deepcopy=False):
"""Wrapper around base class __new__ to catch an internal NoMatchError
exception and raise it as an external FortranSyntaxError exception.

schreiberx marked this conversation as resolved.
Show resolved Hide resolved
:param type cls: the class of object to create
:param string: (source of) Fortran string to parse
:type string: :py:class:`FortranReaderBase`
:param _deepcopy: Flag to signal whether this class is
created by a deep copy
:type _deepcopy: bool
:raises FortranSyntaxError: if the code is not valid Fortran
arporter marked this conversation as resolved.
Show resolved Hide resolved

"""
# pylint: disable=unused-argument
try:
return Base.__new__(cls, string)
return Base.__new__(cls, string, _deepcopy=_deepcopy)
except NoMatchError:
# At the moment there is no useful information provided by
# NoMatchError so we pass on an empty string.
Expand All @@ -277,6 +280,18 @@ def __new__(cls, string):
# provides line number information).
raise FortranSyntaxError(string, excinfo)

def __getnewargs__(self):
"""Method to dictate the values passed to the __new__() method upon
unpickling. The method must return a pair (args, kwargs) where
args is a tuple of positional arguments and kwargs a dictionary
of named arguments for constructing the object. Those will be
passed to the __new__() method upon unpickling.

:return: set of arguments for __new__
:rtype: set
arporter marked this conversation as resolved.
Show resolved Hide resolved
"""
return (self.string, True)

@staticmethod
def match(reader):
"""Implements the matching for a Program. Whilst the rule looks like
Expand Down
44 changes: 44 additions & 0 deletions src/fparser/two/tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,47 @@ class do not affect current calls.
with pytest.raises(ValueError) as excinfo:
parser = ParserFactory().create(std="invalid")
assert "is an invalid standard" in str(excinfo.value)


def test_deepcopy():
"""
Test that we can deepcopy a parsed fparser tree.
"""

f90_source = """
program main

implicit none

end
"""
parser = ParserFactory().create(std="f2008")
reader = FortranStringReader(f90_source)
ast = parser(reader)

import copy

_ = copy.deepcopy(ast)
arporter marked this conversation as resolved.
Show resolved Hide resolved


def test_pickle():
"""
Test that we can pickle and unpickle a parsed fparser tree.
"""

f90_source = """
program main

implicit none

end
"""

parser = ParserFactory().create(std="f2008")
reader = FortranStringReader(f90_source)
ast = parser(reader)

import pickle

s = pickle.dumps(ast)
_ = pickle.loads(s)
arporter marked this conversation as resolved.
Show resolved Hide resolved
19 changes: 18 additions & 1 deletion src/fparser/two/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ def __init__(self, string, parent_cls=None):
self.parent = None

@show_result
def __new__(cls, string, parent_cls=None):
def __new__(cls, string, parent_cls=None, _deepcopy=False):
if parent_cls is None:
parent_cls = [cls]
elif cls not in parent_cls:
Expand All @@ -418,6 +418,11 @@ def __new__(cls, string, parent_cls=None):
# Get the class' match method if it has one
match = getattr(cls, "match", None)

if _deepcopy:
# If this is part of a deep-copy operation (and string is None), simply call
# the super method without string
return super().__new__(cls)

if (
isinstance(string, FortranReaderBase)
and match
Expand Down Expand Up @@ -505,6 +510,18 @@ def __new__(cls, string, parent_cls=None):
errmsg = f"{cls.__name__}: '{string}'"
raise NoMatchError(errmsg)

def __getnewargs__(self):
"""Method to dictate the values passed to the __new__() method upon
unpickling. The method must return a pair (args, kwargs) where
args is a tuple of positional arguments and kwargs a dictionary
of named arguments for constructing the object. Those will be
passed to the __new__() method upon unpickling.

:return: set of arguments for __new__
:rtype: set
arporter marked this conversation as resolved.
Show resolved Hide resolved
"""
return (self.string, None, True)
schreiberx marked this conversation as resolved.
Show resolved Hide resolved

def get_root(self):
"""
Gets the node at the root of the parse tree to which this node belongs.
Expand Down
Loading