Exemplo n.º 1
0
 def resolve_xref(self, env, fromdocname, builder,
                  typ, target, node, contnode):
     if (typ == 'mod' or
         typ == 'obj' and target in self.data['modules']):
         docname, synopsis, platform, deprecated = \
             self.data['modules'].get(target, ('','','', ''))
         if not docname:
             return None
         else:
             title = '%s%s%s' % ((platform and '(%s) ' % platform),
                                 synopsis,
                                 (deprecated and ' (deprecated)' or ''))
             return make_refnode(builder, fromdocname, docname,
                                 'module-' + target, contnode, title)
     else:
         modname = node.get('rb:module')
         clsname = node.get('rb:class')
         searchorder = node.hasattr('refspecific') and 1 or 0
         name, obj = self.find_obj(env, modname, clsname,
                                   target, typ, searchorder)
         if not obj:
             return None
         else:
             return make_refnode(builder, fromdocname, obj[0], name,
                                 contnode, name)
Exemplo n.º 2
0
    def resolve_xref(self, env, fromdocname, builder,
                     type, target, node, contnode):
        modname = node.get('py:module')
        clsname = node.get('py:class')
        searchmode = node.hasattr('refspecific') and 1 or 0
        matches = self.find_obj(env, modname, clsname, target,
                                type, searchmode)
        if not matches:
            return None
        elif len(matches) > 1:
            env.warn_node(
                'more than one target found for cross-reference '
                '%r: %s' % (target, ', '.join(match[0] for match in matches)),
                node)
        name, obj = matches[0]

        if obj[1] == 'module':
            # get additional info for modules
            docname, synopsis, platform, deprecated = self.data['modules'][name]
            assert docname == obj[0]
            title = name
            if synopsis:
                title += ': ' + synopsis
            if deprecated:
                title += _(' (deprecated)')
            if platform:
                title += ' (' + platform + ')'
            return make_refnode(builder, fromdocname, docname,
                                'module-' + name, contnode, title)
        else:
            return make_refnode(builder, fromdocname, obj[0], name,
                                contnode, name)
Exemplo n.º 3
0
	def resolve_xref(self, env, fromdocname, builder,
					typ, target, node, contnode):
		#print 'resolve_xref(%s)'%node
		if typ == 'module' and target in self.data['modules']:
			docname, synopsis, deprecated = self.data['modules'].get(target, ('','',''))
			if docname:
				return make_refnode(builder, fromdocname, docname, target, contnode, synopsis)
			else:
				return None
		#if typ == 'query' and target in self.data['modules']:
		#	docname, synopsis, deprecated = self.data['modules'].get(target, ('','',''))
		#	if not docname:
		#		return None
		#	else:
		#		title = '%s%s' % (synopsis, (deprecated and ' (deprecated)' or ''))
		#		return make_refnode(builder, fromdocname, docname,
		#							'module-' + target, contnode, title)
		else:
			modname = node.get('nscp:module')
			command = node.get('nscp:command')
			confpath = node.get('nscp:confpath')
			name, obj = self._find_obj(env, modname, command, confpath, target, typ)
			if not obj:
				return None
			else:
				return make_refnode(builder, fromdocname, obj, name,
									contnode, name)
Exemplo n.º 4
0
    def resolve_xref(self, env, fromdocname, builder, type, target, node, contnode):
        modname = node.get("lua:module")
        clsname = node.get("lua:class")
        searchmode = node.hasattr("refspecific") and 1 or 0
        matches = self.find_obj(env, modname, clsname, target, type, searchmode)
        if not matches:
            return None
        elif len(matches) > 1:
            env.warn_node(
                "more than one target found for cross-reference "
                "%r: %s" % (target, ", ".join(match[0] for match in matches)),
                node,
            )
        name, obj = matches[0]

        if obj[1] == "module":
            # get additional info for modules
            docname, synopsis, platform, deprecated = self.data["modules"][name]
            assert docname == obj[0]
            title = name
            if synopsis:
                title += ": " + synopsis
            if deprecated:
                title += _(" (deprecated)")
            if platform:
                title += " (" + platform + ")"
            return make_refnode(builder, fromdocname, docname, "module-" + name, contnode, title)
        else:
            return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
Exemplo n.º 5
0
	def resolve_xref(self, env, fromdocname, builder,
					typ, target, node, contnode):
		#print 'resolve_xref(%s)'%node
		if typ == 'module' and target in self.data['modules']:
			docname, synopsis, deprecated = self.data['modules'].get(target, ('','',''))
			if docname:
				return make_refnode(builder, fromdocname, docname, target, contnode, synopsis)
			else:
				return None
		if typ == 'query' and target in self.data['modules']:
			docname, synopsis, deprecated = self.data['modules'].get(target, ('','',''))
			if not docname:
				return None
			else:
				title = '%s%s' % (synopsis, (deprecated and ' (deprecated)' or ''))
				return make_refnode(builder, fromdocname, docname,
									'module-' + target, contnode, title)
		else:
			modname = node.get('nscp:module')
			searchorder = node.hasattr('refspecific') and 1 or 0
			name, obj = self._find_obj(env, modname, target, typ, searchorder)
			if not obj:
				return None
			else:
				return make_refnode(builder, fromdocname, obj, name,
									contnode, name)
Exemplo n.º 6
0
 def resolve_xref(self, env, fromdocname, builder,
                  type, target, node, contnode):
     if (type == 'mod' or
         type == 'obj' and target in self.data['modules']):
         docname, synopsis, platform, deprecated = \
             self.data['modules'].get(target, ('','','', ''))
         if not docname:
             return None
         else:
             title = '%s%s%s' % ((platform and '(%s) ' % platform),
                                 synopsis,
                                 (deprecated and ' (deprecated)' or ''))
             return make_refnode(builder, fromdocname, docname,
                                 'module-' + target, contnode, title)
     else:
         modname = node.get('tcpip:module')
         clsname = node.get('tcpip:class')
         searchorder = node.hasattr('refspecific') and 1 or 0
         matches = self.find_obj(env, modname, clsname, target,
                                 type, searchorder)
         if not matches:
             return None
         elif len(matches) > 1:
             env.warn(fromdocname,
                      'more than one target found for cross-reference '
                      '%r: %s' % (target,
                                  ', '.join(match[0] for match in matches)),
                      node.line)
         name, obj = matches[0]
         return make_refnode(builder, fromdocname, obj[0], name,
                             contnode, name)
