How to use the fparser.one function in fparser

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 stfc / PSyclone / src / psyclone / parse / kernel.py View on Github external
" does not use 'code' as the generic name.".
                            format(name))
                    bname = statement.bname
                else:
                    bname = statement.name
                break
        if bname is None:
            raise ParseError(
                "Kernel type {0} does not bind a specific procedure".
                format(name))
        if bname == '':
            raise InternalError(
                "Empty Kernel name returned for Kernel type {0}.".format(name))
        code = None
        for statement, _ in fpapi.walk(modast, -1):
            if isinstance(statement, fparser1.block_statements.Subroutine) \
               and statement.name == bname:
                code = statement
                break
        if not code:
            raise ParseError(
                "kernel.py:KernelProcedure:get_procedure: Kernel subroutine "
                "'{0}' not found.".format(bname))
        return code, bname
github stfc / PSyclone / src / psyclone / parse / kernel.py View on Github external
# no interface found either
                raise ParseError(
                    "Kernel type {0} does not bind a specific procedure or \
                    provide an explicit interface".format(name))
        elif bname == '':
            raise InternalError(
                "Empty Kernel name returned for Kernel type {0}.".format(name))
        # add the name of the tbp to the list of strings to search for.
        else:
            subnames = [bname]
        # walk the AST to check the subroutine names exist.
        procedure_count = 0
        for subname in subnames:
            for statement, _ in fpapi.walk(modast):
                if isinstance(statement,
                              fparser1.block_statements.Subroutine) \
                              and statement.name.lower() \
                              == subname:
                    procedure_count = procedure_count + 1
                    if procedure_count == 1:
                        # set code to statement if there is one procedure.
                        code = statement
                    else:
                        code = None  # set to None if there is more than one.
                    print(code)
                    break
            else:
                raise ParseError(
                    "kernel.py:KernelProcedure:get_procedure: Kernel "
                    "subroutine '{0}' not found.".format(subname))
        return code, bname
github stfc / PSyclone / src / psyclone / parse_orig.py View on Github external
code = None
        default_public = True
        declared_private = False
        declared_public = False
        for statement, depth in fpapi.walk(modast, -1):
            if isinstance(statement, fparser1.statements.Private):
                if len(statement.items) == 0:
                    default_public = False
                elif bname in statement.items:
                    declared_private = True
            if isinstance(statement, fparser1.statements.Public):
                if len(statement.items) == 0:
                    default_public = True
                elif bname in statement.items:
                    declared_public = True
            if isinstance(statement, fparser1.block_statements.Subroutine) \
               and statement.name == bname:
                if statement.is_public():
                    declared_public = True
                code = statement
        if code is None:
            raise RuntimeError("Kernel subroutine %s not implemented" % bname)
        if declared_private or (not default_public and not declared_public):
            from psyclone.parse import ParseError
            raise ParseError("Kernel subroutine '%s' is not public" % bname)
        return code, bname
github stfc / PSyclone / src / psyclone / parse / kernel.py View on Github external
:param str name: the name of the integer variable to find.

        :return: value of the specified integer variable (lower case) or None.
        :rtype: str

        :raises ParseError: if the RHS of the assignment is not a Name.

        '''
        # Ensure the Fortran2003 parser is initialised
        _ = ParserFactory().create()
        # Fortran is not case sensitive so nor is our matching
        lower_name = name.lower()

        for statement, _ in fpapi.walk(self._ktype):
            if isinstance(statement, fparser1.typedecl_statements.Integer):
                # fparser only goes down to the statement level. We use
                # fparser2 to parse the statement itself (eventually we'll
                # use fparser2 to parse the whole thing).
                assign = Fortran2003.Assignment_Stmt(
                    statement.entity_decls[0])
                if str(assign.items[0]).lower() == lower_name:
                    if not isinstance(assign.items[2], Fortran2003.Name):
                        raise ParseError(
                            "get_integer_variable: RHS of assignment is not "
                            "a variable name: '{0}'".format(str(assign)))
                    return str(assign.items[2]).lower()
        return None
github stfc / PSyclone / src / psyclone / gen_kernel_stub.py View on Github external
:raise ParseError: if the given file could not be parsed.
    '''
    if api == "":
        api = Config.get().default_stub_api
    if api not in Config.get().supported_stub_apis:
        print("Unsupported API '{0}' specified. Supported API's are {1}.".
              format(api, Config.get().supported_stub_apis))
        raise GenerationError(
            "generate: Unsupported API '{0}' specified. Supported types are "
            "{1}.".format(api, Config.get().supported_stub_apis))

    if not os.path.isfile(filename):
        raise IOError("file '{0}' not found".format(filename))

    # drop cache
    fparser.one.parsefortran.FortranParser.cache.clear()
    fparser.logging.disable(fparser.logging.CRITICAL)
    try:
        ast = fparser.api.parse(filename, ignore_comments=False)

    except (fparser.common.utils.AnalyzeError, AttributeError) as error:
        raise ParseError("Code appears to be invalid Fortran: " +
                         str(error))

    metadata = DynKernMetadata(ast)
    kernel = DynKern()
    kernel.load_meta(metadata)
    return kernel.gen_stub
