How to use fparser - 10 common examples

To help you get started, we’ve selected a few fparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github arporter / habakkuk / src / habakkuk / dag.py View on Github external
elif isinstance(child, Fortran2003.Structure_Constructor):
                # This is a structure constructor. Make a node for it.
                node_list.append(self.get_node(parent, name=str(child)))
            elif isinstance(child, Fortran2003.Structure_Constructor_2):
                # This is a structure constructor, e.g.
                # mask = tmask_i(:, :). Make a node for it.
                tmp_node = self.get_node(parent, name=str(child.items[0]))
                node_list.append(tmp_node)
                node_list += self.make_dag(tmp_node, child.items[2:], mapping)
            elif (isinstance(child, Fortran2003.Level_3_Expr) or
                  isinstance(child, Fortran2003.Level_4_Expr)):
                # Have an expression that is something like
                # TRIM(ssnd(ji) % clname) // '_cat' // cli2. Carry on
                # down to the children
                node_list += self.make_dag(parent, child.items, mapping)
            elif isinstance(child, Fortran2003.Data_Ref):
                # Have an expression that is something like
                # ssnd(ji) % clname. Make a node to represent it.
                dvar = Variable()
                dvar.load(child, mapping)
                tmp_node = self.get_node(parent, variable=dvar)
                node_list.append(tmp_node)
                # TODO handle case where the component of the derived type
                # is itself an array, e.g. ssnd % clname(ji,jj)
                # node_list += self.make_dag(tmp_node,
                #                            [child.items[1]], mapping)
            elif isinstance(child, Fortran2003.Equiv_Operand):
                # A logical expression c.f.
                #  kinfo == OASIS_Recvd .OR. kinfo == OASIS_FromRest
                pass
            else:
                raise DAGError("Unrecognised child; type = {0}, str = '{1}'".
github pearu / f2py / fparser / statements.py View on Github external
"""
    match = re.compile(r'equivalence\s*\(.*\)\Z', re.I).match
    def process_item(self):
        items = []
        for s in self.item.get_line()[11:].lstrip().split(','):
            s = s.strip()
            assert s[0]+s[-1]=='()',repr((s,self.item.get_line()))
            s = ', '.join(split_comma(s[1:-1], self.item))
            items.append('('+s+')')
        self.items = items
        return
    def tofortran(self, isfix=None):
        return self.get_indent_tab(isfix=isfix) + 'EQUIVALENCE %s' % (', '.join(self.items))
    def analyze(self): return

class Dimension(Statement):
    """
    DIMENSION [ :: ]  (  ) [ ,  (  ) ]...

    """
    match = re.compile(r'dimension\b', re.I).match
    def process_item(self):
        line = self.item.get_line()[9:].lstrip()
        if line.startswith('::'):
            line = line[2:].lstrip()
        self.items = split_comma(line, self.item)
        return
    def tofortran(self, isfix=None):
        return self.get_indent_tab(isfix=isfix) + 'DIMENSION %s' % (', '.join(self.items))
    def analyze(self):
        for line in self.items:
            i = line.find('(')
github pearu / f2py / fparser / pattern_tools.py View on Github external
abs_intrinsic_type_name = abs(intrinsic_type_name)
double_complex_name = Pattern('','DOUBLE\s*COMPLEX', flags=re.I, value='DOUBLE COMPLEX')
double_precision_name = Pattern('','DOUBLE\s*PRECISION', flags=re.I, value='DOUBLE PRECISION')
abs_double_complex_name = abs(double_complex_name)
abs_double_precision_name = abs(double_precision_name)

access_spec = Pattern('',r'PUBLIC|PRIVATE',flags=re.I)
abs_access_spec = abs(access_spec)

implicit_none = Pattern('',r'IMPLICIT\s*NONE',flags=re.I, value='IMPLICIT NONE')
abs_implicit_none = abs(implicit_none)

attr_spec = Pattern('',r'ALLOCATABLE|ASYNCHRONOUS|EXTERNAL|INTENT|INTRINSIC|OPTIONAL|PARAMETER|POINTER|PROTECTED|SAVE|TARGET|VALUE|VOLATILE',flags=re.I)
abs_attr_spec = abs(attr_spec)

dimension = Pattern('',r'DIMENSION', flags=re.I)
abs_dimension = abs(dimension)

intent = Pattern('', r'INTENT', flags=re.I)
abs_intent = abs(intent)

intent_spec = Pattern('', r'INOUT|IN|OUT', flags=re.I)
abs_intent_spec = abs(intent_spec)

function = Pattern('', r'FUNCTION', flags=re.I)
subroutine = Pattern('', r'SUBROUTINE', flags=re.I)

select_case = Pattern('', r'SELECT\s*CASE', flags=re.I, value='SELECT CASE')
abs_select_case = abs(select_case)

def _test():
    assert name.match('a1_a')
github pearu / f2py / fparser / pattern_tools.py View on Github external
attr_spec = Pattern('',r'ALLOCATABLE|ASYNCHRONOUS|EXTERNAL|INTENT|INTRINSIC|OPTIONAL|PARAMETER|POINTER|PROTECTED|SAVE|TARGET|VALUE|VOLATILE',flags=re.I)
abs_attr_spec = abs(attr_spec)

dimension = Pattern('',r'DIMENSION', flags=re.I)
abs_dimension = abs(dimension)

intent = Pattern('', r'INTENT', flags=re.I)
abs_intent = abs(intent)

intent_spec = Pattern('', r'INOUT|IN|OUT', flags=re.I)
abs_intent_spec = abs(intent_spec)

function = Pattern('', r'FUNCTION', flags=re.I)
subroutine = Pattern('', r'SUBROUTINE', flags=re.I)

select_case = Pattern('', r'SELECT\s*CASE', flags=re.I, value='SELECT CASE')
abs_select_case = abs(select_case)

def _test():
    assert name.match('a1_a')
    assert abs(name).match('a1_a')
    assert not abs(name).match('a1_a[]')

    m = abs(kind_param)
    assert m.match('23')
    assert m.match('SHORT')

    m = abs(signed_digit_string)
    assert m.match('23')
    assert m.match('+ 23')
    assert m.match('- 23')
    assert m.match('-23')
github pearu / f2py / fparser / pattern_tools.py View on Github external
access_spec = Pattern('',r'PUBLIC|PRIVATE',flags=re.I)
abs_access_spec = abs(access_spec)

implicit_none = Pattern('',r'IMPLICIT\s*NONE',flags=re.I, value='IMPLICIT NONE')
abs_implicit_none = abs(implicit_none)

attr_spec = Pattern('',r'ALLOCATABLE|ASYNCHRONOUS|EXTERNAL|INTENT|INTRINSIC|OPTIONAL|PARAMETER|POINTER|PROTECTED|SAVE|TARGET|VALUE|VOLATILE',flags=re.I)
abs_attr_spec = abs(attr_spec)

dimension = Pattern('',r'DIMENSION', flags=re.I)
abs_dimension = abs(dimension)

intent = Pattern('', r'INTENT', flags=re.I)
abs_intent = abs(intent)

intent_spec = Pattern('', r'INOUT|IN|OUT', flags=re.I)
abs_intent_spec = abs(intent_spec)

function = Pattern('', r'FUNCTION', flags=re.I)
subroutine = Pattern('', r'SUBROUTINE', flags=re.I)

select_case = Pattern('', r'SELECT\s*CASE', flags=re.I, value='SELECT CASE')
abs_select_case = abs(select_case)

def _test():
    assert name.match('a1_a')
    assert abs(name).match('a1_a')
    assert not abs(name).match('a1_a[]')

    m = abs(kind_param)
    assert m.match('23')
    assert m.match('SHORT')
github stfc / PSyclone / src / f2pygen.py View on Github external
def __init__(self, parent):

        if not isinstance(parent, ModuleGen) and not isinstance(parent,
                                                                SubroutineGen):
            raise Exception(
                "The parent of ImplicitNoneGen must be a module or a "
                "subroutine, but found {0}".format(type(parent)))
        reader = FortranStringReader("IMPLICIT NONE\n")
        reader.set_mode(True, True)  # free form, strict
        subline = reader.next()

        from fparser.typedecl_statements import Implicit
        my_imp_none = Implicit(parent.root, subline)

        BaseGen.__init__(self, parent, my_imp_none)
github inducer / loopy / loopy / frontend / fortran / __init__.py View on Github external
warn("auto_dependencies is deprecated, use seq_dependencies instead",
                DeprecationWarning, stacklevel=2)
        seq_dependencies = auto_dependencies

    if seq_dependencies is None:
        seq_dependencies = True

    import logging
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('fparser').addHandler(console)

    from fparser import api
    tree = api.parse(source, isfree=free_form, isstrict=strict,
            analyze=False, ignore_comments=False)

    if tree is None:
        raise LoopyError("Fortran parser was unhappy with source code "
                "and returned invalid data (Sorry!)")

    from loopy.frontend.fortran.translator import F2LoopyTranslator
    f2loopy = F2LoopyTranslator(filename, target=target)
    f2loopy(tree)

    return f2loopy.make_kernels(seq_dependencies=seq_dependencies)
github stfc / PSyclone / src / psyclone / f2pygen.py View on Github external
def __init__(self, parent):
        '''
        :param parent: node in AST to which to add 'implicit none' as a child
        :type parent: :py:class:`psyclone.f2pygen.ModuleGen` or
                      :py:class:`psyclone.f2pygen.SubroutineGen`

        :raises Exception: if `parent` is not a ModuleGen or SubroutineGen
        '''
        if not isinstance(parent, ModuleGen) and not isinstance(parent,
                                                                SubroutineGen):
            raise Exception(
                "The parent of ImplicitNoneGen must be a module or a "
                "subroutine, but found {0}".format(type(parent)))
        reader = FortranStringReader("IMPLICIT NONE\n")
        reader.set_format(FortranFormat(True, True))  # free form, strict
        subline = reader.next()

        from fparser.one.typedecl_statements import Implicit
        my_imp_none = Implicit(parent.root, subline)

        BaseGen.__init__(self, parent, my_imp_none)
github stfc / PSyclone / examples / nemo / scripts / kernels_trans.py View on Github external
def contains_unsupported_sum(fpnode):
    '''
    Examines the fparser2 parse tree represented by fpnode and returns True
    if it contains a use of the SUM intrinisc with a 'dim' argument. (If
    such a construct is included in a KERNELS region then the code produced
    by v. 18.10 of the PGI compiler seg. faults.)

    :returns: True if SUM(array(:,:), dim=blah) is found, False otherwise.
    :rtype: bool

    '''
    from fparser.two.utils import walk_ast
    from fparser.two import Fortran2003
    intrinsics = walk_ast([fpnode], [Fortran2003.Intrinsic_Function_Reference])
    for intrinsic in intrinsics:
        if str(intrinsic.items[0]).lower() == "sum":
            # If there's only one argument then we'll just have a Name
            # and not an Actual_Arg_Spec_List (in which case we don't need to
            # check for the 'dim' argument).
            if isinstance(intrinsic.items[1],
                          Fortran2003.Actual_Arg_Spec_List):
                # items[1] contains the Actual_Arg_Spec_List
                actual_args = walk_ast(intrinsic.items[1].items,
                                       [Fortran2003.Actual_Arg_Spec])
                for arg in actual_args:
                    if str(arg.items[0]).lower() == "dim":
                        return True
    return False
github arporter / habakkuk / src / habakkuk / make_dag.py View on Github external
digraph.to_dot(show_weights=show_weights)
                    digraph.report()

                    # Fuse multiply-adds where possible
                    if apply_fma_transformation:
                        num_fused = digraph.fuse_multiply_adds()
                        if num_fused:
                            digraph.name = digraph.name + "_fused"
                            # Re-compute the critical path through this graph
                            digraph.calc_critical_path()
                            digraph.to_dot()
                            digraph.report()
                        else:
                            print("No opportunities to fuse multiply-adds")

        except Fortran2003.NoMatchError:
            # TODO log this error
            print("Parsing '{0}' (starting at {1}) failed at {2}. "
                  "Is the file valid Fortran?".
                  format(filename, reader.fifo_item[0], reader.fifo_item[-1]))
            # Carry on to next file
            continue