Exemplo n.º 7
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        objects = self.data['objects']
        objtypes = self.objtypes_for_role(typ) or []

        for objtype in objtypes:
            for (typ, clspath) in objects:
                # Look up using the full classpath
                if (objtype, target) == (typ, clspath):
                    return make_refnode(
                        builder,
                        fromdocname,
                        objects[typ, clspath],
                        objtype + '-' + target,
                        contnode,
                        target + ' ' + objtype
                    )

                # Try looking it up by the class name--this lets people use
                # shorthand in their roles
                if '.' in clspath:
                    modname, clsname = split_clspath(clspath)
                    if (objtype, target) == (typ, clsname):
                        return make_refnode(
                            builder,
                            fromdocname,
                            objects[typ, clspath],
                            objtype + '-' + clspath,
                            contnode,
                            target + ' ' + objtype
                        )
Exemplo n.º 8
0
def envy_resolve(app, doctree, fromdocname):
    objects = app.env.domaindata['envy']['objects']

    # add uplink info
    for holder in doctree.traverse(uplink_placeholder):
        obj = objects[holder.name]
        links = []
        for sp, pos, name, variants in obj.uplinks:
            signode = addnodes.desc_signature('', '')
            signode['first'] = False
            signode += make_refnode(app.builder, fromdocname, sp.docname, sp.iname + '-' + sp.name, addnodes.desc_addname(sp.name, sp.name), sp.name)
            text = ' {}: {}'.format(pos, name)
            signode += addnodes.desc_name(text, text)
            if variants is not None:
                text = ' [{}]'.format(variants)
                signode += addnodes.desc_annotation(text, text)
            links.append(signode)
        holder.replace_self(links)

    # add subnode list
    for holder in doctree.traverse(sub_placeholder):
        obj = objects[holder.name]
        add_variant = False
        for pos, name, child, variants in obj.subs:
            if variants is not None:
                add_variant = True
        table = nodes.table()
        headers = [(1, 'Address'), (1, 'Name'), (10, 'Description')]
        if add_variant:
            headers.insert(1, (1, 'Variants'))
        tgroup = nodes.tgroup(cols=len(headers))
        table += tgroup
        for colwidth, header in headers:
            tgroup += nodes.colspec(colwidth=colwidth)
        thead = nodes.thead()
        tgroup += thead
        headrow = nodes.row()
        for colwidth, header in headers:
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += nodes.Text(header, header)
            headrow += entry
        thead += headrow
        tbody = nodes.tbody()
        tgroup += tbody
        for pos, name, child, variants in obj.subs:
            row = nodes.row()
            row += wrap_text_entry(pos)
            if add_variant:
                row += wrap_text_entry('all' if variants is None else variants)
            row += wrap_text_entry(name)
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += make_refnode(app.builder, fromdocname, child.docname, child.iname + '-' + child.name, nodes.Text(child.brief, child.brief), obj.brief)
            row += entry
            tbody += row
        holder.replace_self([table])
Exemplo n.º 9
0
Arquivo: std.py Projeto: qsnake/sphinx
 def resolve_xref(self, env, fromdocname, builder,
                  typ, target, node, contnode):
     if typ == 'ref':
         if node['refexplicit']:
             # reference to anonymous label; the reference uses
             # the supplied link caption
             docname, labelid = self.data['anonlabels'].get(target, ('',''))
             sectname = node.astext()
         else:
             # reference to named label; the final node will
             # contain the section name after the label
             docname, labelid, sectname = self.data['labels'].get(target,
                                                                  ('','',''))
         if not docname:
             return None
         newnode = nodes.reference('', '', internal=True)
         innernode = nodes.emphasis(sectname, sectname)
         if docname == fromdocname:
             newnode['refid'] = labelid
         else:
             # set more info in contnode; in case the
             # get_relative_uri call raises NoUri,
             # the builder will then have to resolve these
             contnode = addnodes.pending_xref('')
             contnode['refdocname'] = docname
             contnode['refsectname'] = sectname
             newnode['refuri'] = builder.get_relative_uri(
                 fromdocname, docname)
             if labelid:
                 newnode['refuri'] += '#' + labelid
         newnode.append(innernode)
         return newnode
     elif typ == 'keyword':
         # keywords are oddballs: they are referenced by named labels
         docname, labelid, _ = self.data['labels'].get(target, ('','',''))
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
     elif typ == 'option':
         progname = node['refprogram']
         docname, labelid = self.data['progoptions'].get((progname, target),
                                                         ('', ''))
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
     else:
         objtypes = self.objtypes_for_role(typ) or []
         for objtype in objtypes:
             if (objtype, target) in self.data['objects']:
                 docname, labelid = self.data['objects'][objtype, target]
                 break
         else:
             docname, labelid = '', ''
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
Exemplo n.º 10
0
 def resolve_xref(self, env, fromdocname, builder, type, target, node, contnode):
     if type == 'obj':
         obj = self.data['objects'].get(target)
         if obj is not None:
             return make_refnode(builder, fromdocname, obj.docname, obj.iname + '-' + obj.name, contnode, obj.brief)
     else:
         obj = self.data['genobjs'].get(target)
         if obj is not None:
             return make_refnode(builder, fromdocname, obj.docname, target, contnode, obj.brief)
