Returns the symbol for the specified *fortran* module and subroutine/function
    that has been compiled into a shared library.

    :arg lib: the full path to the shared library *.so file.
195046
def static_symbol(module, method, lib, bindc=False):
    
    from os import path
    from numpy.ctypeslib import load_library
    libpath = path.abspath(lib)
    libkey = libpath.lower()

    if libkey not in compilers:
        compilers[libkey] = detect_compiler(libpath)
        if compilers[libkey] == False:
            raise ValueError("Couldn't auto-detect the compiler for {}".format(libpath))
    compiler = compilers[libkey]

    if libkey not in libs:
        libs[libkey] = load_library(libpath, "")
        if not libs[libkey]:
            raise ValueError("Couldn't auto-load the shared library with ctypes.")
    slib = libs[libkey]
    
    identifier = "{}.{}".format(module, method)
    if bindc:
        symbol = method
    elif compiler == "gfortran":
        symbol = "__" + identifier.lower().replace(".", "_MOD_")
    else:
        #We assume the only other option is ifort.
        symbol = identifier.lower().replace(".", "_mp_") + "_"

    if hasattr(slib, symbol):
        return getattr(slib, symbol)
    else:
        return None
1169459
def _complete_type_chain(self, symbol, fullsymbol):
        """"""
        target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
        if target is None:
            return {}

        result = {}
        #We might know what kind of symbol to limit the completion by depending on whether
        #it was preceded by a "call " for example. Check the context's el_call
        if symbol != "":
            if self.context.el_call != "sub":
                for mkey in target.members:
                    if self._symbol_in(symbol, mkey):
                        result[mkey] = target.members[mkey]

            for ekey in target.executables:
                if (self._symbol_in(symbol, ekey)):
                    if self.context.el_call == "sub":
                        if (isinstance(target.executables[ekey], Subroutine)):
                            result[ekey] = target.executables[ekey]
                    else:
                        if (isinstance(target.executables[ekey], Function)):
                            result[ekey] = target.executables[ekey]
        else:
            if self.context.el_call != "sub":
                result.update(target.members)
                subdict = {k: target.executables[k] for k in target.executables
                           if isinstance(target.executables[k].target, Function)}
                result.update(subdict)
            else:
                subdict = {k: target.executables[k] for k in target.executables
                           if isinstance(target.executables[k].target, Subroutine)}
                result.update(subdict)

        return result
768201
def get_function(pkgpath):
    
    # Extract the module and function name from pkgpath
    elems = pkgpath.split('.')
    if len(elems) <= 1:
        raise PyMacaronCoreException("Path %s is too short. Should be at least module.func." % elems)
    func_name = elems[-1]
    func_module = '.'.join(elems[0:-1])

    # Load the function's module and get the function
    try:
        m = import_module(func_module)
        f = getattr(m, func_name)
        return f
    except Exception as e:
        t = traceback.format_exc()
        raise PyMacaronCoreException("Failed to import %s: %s\nTrace:\n%s" % (pkgpath, str(e), t))
1000592
def _get_module(self, line):
        """"""
        #Finding the module name is trivial; start at the beginning of
        #the module and iterate lines until we find the module.
        for sline in self._source:
            if len(sline) > 0 and sline[0] != "!":
                rmatch = self.RE_MODULE.match(sline)
                if rmatch is not None:
                    self.modulename = rmatch.group("name")
                    break
        else:
            #We don't even have the start of a module in this code file
            return
            
        #Before we carry on with the rest of the context, find the separating
        #CONTAINS keyword so we know whether to look for types or subs/funcs.
        #If the code parser hasn't ever parsed this module, parse it now.
        self.parser.isense_parse(self._orig_path, self.modulename)
        self.module = self.parser.modules[self.modulename]

        if line > self.module.contains_index:
            self.section = "contains"
685445
def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
    
    return fmt % symbol_data[type(obj)]
