text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Fetches the MAL media statistics page and sets the current media's statistics attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_stats(self):
"""Fetches the MAL media statistics page and sets the current media's statistics attributes.
:rtype: :class:`.Media`
:return: current media object.
""" |
stats_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/stats').text
self.set(self.parse_stats(utilities.get_clean_dom(stats_page)))
return self |
<SYSTEM_TASK:>
Fetches the MAL media characters page and sets the current media's character attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_characters(self):
"""Fetches the MAL media characters page and sets the current media's character attributes.
:rtype: :class:`.Media`
:return: current media object.
""" |
characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/characters').text
self.set(self.parse_characters(utilities.get_clean_dom(characters_page)))
return self |
<SYSTEM_TASK:>
Returns a dictionary of builtin functions for Fortran. Checks the
<END_TASK>
<USER_TASK:>
Description:
def load(parser, serializer):
"""Returns a dictionary of builtin functions for Fortran. Checks the
cache first to see if we have a serialized version. If we don't, it
loads it from the XML file.
:arg parser: the DocParser instance for parsing the XML tags.
:arg serializer: a Serializer instance from the CodeParser to cache
the loaded XML file.
""" |
fortdir = os.path.dirname(fortpy.__file__)
xmlpath = os.path.join(fortdir, "isense", "builtin.xml")
if not os.path.isfile(xmlpath):
return {}
changed_time = os.path.getmtime(xmlpath)
cached = serializer.load_module("builtin.xml", changed_time)
if cached is None:
result = _load_builtin_xml(xmlpath, parser)
serializer.save_module("builtin.xml", result, changed_time)
else:
result = cached
return result |
<SYSTEM_TASK:>
Loads the builtin function specifications from the builtin.xml file.
<END_TASK>
<USER_TASK:>
Description:
def _load_builtin_xml(xmlpath, parser):
"""Loads the builtin function specifications from the builtin.xml file.
:arg parser: the DocParser instance for parsing the XML tags.
""" |
#First we need to get hold of the fortpy directory so we can locate
#the isense/builtin.xml file.
result = {}
el = ET.parse(xmlpath).getroot()
if el.tag == "builtin":
for child in el:
anexec = _parse_xml(child, parser)
result[anexec.name.lower()] = anexec
return result |
<SYSTEM_TASK:>
Parses the specified child XML tag and creates a Subroutine or
<END_TASK>
<USER_TASK:>
Description:
def _parse_xml(child, parser):
"""Parses the specified child XML tag and creates a Subroutine or
Function object out of it.""" |
name, modifiers, dtype, kind = _parse_common(child)
#Handle the symbol modification according to the isense settings.
name = _isense_builtin_symbol(name)
if child.tag == "subroutine":
parent = Subroutine(name, modifiers, None)
elif child.tag == "function":
parent = Function(name, modifiers, dtype, kind, None)
if parent is not None:
for kid in child:
if kid.tag == "parameter":
_parse_parameter(kid, parser, parent)
elif kid.tag == "summary":
_parse_summary(kid, parser, parent)
elif kid.tag == "usage":
_parse_usage(kid, parser, parent)
return parent |
<SYSTEM_TASK:>
Prepares a request from a url, params, and optionally authentication.
<END_TASK>
<USER_TASK:>
Description:
def make_request(self, url, params, auth=None):
"""
Prepares a request from a url, params, and optionally authentication.
""" |
req = urllib2.Request(url + urllib.urlencode(params))
if auth:
req.add_header('AUTHORIZATION', 'Basic ' + auth)
return urllib2.urlopen(req) |
<SYSTEM_TASK:>
Splices the full list of subroutines and the module procedure list
<END_TASK>
<USER_TASK:>
Description:
def fpy_interface(fpy, static, interface, typedict):
"""Splices the full list of subroutines and the module procedure list
into the static.f90 file.
:arg static: the string contents of the static.f90 file.
:arg interface: the name of the interface *field* being replaced.
:arg typedict: the dictionary of dtypes and their kind and suffix combos.
""" |
modprocs = []
subtext = []
for dtype, combos in list(typedict.items()):
for tcombo in combos:
kind, suffix = tcombo
xnames, sub = fpy_interface_sub(fpy, dtype, kind, suffix)
modprocs.extend(xnames)
subtext.append(sub)
subtext.append("\n")
#Next, chunk the names of the module procedures into blocks of five
#so that they display nicely for human readability.
from fortpy.printing.formatting import present_params
splice = static.replace(interface, present_params(modprocs, 21))
return splice.replace(interface.replace("py", "xpy"), ''.join(subtext)) |
<SYSTEM_TASK:>
Parses the specified Fortran source file from which the wrappers will
<END_TASK>
<USER_TASK:>
Description:
def _parse():
"""Parses the specified Fortran source file from which the wrappers will
be constructed for ctypes.
""" |
if not args["reparse"]:
settings.use_filesystem_cache = False
c = CodeParser()
if args["verbose"]:
c.verbose = True
if args["reparse"]:
c.reparse(args["source"])
else:
c.parse(args["source"])
return c |
<SYSTEM_TASK:>
Sets up compiled regex objects for parsing code elements.
<END_TASK>
<USER_TASK:>
Description:
def setup_regex(self):
"""Sets up compiled regex objects for parsing code elements.""" |
#Regex for extracting modules from the code
self._RX_MODULE = r"(\n|^)\s*module\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*module"
self.RE_MODULE = re.compile(self._RX_MODULE, re.I | re.DOTALL)
self._RX_PROGRAM = r"(\n|^)\s*program\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*program"
self.RE_PROGRAM = re.compile(self._RX_PROGRAM, re.I | re.DOTALL)
#Regex for use statements in a module
self._RX_USE = r"^\s*use\s+(?P<name>[^,]+?)(\s*,\s+only\s*:(?P<only>[A-Za-z0-9_\s,]+?))?$"
self.RE_USE = re.compile(self._RX_USE, re.I | re.M)
#Regex for finding if the module is private
self._RX_PRIV = "private.+?(type|contains)"
self.RE_PRIV = re.compile(self._RX_PRIV, re.DOTALL | re.I)
#Regex for finding publcily labeled members declared using public keyword.
self._RX_PUBLIC = r"\n\s*public\s+(?P<methods>[A-Za-z0-9_,\s&\n]+)"
self.RE_PUBLIC = re.compile(self._RX_PUBLIC, re.I)
#Regex for finding text before type or contains declarations that may contian members.
self._RX_MEMBERS = "(?P<preamble>.+?)(\s+type[,\s]|contains)"
self.RE_MEMBERS = re.compile(self._RX_MEMBERS, re.DOTALL | re.I)
self._RX_PRECOMP = r"#endif"
self.RE_PRECOMP = re.compile(self._RX_PRECOMP, re.I) |
<SYSTEM_TASK:>
Extracts a PROGRAM from the specified fortran code file.
<END_TASK>
<USER_TASK:>
Description:
def _parse_programs(self, string, parent, filepath=None):
"""Extracts a PROGRAM from the specified fortran code file.""" |
#First, get hold of the docstrings for all the modules so that we can
#attach them as we parse them.
moddocs = self.docparser.parse_docs(string)
#Now look for modules in the file and then match them to their decorators.
matches = self.RE_PROGRAM.finditer(string)
result = []
for rmodule in matches:
name = rmodule.group("name").lower()
contents = re.sub("&[ ]*\n", "", rmodule.group("contents"))
module = self._process_module(name, contents, parent, rmodule, filepath)
#Check whether the docparser found docstrings for the module.
if name in moddocs:
module.docstring = self.docparser.to_doc(moddocs[name][0], name)
module.docstart, module.docend = module.absolute_charindex(string, moddocs[name][1],
moddocs[name][2])
result.append(module)
return result |
<SYSTEM_TASK:>
Extracts a list of public members, types and executables that were declared using
<END_TASK>
<USER_TASK:>
Description:
def _process_publics(self, contents):
"""Extracts a list of public members, types and executables that were declared using
the public keyword instead of a decoration.""" |
matches = self.RE_PUBLIC.finditer(contents)
result = {}
start = 0
for public in matches:
methods = public.group("methods")
#We need to keep track of where the public declarations start so that the unit
#testing framework can insert public statements for those procedures being tested
#who are not marked as public
if start == 0:
start = public.start("methods")
for item in re.split(r"[\s&\n,]+", methods.strip()):
if item.lower() in ["interface", "type", "use"]:
#We have obviously reached the end of the actual public
#declaration in this regex match.
break
self._dict_increment(result, item.lower())
return (result, start) |
<SYSTEM_TASK:>
Extracts use dependencies from the innertext of a module.
<END_TASK>
<USER_TASK:>
Description:
def _parse_use(self, string):
"""Extracts use dependencies from the innertext of a module.""" |
result = {}
for ruse in self.RE_USE.finditer(string):
#We also handle comments for individual use cases, the "only" section
#won't pick up any comments.
name = ruse.group("name").split("!")[0].strip()
if name.lower() == "mpi":
continue
if ruse.group("only"):
only = ruse.group("only").split(",")
for method in only:
key = "{}.{}".format(name, method.strip())
self._dict_increment(result, key)
else:
self._dict_increment(result, name)
return result |
<SYSTEM_TASK:>
Increments the value of the dictionary at the specified key.
<END_TASK>
<USER_TASK:>
Description:
def _dict_increment(self, dictionary, key):
"""Increments the value of the dictionary at the specified key.""" |
if key in dictionary:
dictionary[key] += 1
else:
dictionary[key] = 1 |
<SYSTEM_TASK:>
Extracts any module-level members from the code. They must appear before
<END_TASK>
<USER_TASK:>
Description:
def _parse_members(self, contents, module):
"""Extracts any module-level members from the code. They must appear before
any type declalations.""" |
#We need to get hold of the text before the module's main CONTAINS keyword
#so that we don't find variables from executables and claim them as
#belonging to the module.
icontains = module.contains_index
ichar = module.charindex(icontains, 0)
module.preamble = module.refstring[:ichar]
#Get a dictionary of all the members in this module body
#We only want to look at variable definitions before the first type
lowest = ichar
remove = [] #Will use later below, see next comment
for t in module.types:
remove.append((module.types[t].start, module.types[t].end))
if module.types[t].start < lowest:
lowest = module.types[t].start
module.members.update(self.vparser.parse(contents[:lowest-(module.start + 10 + len(module.name))], module))
#The docstrings for these members will appear as member tags in the same
#preamble text. We can't use the entire preamble for this because member
#docs inside of a type declaration will show up as belonging to the
#module, when in fact, they don't.
remove.sort(key=lambda tup: tup[0])
retain = []
cur_end = 0
for rem in remove:
signature = module.refstring[rem[0]+1:rem[1]].index("\n") + 2
keep = module.refstring[cur_end:rem[0] + signature]
cur_end = rem[1]
retain.append(keep)
#If there weren't any types in the module, we still want to get at the docs in
#the preamble.
if len(remove) == 0:
retain = module.preamble
docsearch = "".join(retain)
module.predocs = self.docparser.parse_docs(docsearch, module)
if module.name in module.predocs:
#We can only do member docstrings if the module had internal docstrings
#that may to members.
memdocs = self.docparser.to_doc(module.predocs[module.name][0], module.name)
remainingdocs = self.docparser.process_memberdocs(memdocs, module)
module.predocs[module.name] = remainingdocs |
<SYSTEM_TASK:>
Sets up compiled regex objects for parsing the executables from a module.
<END_TASK>
<USER_TASK:>
Description:
def setup_regex(self):
"""Sets up compiled regex objects for parsing the executables from a module.""" |
self._RX_CONTAINS = r"^\s*contains[^\n]*?$"
self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.M | re.I)
#Setup a regex that can extract information about both functions and subroutines
self._RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + \
r"(?P<kind>\([a-z0-9_]+\))?)?((?P<modifiers>[\w, \t]+?))?[ \t]*" + \
r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \
r"\s*\((?P<parameters>[^)]*)\)(?P<result>\sresult\([a-z0-9_]+\))?" + \
r"(?P<contents>.+?)end\s*(?P=codetype)\s+(?P=name)"
self.RE_EXEC = re.compile(self._RX_EXEC, re.DOTALL | re.I)
#Regex for the signature is almost identical to the full executable, but it doesn't
#look for any contents after the parameter list.
self._RX_SIG = r"((?P<type>character|real|type|logical|integer|complex)?" + \
r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?\s*" + \
r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \
r"\s*\((?P<parameters>[^)]*)\)"
self.RE_SIG = re.compile(self._RX_SIG, re.I)
#The contents of the executable already have any & line continuations
#removed, so we can use a simple multiline regex.
self._RX_ASSIGN = r"^(?P<assignee>[^!<=\n/]+?)=[^\n]+?$"
self.RE_ASSIGN = re.compile(self._RX_ASSIGN, re.M)
self._RX_DEPEND = r"^\s*(?P<sub>call\s+)?(?P<exec>[a-z0-9_%]+\s*\([^\n]+)$"
self.RE_DEPEND = re.compile(self._RX_DEPEND, re.M | re. I)
self._RX_DEPCLEAN = r"(?P<key>[a-z0-9_%]+)\("
self.RE_DEPCLEAN = re.compile(self._RX_DEPCLEAN, re.I)
self._RX_CONST = '[^"\']+(?P<const>["\'][^\'"]+["\'])'
self.RE_CONST = re.compile(self._RX_CONST)
self._RX_COMMENTS = r'\s*![^\n"]+?\n'
self.RE_COMMENTS = re.compile(self._RX_COMMENTS) |
<SYSTEM_TASK:>
Extracts all the subroutine and function definitions from the specified module.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, module):
"""Extracts all the subroutine and function definitions from the specified module.""" |
#Because of embedded types, we have to examine the entire module for
#executable definitions.
self.parse_block(module.refstring, module, module, 0)
#Now we can set the value of module.contains as the text after the start of
#the *first* non-embedded executable.
min_start = len(module.refstring)
for x in module.executables:
if module.executables[x].start < min_start:
min_start = module.executables[x].start
module.contains = module.refstring[min_start::] |
<SYSTEM_TASK:>
Extracts all executable definitions from the specified string and adds
<END_TASK>
<USER_TASK:>
Description:
def parse_block(self, contents, parent, module, depth):
"""Extracts all executable definitions from the specified string and adds
them to the specified parent.""" |
for anexec in self.RE_EXEC.finditer(contents):
x = self._process_execs(anexec, parent, module)
parent.executables[x.name.lower()] = x
if isinstance(parent, Module) and "public" in x.modifiers:
parent.publics[x.name.lower()] = 1
#To handle the embedded executables, run this method recursively
self.parse_block(x.contents, x, module, depth + 1)
#Now that we have the executables, we can use them to compile a string
#that includes only documentation *external* to the executable definitions
#Because we enforce adding the name to 'end subroutine' statements etc.
#all the embedded executables haven't been parsed yet.
if len(parent.executables) > 0:
remove = []
for x in parent.executables:
remove.append((parent.executables[x].start, parent.executables[x].end))
remove.sort(key=lambda tup: tup[0])
retain = []
cur_end = 0
for rem in remove:
if "\n" in contents[rem[0]+1:rem[1]]:
signature = contents[rem[0]+1:rem[1]].index("\n") + 2
keep = contents[cur_end:rem[0] + signature]
cur_end = rem[1]
retain.append(keep)
#Now we have a string of documentation segments and the signatures they
#decorate that only applies to the non-embedded subroutines
docsearch = "".join(retain)
docblocks = self.docparser.parse_docs(docsearch, parent)
#Process the decorating documentation for the executables including the
#parameter definitions.
for x in parent.executables:
self._process_docs(parent.executables[x], docblocks,
parent, module, docsearch) |
<SYSTEM_TASK:>
Processes the regex match of an executable from the match object.
<END_TASK>
<USER_TASK:>
Description:
def _process_execs(self, execmatch, parent, module):
"""Processes the regex match of an executable from the match object.""" |
#Get the matches that must be present for every executable.
name = execmatch.group("name").strip()
modifiers = execmatch.group("modifiers")
if modifiers is None:
modifiers = []
else:
modifiers = re.split(",[ \t]*", modifiers)
codetype = execmatch.group("codetype")
params = re.split("[\s,]+", execmatch.group("parameters"))
contents = execmatch.group("contents")
#If the exec is a function, we also may have a type and kind specified.
if codetype.lower() == "function":
dtype = execmatch.group("type")
kind = execmatch.group("kind")
result = Function(name, modifiers, dtype, kind, parent)
else:
result = Subroutine(name, modifiers, parent)
#Set the regex start and end char indices
result.start, result.end = module.absolute_charindex(execmatch.string, execmatch.start(),
execmatch.end())
result.contents = contents
#Now we can handle the rest which is common to both types of executable
#Extract a list of local variables
self._parse_members(contents, result, params)
if isinstance(result, Function):
#We need to handle the syntax for defining a function with result(variable)
#to specify the return type of the function.
if execmatch.group("result") is not None:
resvar = execmatch.group("result").lower().split("result(")[1].replace(")", "")
else:
resvar = None
result.update_dtype(resvar)
#Fortran allows lines to be continued using &. The easiest way
#to deal with this is to remove all of those before processing
#any of the regular expressions
decommented = "\n".join([ self._depend_exec_clean(l) for l in contents.split("\n") ])
cleaned = re.sub("&\s*", "", decommented)
#Finally, process the dependencies. These are calls to functions and
#subroutines from within the executable body
self._process_dependencies(result, cleaned)
self._process_assignments(result, cleaned)
return result |
<SYSTEM_TASK:>
Extracts all variable assignments from the body of the executable.
<END_TASK>
<USER_TASK:>
Description:
def _process_assignments(self, anexec, contents, mode="insert"):
"""Extracts all variable assignments from the body of the executable.
:arg mode: for real-time update; either 'insert', 'delete' or 'replace'.
""" |
for assign in self.RE_ASSIGN.finditer(contents):
assignee = assign.group("assignee").strip()
target = re.split(r"[(%\s]", assignee)[0].lower()
#We only want to include variables that we know are in the scope of the
#current executable. This excludes function calls etc. with optional params.
if target in self._intrinsic:
continue
if target in anexec.members or \
target in anexec.parameters or \
(isinstance(anexec, Function) and target.lower() == anexec.name.lower()):
if mode == "insert":
anexec.add_assignment(re.split(r"[(\s]", assignee)[0])
elif mode == "delete":
#Remove the first instance of this assignment from the list
try:
index = element.assignments.index(assign)
del element.assignments[index]
except ValueError:
#We didn't have anything to remove, but python
pass |
<SYSTEM_TASK:>
Extracts a list of subroutines and functions that are called from
<END_TASK>
<USER_TASK:>
Description:
def _process_dependencies(self, anexec, contents, mode="insert"):
"""Extracts a list of subroutines and functions that are called from
within this executable.
:arg mode: specifies whether the matches should be added, removed
or merged into the specified executable.
""" |
#At this point we don't necessarily know which module the executables are
#in, so we just extract the names. Once all the modules in the library
#have been parsed, we can do the associations at that level for linking.
for dmatch in self.RE_DEPEND.finditer(contents):
isSubroutine = dmatch.group("sub") is not None
if "!" in dmatch.group("exec"):
execline = self._depend_exec_clean(dmatch.group("exec"))
else:
execline = "(" + dmatch.group("exec").split("!")[0].replace(",", ", ") + ")"
if not "::" in execline:
try:
dependent = self.nester.parseString(execline).asList()[0]
except:
msg.err("parsing executable dependency call {}".format(anexec.name))
msg.gen("\t" + execline)
#Sometimes the parameter passed to a subroutine or function is
#itself a function call. These are always the first elements in
#their nested lists.
self._process_dependlist(dependent, anexec, isSubroutine, mode) |
<SYSTEM_TASK:>
Cleans any string constants in the specified dependency text to remove
<END_TASK>
<USER_TASK:>
Description:
def _depend_exec_clean(self, text):
"""Cleans any string constants in the specified dependency text to remove
embedded ! etc. that break the parsing.
""" |
#First remove the escaped quotes, we will add them back at the end.
unquoted = text.replace('""', "_FORTPYDQ_").replace("''", "_FORTPYSQ_")
for cmatch in self.RE_CONST.finditer(unquoted):
string = cmatch.string[cmatch.start():cmatch.end()]
newstr = string.replace("!", "_FORTPYEX_")
unquoted = unquoted.replace(string, newstr)
requote = unquoted.split("!")[0].replace("_FORTPYDQ_", '""').replace("_FORTPYSQ_", "''")
result = "(" + requote.replace("_FORTPYEX_", "!").replace(",", ", ") + ")"
return result |
<SYSTEM_TASK:>
Processes a list of nested dependencies recursively.
<END_TASK>
<USER_TASK:>
Description:
def _process_dependlist(self, dependlist, anexec, isSubroutine, mode="insert"):
"""Processes a list of nested dependencies recursively.""" |
for i in range(len(dependlist)):
#Since we are looping over all the elements and some will
#be lists of parameters, we need to skip any items that are lists.
if isinstance(dependlist[i], list):
continue
key = dependlist[i].lower()
if len(dependlist) > i + 1:
has_params = isinstance(dependlist[i + 1], list)
else:
has_params = False
#Clean the dependency key to make sure we are only considering valid
#executable symbols.
cleanmatch = self.RE_DEPCLEAN.match(key + "(")
if not cleanmatch:
continue
else:
key = cleanmatch.group("key")
#We need to handle if and do constructs etc. separately
if key not in ["then", ",", "", "elseif"] and has_params \
and not "=" in key and not ">" in key:
if key in ["if", "do"]:
self._process_dependlist(dependlist[i + 1], anexec, False, mode)
else:
#This must be valid call to an executable, add it to the list
#with its parameters and then process its parameters list
#to see if there are more nested executables
if mode == "insert":
self._add_dependency(key, dependlist, i, isSubroutine, anexec)
elif mode == "delete":
#Try and find a dependency already in the executable that
#has the same call signature; then remove it.
self._remove_dependency(dependlist, i, isSubroutine, anexec)
self._process_dependlist(dependlist[i + 1], anexec, False, mode) |
<SYSTEM_TASK:>
Removes the specified dependency from the executable if it exists
<END_TASK>
<USER_TASK:>
Description:
def _remove_dependency(self, dependlist, i, isSubroutine, anexec):
"""Removes the specified dependency from the executable if it exists
and matches the call signature.""" |
if dependlist[i] in anexec.dependencies:
all_depends = anexec.dependencies[dependlist[i]]
if len(all_depends) > 0:
clean_args = all_depends[0].clean(dependlist[i + 1])
for idepend in range(len(all_depends)):
#Make sure we match across all relevant parameters
if (all_depends[idepend].argslist == clean_args
and all_depends[idepend].isSubroutine == isSubroutine):
del anexec.dependencies[dependlist[i]][idepend]
#We only need to delete one, even if there are multiple
#identical calls from elsewhere in the body.
break |
<SYSTEM_TASK:>
Determines whether the item in the dependency list is a valid function
<END_TASK>
<USER_TASK:>
Description:
def _add_dependency(self, key, dependlist, i, isSubroutine, anexec):
"""Determines whether the item in the dependency list is a valid function
call by excluding local variables and members.""" |
#First determine if the reference is to a derived type variable
lkey = key.lower()
if "%" in key:
#Find the type of the base variable and then perform a tree
#search at the module level to determine if the final reference
#is a valid executable
base = key.split("%")[0]
ftype = None
if base in anexec.members and anexec.members[base].is_custom:
ftype = anexec.members[base].kind
elif base in anexec.parameters and anexec.parameters[base].is_custom:
ftype = anexec.parameters[base].kind
if ftype is not None:
end = anexec.module.type_search(ftype, key)
if end is not None and isinstance(end, TypeExecutable):
#We have to overwrite the key to include the actual name of the type
#that is being referenced instead of the local name of its variable.
tname = "{}%{}".format(ftype, '%'.join(key.split('%')[1:]))
d = Dependency(tname, dependlist[i + 1], isSubroutine, anexec)
anexec.add_dependency(d)
elif lkey not in ["for", "forall", "do"]:
#This is a straight forward function/subroutine call, make sure that
#the symbol is not a local variable or parameter, then add it
if not lkey in anexec.members and not lkey in anexec.parameters \
and not lkey in self._intrinsic:
#One issue with the logic until now is that some one-line statements
#like "if (cond) call subroutine" don't trigger the subroutine flag
#of the dependency.
if dependlist[i-1] == "call":
isSubroutine = True
d = Dependency(dependlist[i], dependlist[i + 1], isSubroutine, anexec)
anexec.add_dependency(d) |
<SYSTEM_TASK:>
Associates the docstrings from the docblocks with their parameters.
<END_TASK>
<USER_TASK:>
Description:
def _process_docs(self, anexec, docblocks, parent, module, docsearch):
"""Associates the docstrings from the docblocks with their parameters.""" |
#The documentation for the parameters is stored outside of the executable
#We need to get hold of them from docblocks from the parent text
key = "{}.{}".format(parent.name, anexec.name)
if key in docblocks:
docs = self.docparser.to_doc(docblocks[key][0], anexec.name)
anexec.docstart, anexec.docend = (docblocks[key][1], docblocks[key][2])
self.docparser.process_execdocs(docs, anexec, key) |
<SYSTEM_TASK:>
Parses the local variables for the contents of the specified executable.
<END_TASK>
<USER_TASK:>
Description:
def _parse_members(self, contents, anexec, params, mode="insert"):
"""Parses the local variables for the contents of the specified executable.""" |
#First get the variables declared in the body of the executable, these can
#be either locals or parameter declarations.
members = self.vparser.parse(contents, anexec)
#If the name matches one in the parameter list, we can connect them
for param in list(params):
lparam = param.lower()
if lparam in members:
if mode == "insert" and not lparam in anexec.parameters:
anexec.add_parameter(members[lparam])
elif mode == "delete":
anexec.remove_parameter(members[lparam])
#The remaining members that aren't in parameters are the local variables
for key in members:
if mode == "insert":
if not key.lower() in anexec.parameters:
anexec.members[key] = members[key]
elif mode == "delete" and key in anexec.members:
del anexec.members[key]
#Next we need to get hold of the docstrings for these members
if mode == "insert":
memdocs = self.docparser.parse_docs(contents, anexec)
if anexec.name in memdocs:
docs = self.docparser.to_doc(memdocs[anexec.name][0], anexec.name)
self.docparser.process_memberdocs(docs, anexec)
#Also process the embedded types and executables who may have
#docstrings just like regular executables/types do.
self.docparser.process_embedded(memdocs, anexec) |
<SYSTEM_TASK:>
Parses the DOM and returns character attributes in the sidebar.
<END_TASK>
<USER_TASK:>
Description:
def parse_sidebar(self, character_page):
"""Parses the DOM and returns character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: Character attributes
:raises: :class:`.InvalidCharacterError`, :class:`.MalformedCharacterPageError`
""" |
character_info = {}
error_tag = character_page.find(u'div', {'class': 'badresult'})
if error_tag:
# MAL says the character does not exist.
raise InvalidCharacterError(self.id)
try:
full_name_tag = character_page.find(u'div', {'id': 'contentWrapper'}).find(u'h1')
if not full_name_tag:
# Page is malformed.
raise MalformedCharacterPageError(self.id, html, message="Could not find title div")
character_info[u'full_name'] = full_name_tag.text.strip()
except:
if not self.session.suppress_parse_exceptions:
raise
info_panel_first = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'td')
try:
picture_tag = info_panel_first.find(u'img')
character_info[u'picture'] = picture_tag.get(u'src').decode('utf-8')
except:
if not self.session.suppress_parse_exceptions:
raise
try:
# assemble animeography for this character.
character_info[u'animeography'] = {}
animeography_header = info_panel_first.find(u'div', text=u'Animeography')
if animeography_header:
animeography_table = animeography_header.find_next_sibling(u'table')
for row in animeography_table.find_all(u'tr'):
# second column has anime info.
info_col = row.find_all(u'td')[1]
anime_link = info_col.find(u'a')
link_parts = anime_link.get(u'href').split(u'/')
# of the form: /anime/1/Cowboy_Bebop
anime = self.session.anime(int(link_parts[2])).set({'title': anime_link.text})
role = info_col.find(u'small').text
character_info[u'animeography'][anime] = role
except:
if not self.session.suppress_parse_exceptions:
raise
try:
# assemble mangaography for this character.
character_info[u'mangaography'] = {}
mangaography_header = info_panel_first.find(u'div', text=u'Mangaography')
if mangaography_header:
mangaography_table = mangaography_header.find_next_sibling(u'table')
for row in mangaography_table.find_all(u'tr'):
# second column has manga info.
info_col = row.find_all(u'td')[1]
manga_link = info_col.find(u'a')
link_parts = manga_link.get(u'href').split(u'/')
# of the form: /manga/1/Cowboy_Bebop
manga = self.session.manga(int(link_parts[2])).set({'title': manga_link.text})
role = info_col.find(u'small').text
character_info[u'mangaography'][manga] = role
except:
if not self.session.suppress_parse_exceptions:
raise
try:
num_favorites_node = info_panel_first.find(text=re.compile(u'Member Favorites: '))
character_info[u'num_favorites'] = int(num_favorites_node.strip().split(u': ')[1])
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
<SYSTEM_TASK:>
Parses the DOM and returns character attributes in the main-content area.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, character_page):
"""Parses the DOM and returns character attributes in the main-content area.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: Character attributes.
""" |
character_info = self.parse_sidebar(character_page)
second_col = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
name_elt = second_col.find(u'div', {'class': 'normal_header'})
try:
name_jpn_node = name_elt.find(u'small')
if name_jpn_node:
character_info[u'name_jpn'] = name_jpn_node.text[1:-1]
else:
character_info[u'name_jpn'] = None
except:
if not self.session.suppress_parse_exceptions:
raise
try:
name_elt.find(u'span').extract()
character_info[u'name'] = name_elt.text.rstrip()
except:
if not self.session.suppress_parse_exceptions:
raise
try:
description_elts = []
curr_elt = name_elt.nextSibling
while True:
if curr_elt.name not in [None, u'br']:
break
description_elts.append(unicode(curr_elt))
curr_elt = curr_elt.nextSibling
character_info[u'description'] = ''.join(description_elts)
except:
if not self.session.suppress_parse_exceptions:
raise
try:
character_info[u'voice_actors'] = {}
voice_actors_header = second_col.find(u'div', text=u'Voice Actors')
if voice_actors_header:
voice_actors_table = voice_actors_header.find_next_sibling(u'table')
for row in voice_actors_table.find_all(u'tr'):
# second column has va info.
info_col = row.find_all(u'td')[1]
voice_actor_link = info_col.find(u'a')
name = ' '.join(reversed(voice_actor_link.text.split(u', ')))
link_parts = voice_actor_link.get(u'href').split(u'/')
# of the form: /people/82/Romi_Park
person = self.session.person(int(link_parts[2])).set({'name': name})
language = info_col.find(u'small').text
character_info[u'voice_actors'][person] = language
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
<SYSTEM_TASK:>
Parses the DOM and returns character favorites attributes.
<END_TASK>
<USER_TASK:>
Description:
def parse_favorites(self, favorites_page):
"""Parses the DOM and returns character favorites attributes.
:type favorites_page: :class:`bs4.BeautifulSoup`
:param favorites_page: MAL character favorites page's DOM
:rtype: dict
:return: Character favorites attributes.
""" |
character_info = self.parse_sidebar(favorites_page)
second_col = favorites_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
character_info[u'favorites'] = []
favorite_links = second_col.find_all('a', recursive=False)
for link in favorite_links:
# of the form /profile/shaldengeki
character_info[u'favorites'].append(self.session.user(username=link.text))
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
<SYSTEM_TASK:>
Parses the DOM and returns character pictures attributes.
<END_TASK>
<USER_TASK:>
Description:
def parse_pictures(self, picture_page):
"""Parses the DOM and returns character pictures attributes.
:type picture_page: :class:`bs4.BeautifulSoup`
:param picture_page: MAL character pictures page's DOM
:rtype: dict
:return: character pictures attributes.
""" |
character_info = self.parse_sidebar(picture_page)
second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
picture_table = second_col.find(u'table', recursive=False)
character_info[u'pictures'] = []
if picture_table:
character_info[u'pictures'] = map(lambda img: img.get(u'src').decode('utf-8'), picture_table.find_all(u'img'))
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
<SYSTEM_TASK:>
Parses the DOM and returns character clubs attributes.
<END_TASK>
<USER_TASK:>
Description:
def parse_clubs(self, clubs_page):
"""Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
""" |
character_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
clubs_header = second_col.find(u'div', text=u'Related Clubs')
character_info[u'clubs'] = []
if clubs_header:
curr_elt = clubs_header.nextSibling
while curr_elt is not None:
if curr_elt.name == u'div':
link = curr_elt.find(u'a')
club_id = int(re.match(r'/clubs\.php\?cid=(?P<id>[0-9]+)', link.get(u'href')).group(u'id'))
num_members = int(re.match(r'(?P<num>[0-9]+) members', curr_elt.find(u'small').text).group(u'num'))
character_info[u'clubs'].append(self.session.club(club_id).set({'name': link.text, 'num_members': num_members}))
curr_elt = curr_elt.nextSibling
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
<SYSTEM_TASK:>
Fetches the MAL character page and sets the current character's attributes.
<END_TASK>
<USER_TASK:>
Description:
def load(self):
"""Fetches the MAL character page and sets the current character's attributes.
:rtype: :class:`.Character`
:return: Current character object.
""" |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id)).text
self.set(self.parse(utilities.get_clean_dom(character)))
return self |
<SYSTEM_TASK:>
Fetches the MAL character favorites page and sets the current character's favorites attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_favorites(self):
"""Fetches the MAL character favorites page and sets the current character's favorites attributes.
:rtype: :class:`.Character`
:return: Current character object.
""" |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/favorites').text
self.set(self.parse_favorites(utilities.get_clean_dom(character)))
return self |
<SYSTEM_TASK:>
Fetches the MAL character pictures page and sets the current character's pictures attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_pictures(self):
"""Fetches the MAL character pictures page and sets the current character's pictures attributes.
:rtype: :class:`.Character`
:return: Current character object.
""" |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/pictures').text
self.set(self.parse_pictures(utilities.get_clean_dom(character)))
return self |
<SYSTEM_TASK:>
Fetches the MAL character clubs page and sets the current character's clubs attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_clubs(self):
"""Fetches the MAL character clubs page and sets the current character's clubs attributes.
:rtype: :class:`.Character`
:return: Current character object.
""" |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(character)))
return self |
<SYSTEM_TASK:>
Generates words of different length without storing
<END_TASK>
<USER_TASK:>
Description:
def generate(self, minlen, maxlen):
"""
Generates words of different length without storing
them into memory, enforced by itertools.product
""" |
if minlen < 1 or maxlen < minlen:
raise ValueError()
for cur in range(minlen, maxlen + 1):
# string product generator
str_generator = product(self.charset, repeat=cur)
for each in str_generator:
# yield the produced word
yield ''.join(each)+self.delimiter |
<SYSTEM_TASK:>
Parses the DOM and returns user clubs attributes.
<END_TASK>
<USER_TASK:>
Description:
def parse_clubs(self, clubs_page):
"""Parses the DOM and returns user clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL user clubs page's DOM
:rtype: dict
:return: User clubs attributes.
""" |
user_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'clubs'] = []
club_list = second_col.find(u'ol')
if club_list:
clubs = club_list.find_all(u'li')
for row in clubs:
club_link = row.find(u'a')
link_parts = club_link.get(u'href').split(u'?cid=')
# of the form /clubs.php?cid=10178
user_info[u'clubs'].append(self.session.club(int(link_parts[1])).set({u'name': club_link.text}))
except:
if not self.session.suppress_parse_exceptions:
raise
return user_info |
<SYSTEM_TASK:>
Parses the DOM and returns user friends attributes.
<END_TASK>
<USER_TASK:>
Description:
def parse_friends(self, friends_page):
"""Parses the DOM and returns user friends attributes.
:type friends_page: :class:`bs4.BeautifulSoup`
:param friends_page: MAL user friends page's DOM
:rtype: dict
:return: User friends attributes.
""" |
user_info = self.parse_sidebar(friends_page)
second_col = friends_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'friends'] = {}
friends = second_col.find_all(u'div', {u'class': u'friendHolder'})
if friends:
for row in friends:
block = row.find(u'div', {u'class': u'friendBlock'})
cols = block.find_all(u'div')
friend_link = cols[1].find(u'a')
friend = self.session.user(friend_link.text)
friend_info = {}
if len(cols) > 2 and cols[2].text != u'':
friend_info[u'last_active'] = utilities.parse_profile_date(cols[2].text.strip())
if len(cols) > 3 and cols[3].text != u'':
friend_info[u'since'] = utilities.parse_profile_date(cols[3].text.replace(u'Friends since', '').strip())
user_info[u'friends'][friend] = friend_info
except:
if not self.session.suppress_parse_exceptions:
raise
return user_info |
<SYSTEM_TASK:>
Fetches the MAL user page and sets the current user's attributes.
<END_TASK>
<USER_TASK:>
Description:
def load(self):
"""Fetches the MAL user page and sets the current user's attributes.
:rtype: :class:`.User`
:return: Current user object.
""" |
user_profile = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username)).text
self.set(self.parse(utilities.get_clean_dom(user_profile)))
return self |
<SYSTEM_TASK:>
Fetches the MAL user reviews page and sets the current user's reviews attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_reviews(self):
"""Fetches the MAL user reviews page and sets the current user's reviews attributes.
:rtype: :class:`.User`
:return: Current user object.
""" |
page = 0
# collect all reviews over all pages.
review_collection = []
while True:
user_reviews = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/reviews&' + urllib.urlencode({u'p': page})).text
parse_result = self.parse_reviews(utilities.get_clean_dom(user_reviews))
if page == 0:
# only set attributes once the first time around.
self.set(parse_result)
if len(parse_result[u'reviews']) == 0:
break
review_collection.append(parse_result[u'reviews'])
page += 1
# merge the review collections into one review dict, and set it.
self.set({
'reviews': {k: v for d in review_collection for k,v in d.iteritems()}
})
return self |
<SYSTEM_TASK:>
Fetches the MAL user recommendations page and sets the current user's recommendations attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_recommendations(self):
"""Fetches the MAL user recommendations page and sets the current user's recommendations attributes.
:rtype: :class:`.User`
:return: Current user object.
""" |
user_recommendations = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/recommendations').text
self.set(self.parse_recommendations(utilities.get_clean_dom(user_recommendations)))
return self |
<SYSTEM_TASK:>
Fetches the MAL user clubs page and sets the current user's clubs attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_clubs(self):
"""Fetches the MAL user clubs page and sets the current user's clubs attributes.
:rtype: :class:`.User`
:return: Current user object.
""" |
user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(user_clubs)))
return self |
<SYSTEM_TASK:>
Fetches the MAL user friends page and sets the current user's friends attributes.
<END_TASK>
<USER_TASK:>
Description:
def load_friends(self):
"""Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object.
""" |
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text
self.set(self.parse_friends(utilities.get_clean_dom(user_friends)))
return self |
<SYSTEM_TASK:>
Prints a line of text in arbitrary colors specified by the numeric
<END_TASK>
<USER_TASK:>
Description:
def arb(text, cols, split):
"""Prints a line of text in arbitrary colors specified by the numeric
values contained in msg.cenum dictionary.
""" |
stext = text if text[-1] != split else text[0:-1]
words = stext.split(split)
for i, word in enumerate(words):
col = icols[cols[i]]
printer(word, col, end="")
if i < len(words)-1:
printer(split, end="")
else:
printer(split) |
<SYSTEM_TASK:>
Returns True if the current global status of messaging would print a
<END_TASK>
<USER_TASK:>
Description:
def will_print(level=1):
"""Returns True if the current global status of messaging would print a
message using any of the printing functions in this module.
""" |
if level == 1:
#We only affect printability using the quiet setting.
return quiet is None or quiet == False
else:
return ((isinstance(verbosity, int) and level <= verbosity) or
(isinstance(verbosity, bool) and verbosity == True)) |
<SYSTEM_TASK:>
Prints the specified message as a warning; prepends "WARNING" to
<END_TASK>
<USER_TASK:>
Description:
def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
""" |
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") |
<SYSTEM_TASK:>
Prints the specified message as an error; prepends "ERROR" to
<END_TASK>
<USER_TASK:>
Description:
def err(msg, level=-1, prefix=True):
"""Prints the specified message as an error; prepends "ERROR" to
the message, so that can be left off.
""" |
if will_print(level) or verbosity is None:
printer(("ERROR: " if prefix else "") + msg, "red") |
<SYSTEM_TASK:>
Retrieves the value of an environment variable if it exists.
<END_TASK>
<USER_TASK:>
Description:
def getenvar(self, envar):
from os import getenv
"""Retrieves the value of an environment variable if it exists.""" |
if getenv(envar) is not None:
self._vardict[envar] = getenv(envar) |
<SYSTEM_TASK:>
Loads isense configuration as a dict of dicts into vardict.
<END_TASK>
<USER_TASK:>
Description:
def _load_isense(self, tag):
"""Loads isense configuration as a dict of dicts into vardict.""" |
isense = {}
for child in tag:
if child.tag in isense:
isense[child.tag].update(child.attrib)
else:
isense[child.tag] = child.attrib
self._vardict["isense"] = isense |
<SYSTEM_TASK:>
Loads the SSH configuration into the vardict.
<END_TASK>
<USER_TASK:>
Description:
def _load_ssh(self, tag):
"""Loads the SSH configuration into the vardict.""" |
for child in tag:
if child.tag == "server":
self._vardict["server"] = child.attrib
elif child.tag == "codes":
self._load_codes(child, True)
elif child.tag == "mappings":
self._load_mapping(child, True)
elif child.tag == "libraries":
self._load_includes(child, True) |
<SYSTEM_TASK:>
Extracts all additional libraries that should be included when linking
<END_TASK>
<USER_TASK:>
Description:
def _load_includes(self, tag, ssh=False):
"""Extracts all additional libraries that should be included when linking
the unit testing executables.
""" |
import re
includes = []
for child in tag:
if child.tag == "include" and "path" in child.attrib:
incl = { "path": child.attrib["path"] }
if "modules" in child.attrib:
incl["modules"] = re.split(",\s*", child.attrib["modules"].lower())
includes.append(incl)
if ssh == False:
self._vardict["includes"] = includes
else:
self._vardict["ssh.includes"] = includes |
<SYSTEM_TASK:>
Extracts all the paths to additional code directories to
<END_TASK>
<USER_TASK:>
Description:
def _load_codes(self, tag, ssh=False):
"""Extracts all the paths to additional code directories to
be considered.
:arg tag: the ET tag for the <codes> element.""" |
codes = []
for code in tag:
if code.tag == "trunk":
codes.append(code.attrib["value"])
if ssh == False:
self._vardict["codes"] = codes
else:
self._vardict["ssh.codes"] = codes |
<SYSTEM_TASK:>
Extracts all the alternate module name mappings to
<END_TASK>
<USER_TASK:>
Description:
def _load_mapping(self, tag, ssh=False):
"""Extracts all the alternate module name mappings to
be considered.
:arg tag: the ET tag for the <mappings> element.""" |
mappings = {}
for mapping in tag:
if mapping.tag == "map":
mappings[mapping.attrib["module"]] = mapping.attrib["file"]
if ssh == False:
self._vardict["mappings"] = mappings
else:
self._vardict["ssh.mappings"] = mappings |
<SYSTEM_TASK:>
Recursively copies the source directory to the destination
<END_TASK>
<USER_TASK:>
Description:
def copytree(src, dst):
"""Recursively copies the source directory to the destination
only if the files are newer or modified by using rsync.
""" |
from os import path, waitpid
from subprocess import Popen, PIPE
#Append any trailing / that we need to get rsync to work correctly.
source = path.join(src, "")
desti = path.join(dst, "")
if not path.isdir(desti):
from os import mkdir
mkdir(desti)
prsync = Popen("rsync -t -u -r {} {}".format(source, desti), close_fds=True,
shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
waitpid(prsync.pid, 0)
#Redirect the output and errors so that we don't pollute stdout.
#output = prsync.stdout.readlines()
error = prsync.stderr.readlines()
prsync.stderr.close()
prsync.stdout.close()
if len(error) > 0:
from fortpy.msg import warn
warn("Error while copying {} using rsync.\n\n{}".format(source, '\n'.join(error))) |
<SYSTEM_TASK:>
Gets the templates directory from the fortpy package.
<END_TASK>
<USER_TASK:>
Description:
def get_fortpy_templates_dir():
"""Gets the templates directory from the fortpy package.""" |
import fortpy
from os import path
fortdir = path.dirname(fortpy.__file__)
return path.join(fortdir, "templates") |
<SYSTEM_TASK:>
Sets the directory path for the fortpy templates. If no directory
<END_TASK>
<USER_TASK:>
Description:
def set_fortpy_templates(obj, fortpy_templates=None):
"""Sets the directory path for the fortpy templates. If no directory
is specified, use the default one that shipped with the package.
""" |
#If they didn't specify a custom templates directory, use the default
#one that shipped with the package.
from os import path
if fortpy_templates is not None:
obj.fortpy_templates = path.abspath(path.expanduser(fortpy_templates))
else:
from fortpy.utility import get_fortpy_templates_dir
obj.fortpy_templates = get_fortpy_templates_dir() |
<SYSTEM_TASK:>
Returns the absolute path to the 'relpath' taken relative to the base
<END_TASK>
<USER_TASK:>
Description:
def get_dir_relpath(base, relpath):
"""Returns the absolute path to the 'relpath' taken relative to the base
directory.
:arg base: the base directory to take the path relative to.
:arg relpath: the path relative to 'base' in terms of '.' and '..'.
""" |
from os import path
xbase = path.abspath(path.expanduser(base))
if not path.isdir(xbase):
return path.join(xbase, relpath)
if relpath[0:2] == "./":
return path.join(xbase, relpath[2::])
else:
from os import chdir, getcwd
cd = getcwd()
chdir(xbase)
result = path.abspath(relpath)
chdir(cd)
return result |
<SYSTEM_TASK:>
Wraps the specified line of text on whitespace to make sure that none of the
<END_TASK>
<USER_TASK:>
Description:
def wrap_line(line, limit=None, chars=80):
"""Wraps the specified line of text on whitespace to make sure that none of the
lines' lengths exceeds 'chars' characters.
""" |
result = []
builder = []
length = 0
if limit is not None:
sline = line[0:limit]
else:
sline = line
for word in sline.split():
if length <= chars:
builder.append(word)
length += len(word) + 1
else:
result.append(' '.join(builder))
builder = [word]
length = 0
result.append(' '.join(builder))
return result |
<SYSTEM_TASK:>
Explains the specified ParseError instance to show the user where the error
<END_TASK>
<USER_TASK:>
Description:
def x_parse_error(err, content, source):
"""Explains the specified ParseError instance to show the user where the error
happened in their XML.
""" |
lineno, column = err.position
if "<doc>" in content:
#Adjust the position since we are taking the <doc> part out of the tags
#since we may have put that in ourselves.
column -= 5
start = lineno - (1 if lineno == 1 else 2)
lines = []
tcontent = content.replace("<doc>", "").replace("</doc>", "").split('\n')
for context in IT.islice(tcontent, start, lineno):
lines.append(context.strip())
last = wrap_line(lines.pop(), column)
lines.extend(last)
caret = '{:=>{}}'.format('^', len(last[-1]))
if source is not None:
err.msg = '\nIn: {}\n{}\n{}\n{}'.format(source, err, '\n'.join(lines), caret)
else:
err.msg = '{}\n{}\n{}'.format(err, '\n'.join(lines), caret)
raise err |
<SYSTEM_TASK:>
Parses the XML string into a node tree. If an ParseError exception is raised,
<END_TASK>
<USER_TASK:>
Description:
def XML_fromstring(content, source=None):
"""Parses the XML string into a node tree. If an ParseError exception is raised,
the error message is formatted nicely to show the badly formed XML to the user.
""" |
try:
tree = ET.fromstring(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree |
<SYSTEM_TASK:>
Formats all of the docstrings in the specified element and its
<END_TASK>
<USER_TASK:>
Description:
def format(element):
"""Formats all of the docstrings in the specified element and its
children into a user-friendly paragraph format for printing.
:arg element: an instance of fortpy.element.CodeElement.
""" |
result = []
if type(element).__name__ in ["Subroutine", "Function"]:
_format_executable(result, element)
elif type(element).__name__ == "CustomType":
_format_type(result, element)
elif isinstance(element, ValueElement):
_format_value_element(result, element)
return '\n'.join(result) |
<SYSTEM_TASK:>
Performs formatting specific to a Subroutine or Function code
<END_TASK>
<USER_TASK:>
Description:
def _format_executable(lines, element, spacer=""):
"""Performs formatting specific to a Subroutine or Function code
element for relevant docstrings.
""" |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
rlines.append("PARAMETERS")
for p in element.ordered_parameters:
_format_value_element(rlines, p)
rlines.append("")
_format_generic(rlines, element, ["summary"])
#Subroutines can have embedded types and functions which need to be handled.
if len(element.types) > 0:
rlines.append("\nEMBEDDED TYPES")
for key, value in list(element.types.items()):
_format_type(rlines, value, " ")
if len(element.executables) > 0:
rlines.append("\nEMBEDDED EXECUTABLES")
for key, value in list(element.executables.items()):
_format_executable(rlines, value, " ")
lines.extend([spacer + l for l in rlines]) |
<SYSTEM_TASK:>
Formats a derived type for full documentation output.
<END_TASK>
<USER_TASK:>
Description:
def _format_type(lines, element, spacer=""):
"""Formats a derived type for full documentation output.""" |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
_format_generic(rlines, element, ["summary"])
if len(element.executables) > 0:
rlines.append("\nEMBEDDED PROCEDURES")
for key, value in list(element.executables.items()):
rlines.append(" {}".format(value.__str__()))
target = value.target
if target is not None:
_format_executable(rlines, target, " ")
if len(element.members) > 0:
rlines.append("\nEMBEDDED MEMBERS")
for key, value in list(element.members.items()):
_format_value_element(rlines, value, " ")
lines.extend([spacer + l for l in rlines]) |
<SYSTEM_TASK:>
Formats a member or parameter for full documentation output.
<END_TASK>
<USER_TASK:>
Description:
def _format_value_element(lines, element, spacer=""):
"""Formats a member or parameter for full documentation output.""" |
lines.append(spacer + element.definition())
_format_summary(lines, element)
_format_generic(lines, element, ["summary"]) |
<SYSTEM_TASK:>
Adds the element's summary tag to the lines if it exists.
<END_TASK>
<USER_TASK:>
Description:
def _format_summary(lines, element, spacer=" "):
"""Adds the element's summary tag to the lines if it exists.""" |
summary = spacer + element.summary
if element.summary == "":
summary = spacer + "No description given in XML documentation for this element."
lines.append(summary) |
<SYSTEM_TASK:>
Generically formats all remaining docstrings and custom XML
<END_TASK>
<USER_TASK:>
Description:
def _format_generic(lines, element, printed, spacer=""):
"""Generically formats all remaining docstrings and custom XML
tags that don't appear in the list of already printed documentation.
:arg printed: a list of XML tags for the element that have already
been handled by a higher method.
""" |
for doc in element.docstring:
if doc.doctype.lower() not in printed:
lines.append(spacer + doc.__str__()) |
<SYSTEM_TASK:>
Returns the code to create the argtype to assign to the methods argtypes
<END_TASK>
<USER_TASK:>
Description:
def _py_ex_argtype(executable):
"""Returns the code to create the argtype to assign to the methods argtypes
attribute.
""" |
result = []
for p in executable.ordered_parameters:
atypes = p.argtypes
if atypes is not None:
result.extend(p.argtypes)
else:
print(("No argtypes for: {}".format(p.definition())))
if type(executable).__name__ == "Function":
result.extend(executable.argtypes)
return result |
<SYSTEM_TASK:>
Returns the ctypes type name for the specified fortran parameter.
<END_TASK>
<USER_TASK:>
Description:
def _py_ctype(parameter):
"""Returns the ctypes type name for the specified fortran parameter.
""" |
ctype = parameter.ctype
if ctype is None:
raise ValueError("Can't bind ctypes py_parameter for parameter"
" {}".format(parameter.definition()))
return ctype.lower() |
<SYSTEM_TASK:>
Appends all the code lines needed to create the result class instance and populate
<END_TASK>
<USER_TASK:>
Description:
def _py_code_clean(lines, tab, executable):
"""Appends all the code lines needed to create the result class instance and populate
its keys with all output variables.
""" |
count = 0
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
value = _py_clean(p, tab)
if value is not None:
count += 1
lines.append(value)
return count |
<SYSTEM_TASK:>
Returns the code to declare an Ftype object that handles memory
<END_TASK>
<USER_TASK:>
Description:
def _py_ftype(parameter, tab):
"""Returns the code to declare an Ftype object that handles memory
deallocation for Fortran return arrays that were allocated by the
method called in ctypes.
""" |
splice = ', '.join(["{0}_{1:d}".format(parameter.lname, i)
for i in range(parameter.D)])
return "{2}{0}_ft = Ftype({0}_o, [{1}], libpath)".format(parameter.lname, splice, tab) |
<SYSTEM_TASK:>
Returns the code line to clean the output value of the specified parameter.
<END_TASK>
<USER_TASK:>
Description:
def _py_clean(parameter, tab):
"""Returns the code line to clean the output value of the specified parameter.
""" |
if "out" in parameter.direction:
if parameter.D > 0:
if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
if parameter.D == 1:
clarray = "as_array({0}_o, ({0}_0.value,))".format(parameter.lname)
else:
#We have to reverse the order of the indices because of the way that
#fortran orders the array elements. We undo this using a transpose in
#the ftypes.as_array() so that the elements are ordered correctly.
splice = ', '.join(reversed(["{0}_{1:d}.value".format(parameter.lname, i)
for i in range(parameter.D)]))
clarray = "as_array({0}_o, ({1}))".format(parameter.lname, splice)
assign = '{0}result.add("{1}", {2}, {1}_ft)'.format(tab, parameter.lname, clarray)
fstr = _py_ftype(parameter, tab)
#For optional out parameters, we won't necessarily have anything to report.
return _py_check_optional(parameter, tab, [fstr, assign])
else:
return '{1}result.add("{0}", {0}_a)'.format(parameter.lname, tab)
else: #This handles scalar (inout) and (out) variables.
return '{1}result.add("{0}", {0}_c.value)'.format(parameter.lname, tab) |
<SYSTEM_TASK:>
Adds the variable code lines for all the parameters in the executable.
<END_TASK>
<USER_TASK:>
Description:
def _py_code_variables(lines, executable, lparams, tab):
"""Adds the variable code lines for all the parameters in the executable.
:arg lparams: a list of the local variable declarations made so far that need to be passed
to the executable when it is called.
""" |
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
_py_code_parameter(lines, p, "invar", lparams, tab)
if p.direction == "(out)":
#We need to reverse the order of the indices to match the fortran code
#generation of the wrapper.
_py_code_parameter(lines, p, "outvar", lparams, tab)
_py_code_parameter(lines, p, "indices", lparams, tab)
else:
_py_code_parameter(lines, p, "indices", lparams, tab)
_py_code_parameter(lines, p, "outvar", lparams, tab) |
<SYSTEM_TASK:>
Appends the code to produce the parameter at the specified position in the executable.
<END_TASK>
<USER_TASK:>
Description:
def _py_code_parameter(lines, parameter, position, lparams, tab):
"""Appends the code to produce the parameter at the specified position in the executable.
:arg position: one of ['invar', 'outvar', 'indices'].
:arg lparams: a list of the local variable declarations made so far that need to be passed
to the executable when it is called.
""" |
mdict = {
"invar": _py_invar,
"outvar": _py_outvar,
"indices": _py_indices
}
line = mdict[position](parameter, lparams, tab)
if line is not None:
value, blank = line
lines.append(tab + value)
if blank:
lines.append("") |
<SYSTEM_TASK:>
Returns the code to create the local input parameter that is coerced to have the
<END_TASK>
<USER_TASK:>
Description:
def _py_invar(parameter, lparams, tab):
"""Returns the code to create the local input parameter that is coerced to have the
correct type for ctypes interaction.
""" |
if ("in" in parameter.direction and parameter.D > 0):
if parameter.direction == "(inout)" and ":" not in parameter.dimension:
wstr = ", writeable"
else:
wstr = ""
pytype = _py_pytype(parameter)
lparams.append("{}_a".format(parameter.lname))
return ('{0}_a = require({0}, {1}, "F{2}")'.format(parameter.lname, pytype, wstr), False)
elif parameter.D == 0:
#Even for scalar outvars, we need to initialize a variable to pass by reference.
lparams.append("byref({}_c)".format(parameter.lname))
if parameter.direction == "(out)":
initval = parameter.py_initval
return ("{0}_c = {1}({2})".format(parameter.lname, _py_ctype(parameter), initval), False)
else:
return ("{0}_c = {1}({0})".format(parameter.lname, _py_ctype(parameter)), False) |
<SYSTEM_TASK:>
Returns the code to produce a ctypes output variable for interacting with fortran.
<END_TASK>
<USER_TASK:>
Description:
def _py_outvar(parameter, lparams, tab):
"""Returns the code to produce a ctypes output variable for interacting with fortran.
""" |
if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and
("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)):
lparams.append("byref({}_o)".format(parameter.lname))
blank = True if parameter.direction == "(inout)" else False
return ("{0}_o = POINTER({1})()".format(parameter.lname, _py_ctype(parameter)), blank) |
<SYSTEM_TASK:>
Returns the code to produce py ctypes for the indices of the specified parameter
<END_TASK>
<USER_TASK:>
Description:
def _py_indices(parameter, lparams, tab):
"""Returns the code to produce py ctypes for the indices of the specified parameter
that has D > 0.
""" |
if parameter.D > 0 and ":" in parameter.dimension:
if "in" in parameter.direction:
indexstr = "{0}_{1:d} = c_int({0}_a.shape[{1:d}])"
else:
indexstr = "{0}_{1:d} = c_int(0)"
lparams.extend(["byref({}_{})".format(parameter.lname, i) for i in range(parameter.D)])
joinstr = "\n" + tab
blank = True if parameter.direction == "(out)" else False
return (joinstr.join([indexstr.format(parameter.lname, i)
for i in range(parameter.D)]), blank) |
<SYSTEM_TASK:>
Returns the code for the specified parameter being written into a subroutine wrapper.
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_code_parameter(lines, parameter, position):
"""Returns the code for the specified parameter being written into a subroutine wrapper.
:arg position: one of ['indices', 'variable', 'out', 'regular', 'saved', 'assign', 'clean']
""" |
mdict = {
'indices': _ctypes_indices,
'variable': _ctypes_variables,
'out': _ctypes_out,
'regular': _ctypes_regular,
'saved': _ctypes_saved,
'assign': _ctypes_assign,
'clean': _ctypes_clean
}
line = mdict[position](parameter)
if line is not None:
value, blank = line
lines.append(value)
if blank:
lines.append("") |
<SYSTEM_TASK:>
Determines the ISO_C data type to use for describing the specified parameter.
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_dtype(parameter):
"""Determines the ISO_C data type to use for describing the specified parameter.
""" |
ctype = parameter.ctype
if ctype is None:
if parameter.kind is not None:
return "{}({})".format(parameter.dtype, parameter.kind)
else:
return parameter.dtype
else:
return"{}({})".format(parameter.dtype, ctype) |
<SYSTEM_TASK:>
Returns a list of variable names that define the size of each dimension.
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_splice(parameter):
"""Returns a list of variable names that define the size of each dimension.
""" |
params = parameter.ctypes_parameter()
if parameter.direction == "(inout)" and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
return ', '.join(params[1:-1])
else:
return ', '.join(params[1::]) |
<SYSTEM_TASK:>
Returns code for parameter variable declarations specifying the size of each
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_indices(parameter):
"""Returns code for parameter variable declarations specifying the size of each
dimension in the specified parameter.
""" |
if (parameter.dimension is not None and ":" in parameter.dimension):
splice = _ctypes_splice(parameter)
if "out" in parameter.direction:
#Even for pure out variables, the ctypes pointer is passed in and will
#have a value already.
return ("integer, intent(inout) :: {}".format(splice), False)
else:
return ("integer, intent(in) :: {}".format(splice), False) |
<SYSTEM_TASK:>
Returns the local parameter definition for implementing a Fortran wrapper subroutine
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_variables(parameter):
"""Returns the local parameter definition for implementing a Fortran wrapper subroutine
for this parameter's parent executable.
""" |
if parameter.dimension is not None and ":" in parameter.dimension:
#For arrays that provide input (including 'inout'), we pass the output separately
#through a c-pointer. They will always be input arrays. For pure (out) parameters
#we use *only* a c-ptr, but it needs intent (inout) since it is created by ctypes.
if "in" in parameter.direction or parameter.direction == "":
#We have to get the ctypes-compatible data type for the parameters.
#stype = _ctypes_dtype(parameter)
splice = _ctypes_splice(parameter)
name = parameter.ctypes_parameter()[0]
if parameter.direction == "(inout)" and not ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
return (parameter.definition(optionals=False, customdim=splice), False)
else:
return ("{}, intent(in) :: {}({})".format(parameter.strtype, name, splice), False)
else:
if parameter.dtype == "logical":
stype = _ctypes_dtype(parameter)
suffix = "_c"
modifiers = None
elif hasattr(parameter, "parameters"):
stype = None
suffix = "_f"
modifiers = ["intent(out)"]
else:
stype = None
suffix = ""
modifiers = None
return (parameter.definition(ctype=stype, optionals=False, suffix=suffix,
modifiers=modifiers), False) |
<SYSTEM_TASK:>
Returns a parameter variable declaration for an output variable for the specified
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_out(parameter):
"""Returns a parameter variable declaration for an output variable for the specified
parameter.
""" |
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
if parameter.direction == "(inout)":
return ("type(C_PTR), intent(inout) :: {}_o".format(parameter.name), True)
else: #self.direction == "(out)" since that is the only other option.
return ("type(C_PTR), intent(inout) :: {}_c".format(parameter.name), True) |
<SYSTEM_TASK:>
Returns local variable declarations that create allocatable variables that can persist
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_saved(parameter):
"""Returns local variable declarations that create allocatable variables that can persist
long enough to return their value through ctypes.
""" |
if ("out" in parameter.direction and parameter.dimension is not None and
":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
stype = _ctypes_dtype(parameter)
name = "{}_t({})".format(parameter.name, parameter.dimension)
return ("{}, allocatable, target, save :: {}".format(stype, name), True) |
<SYSTEM_TASK:>
Returns the lines of code required to assign the correct values to the integers
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_clean(parameter):
"""Returns the lines of code required to assign the correct values to the integers
representing the indices of the output arrays in the ctypes wrapper subroutine.
""" |
if ("out" in parameter.direction and parameter.dimension is not None
and ":" in parameter.dimension and ("pointer" in parameter.modifiers or
"allocatable" in parameter.modifiers)):
params = parameter.ctypes_parameter()
result = []
spacer = " "
#We get segfaults if we try to assign c-pointers to unallocated pointers or arrays.
if "optional" in parameter.modifiers:
if "pointer" in parameter.modifiers:
result.append("{}if (associated({})) then".format(spacer, parameter.name))
spacer += " "
elif "allocatable" in parameter.modifiers:
result.append("{}if (allocated({})) then".format(spacer, parameter.name))
spacer += " "
#We have to copy the values or at least update the pointer to access the
#variables with 'target' and 'save' attributes.
result.append("{0}{1}_t = {1}".format(spacer, parameter.name))
if parameter.direction == "(inout)":
result.append("{1}{0}_o = C_LOC({0}_t)".format(parameter.name, spacer))
#Update the index variables for the dimensions of the output variable.
for i, p in enumerate(params[1:-1]):
result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1))
else:
#This is the case for intent(out)
result.append("{1}{0}_c = C_LOC({0}_t)".format(parameter.name, spacer))
for i, p in enumerate(params[1::]):
result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1))
if ("optional" in parameter.modifiers and
("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers)):
result.append(" end if")
return ('\n'.join(result), True)
elif parameter.dtype == "logical" and "out" in parameter.direction:
return (" {0}_c = {0}".format(parameter.name), False) |
<SYSTEM_TASK:>
Returns a list of the parameters to form the wrapper executable to interact
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_ex_parameters(executable):
"""Returns a list of the parameters to form the wrapper executable to interact
with ctypes.
""" |
result = []
for p in executable.ordered_parameters:
result.extend(p.ctypes_parameter())
if type(executable).__name__ == "Function":
result.extend(executable.ctypes_parameter()) #This method inherits from ValueElement.
return result |
<SYSTEM_TASK:>
Returns a list of the local variable definitions required to construct the
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_ex_variables(executable):
"""Returns a list of the local variable definitions required to construct the
ctypes interop wrapper.
""" |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "indices")
_ctypes_code_parameter(result, p, "variable")
_ctypes_code_parameter(result, p, "out")
if type(executable).__name__ == "Function":
#For functions, we still create a subroutine-type interface and then just add an extra
#output-type parameter for the function's return type.
_ctypes_code_parameter(result, executable, "indices")
_ctypes_code_parameter(result, executable, "variable")
_ctypes_code_parameter(result, executable, "out")
return result |
<SYSTEM_TASK:>
Returns a list of code lines for signature matching variables, and
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_ex_compatvars(executable):
"""Returns a list of code lines for signature matching variables, and
pointer saving variables.
""" |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "regular")
_ctypes_code_parameter(result, p, "saved")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "regular")
_ctypes_code_parameter(result, executable, "saved")
return result |
<SYSTEM_TASK:>
Return a list of code lines to allocate and assign the local parameter definitions
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_ex_assign(executable):
"""Return a list of code lines to allocate and assign the local parameter definitions
that match those in the signature of the wrapped executable.
""" |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "assign")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "assign")
return result |
<SYSTEM_TASK:>
Return a list of code lines to take care of assigning pointers for output variables
<END_TASK>
<USER_TASK:>
Description:
def _ctypes_ex_clean(executable):
"""Return a list of code lines to take care of assigning pointers for output variables
interacting with ctypes.
""" |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "clean")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "clean")
return result |
<SYSTEM_TASK:>
Returns the name of the shared library file compiled for the wrapper
<END_TASK>
<USER_TASK:>
Description:
def libname(self):
"""Returns the name of the shared library file compiled for the wrapper
subroutines coded in fortran.
""" |
if self.library is not None:
return "ftypes.{}.so".format(self.library)
else:
return "{}.so".format(self.name) |
<SYSTEM_TASK:>
Makes sure that the linked library with the original code exists. If it doesn't
<END_TASK>
<USER_TASK:>
Description:
def _check_lib(self, remake, compiler, debug, profile):
"""Makes sure that the linked library with the original code exists. If it doesn't
the library is compiled from scratch.
""" |
from os import path
if self.link is None or not path.isfile(self.link):
self.makelib(remake, True, compiler, debug, profile) |
<SYSTEM_TASK:>
Compiles the makefile at the specified location with 'compiler'.
<END_TASK>
<USER_TASK:>
Description:
def _compile(self, dirpath, makename, compiler, debug, profile):
"""Compiles the makefile at the specified location with 'compiler'.
:arg dirpath: the full path to the directory where the makefile lives.
:arg compiler: one of ['ifort', 'gfortran'].
:arg makename: the name of the make file to compile.
""" |
from os import path
options = ""
if debug:
options += " DEBUG=true"
if profile:
options += " GPROF=true"
from os import system
codestr = "cd {}; make -f '{}' F90={} FAM={}" + options
code = system(codestr.format(dirpath, makename, compiler, compiler[0]))
#It turns out that the compiler still returns a code of zero, even if the compile
#failed because the actual compiler didn't fail; it did its job properly. We need to
#check for the existence of errors in the 'compile.log' file.
lcount = 0
errors = []
log = path.join(dirpath, "compile.log")
with open(log) as f:
for line in f:
lcount += 1
if lcount > 21 and lcount < 32:
errors.append(line)
elif lcount > 21:
break
if len(errors) > 0:
#There are 21 lines in the compile.log file when everything runs correctly
#Overwrite code with a bad exit value since we have some other problems.
code = 1
#We want to write the first couple of errors to the console and give them the
#option to still execute if the compile only generated warnings.
msg.warn("compile generated some errors or warnings:")
msg.blank()
msg.info(''.join(errors))
return code |
<SYSTEM_TASK:>
Generates a makefile for the code files that reside in the same directory as the source
<END_TASK>
<USER_TASK:>
Description:
def makelib(self, remake=False, full=True, compiler="gfortran", debug=False, profile=False):
"""Generates a makefile for the code files that reside in the same directory as the source
that was parsed by the code parser.
:arg full: when True, the shared library is compiled for *all* the code files in the directory
not just the one's that are dependencies of the source module.
""" |
if self.link is None or remake:
from os import path
if self.library is not None:
outpath = path.join(self.dirpath, "{}.a".format(self.library))
else:
outpath = path.join(self.dirpath, "{}.a".format(self.name))
if not remake and path.isfile(outpath): #No need to recompile
self.link = outpath
return
dependencies = self._get_lib_modules(full)
makepath = path.join(path.dirname(self.module.filepath), "Makefile.ftypes")
if full:
compileid = "ftypes.all_libs"
identifier = self.library
else:
compileid = "ftypes.{}_c".format(self.module.name)
identifier = self.module.name
makefile(identifier, dependencies, makepath, compileid,
self.module.precompile, False, self.module.parent, "a")
code = self._compile(path.dirname(self.module.filepath), "Makefile.ftypes",
compiler, debug, profile)
if code == 0:
self.link = path.join(path.dirname(self.module.filepath), "{}.a".format(identifier))
self._copy_so(outpath)
self.link = outpath
else:
#Just make sure it is copied over into the directory where we want to compile the wrapper
#module for ftypes.
self._copy_so(self.dirpath) |
<SYSTEM_TASK:>
Copies the shared library in self.so into the working directory for the wrapper
<END_TASK>
<USER_TASK:>
Description:
def _copy_so(self, outpath):
"""Copies the shared library in self.so into the working directory for the wrapper
module if it doesn't already exist.
""" |
from os import path
if not path.isfile(outpath) and path.isfile(self.link):
from shutil import copy
copy(self.link, outpath) |
<SYSTEM_TASK:>
Returns a list of the modules in the same folder as the one being wrapped for
<END_TASK>
<USER_TASK:>
Description:
def _get_lib_modules(self, full):
"""Returns a list of the modules in the same folder as the one being wrapped for
compilation as a linked library.
:arg full: when True, all the code files in the source file's directory are considered
as dependencies; otherwise only those explicitly needed are kept.
""" |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
result = []
if full:
found = {}
from os import path
mypath = path.dirname(self.module.filepath)
self.module.parent.scan_path(mypath, found)
for codefile in found:
self.module.parent.load_dependency(codefile.replace(".f90", ""), True, True, False)
for modname, module in list(self.module.parent.modules.items()):
if path.dirname(module.filepath).lower() == mypath.lower():
result.append(modname)
else:
result.extend(self.module.search_dependencies())
return self._process_module_needs(result) |
<SYSTEM_TASK:>
Gets a list of the module names that should be included in the shared lib compile
<END_TASK>
<USER_TASK:>
Description:
def _get_dependencies(self):
"""Gets a list of the module names that should be included in the shared lib compile
as dependencies for the current wrapper module.
""" |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
from os import path
modules = self.module.search_dependencies()
result = {}
for module in modules:
self.module.parent.load_dependency(module, True, True, False)
for modname, module in list(self.module.parent.modules.items()):
pathkey = path.dirname(module.filepath).lower()
if pathkey not in result:
result[pathkey] = path.dirname(module.filepath)
return result |
<SYSTEM_TASK:>
Finds the list of executables that pass the requirements necessary to have
<END_TASK>
<USER_TASK:>
Description:
def _find_executables(self):
"""Finds the list of executables that pass the requirements necessary to have
a wrapper created for them.
""" |
if len(self.needs) > 0:
return
for execname, executable in list(self.module.executables.items()):
skip = False
#At the moment we can't handle executables that use special derived types.
if not execname in self.module.publics or not executable.primitive:
msg.info("Skipping {}.{} because it is not public.".format(self.module.name, execname))
skip = True
#Check that all the parameters have intent specified, otherwise we won't handle them well.ha
if any([p.direction == "" for p in executable.ordered_parameters]):
msg.warn("Some parameters in {}.{} have no intent".format(self.module.name, execname) +
" specified. Can't wrap that executable.")
skip = True
if not skip:
self.uses.append(execname)
for depmod in executable.search_dependencies():
if depmod not in self.needs:
self.needs.append(depmod) |
<SYSTEM_TASK:>
Makes sure that the working directory for the wrapper modules exists.
<END_TASK>
<USER_TASK:>
Description:
def _check_dir(self):
"""Makes sure that the working directory for the wrapper modules exists.
""" |
from os import path, mkdir
if not path.isdir(self.dirpath):
mkdir(self.dirpath)
#Copy the ftypes.py module shipped with fortpy to the local directory.
ftypes = path.join(get_fortpy_templates(), "ftypes.py")
from shutil import copy
copy(ftypes, self.dirpath)
#Create the __init__.py file so that the library becomes a package for
#its module contents.
with open(path.join(self.dirpath, "__init__.py"), 'w') as f:
f.write("# Auto-generated for package structure by fortpy.")
#We also need to make sure that the fortpy deallocator module is present for
#compilation in the shared library.
if not path.isdir(self.f90path):
mkdir(self.f90path)
#Copy the ftypes.py module shipped with fortpy to the local directory.
ftypes = path.join(get_fortpy_templates(), "ftypes_dealloc.f90")
from shutil import copy
copy(ftypes, self.f90path) |
<SYSTEM_TASK:>
Writes a python module file to the current working directory for the library.
<END_TASK>
<USER_TASK:>
Description:
def write_py(self):
"""Writes a python module file to the current working directory for the library.
""" |
self._check_dir()
#We make it so that the write py method can be called independently (as opposed
#to first needing the F90 write method to be called).
self._find_executables()
lines = []
lines.append('"""Auto-generated python module for interaction with Fortran shared library\n'
'via ctypes. Generated for module {}.\n'.format(self.module.name) +
'"""')
lines.append("from ctypes import *")
lines.append("from ftypes import *")
lines.append("from numpy.ctypeslib import load_library, ndpointer")
lines.append("from numpy import require")
lines.append("from os import path")
lines.append("")
for execkey in self.uses:
self._write_executable_py(execkey, lines)
from os import path
pypath = path.join(self.dirpath, "{}.py".format(self.module.name.lower()))
with open(pypath, 'w') as f:
f.write('\n'.join(lines)) |
<SYSTEM_TASK:>
Writes the F90 module file to the specified directory.
<END_TASK>
<USER_TASK:>
Description:
def write_f90(self):
"""Writes the F90 module file to the specified directory.
""" |
from os import path
self._check_dir()
#Find the list of executables that we actually need to write wrappers for.
self._find_executables()
lines = []
lines.append("!!<summary>Auto-generated Fortran module for interaction with ctypes\n"
"!!through python. Generated for module {}.</summary>".format(self.module.name))
lines.append("MODULE {}_c".format(self.module.name))
#Some of the variables and parameters will have special kinds that need to be imported.
#Check each of the executables to find additional dependencies.
lines.append(" use {}".format(self.module.name))
lines.append(" use ISO_C_BINDING")
for modname in self.needs:
lines.append(" use {}".format(modname))
lines.append(" implicit none")
lines.append("CONTAINS")
#We want everything in these wrapper modules to be public, so we just exclude the 'private'.
for execkey in self.uses:
self._write_executable_f90(execkey, lines)
lines.append("END MODULE {}_c".format(self.module.name))
fullpath = path.join(self.f90path, "{}_c.f90".format(self.module.name))
with open(fullpath, 'w') as f:
f.write('\n'.join(lines)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.