Exemplo n.º 11
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        if typ == 'ref':
            nodeargs = self.data['refnodes'].get(target, None)
            if nodeargs is not None:
                todocname = nodeargs[0]
                targetid = nodeargs[1]
                return make_refnode(builder, fromdocname, todocname, targetid, contnode)

        if typ in ['lib', 'mod', 'class', 'var', 'const', 'func', 'gf', 'meth', 'macro', 'type']:
            # Target will have been transformed to the standard ID format:
            # no spaces and <> changed to []. Additionally, the node will have
            # dylan_curlibrary and dylan_curmodule set if possible. This is all
            # done by the role processing function and the DylanXRefRole class.
            colons = target.count(':')
            fulltarget = None

            if hasattr(node, "dylan_curlibrary"):
                library = node.dylan_curlibrary
            else:
                library = None

            if hasattr(node, "dylan_curmodule"):
                module = node.dylan_curmodule
            else:
                module = None

            # Use current library and module
            if colons == 2:
                fulltarget = target
            elif library is not None:
                library_id = name_to_id(library)
                if colons == 1:
                    fulltarget = "{0}:{1}".format(library_id, target)
                elif module is not None:
                    module_id = name_to_id(module)
                    if colons == 0:
                        fulltarget = "{0}:{1}:{2}".format(library_id, module_id, target)

            # Fetch link info based on current library and module and passed target
            nodeargs = self.data['objects'].get(fulltarget, None)

            # Can't find it that way; check the unique shortname list
            if nodeargs is None and colons == 0:
                targlist = self.data['fullids'].get(target, [])
                if len(targlist) == 1:
                    fulltarget = targlist[0]
                    nodeargs = self.data['objects'].get(fulltarget, None)

            # Found it; make a link.
            if nodeargs is not None:
                todocname = nodeargs[0]
                return make_refnode(builder, fromdocname, todocname, fulltarget, contnode)

        return None
Exemplo n.º 12
0
 def resolve_xref(self, env, fromdocname, builder, role, targetname, node, contnode):
     # ‘target’ is the name that was written in the document
     # ‘role’ is where this xref comes from; it's exactly one of our subdomains
     if role == 'index':
         index = CoqDomain.find_index_by_name(targetname)
         if index:
             return make_refnode(builder, fromdocname, "coq-" + index.name, '', contnode, index.localname)
     else:
         resolved = self.data['objects'][role].get(targetname)
         if resolved:
             (todocname, _, targetid) = resolved
             return make_refnode(builder, fromdocname, todocname, targetid, contnode, targetname)
Exemplo n.º 13
0
 def resolve_xref(self, env, fromdocname, builder,
                  typ, target, node, contnode):
     
     parent = node.get('idl:parent')
     if parent:
         ptarget = parent + '.' + target
     if parent and (ptarget in self.data['objects']):
         obj = self.data['objects'][ptarget]
         return make_refnode(builder, fromdocname, obj[0], ptarget,
                             contnode, ptarget)
     elif target in self.data['objects']:
         obj = self.data['objects'][target]
         return make_refnode(builder, fromdocname, obj[0], target,
                             contnode, target)
     return None
Exemplo n.º 14
0
 def resolve_xref(self, env, fromdocname, builder,
                  type, target, node, contnode):
     if target not in self.data['types']:
         return None
     todocname = self.data['types'][target]
     return make_refnode(
         builder, fromdocname, todocname, target, contnode, target)
Exemplo n.º 15
0
 def resolve_xref(self, env, fromdoc, builder, objtype, target, node,
                  content):
     if target not in self.data['objects']:
         return None
     docname, _ = self.data['objects'][target]
     return make_refnode(builder, fromdoc, docname,
                         'flyc:'+target, content, target)
Exemplo n.º 16
0
def missing_reference(app, env, node, contnode):
    target = node['reftarget']
    typ = node['reftype']
    fromdocname = node["refdoc"]
    if 'refdomain' in node and node['refdomain']:
        try:
            domain = env.domains[node['refdomain']]
        except KeyError:
            pass
    if node["reftarget"] in aliases and domain:
        node['reftarget'] = aliases[target]
        return domain.resolve_xref(env, fromdocname, app.builder,
                                   typ, aliases[target], node, contnode)
    if node["reftarget"].startswith("chapter") or node["reftarget"].startswith("appendix"):
        chap, appe, app_num = re.search("chapter (\d+)|appendix (\w+)\.?(\d+)?", node["reftarget"]).groups()
        if chap:
            chap_lookup = dict(enumerate(env.toctree_includes["index"]))
            file = chap_lookup[int(chap)]
        elif appe:
            app_lookup = {chr(i + ord("a")): j for i, j in enumerate(env.config["latex_appendices"])}
            file = app_lookup[appe]
        else:
            RuntimeError("Panic, regex failed!")
        if app_num is None:
            name = file.split("/")[-1].lower()
        else:
            app_num = int(app_num)
            name = env.tocs[file][0][1][app_num][0][0].astext().lower()
        subref = "".join((x if x.isalpha() else "-") for x in name).rstrip("-")
        ref = file + ":" + subref
        node['reftarget'] = subref
        node['refexplicit'] = True
        #print(subref, domain, fromdocname, typ)
        #print(domain.data['anonlabels'])
        return sphinxnodes.make_refnode(app.builder, fromdocname, file, subref, contnode)
Exemplo n.º 17
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        objectname = node.get('mongodb:object')
        searchorder = node.hasattr('refspecific') and 1 or 0
        name, obj = self.find_obj(env, objectname, target, typ, searchorder)

        if obj is None:
            name, obj = self.find_obj(env, 'iddup.' + name, target, typ, searchorder)
            if obj is None:
                # print names and info from the node object at this
                # point to report on links that fail to resolve
                return None

        if name.startswith('bin.'):
            name = name.split('.', 1)[1]
        elif name.startswith('dbcmd.'):
            name = name.split('.', 1)[1]
        elif name.startswith('iddup.'):
            name = name.split('.', 1)[1]
        elif name.startswith('op.'):
            name = name.split('.', 1)[1]
        elif name.startswith('prj.'):
            name = name.split('.', 1)[1]
        

        return make_refnode(builder, fromdocname, obj[0],
                            name.replace('$', '_S_'), contnode, name)
Exemplo n.º 18
0
    def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):
        if " " in target:
            matches = self.find_method(env, target.upper(), node)
        else:
            matches = self.find_obj(env, target.upper())

        if not matches:
            return None
        elif len(matches) > 1:
            env.warn_node(
                'more than one target found for cross-reference '
                '%r: %s' % (target, ', '.join(match[0] for match in matches)),
                node)
        # TODO (RS) this just chooses the first symbol, instead every
        # symbol should be presented.

        if " " in target:
            sexp = target.split(" ")
            generic = sexp[0].lower()
            specializer = " ".join(sexp[1:])
            name = generic
            filename = matches[0][0]  # the first filename
            link = "method" + ":" + generic + "(" + specializer + ")"
        else:
            name = matches[0][0]  # the symbol name
            filename = matches[0][1][0][0]  # the first filename
            type = matches[0][1][0][1]  # the first type
            link = type + ":" + name
        return make_refnode(builder, fromdocname, filename,
                            link, contnode, name)