1345306
def findLibrary(name):
    
    assert is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)"

    lib = None

    # Look in the LD_LIBRARY_PATH
    lp = compat.getenv('LD_LIBRARY_PATH', '')
    for path in lp.split(os.pathsep):
        libs = glob(os.path.join(path, name + '*'))
        if libs:
            lib = libs[0]
            break

    # Look in /etc/ld.so.cache
    if lib is None:
        expr = r'/[^\(\)\s]*%s\.[^\(\)\s]*' % re.escape(name)
        m = re.search(expr, compat.exec_command('/sbin/ldconfig', '-p'))
        if m:
            lib = m.group(0)

    # Look in the known safe paths
    if lib is None:
        paths = ['/lib', '/usr/lib']
        if is_aix:
            paths.append('/opt/freeware/lib')
        for path in paths:
            libs = glob(os.path.join(path, name + '*'))
            if libs:
                lib = libs[0]
                break

    # give up :(
    if lib is None:
        return None

    # Resolve the file name into the soname
    dir, file = os.path.split(lib)
    return os.path.join(dir, getSoname(lib))
1139629
def get_library_name():
    
    from os.path import split, abspath

    __lib_name = split(split(abspath(sys.modules[__name__].__file__))[0])[1]

    assert __lib_name in ["sframe", "turicreate"]

    return __lib_name
459806
def _complete_el(self, symbol, attribute, fullsymbol):
        """"""
        if symbol != fullsymbol:
            #We have a sym%sym%... chain and the completion just needs to
            #be a member variable or method of the type being referenced.
            return self._complete_type_chain(symbol, fullsymbol)

        if self.context.el_section == "params":
            #They are in the process of defining a new executable and are
            #picking the names themselves, return normal word complete.
            return self._complete_word(symbol, attribute)
        elif self.context.el_section == "body":
            if self.context.el_call in ["sub", "fun"]:
                return self._complete_sig(symbol, attribute)
            else:
                return self._complete_word(symbol, attribute)
        else:
            return self._complete_word(symbol, attribute)
181801
def method(self, symbol):
        '''
        
        '''
        assert issubclass(symbol, SymbolBase)
        def wrapped(fn):
            setattr(symbol, fn.__name__, fn)
        return wrapped
447603
def visit_Module(self, node):
        
        module_body = list()
        symbols = set()
        # Gather top level assigned variables.
        for stmt in node.body:
            if isinstance(stmt, (ast.Import, ast.ImportFrom)):
                for alias in stmt.names:
                    name = alias.asname or alias.name
                    symbols.add(name)  # no warning here
            elif isinstance(stmt, ast.FunctionDef):
                if stmt.name in symbols:
                    raise PythranSyntaxError(
                        "Multiple top-level definition of %s." % stmt.name,
                        stmt)
                else:
                    symbols.add(stmt.name)

            if not isinstance(stmt, ast.Assign):
                continue

            for target in stmt.targets:
                if not isinstance(target, ast.Name):
                    raise PythranSyntaxError(
                        "Top-level assignment to an expression.",
                        target)
                if target.id in self.to_expand:
                    raise PythranSyntaxError(
                        "Multiple top-level definition of %s." % target.id,
                        target)
                if isinstance(stmt.value, ast.Name):
                    if stmt.value.id in symbols:
                        continue  # create aliasing between top level symbols
                self.to_expand.add(target.id)

        for stmt in node.body:
            if isinstance(stmt, ast.Assign):
                # that's not a global var, but a module/function aliasing
                if all(isinstance(t, ast.Name) and t.id not in self.to_expand
                       for t in stmt.targets):
                    module_body.append(stmt)
                    continue

                self.local_decl = set()
                cst_value = self.visit(stmt.value)
                for target in stmt.targets:
                    assert isinstance(target, ast.Name)
                    module_body.append(
                        ast.FunctionDef(target.id,
                                        ast.arguments([], None,
                                                      [], [], None, []),
                                        [ast.Return(value=cst_value)],
                                        [], None))
                    metadata.add(module_body[-1].body[0],
                                 metadata.StaticReturn())
            else:
                self.local_decl = self.gather(
                    LocalNameDeclarations, stmt)
                module_body.append(self.visit(stmt))

        self.update |= bool(self.to_expand)

        node.body = module_body
        return node
1317218
def get_libgfortran_dir():
    
    for ending in [".3.dylib", ".dylib", ".3.so", ".so"]:
        try:
            p = Popen(['gfortran', "-print-file-name=libgfortran" + ending],
                      stdout=PIPE, stderr=PIPE)
            p.stderr.close()
            line = p.stdout.readline().decode().strip()
            p.stdout.close()
            if os.path.exists(line):
                return [os.path.dirname(line)]
        except:
            continue
        return []