github stfc / PSyclone / src / psyclone / f2pygen.py View on Github external
index = self._skip_use_and_comments(index)
                # skip over implicit none if it exists
                index = self._skip_imp_none_and_comments(index)
                # skip over any declarations which have an intent
                try:
                    intent = True
                    while intent:
                        intent = False
                        for attr in self.root.content[index].attrspec:
                            if attr.find("intent") == 0:
                                intent = True
                                index += 1
                                break
                except AttributeError:
                    pass
            elif isinstance(content.root, fparser1.statements.Use):
                # have I already been declared?
                for child in self._children:
                    if isinstance(child, UseGen):
                        if child.root.name == content.root.name:
                            # found an existing use with the same name
                            if not child.root.isonly and not \
                               content.root.isonly:
                                # both are generic use statements so
                                # skip this declaration
                                return
                            if child.root.isonly and not content.root.isonly:
                                # new use is generic and existing use
                                # is specific so we can safely add
                                pass
                            if not child.root.isonly and content.root.isonly:
                                # existing use is generic and new use
github stfc / PSyclone / src / psyclone / parse / kernel.py View on Github external
statement and the name of that Subroutine.
        :rtype: (:py:class:`fparser1.block_statements.Subroutine`, str)

        :raises ParseError: if the supplied Kernel meta-data does not \
                            have a type-bound procedure.
        :raises ParseError: if no implementation is found for the \
                             type-bound procedure.
        :raises ParseError: if the type-bound procedure specifies a binding \
                            name but the generic name is not "code".
        :raises InternalError: if we get an empty string for the name of the \
                               type-bound procedure.
        '''
        bname = None
        # Search the the meta-data for a SpecificBinding
        for statement in ast.content:
            if isinstance(statement, fparser1.statements.SpecificBinding):
                # We support either:
                # PROCEDURE, nopass :: code =>  or
                # PROCEDURE, nopass :: 
                if statement.bname:
                    if statement.name.lower() != "code":
                        raise ParseError(
                            "Kernel type {0} binds to a specific procedure but"
                            " does not use 'code' as the generic name.".
                            format(name))
                    bname = statement.bname
                else:
                    bname = statement.name
                break
        if bname is None:
            raise ParseError(
                "Kernel type {0} does not bind a specific procedure".
github stfc / PSyclone / src / psyclone / f2pygen.py View on Github external
:param str name: name of module to USE
    :param parent: node in fparser1 AST to which to add this USE as a child
    :type parent: :py:class:`fparser.one.block_statements.*`
    :param bool only: whether this USE has an "ONLY" clause
    :param list funcnames: list of quantities to follow the "ONLY" clause

    :returns: an fparser1 Use object
    :rtype: :py:class:`fparser.one.block_statements.Use`
    '''
    reader = FortranStringReader("use kern,only : func1_kern=>func1")
    reader.set_format(FortranFormat(True, True))  # free form, strict
    myline = reader.next()

    # find an appropriate place to add in our use statement
    while not isinstance(parent, (fparser1.block_statements.Program,
                                  fparser1.block_statements.Module,
                                  fparser1.block_statements.Subroutine)):
        parent = parent.parent
    use = fparser1.block_statements.Use(parent, myline)
    use.name = name
    use.isonly = only
    if funcnames is None:
        funcnames = []
        use.isonly = False
    use.items = funcnames

    parent.content.insert(0, use)
    return use
github stfc / PSyclone / src / psyclone / parse_orig.py View on Github external
def checkMetadataPublic(self, name, ast):
        default_public = True
        declared_private = False
        declared_public = False
        for statement, depth in fpapi.walk(ast, -1):
            if isinstance(statement, fparser1.statements.Private):
                if len(statement.items) == 0:
                    default_public = False
                elif name in statement.items:
                    declared_private = True
            if isinstance(statement, fparser1.statements.Public):
                if len(statement.items) == 0:
                    default_public = True
                elif name in statement.items:
                    declared_public = True
            if isinstance(statement, fparser1.block_statements.Type) \
               and statement.name == name and statement.is_public():
                declared_public = True
        if declared_private or (not default_public and not declared_public):
            from psyclone.parse import ParseError
            raise ParseError("Kernel type '%s' is not public" % name)
github stfc / PSyclone / src / psyclone / f2pygen.py View on Github external
def __init__(self, parent, entity_decls=None, intent="",
                 pointer=False, kind="", dimension="", allocatable=False,
                 save=False, target=False, length="", initial_values=None):

        reader = FortranStringReader(
            "character(len=vanilla_len) :: vanilla")
        reader.set_format(FortranFormat(True, False))
        myline = reader.next()
        self._decl = fparser1.typedecl_statements.Character(parent.root,
                                                            myline)
        # Add character- and kind-selectors
        self._decl.selector = (length, kind)

        super(CharDeclGen, self).__init__(parent=parent,
                                          datatype="character",
                                          entity_decls=entity_decls,
                                          intent=intent, pointer=pointer,
                                          dimension=dimension,
                                          allocatable=allocatable, save=save,
                                          target=target,
                                          initial_values=initial_values)