Exemplo n.º 19
0
    def resolve_xref(self, env, fromdocname, builder, typ, target,
                     node, contnode):
        try:
            info = self.data[str(typ)][target]
        except KeyError:
            text = contnode.rawsource
            role = self.roles.get(typ)
            if role is None:
                return None

            if fromdocname not in _doctree_cache:
                _doctree_cache[fromdocname] = env.get_doctree(fromdocname)
            doctree = _doctree_cache[fromdocname]

            resnode = role.result_nodes(doctree, env, node, None)[0][0]
            if isinstance(resnode, addnodes.pending_xref):
                text = node[0][0]
                reporter = doctree.reporter
                reporter.warning('Cannot resolve reference to %r' % text,
                                 line=node.line)
                return None
            return resnode
        else:
            anchor = http_resource_anchor(typ, target)
            title = typ.upper() + ' ' + target
            return make_refnode(builder, fromdocname, info[0], anchor,
                                contnode, title)
Exemplo n.º 20
0
 def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
     objectname = node.get("mongodb:object")
     searchorder = node.hasattr("refspecific") and 1 or 0
     name, obj = self.find_obj(env, objectname, target, typ, searchorder)
     if not obj:
         return None
     return make_refnode(builder, fromdocname, obj[0], name.replace("$", "_S_"), contnode, name)
Exemplo n.º 21
0
 def _resolve_keyword_xref(self, env, fromdocname, builder, typ, target, node, contnode):
     # keywords are oddballs: they are referenced by named labels
     docname, labelid, _ = self.data['labels'].get(target, ('', '', ''))
     if not docname:
         return None
     return make_refnode(builder, fromdocname, docname,
                         labelid, contnode)
Exemplo n.º 22
0
 def resolve_xref(self, env, fromdocname, builder, type, target, node, contnode):
     if target[0] == '~':
         target = target[1:]
     doc, _ = self.data['objects'].get(target, (None, None))
     if doc:
         return make_refnode(builder, fromdocname, doc, target, contnode,
                             target)
Exemplo n.º 23
0
def resolve_required_by_xrefs(app, env, node, contnode):
    """Now that all recipes and packages have been parsed, we are called here
    for each ``pending_xref`` node that sphinx has not been able to resolve.

    We handle specifically the ``requiredby`` reftype created by the
    `RequiredByField` fieldtype allowed in ``conda:package::``
    directives, where we replace the ``pending_ref`` node with a bullet
    list of reference nodes pointing to the package pages that
    "depended" on the package.
    """
    if node['reftype'] == 'requiredby' and node['refdomain'] == 'conda':
        target = node['reftarget']
        docname = node['refdoc']
        backrefs = env.domains['conda'].data['backrefs'].get(target, set())
        listnode = nodes.bullet_list()
        for back_docname, back_target in backrefs:
            par = nodes.paragraph()
            name_node = addnodes.literal_strong(back_target, back_target,
                                      classes=['xref', 'backref'])
            refnode = make_refnode(app.builder, docname,
                                   back_docname, back_target, name_node)
            refnode.set_class('conda-package')
            par += refnode
            listnode += nodes.list_item('', par)
        return listnode
Exemplo n.º 24
0
 def resolve_xref(self, env, fromdocname, builder,
                  typ, target, node, contnode):
     if target not in self.data['objects']:
         return None
     obj = self.data['objects'][target]
     return make_refnode(builder, fromdocname, obj[0], target,
                         contnode, target)
Exemplo n.º 25
0
    def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):
        """
        Resolve the ``pending_xref`` *node* with the given *typ* and *target*.

        Returns a new reference node, to replace the xref node.

        If no resolution can be found, returns None.
        """
        match = self.find_xref(env, typ, target)
        if match:
            docname = match[0]
            sig = match[1]
            title = match[2]
            # Coerce contnode into the right nodetype
            nodetype = type(contnode)
            if issubclass(nodetype, literal):
                nodetype = self.directives[typ].nodetype
            # Override contnode with title, unless it has been manually
            # overridden in the text.
            if contnode.astext() == target:
                contnode = nodetype(title, title)
            else:
                child = contnode.children[0]
                contnode = nodetype(child, child)
            # Return the new reference node
            return make_refnode(builder, fromdocname, docname,
                                typ + '-' + target, contnode, sig)
Exemplo n.º 26
0
    def resolve_xref(self, env, fromdocname, builder,
                     type, target, node, contnode):

        modname = node.get('lua:module')
        clsname = node.get('lua:class')
        searchmode = node.hasattr('refspecific') and 1 or 0
        matches = self.find_obj(env, modname, clsname, target,
                                type, searchmode)

        if not matches:
            # If type is 'obj', we don't want to display any WARNING.
            # Otherwise, we have too many due to unknown type used
            # as parameter type in function description (number, string...).
            if type != "obj":
                env.warn_node(
                    'no target found for cross-reference '
                    '%r' % (target), node)
            return None
        elif len(matches) > 1:
            env.warn_node(
                'more than one target found for cross-reference '
                '%r: %s' % (target, ', '.join(match[0] for match in matches)),
                node)
        name, obj = matches[0]

        return make_refnode(builder, fromdocname, obj[0], obj[2],
                            contnode, name)
Exemplo n.º 27
0
 def _make_item_refnode(self, builder, fromdocname, name, contnode):
     """Make a reference node for a Qbs item."""
     docname, synopsis = self.data['items'][name]
     title = name
     if synopsis:
         title += ': ' + synopsis
     return make_refnode(builder, fromdocname, docname, name, contnode, title)
Exemplo n.º 28
0
 def _make_package_refnode(self, builder, fromdocname, name, contnode):
     """Make a reference node for a Qbs package."""
     docname, synopsis = self.data['packages'][name]
     title = name
     if synopsis:
         title += ': ' + synopsis
     return make_refnode(builder, fromdocname, docname, 'package-' + name, contnode, title)
Exemplo n.º 29
0
 def _make_sdk_refnode(self, builder, fromdocname, name, contnode):
     """Make a reference node for a Qbs SDK."""
     docname, synopsis = self.data['sdks'][name]
     title = name
     if synopsis:
         title += ': ' + synopsis
     return make_refnode(builder, fromdocname, docname, 'sdk-' + name, contnode, title)