45509
def get_original_function_name(self, line, col, minified_name,
                                   minified_source):
        
        # Silently ignore underflows
        if line < 0 or col < 0:
            return None
        minified_name = minified_name.encode('utf-8')
        sout = _ffi.new('const char **')
        try:
            slen = rustcall(_lib.lsm_view_get_original_function_name,
                            self._get_ptr(), line, col, minified_name,
                            minified_source, sout)
            if slen > 0:
                return _ffi.unpack(sout[0], slen).decode('utf-8', 'replace')
        except SourceMapError:
            # In some rare cases the library is/was known to panic.  We do
            # not want to report this upwards  (this happens on slicing
            # out of range on older rust versions in the rust-sourcemap
            # library)
            pass
42111
def find_symbol(symbol, method=nil)
      result = nil
      case symbol
      when /^::(.*)/
        result = toplevel.find_symbol($1)
      when /::/
        modules = symbol.split(/::/)
        unless modules.empty?
          module_name = modules.shift
          result = find_module_named(module_name)
          if result
            modules.each do |module_name|
              result = result.find_module_named(module_name)
              break unless result
            end
          end
        end
      else
        # if a method is specified, then we're definitely looking for
        # a module, otherwise it could be any symbol
        if method
          result = find_module_named(symbol)
        else
          result = find_local_symbol(symbol)
          if result.nil?
            if symbol =~ /^[A-Z]/
              result = parent
              while result && result.name != symbol
                result = result.parent
              end
            end
          end
        end
      end
      if result && method
        if !result.respond_to?(:find_local_symbol)
          p result.name
          p method
          fail
        end
        result = result.find_local_symbol(method)
      end
      result
    end
951744
def detect_compiler(libpath):
    
    from os import waitpid, path
    from subprocess import Popen, PIPE
    command = "nm {0}".format(path.abspath(libpath))
    child = Popen(command, shell=True, executable="/bin/bash", stdout=PIPE)
    # Need to do this so that we are sure the process is done before moving on
    waitpid(child.pid, 0)
    contents = child.stdout.readlines()
    i = 0
    found = False
    while i < len(contents) and found == False:
        if "_MOD_" in contents[i]:
            found = "gfortran"
        elif "_mp_" in contents[i]:
            found = "ifort"
        i += 1

    return found
1138655
def _raw_object_cache_getbuffer(self, data):
        
        if self._object_cache_getbuffer is None:
            return
        module_ptr = data.contents.module_ptr
        module = self._find_module_ptr(module_ptr)
        if module is None:
            # The LLVM EE should only give notifications for modules
            # known by us.
            raise RuntimeError("object compilation notification "
                               "for unknown module %s" % (module_ptr,))

        buf = self._object_cache_getbuffer(module)
        if buf is not None:
            # Create a copy, which will be freed by the caller
            data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf))
            data[0].buf_len = len(buf)
726159
def _bracket_complete_sig(self, symbol, fullsymbol):
        """"""
        if symbol != fullsymbol:
            #We have a sym%sym%... chain and the completion just needs to
            #be the signature of the member method.
            target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)

            if symbol in target.executables:
                child = target.executables[symbol]
                return self._compile_signature(child.target, child.name)
            elif symbol in target.members:
                #We are dealing with a dimension request on an array that
                #is a member of the type.
                child = target.members[symbol]
                return self._bracket_dim_suggest(child)
            else:                
                return {}
        else:
            #We must be dealing with a regular executable or builtin fxn
            #or a regular variable dimension.
            iexec = self._bracket_exact_exec(symbol)
            if iexec is not None:
                #It is indeed a function we are completing for.
                return self._compile_signature(iexec, iexec.name)
            else:
                #We need to look at local and global variables to find the
                #variable declaration and dimensionality.
                ivar = self._bracket_exact_var(symbol)
                return self._bracket_dim_suggest(ivar)
481004
def is_module_stdlib(file_name):
    """"""
    # TODO: Move these calls away from this function so it doesn't have to run
    # every time.
    lib_path = sysconfig.get_python_lib()
    path = os.path.split(lib_path)
    if path[1] == 'site-packages':
        lib_path = path[0]
    return file_name.lower().startswith(lib_path.lower())