Exemplo n.º 30
0
    def resolve_xref(self, env, fromdocname, builder, type, target, node, contnode):
        sdkname = node.get('qbs:sdk')
        pkgname = node.get('qbs:package')
        modname = node.get('qbs:module')
        itemname = node.get('qbs:item')
        searchmode = node.hasattr('refspecific')

        matches = self.find_objects(env, sdkname, modname, pkgname, itemname, target, type,
                                    searchmode)

        if not matches:
            return None
        elif len(matches) > 1:
            env.warn_node('more than one target found for cross-reference %r: %s' %
                          (target, ', '.join(match[0] for match in matches)), node)

        name, obj = matches[0]

        if obj[1] == 'sdk':
            return self._make_sdk_refnode(builder, fromdocname, name, contnode)
        elif obj[1] == 'package':
            return self._make_package_refnode(builder, fromdocname, name, contnode)
        elif obj[1] == 'module':
            return self._make_module_refnode(builder, fromdocname, name, contnode)
        elif obj[1] == 'item':
            return self._make_item_refnode(builder, fromdocname, name, contnode)
        else:
            return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
Exemplo n.º 31
0
 def _resolve_term_xref(self, env: "BuildEnvironment", fromdocname: str,
                        builder: "Builder", typ: str, target: str,
                        node: pending_xref, contnode: Element) -> Element:
     result = self._resolve_obj_xref(env, fromdocname, builder, typ,
                                     target, node, contnode)
     if result:
         return result
     else:
         for objtype, term in self.objects:
             if objtype == 'term' and term.lower() == target.lower():
                 docname, labelid = self.objects[objtype, term]
                 logger.warning(__('term %s not found in case sensitive match.'
                                   'made a reference to %s instead.'),
                                target, term, location=node, type='ref', subtype='term')
                 break
         else:
             docname, labelid = '', ''
         if not docname:
             return None
         return make_refnode(builder, fromdocname, docname,
                             labelid, contnode)
Exemplo n.º 32
0
    def _resolve_option_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
        progname = node.get('std:program')
        target = target.strip()
        docname, labelid = self.data['progoptions'].get((progname, target), ('', ''))
        if not docname:
            commands = []
            while ws_re.search(target):
                subcommand, target = ws_re.split(target, 1)
                commands.append(subcommand)
                progname = "-".join(commands)

                docname, labelid = self.data['progoptions'].get((progname, target),
                                                                ('', ''))
                if docname:
                    break
            else:
                return None

        return make_refnode(builder, fromdocname, docname,
                            labelid, contnode)
Exemplo n.º 33
0
    def _resolve_option_xref(self, env: "BuildEnvironment", fromdocname: str,
                             builder: "Builder", typ: str, target: str,
                             node: pending_xref, contnode: Element) -> Element:
        progname = node.get('std:program')
        target = target.strip()
        docname, labelid = self.progoptions.get((progname, target), ('', ''))
        if not docname:
            commands = []
            while ws_re.search(target):
                subcommand, target = ws_re.split(target, 1)
                commands.append(subcommand)
                progname = "-".join(commands)

                docname, labelid = self.progoptions.get((progname, target),
                                                        ('', ''))
                if docname:
                    break
            else:
                return None

        return make_refnode(builder, fromdocname, docname, labelid, contnode)
Exemplo n.º 34
0
 def resolve_xref(
     self,
     env,
     fromdocname,
     builder,
     typ,
     target,
     node,
     contnode,
 ):
     """Resolve cross-references"""
     if typ == 'option':
         return sphinx_nodes.make_refnode(
             builder,
             fromdocname,
             env.domaindata['nova']['extra_specs'][target],
             target,
             contnode,
             target,
         )
     return None
Exemplo n.º 35
0
 def resolve_any_xref(self, env, fromdocname, builder, target, node,
                      contnode):
     results = []
     ltarget = target.lower()  # :ref: lowercases its target automatically
     for role in ('ref', 'option'):  # do not try "keyword"
         res = self.resolve_xref(env, fromdocname, builder, role,
                                 ltarget if role == 'ref' else target, node,
                                 contnode)
         if res:
             results.append(('std:' + role, res))
     # all others
     for objtype in self.object_types:
         key = (objtype, target)
         if objtype == 'term':
             key = (objtype, ltarget)
         if key in self.data['objects']:
             docname, labelid = self.data['objects'][key]
             results.append(('std:' + self.role_for_objtype(objtype),
                             make_refnode(builder, fromdocname, docname,
                                          labelid, contnode)))
     return results
Exemplo n.º 36
0
    def resolve_xref(self, env, fromdocname, builder,
                     typ, target, node, contnode):
        targets = get_targets(target, node)

        objects = self.data['objects']
        roletypes = self.objtypes_for_role(typ)

        types = ('type', 'enum', 'method') if typ is None else roletypes

        for t in targets:
            for objtyp in types:
                key = (objtyp, t)
                if key in objects:
                    obj = objects[key]
                    if typ is not None: 
                        role = self.role_for_objtype(objtyp)
                        node['reftype'] = role
                    return make_refnode(builder, fromdocname, obj[0],
                                        '{}-{}'.format(objtyp, t), contnode,
                                        '{} {}'.format(obj[1], t))
        return None
Exemplo n.º 37
0
    def resolve_xref(
        self,
        env: BuildEnvironment,
        fromdocname: str,
        builder: Builder,
        typ: str,
        target: str,
        node: pending_xref,
        contnode: nodes.Element,
    ) -> Optional[nodes.Element]:
        match = [(docname, anchor)
                 for name, _, _, docname, anchor, _ in self.get_objects()
                 if name == target]

        if match:
            todocname, anchor = match[0]

            return make_refnode(builder, fromdocname, todocname, anchor,
                                contnode, anchor)
        else:
            return None
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        """
        Generate a cross-reference node.

        :param str fromdocname: document name that contains the reference
        :param sphinx.builders.Builder builder: active builder
        :param str typ: identifies the type of cross reference
        :param str target: cross-reference target.  In the case of a
            property, this will be the property type.
        :param docutils.nodes.Element node: unresolved cross-reference
            node.  If this has a ``json:name`` attribute then it was
            processed by :class:`JSONXRef`
        :param docutils.nodes.Element contnode: content node.  This is
            what the new reference node should wrap
        :return: a cross-reference node or :data:`None`
        :rtype: docutils.nodes.reference|NoneType

        This method is also used to make property types ``clickable``.
        In this case the `typ` will be ``jsonprop`` and `target` will
        be the property type.  :data:`.REF_TYPES` is consulted to
        generate an appropriate link and tool tip -- for example, if
        the type is ``uri``, then a link to the RFC is generated.

        """
        if node.get('json:name'):
            objdef = self.get_object(node['json:name'])
            if objdef:
                return node_utils.make_refnode(builder, fromdocname,
                                               objdef.docname, objdef.key,
                                               contnode)

        if typ in self.REF_TYPES:
            try:
                ref = nodes.reference(internal=False)
                ref['refuri'], ref['reftitle'] = self.REF_TYPES[target]
                ref.append(contnode)
                return ref
            except KeyError:
                pass
Exemplo n.º 39
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        objectname = node.get('mongodb:object')
        searchorder = node.hasattr('refspecific') and 1 or 0

        name, obj = self.find_obj(env, objectname, target, typ, searchorder)

        if obj is not None:
            if fromdocname == obj[0]:
                return None

        if obj is None:
            name, obj = self.find_obj(env, 'iddup.' + name, target, typ, searchorder)

            if obj is None:
                # print names and info from the node object at this
                # point to report on links that fail to resolve
                return None

        name = name.replace('$', '_S_').replace(' ', '-')

        return make_refnode(builder, fromdocname, obj[0], name, contnode, target)
Exemplo n.º 40
0
    def _resolve_citation_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        # type: (BuildEnvironment, str, Builder, str, str, addnodes.pending_xref, nodes.Element) -> nodes.Element  # NOQA
        warnings.warn('StandardDomain._resolve_citation_xref() is deprecated.',
                      RemovedInSphinx30Warning)
        docname, labelid, lineno = self.data['citations'].get(target, ('', '', 0))
        if not docname:
            if 'ids' in node:
                # remove ids attribute that annotated at
                # transforms.CitationReference.apply.
                del node['ids'][:]
            return None

        try:
            return make_refnode(builder, fromdocname, docname,
                                labelid, contnode)
        except NoUri:
            # remove the ids we added in the CitationReferences
            # transform since they can't be transfered to
            # the contnode (if it's a Text node)
            if not isinstance(contnode, nodes.Element):
                del node['ids'][:]
            raise
Exemplo n.º 41
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
        """Resolve the pending_xref *node* with the given *typ* and *target*.

        This method should return a new node, to replace the xref node,
        containing the *contnode* which is the markup content of the
        cross-reference.

        If no resolution can be found, None can be returned; the xref node will
        then given to the :event:`missing-reference` event, and if that yields no
        resolution, replaced by *contnode*.

        The method can also raise :exc:`sphinx.environment.NoUri` to suppress
        the :event:`missing-reference` event being emitted.
        """
        for fullname, (docname, objtype) in self.data['objects'].items():
            if fullname.name == target:
                return make_refnode(builder, fromdocname, docname,
                                    fullname2id(fullname), contnode,
                                    fullname.name)
        return None
Exemplo n.º 42
0
    def resolve_xref(self, env, fromdocname, builder,
                     type, target, node, contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
        modname = node.get('py:module')
        clsname = node.get('py:class')
        searchmode = node.hasattr('refspecific') and 1 or 0
        matches = self.find_obj(env, modname, clsname, target,
                                type, searchmode)
        if not matches:
            return None
        elif len(matches) > 1:
            logger.warning(__('more than one target found for cross-reference %r: %s'),
                           target, ', '.join(match[0] for match in matches),
                           type='ref', subtype='python', location=node)
        name, obj = matches[0]

        if obj[1] == 'module':
            return self._make_module_refnode(builder, fromdocname, name,
                                             contnode)
        else:
            return make_refnode(builder, fromdocname, obj[0], name,
                                contnode, name)
Exemplo n.º 43
0
    def resolve_xref(self, env, fromdocname, builder,
                     type, target, node, contnode):
        modname = node.get('py:module')
        clsname = node.get('py:class')
        searchmode = node.hasattr('refspecific') and 1 or 0
        matches = self.find_obj(env, modname, clsname, target,
                                type, searchmode)
        if not matches:
            return None
        elif len(matches) > 1:
            env.warn_node(
                'more than one target found for cross-reference '
                '%r: %s' % (target, ', '.join(match[0] for match in matches)),
                node)
        name, obj = matches[0]

        if obj[1] == 'module':
            return self._make_module_refnode(builder, fromdocname, name,
                                             contnode)
        else:
            return make_refnode(builder, fromdocname, obj[0], name,
                                contnode, name)
Exemplo n.º 44
0
    def resolve_any_xref(self, env, fromdocname, builder, target, node,
                         contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, nodes.Node, nodes.Node) -> List[Tuple[unicode, nodes.Node]]  # NOQA
        """Resolve the pending_xref *node* with the given *target*."""
        results = []
        for objtyp in self.object_types:
            try:
                todocname, targetid = self.data[objtyp][target]
            except KeyError:
                pass
            else:
                results.append(('{}:{}'.format(self.name,
                                               self.role_for_objtype(objtyp)),
                                nodeutils.make_refnode(
                                    builder,
                                    fromdocname,
                                    todocname,
                                    targetid,
                                    contnode,
                                )))

        return results
Exemplo n.º 45
0
def construct_headline(need_data, app):
    """
    Constructs the node-structure for the headline/title container
    :param need_data: need_info container
    :return: node
    """
    # need title calculation
    title_type = '{}: '.format(need_data["type_name"])
    title_headline = need_data["title"]
    title_id = "{}".format(need_data["id"])
    title_spacer = " "

    # need title
    node_type = nodes.inline(title_type, title_type, classes=["needstype"])
    node_title = nodes.inline(title_headline,
                              title_headline,
                              classes=["needstitle"])

    nodes_id = nodes.inline(classes=["needsid"])

    nodes_id_text = nodes.Text(title_id, title_id)
    id_ref = make_refnode(app.builder,
                          fromdocname=need_data['docname'],
                          todocname=need_data['docname'],
                          targetid=need_data['id'],
                          child=nodes_id_text.deepcopy(),
                          title=title_id)
    nodes_id += id_ref

    node_spacer = nodes.inline(title_spacer,
                               title_spacer,
                               classes=["needsspacer"])

    headline_line = nodes.line(classes=["headline"])
    headline_line.append(nodes_id)
    headline_line.append(node_spacer)
    headline_line.append(node_title)

    return headline_line
Exemplo n.º 46
0
    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                     contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
        """
        Resolve the pending_xref *node* with the given *typ* and *target*.

        :param typ: == roles key
        :param target: == target text e.g. ``GET /path``
        """
        for objtyp in self.objtypes_for_role(typ):
            try:
                todocname, targetid = self.data[objtyp][target]
            except KeyError:
                pass
            else:
                return nodeutils.make_refnode(
                    builder,
                    fromdocname,
                    todocname,
                    targetid,
                    contnode,
                )
Exemplo n.º 47
0
    def _resolve_citation_xref(self, env, fromdocname, builder, typ, target, node, contnode):
        # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
        from sphinx.environment import NoUri

        docname, labelid, lineno = self.data['citations'].get(target, ('', '', 0))
        if not docname:
            if 'ids' in node:
                # remove ids attribute that annotated at
                # transforms.CitationReference.apply.
                del node['ids'][:]
            return None

        try:
            return make_refnode(builder, fromdocname, docname,
                                labelid, contnode)
        except NoUri:
            # remove the ids we added in the CitationReferences
            # transform since they can't be transfered to
            # the contnode (if it's a Text node)
            if not isinstance(contnode, nodes.Element):
                del node['ids'][:]
            raise
Exemplo n.º 48
0
 def resolve_any_xref(self, env: "BuildEnvironment", fromdocname: str,
                      builder: "Builder", target: str, node: pending_xref,
                      contnode: Element) -> List[Tuple[str, Element]]:
     results = []  # type: List[Tuple[str, Element]]
     ltarget = target.lower()  # :ref: lowercases its target automatically
     for role in ('ref', 'option'):  # do not try "keyword"
         res = self.resolve_xref(env, fromdocname, builder, role,
                                 ltarget if role == 'ref' else target, node,
                                 contnode)
         if res:
             results.append(('std:' + role, res))
     # all others
     for objtype in self.object_types:
         key = (objtype, target)
         if objtype == 'term':
             key = (objtype, ltarget)
         if key in self.objects:
             docname, labelid = self.objects[key]
             results.append(('std:' + self.role_for_objtype(objtype),
                             make_refnode(builder, fromdocname, docname,
                                          labelid, contnode)))
     return results
Exemplo n.º 49
0
 def resolve_xref(self, env, fromdoc, builder, objtype, target, node,
                  content):
     scopes = self.data['symbols'][target]
     if objtype == 'symbol' and len(scopes) > 1:
         # The generic symbol reference is ambiguous, because the symbol has
         # multiple scopes attached
         scope = next(
             ifilter(lambda s: s in scopes,
                     ['function', 'variable', 'face', 'struct']), None)
         if not scope:
             # If we have an unknown scope
             raise ValueError('Unknown scopes: {0!r}'.format(scopes))
         message = 'Ambiguous reference to {0}, in scopes {1}, using {2}'.format(
             target, ', '.join(scopes), scope)
         env.warn(fromdoc, message, getattr(node, 'line'))
     else:
         scope = self.object_types[objtype].attrs['scope']
     if scope not in scopes:
         return None
     docname, _ = scopes[scope]
     return make_refnode(builder, fromdoc, docname,
                         make_target(scope, target), content, target)
Exemplo n.º 50
0
    def resolve_xref(
            self, env, fromdocname, builder, typ, target, node, contnode):
        if '#' in target:
            todocname, targetid = target.split('#')
        else:
            todocname = target
            targetid = ''

        if todocname not in self.mapping['code2docs']:
            # Could be a link to a repository's code tree directory/file
            todocname = '{}{}{}'.format(self.github_repo_url, self.github_repo_branch, todocname)

            newnode = nodes.reference('', '', internal=True, refuri=todocname)
            newnode.append(contnode[0])
        else:
            # Removing filename extension (e.g. contributing.md -> contributing)
            todocname, _ = os.path.splitext(self.mapping['code2docs'][todocname])

            newnode = make_refnode(
                builder, fromdocname, todocname, targetid, contnode[0])

        return newnode
Exemplo n.º 51
0
def _make_viewcode_node(
		title: str,
		pagename: str,
		env: BuildEnvironment,
		) -> nodes.Node:
	"""
	Construct a node for the :mod:`sphinx.ext.viewcode` link.

	Handles Sphinx 3.5+ compatibility.
	"""

	if _sphinx_version < (3, 5, 0):
		return addnodes.pending_xref(
				title,
				nodes.inline(title, title),
				reftype="viewcode",
				refdomain="std",
				refexplicit=False,
				reftarget=pagename,
				refid=title,
				refdoc=env.docname,
				)
	else:
		# 3rd party
		from sphinx.util.nodes import make_refnode

		assert env.app.builder is not None

		try:
			return make_refnode(
					env.app.builder,
					fromdocname=env.docname,
					todocname=pagename,
					targetid=title,
					child=nodes.inline(title, title),
					)
		except NoUri:
			return nodes.inline(title, title)
Exemplo n.º 52
0
    def resolve_xref(self, env: BuildEnvironment, fromdocname: str,
                     builder, role, target, node, contnode):
        """Resolve the ``pending_xref`` **node** with the given **role** and **target**."""
        for objtype in self.objtypes_for_role(role) or []:
            if (objtype, target) in self.data['objects']:
                node = make_refnode(
                    builder, fromdocname,
                    self.data['objects'][objtype, target][0],
                    self.data['objects'][objtype, target][1],
                    contnode, target + ' ' + objtype)
                node.set_class('conda-package')
                return node

            if objtype == "package":
                for channel, urlformat in env.app.config.bioconda_other_channels.items():
                    if RepoData().get_package_data(channels=channel, name=target):
                        uri = urlformat.format(target)
                        node = nodes.reference('', '', internal=False,
                                               refuri=uri, classes=[channel])
                        node += contnode
                        return node

        return None  # triggers missing-reference
Exemplo n.º 53
0
 def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                  contnode):
     try:
         info = self.data[str(typ)][target]
     except KeyError:
         text = contnode.rawsource
         role = self.roles.get(typ)
         if role is None:
             return nodes.emphasis(text, text)
         resnode = role.result_nodes(env.get_doctree(fromdocname), env,
                                     node, None)[0][0]
         if isinstance(resnode, addnodes.pending_xref):
             text = node[0][0]
             reporter = env.get_doctree(fromdocname).reporter
             reporter.error('Cannot resolve reference to %r' % text,
                            line=node.line)
             return nodes.problematic(text, text)
         return resnode
     else:
         anchor = http_resource_anchor(typ, target)
         title = typ.upper() + ' ' + target
         return make_refnode(builder, fromdocname, info[0], anchor,
                             contnode, title)
Exemplo n.º 54
0
def missing_reference(app, env, node, contnode):
    reftarget = ''
    refdoc = ''
    reftype = ''
    module = ''
    if 'refdomain' in node.attributes and node.attributes['refdomain'] == 'py':
        reftarget = node['reftarget']
        reftype = node['reftype']
        if 'refdoc' in node:
            refdoc = node['refdoc']
        if 'py:module' in node:
            module = node['py:module']

        #Refactor reftarget to fullname if it is a short name
        if reftype in [CLASS, REFFUNCTION, REFMETHOD
                       ] and module and '.' not in reftarget:
            if reftype in [CLASS, REFFUNCTION]:
                fields = (module, reftarget)
            else:
                fields = (module, node['py:class'], reftarget)
            reftarget = '.'.join(fields)

        return make_refnode(app.builder, refdoc, reftarget, '', contnode)
Exemplo n.º 55
0
    def resolve_xref(self, _, fromdocname, builder, typ, target, node,
                     contnode):
        targets = [target]
        if node['csharp:parent'] is not None:
            parts = node['csharp:parent'].split('.')
            while parts:
                targets.append('.'.join(parts) + '.' + target)
                parts = parts[:-1]

        objects = self.data['objects']
        objtypes = self.objtypes_for_role(typ)
        for tgt in targets:
            for objtype in objtypes:
                if (objtype, tgt) in objects:
                    return make_refnode(builder, fromdocname, objects[objtype,
                                                                      tgt],
                                        objtype + '-' + tgt, contnode,
                                        tgt + ' ' + objtype)

        for tgt in targets:
            ref = get_msdn_ref(tgt)
            if ref is not None:
                return ref
Exemplo n.º 56
0
 def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                  contnode):
     prefix = {
         'svc': 'od-service',
         'feed': 'od-feed',
         'type': 'od-type',
         'prop': 'od-prop',
     }.get(typ, None)
     if not prefix:
         return None
     qtarget = "%s.%s" % (prefix, target)
     objects = self.data['objects']
     obj = objects.get(qtarget, None)
     # TODO: add some context from the environment to support links
     # that happen within a service or type definition
     if obj is None:
         obj = objects.get(qtarget.lower(), None)
     if obj is not None:
         return make_refnode(builder, fromdocname, obj.docname,
                             obj.get_target_id(), contnode, obj.title)
     else:
         print qtarget
         return None
Exemplo n.º 57
0
    def meta_id(self):
        """
        Returns the current need id as clickable and linked reference.

        Usage::

            <<meta_id()>>

        :return: docutils node
        """
        from sphinx.util.nodes import make_refnode
        id_container = nodes.inline(classes=["needs-id"])

        nodes_id_text = nodes.Text(self.need['id'], self.need['id'])
        id_ref = make_refnode(
            self.app.builder,
            # fromdocname=self.need['docname'],
            fromdocname=self.fromdocname,
            todocname=self.need['docname'],
            targetid=self.need['id'],
            child=nodes_id_text.deepcopy(),
            title=self.need['id'])
        id_container += id_ref
        return id_container
Exemplo n.º 58
0
 def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                  contnode):
     prefix = {
         'db': 'qm-db',
         'table': 'qm-table',
         'field': 'qm-field',
         'meth': 'qm-meth',
         'xfield': 'qm-xfield',
         'xtype': 'qm-xtype',
     }.get(typ, None)
     if not prefix:
         return None
     objects = self.env.domaindata['qm']['objects']
     qtarget = "%s.%s" % (prefix, target)
     target_obj = objects.get(qtarget, None)
     if target_obj is None:
         qtarget = "%s.%s" % (prefix, target.lower())
     target_obj = objects.get(qtarget, None)
     if target_obj is not None:
         return make_refnode(builder, fromdocname, target_obj.docname,
                             qtarget, contnode, target_obj.title)
     else:
         print qtarget
         return None
Exemplo n.º 59
0
 def resolve_xref(self, env, fromdocname, builder, typ, target, node,
                  contnode):
     # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node  # NOQA
     assert typ == 'eq'
     docname, number = self.data['objects'].get(target, (None, None))
     if docname:
         if builder.name == 'latex':
             newnode = eqref('', **node.attributes)
             newnode['docname'] = docname
             newnode['target'] = target
             return newnode
         else:
             try:
                 eqref_format = env.config.math_eqref_format or "({number})"
                 title = nodes.Text(eqref_format.format(number=number))
             except KeyError as exc:
                 logger.warning('Invalid math_eqref_format: %r',
                                exc,
                                location=node)
                 title = nodes.Text("(%d)" % number)
             return make_refnode(builder, fromdocname, docname,
                                 "equation-" + target, title)
     else:
         return None
    def resolve_any_xref(self, env, fromdocname, builder, target,
                         node, contnode):
        """Similar to :py:meth:`ChapelDomain.resolve_xref`, but applies to *any* or
        similar role where type is not known. This returns a list of tuples
        with ("domain:role", newnode).
        """
        modname = node.get('chpl:module')
        clsname = node.get('chpl:class')
        results = []

        # Always search in "refspecific" mode with the :any: role.
        matches = self.find_obj(env, modname, clsname, target, None, 1)
        for name, obj in matches:
            if obj[1] == 'module':
                results.append(('chpl:mod',
                                self._make_module_refnode(builder, fromdocname,
                                                          name, contnode)))
            else:
                results.append(
                    ('chpl:' + self.role_for_objtype(obj[1]),
                     make_refnode(builder, fromdocname, obj[0], name,
                                  contnode, name)))

        return results