Ejemplo n.º 1
0
    def make_nodes(self, contents_node):
        functor_parameters = desc_content()
        contents = desc_content()
        for node in contents_node.children:
            contents += node

        yield desc_signature(*self.make_signature_nodes())
        yield contents
        footer = self.get_footer()
        if footer is not None:
            yield desc_signature(desc_annotation(footer))
Ejemplo n.º 2
0
Archivo: nscp.py Proyecto: r1se/nscp
	def handle_signature(self, sig, signode):
		#synopsis = unicodedata.normalize('NFD', self.options.get('synopsis'))
		synopsis = self.options.get('synopsis')
		module = self.env.temp_data.get('nscp:module')
		fullname = 'TODO'
		if self.objtype == 'query':
			fullname = '%s.%s'%(module, sig)
			signode['fullname'] = fullname
			signode += addnodes.desc_addname(module, module)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_content('')
			signode += addnodes.compact_paragraph(synopsis, synopsis)
		elif self.objtype == 'option':
			command = self.env.temp_data.get('nscp:command')
			fullname = '%s.%s:%s'%(module, command, sig)
			signode['fullname'] = fullname
			ann = ' (%s, %s)'%(module, command)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		elif self.objtype == 'confpath':
			fullname = '%s:%s'%(module, sig)
			signode['fullname'] = fullname
			ann = ' (%s)'%(module)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		elif self.objtype == 'confkey':
			confpath = self.env.temp_data.get('nscp:confpath', '')
			fullname = '%s:%s:%s'%(module, confpath, sig)
			signode['fullname'] = fullname
			ann = ' (%s, %s)'%(module, confpath)
			signode += addnodes.desc_name(sig, sig)
			signode += addnodes.desc_annotation(ann, ann)
		#print 'handle_signature(%s, %s) => %s'%(sig, signode, fullname)
		return fullname, sig
Ejemplo n.º 3
0
def getChildren(Parent, prefix):
  Children = []

  for name, Child in Parent.Members.iteritems():
    if Child.Config.get('alias') == name: # don't process aliases
      continue

    id = '%s.%s' % (prefix, name)

    if hasattr(Child, 'Members'):
      Children += desc_content(prefix, *getGroupTree(Child, id))

    else:
      Children += desc_content(prefix, *getTaskTree(Child, id))

  return Children
Ejemplo n.º 4
0
    def run(self):
        # type: () -> List[nodes.Node]
        """
        """
        self.env = self.state.document.settings.env  # type: BuildEnvironment

        node = addnodes.desc()
        node.document = self.state.document
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype

        targetid = self.compute_target_id()
        caption = self.arguments[0]
        signode = addnodes.desc_signature(targetid, '')
        signode['names'].append(caption)
        signode['ids'].append(targetid)
        signode['first'] = 1
        targetnode = nodes.target('', '', ids=[targetid], names=[caption])
        signode += targetnode 
        signode += addnodes.desc_name(caption, caption)
        node.append(signode)        
        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.add_label(targetid, caption)
        if not 'setting_group' in self.env.temp_data:
            self.env.temp_data['setting_group'] = []
        self.env.temp_data['setting_group'].append(targetid)
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.env.temp_data['setting_group'].pop()
        return [node]        
Ejemplo n.º 5
0
    def render(self):

        title = self.title()
        rettype, name, arglist, const, signature = self.directive.parse_title(
            title)
        target = self.directive.create_target(name)

        # add a signature node
        signode = addnodes.desc_signature(signature, '')
        signode['first'] = False

        signode += addnodes.desc_type('', '')

        self.directive.add_return_type(signode[-1], rettype)
        name = self.directive.add_sig_name(signode, name)
        self.directive.set_name(name)
        self.directive.add_sig_args(signode, arglist, const)

        self.directive.before_content()
        description_nodes = self.description()
        content_node = addnodes.desc_content('')
        content_node += description_nodes
        self.directive.after_content()

        target.extend(signode)
        term = self.node_factory.term("", "", ids=[name], *target)
        entry = self.node_factory.definition_list_item("", term, content_node)

        return [entry]
Ejemplo n.º 6
0
    def render(self):
        title = self.title()
        rettype, name, arglist, const, signature = self.directive.parse_title(title)
        fullname = self.directive.get_full_name(name)

        if self.data_object.kind == "function":
            # set True that this might be a structure method
            self.directive.sphinx_directive.typemethod_set = True
        
        target = self.directive.create_target(fullname)

        if self.data_object.kind == "function":
            self.directive.sphinx_directive.typemethod_set = False
      
        # add a signature node 
        signode = addnodes.desc_signature(signature, '')
        signode['first'] = False

        signode += addnodes.desc_type('', '')
        
        self.directive.add_return_type(signode[-1] , rettype)
        name = self.directive.add_sig_name(signode, name)
        self.directive.add_sig_args(signode, arglist, const)

        description_nodes = self.description()
        content_node = addnodes.desc_content('')
        content_node += description_nodes
        

        target.extend(signode)
        term = self.node_factory.term("","", ids=[name], *target )
        entry = self.node_factory.definition_list_item("",term, content_node)

        return [entry]
Ejemplo n.º 7
0
    def handle_object_decl(self, decl, node, signode, annotations):
        # type: (lal.ObjectTypeDecl, N.desc, N.desc_signature) -> None
        node['objtype'] = node['desctype'] = 'object'
        name = decl.p_defining_name.text

        if decl.f_default_expr and annotations.get('document-value', True):
            # If there is a default expression to describe, do it as an
            # additional description. The title will only contain the name up
            # to the type expression.
            default_expr = decl.f_default_expr.text
            content = N.desc_content()
            node.append(content)
            content += nodes.Text('Value: ')
            content += N.desc_annotation(default_expr, default_expr)

            last_token = decl.f_type_expr.token_end

        elif decl.f_renaming_clause:
            # If there is a renaming clause, just put everything until the
            # renaming clause in the title.
            last_token = decl.f_renaming_clause.token_end

        else:
            # By default, go until the type expression
            last_token = decl.f_type_expr.token_end

        descr = lal.Token.text_range(decl.p_defining_name.token_end.next,
                                     last_token)

        signode += N.desc_name(name, name)
        signode += N.desc_annotation(descr, descr)
Ejemplo n.º 8
0
    def handle_signature(self, sig: str, signode: desc_signature) -> str:
        params = addnodes.desc_parameterlist()
        returns = addnodes.desc_parameterlist()

        contentnode = addnodes.desc_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        for child in contentnode:
            if isinstance(child, nodes.field_list):
                for field in child:
                    ty, sg, name = field[0].astext().split(None, 2)
                    param = addnodes.desc_parameter()
                    param += addnodes.desc_sig_keyword_type(sg, sg)
                    param += addnodes.desc_sig_space()
                    param += addnodes.desc_sig_name(name, name)
                    if ty == "arg":
                        params += param
                    elif ty == "ret":
                        returns += param

        anno = "signal " if self.signal else "method "
        signode += addnodes.desc_annotation(anno, anno)
        signode += addnodes.desc_name(sig, sig)
        signode += params
        if not self.signal and "noreply" not in self.options:
            ret = addnodes.desc_returns()
            ret += returns
            signode += ret

        return sig
Ejemplo n.º 9
0
def declarations_to_block(
    declarations: Iterable[summary.DeclarationSummary],
    *,
    env: Optional[sphinx.environment.BuildEnvironment] = None,
) -> Generator[addnodes.desc, None, None]:
    # These nodes translate into the following in html:
    # desc -> dl
    # desc_signature -> dt
    # desc_content -> dd
    # So:
    #  desc
    #  -> desc_signature
    #      -> desc_sig_name, desc_sig_punctuation, etc.
    #  -> desc_content
    #      -> paragraph, etc.
    for decl in declarations:
        desc = addnodes.desc(classes=["declaration"])
        signode = addnodes.desc_signature()
        signode += declaration_to_signature(signode, decl, env=env)

        decl_info = addnodes.desc_content()
        decl_info += declaration_to_content(decl)

        desc += signode
        desc += decl_info

        yield desc
Ejemplo n.º 10
0
def getChildren(Parent, prefix):
  Children = []

  for name, Child in Parent.Members.iteritems():
    if Child.Config.get('alias') == name: # don't process aliases
      continue

    id = '%s.%s' % (prefix, name)

    if hasattr(Child, 'Members'):
      Children += desc_content(prefix, *getGroupTree(Child, id))

    else:
      Children += desc_content(prefix, *getTaskTree(Child, id))

  return Children
Ejemplo n.º 11
0
    def render(self):

        title = self.title()
        rettype, name, arglist, const, signature = self.directive.parse_title(title)
        target = self.directive.create_target(name)

        # add a signature node 
        signode = addnodes.desc_signature(signature, '')
        signode['first'] = False

        signode += addnodes.desc_type('', '')
        
        self.directive.add_return_type(signode[-1] , rettype)
        name = self.directive.add_sig_name(signode, name)
        self.directive.set_name(name)
        self.directive.add_sig_args(signode, arglist, const)


        self.directive.before_content()
        description_nodes = self.description()
        content_node = addnodes.desc_content('')
        content_node += description_nodes
        self.directive.after_content()

        target.extend(signode)
        term = self.node_factory.term("","", ids=[name], *target )
        entry = self.node_factory.definition_list_item("",term, content_node)

        
        return [entry]
Ejemplo n.º 12
0
    def make_content(self, all_members):
        doc = self.item
        content = addnodes.desc_content()

        if doc.exports or doc.dependencies:
            with addto(content, nodes.field_list()) as fields:
                if doc.exports:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name('Exports', 'Exports')
                        with addto(field, nodes.field_body()) as body:
                            ref = doc['exports'] # warning: not the same as doc.exports
                            label = ref or '<anonymous>'
                            link = addnodes.pending_xref(
                                ref, nodes.paragraph(ref, label),
                                refdomain='js',
                                reftype='any',
                                reftarget=ref,
                            )
                            link['js:module'] = doc.name
                            body += link

                if doc.dependencies:
                    with addto(fields, nodes.field()) as field:
                        self.make_dependencies(field, doc)

        if doc.doc:
            # FIXME: source offset
            self.directive.state.nested_parse(to_list(doc.doc, source=doc['sourcefile']), 0, content)

        self.directive.state.nested_parse(self.directive.content, 0, content)

        content += self.document_properties(all_members)

        return content
Ejemplo n.º 13
0
    def run(self):
        def _get_iter_source(src, varname):
            # 1. identifies target iterable by variable name, (cannot be spaced)
            # 2. determines iter source code start & end by tracking brackets
            # 3. returns source code between found start & end
            start = end = None
            open_brackets = closed_brackets = 0
            for i, line in enumerate(src):
                if line.startswith(varname):
                    if start is None:
                        start = i
                if start is not None:
                    open_brackets += sum(line.count(b) for b in "([{")
                    closed_brackets += sum(line.count(b) for b in ")]}")

                if open_brackets > 0 and (open_brackets - closed_brackets
                                          == 0):
                    end = i + 1
                    break
            return '\n'.join(src[start:end])

        module_path, member_name = self.arguments[0].rsplit('.', 1)
        src = getsource(import_module(module_path)).split('\n')
        code = _get_iter_source(src, member_name)

        literal = nodes.literal_block(code, code)
        literal['language'] = 'python'

        return [
            addnodes.desc_name(text=member_name),
            addnodes.desc_content('', literal)
        ]
Ejemplo n.º 14
0
    def run(self):
        """Same as :meth:`sphinx.directives.ObjectDescription`
        but using :class:`FortranDocFieldTransformer`"""
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        if not hasattr(self, 'env'):
            self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if not isinstance(name[0], six.string_types):
                name = (str(name), name[1])
            if not noindex and name not in self.names:
                # only add target and index entry if this is the first
                # description of the object with this name in this desc block
                self.names.append(name)
                self.add_target_and_index(name, sig, signode)

        modname = signode.get('module')
        typename = signode.get('type')
        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        FortranDocFieldTransformer(
            self,
            modname=modname,
            typename=typename).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]
Ejemplo n.º 15
0
 def run(self):
     result = super(ELSExp, self).run()
     if "nodoc" not in self.options:
         package = self.env.temp_data.get('el:package')
         node = addnodes.desc_content()
         string = DATA_DOC_STRINGS.get(package, {}) \
                                  .get(self.names[0][1], "")
         lines = string2lines(string)
         if lines and lines[-1].startswith('(fn '):
             lines = lines[:-1]
         self.state.nested_parse(StringList(lines), 0, node)
         if (result[1][1].children and
             isinstance(result[1][1][0], nodes.field_list)):
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.append(cresult[0])
             target.extend(node)
             target.extend(cresult[1:])
         else:
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.extend(node)
             target.extend(cresult)
     return result
Ejemplo n.º 16
0
    def make_content(self, all_members):
        doc = self.item
        content = addnodes.desc_content()

        if doc.exports or doc.dependencies:
            with addto(content, nodes.field_list()) as fields:
                if doc.exports:
                    with addto(fields, nodes.field()) as field:
                        field += nodes.field_name('Exports', 'Exports')
                        with addto(field, nodes.field_body()) as body:
                            ref = doc['exports'] # warning: not the same as doc.exports
                            label = ref or '<anonymous>'
                            link = addnodes.pending_xref(
                                ref, nodes.paragraph(ref, label),
                                refdomain='js',
                                reftype='any',
                                reftarget=ref,
                            )
                            link['js:module'] = doc.name
                            body += link

                if doc.dependencies:
                    with addto(fields, nodes.field()) as field:
                        self.make_dependencies(field, doc)

        if doc.doc:
            # FIXME: source offset
            self.directive.state.nested_parse(to_list(doc.doc, source=doc['sourcefile']), 0, content)

        self.directive.state.nested_parse(self.directive.content, 0, content)

        content += self.document_properties(all_members)

        return content
Ejemplo n.º 17
0
    def run_definition(self, definition, base_ids):
        r"""
        Writes down the definition of a field of a message and parses its
        description.

        In general it can be seen as a function that converts `MessageField` in
        parsed document, with a description section containing both signature and
        informative content text.

        The signature are set as `attribute` object type.
        
        :param definition: a definition that should be parsed
        :param base_ids: the base id for indexing, local scope will be added to that 
                         id, based on the name of the field.
        :return: a full `desc` node, to be added to the main document
        """
        ids = f"{base_ids}.{definition.name}"
        desc_type = addnodes.desc_type(text=definition.type_text)
        desc_name = addnodes.desc_name(text=definition.name)
        desc_annotation = addnodes.desc_annotation(
            text=definition.default_text)
        desc_signature = addnodes.desc_signature(ids=[ids],
                                                 fullname=[definition.name])
        desc_signature += desc_type
        desc_signature += desc_name
        desc_signature += desc_annotation

        section = self.run_section(definition.text, ids)
        desc_content = addnodes.desc_content()
        desc_content += section
        desc = addnodes.desc(objtype="attribute")
        desc += desc_signature
        desc += desc_content
        return desc
Ejemplo n.º 18
0
 def run(self):
     result = super(ELSExp, self).run()
     if "nodoc" not in self.options:
         package = self.env.temp_data.get('el:package')
         node = addnodes.desc_content()
         string = DATA_DOC_STRINGS.get(package, {}) \
                                  .get(self.names[0][1], "")
         lines = string2lines(string)
         if lines and lines[-1].startswith('(fn '):
             lines = lines[:-1]
         self.state.nested_parse(StringList(lines), 0, node)
         if (result[1][1].children
                 and isinstance(result[1][1][0], nodes.field_list)):
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.append(cresult[0])
             target.extend(node)
             target.extend(cresult[1:])
         else:
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.extend(node)
             target.extend(cresult)
     return result
Ejemplo n.º 19
0
    def render(self):
        title = self.title()
        rettype, name, arglist, const, signature = self.directive.parse_title(
            title)
        fullname = self.directive.get_full_name(name)

        if self.data_object.kind == "function":
            # set True that this might be a structure method
            self.directive.sphinx_directive.typemethod_set = True

        target = self.directive.create_target(fullname)

        if self.data_object.kind == "function":
            self.directive.sphinx_directive.typemethod_set = False

        # add a signature node
        signode = addnodes.desc_signature(signature, '')
        signode['first'] = False

        signode += addnodes.desc_type('', '')

        self.directive.add_return_type(signode[-1], rettype)
        name = self.directive.add_sig_name(signode, name)
        self.directive.add_sig_args(signode, arglist, const)

        description_nodes = self.description()
        content_node = addnodes.desc_content('')
        content_node += description_nodes

        target.extend(signode)
        term = self.node_factory.term("", "", ids=[name], *target)
        entry = self.node_factory.definition_list_item("", term, content_node)

        return [entry]
Ejemplo n.º 20
0
    def run(self):
        document = self.state.document
        env = document.settings.env
        docname = env.docname

        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = 'py', self.name

        key = self.find_key(self.content.parent)

        targetnode = nodes.target('', '', ids=[key])

        key_elem = keynode(key)

        # Separating argument and content causes two <dd>-s to be generated in
        # the same <dl>
        doc = addnodes.desc_content()
        update_attrs(doc, self)
        txt = '\n'.join(self.arguments)
        self.before_content()
        details = keydoc(self.state, self.content)
        update_attrs(details, self)
        DocFieldTransformer(self).transform_all(details)
        self.after_content()
        doc += nodes.paragraph(txt, txt)
        doc += details

        import os
        source_line = self.lineno
        source, _ = self.state_machine.get_source_and_line(source_line)
        src_file, src_other = source.split(':', 1)
        source_file = os.path.basename(src_file)

        doc_entry = ibkey(self, key, key_elem, doc)
        #doc_entry = make_admonition(dummy, self.name, 'Alma', self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine)[0]
        
        catalog_entry = iblist_entry(
            self,
            env, docname, src_other, source_file, source_line,
            key, key_elem, doc)

        set_source_info(self, doc_entry)
        set_source_info(self, catalog_entry)
        env.resolve_references(doc_entry, docname, env.app.builder)
        env.resolve_references(catalog_entry, docname, env.app.builder)

        if not hasattr(env, 'ibkey_all_ibkeys'):
            env.ibkey_all_ibkeys = dict()

        env.ibkey_all_ibkeys[key] = dict(docname=docname,
                                         catalog_entry=catalog_entry)

        # - super.run() doesnt't kill the structure, it works fine
        # - returning both superrun and doc_entry does (in any order)
        # - The todo in the method docstring is rendered outside the 
        #   method's documentation (?!)
        return [doc_entry] #[targetnode, doc_entry]
Ejemplo n.º 21
0
    def make_nodes(self, contents_node):
        functor_parameters = desc_content()
        contents = desc_content()
        for node in contents_node.children:
            if node.get("objtype") == FunctorParameter.object_type:
                functor_parameters += node
            else:
                contents += node

        yield desc_signature(*self.make_signature_nodes(functor_parameters))
        if functor_parameters.children:
            yield functor_parameters
            yield desc_signature(desc_annotation("-> sig"))
        yield contents
        footer = self.get_footer()
        if footer is not None:
            yield desc_signature(desc_annotation(footer))
Ejemplo n.º 22
0
    def run(self):
        document = self.state.document
        env = document.settings.env
        docname = env.docname

        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = 'py', self.name

        key = self.find_key(self.content.parent)

        targetnode = nodes.target('', '', ids=[key])

        key_elem = keynode(key)

        # Separating argument and content causes two <dd>-s to be generated in
        # the same <dl>
        doc = addnodes.desc_content()
        update_attrs(doc, self)
        txt = '\n'.join(self.arguments)
        self.before_content()
        details = keydoc(self.state, self.content)
        update_attrs(details, self)
        DocFieldTransformer(self).transform_all(details)
        self.after_content()
        doc += nodes.paragraph(txt, txt)
        doc += details

        import os
        source_line = self.lineno
        source, _ = self.state_machine.get_source_and_line(source_line)
        src_file, src_other = source.split(':', 1)
        source_file = os.path.basename(src_file)

        doc_entry = ibkey(self, key, key_elem, doc)
        #doc_entry = make_admonition(dummy, self.name, 'Alma', self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine)[0]

        catalog_entry = iblist_entry(self, env, docname, src_other,
                                     source_file, source_line, key, key_elem,
                                     doc)

        set_source_info(self, doc_entry)
        set_source_info(self, catalog_entry)
        env.resolve_references(doc_entry, docname, env.app.builder)
        env.resolve_references(catalog_entry, docname, env.app.builder)

        if not hasattr(env, 'ibkey_all_ibkeys'):
            env.ibkey_all_ibkeys = dict()

        env.ibkey_all_ibkeys[key] = dict(docname=docname,
                                         catalog_entry=catalog_entry)

        # - super.run() doesnt't kill the structure, it works fine
        # - returning both superrun and doc_entry does (in any order)
        # - The todo in the method docstring is rendered outside the
        #   method's documentation (?!)
        return [doc_entry]  #[targetnode, doc_entry]
    def run(self):
        node = addnodes.desc_content()
        self.state.nested_parse(self.content, self.content_offset, node)

        return [
            CodeBlock(self.name, ['rst'], {}, self.content, self.lineno,
                      self.content_offset, self.block_text, self.state,
                      self.state_machine).run()[0], node
        ]
Ejemplo n.º 24
0
    def run(self) -> List[nodes.Node]:  # noqa: D102
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.indexnode = addnodes.index(entries=[])

        node = OptionDesc()
        node.document = self.state.document
        node["domain"] = self.domain
        # 'desctype' is a backwards compatible attribute
        node["objtype"] = node["desctype"] = self.objtype
        node["noindex"] = noindex = ("noindex" in self.options)
        if self.domain:
            node["classes"].append(self.domain)

        self.names: List[Any] = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            self.set_source_info(signode)
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    # only add target and index entry if this is the first
                    # description of the object with this name in this desc block
                    self.add_target_and_index(name, sig, signode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data["object"] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.transform_content(contentnode)
        self.env.app.emit("object-description-transform", self.domain,
                          self.objtype, contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data["object"] = None
        self.after_content()

        return [self.indexnode, node]
Ejemplo n.º 25
0
Archivo: ext.py Proyecto: Cray/buildbot
    def run(self):
        self.env = env = self.state.document.settings.env
        # normalize whitespace in fullname like XRefRole does
        fullname = ws_re.sub(' ', self.arguments[0].strip())
        targetname = '%s-%s' % (self.ref_type, fullname)

        # keep the target; this may be used to generate a BBIndex later
        targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {})
        targets[fullname] = env.docname, targetname

        # make up the descriptor: a target and potentially an index descriptor
        node = nodes.target('', '', ids=[targetname])
        ret = [node]

        # add the target to the document
        self.state.document.note_explicit_target(node)

        # append the index node if necessary
        entries = []
        for tpl in self.indextemplates:
            colon = tpl.find(':')
            if colon != -1:
                indextype = tpl[:colon].strip()
                indexentry = tpl[colon + 1:].strip() % (fullname,)
            else:
                indextype = 'single'
                indexentry = tpl % (fullname,)
            entries.append(
                (indextype, indexentry, targetname, targetname, None))

        if entries:
            inode = addnodes.index(entries=entries)
            ret.insert(0, inode)

        # if the node has content, set up a signature and parse the content
        if self.has_content:
            descnode = addnodes.desc()
            descnode['domain'] = 'bb'
            descnode['objtype'] = self.ref_type
            descnode['noindex'] = True
            signode = addnodes.desc_signature(fullname, '')

            if self.name_annotation:
                annotation = "%s " % self.name_annotation
                signode += addnodes.desc_annotation(annotation, annotation)
            signode += addnodes.desc_name(fullname, fullname)
            descnode += signode

            contentnode = addnodes.desc_content()
            self.state.nested_parse(self.content, 0, contentnode)
            DocFieldTransformer(self).transform_all(contentnode)
            descnode += contentnode

            ret.append(descnode)

        return ret
Ejemplo n.º 26
0
    def run(self):
        self.env = env = self.state.document.settings.env
        # normalize whitespace in fullname like XRefRole does
        fullname = ws_re.sub(' ', self.arguments[0].strip())
        targetname = '%s-%s' % (self.ref_type, fullname)

        # keep the target; this may be used to generate a BBIndex later
        targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {})
        targets[fullname] = env.docname, targetname

        # make up the descriptor: a target and potentially an index descriptor
        node = nodes.target('', '', ids=[targetname])
        ret = [node]

        # add the target to the document
        self.state.document.note_explicit_target(node)

        # append the index node if necessary
        entries = []
        for tpl in self.indextemplates:
            colon = tpl.find(':')
            if colon != -1:
                indextype = tpl[:colon].strip()
                indexentry = tpl[colon + 1:].strip() % (fullname, )
            else:
                indextype = 'single'
                indexentry = tpl % (fullname, )
            entries.append(
                (indextype, indexentry, targetname, targetname, None))

        if entries:
            inode = addnodes.index(entries=entries)
            ret.insert(0, inode)

        # if the node has content, set up a signature and parse the content
        if self.has_content:
            descnode = addnodes.desc()
            descnode['domain'] = 'bb'
            descnode['objtype'] = self.ref_type
            descnode['noindex'] = True
            signode = addnodes.desc_signature(fullname, '')

            if self.name_annotation:
                annotation = "%s " % self.name_annotation
                signode += addnodes.desc_annotation(annotation, annotation)
            signode += addnodes.desc_name(fullname, fullname)
            descnode += signode

            contentnode = addnodes.desc_content()
            self.state.nested_parse(self.content, 0, contentnode)
            DocFieldTransformer(self).transform_all(contentnode)
            descnode += contentnode

            ret.append(descnode)

        return ret
Ejemplo n.º 27
0
    def run(self):
        """Same as :meth:`sphinx.directives.ObjectDescription`
        but using :class:`FortranDocFieldTransformer`"""
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if not isinstance(name[0], unicode):
                name = (unicode(name), name[1])
            if not noindex and name not in self.names:
                # only add target and index entry if this is the first
                # description of the object with this name in this desc block
                self.names.append(name)
                self.add_target_and_index(name, sig, signode)

        modname = signode.get('module')
        typename = signode.get('type')
        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        FortranDocFieldTransformer(self, modname=modname, typename=typename).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]
Ejemplo n.º 28
0
def _split_content(node):
    content = addnodes.desc_content()
    fields = []

    for child in node:
        if isinstance(child, nodes.field_list):
            fields.extend([f for f in child])
        else:
            content.append(child)
    return content, fields
Ejemplo n.º 29
0
def getArgsContent(Args):
  Container = desc('', desc_signature(text='Args'), objtype="Args")

  for name, Arg in Args.items():
    Content = desc_content()
    Content.append(desc_name(text='%s: ' % name))
    Content.append(compact_paragraph(text=getArgDesc(Arg)))
    Container.append(Content)

  return Container
Ejemplo n.º 30
0
def getArgsContent(Args):
  Container = desc('', desc_signature(text='Args'), objtype="Args")

  for name, Arg in Args.items():
    Content = desc_content()
    Content.append(desc_name(text='%s: ' % name))
    Content.append(compact_paragraph(text=getArgDesc(Arg)))
    Container.append(Content)

  return Container
Ejemplo n.º 31
0
    def handle_signature(self, sig: str, signode: desc_signature) -> str:
        contentnode = addnodes.desc_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        ty = self.options.get("type")

        signode += addnodes.desc_annotation("property ", "property ")
        signode += addnodes.desc_name(sig, sig)
        signode += addnodes.desc_sig_punctuation("", ":")
        signode += addnodes.desc_sig_keyword_type(ty, ty)
        return sig
Ejemplo n.º 32
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        obj = self.make_obj()
        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)
        node.name = obj.name
        obj.docname = self.env.docname

        objects = self.env.domaindata['envy']['objects']

        signode = addnodes.desc_signature('', '')
        signode['first'] = True
        node.append(signode)
        self.make_signature(obj, signode)
        if not noindex and self.name not in objects:
            # only add target and index entry if this is the first
            # description of the object with this name in this desc block
            #self.add_target_and_index(self.name, sig, signode)
            nid = obj.iname + '-' + self.name
            signode['names'].append(nid)
            signode['ids'].append(nid)
            self.state.document.note_explicit_target(signode)

        for loc in self.locs:
            signode = addnodes.desc_signature('', '')
            signode['first'] = False
            node.append(signode)
            signode += addnodes.desc_name(loc, loc)

        node.append(uplink_placeholder(self.name))

        if self.name in objects:
            other = objects[self.name]
            self.state_machine.reporter.warning(
                'duplicate object {}, other instance in {}'.format(
                    self.name, self.env.doc2path(other.docname)))
        objects[self.name] = obj

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.env.temp_data['object'] = self.name
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.env.temp_data['object'] = None
        contentnode += self.after_content()
        return [self.indexnode, node]
Ejemplo n.º 33
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain

        node['classes'].append('csharp')

        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            beforesignode = CSNodes.EmptyNode()
            node.append(beforesignode)

            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            self.before_sig(beforesignode)
            try:
                name = self.handle_signature(sig, signode)
            except ValueError:
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    self.add_target_and_index(name, sig, signode)

            aftersignode = CSNodes.EmptyNode()
            node.append(aftersignode)
            self.after_sig(aftersignode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.before_content_node(contentnode)
        if self.names:
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.after_content_node(contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]
Ejemplo n.º 34
0
def getMemberContent(Member, *Children):
  Config = Member.Config
  Content = desc_content(*Children)

  doc = Member.Underlying.__doc__
  if doc:
    Content.insert(0, getNodeTreeFromStr(doc)) # add the parsed docstring to the content.

  if 'desc' in Config:
    Content.insert(0, paragraph(text=Config['desc']))

  return Content
Ejemplo n.º 35
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        obj = self.make_obj()
        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)
        node.name = obj.name
        obj.docname = self.env.docname

        objects = self.env.domaindata['envy']['objects']

        signode = addnodes.desc_signature('', '')
        signode['first'] = True
        node.append(signode)
        self.make_signature(obj, signode)
        if not noindex and self.name not in objects:
            # only add target and index entry if this is the first
            # description of the object with this name in this desc block
            #self.add_target_and_index(self.name, sig, signode)
            nid = obj.iname + '-' + self.name
            signode['names'].append(nid)
            signode['ids'].append(nid)
            self.state.document.note_explicit_target(signode)

        for loc in self.locs:
            signode = addnodes.desc_signature('', '')
            signode['first'] = False
            node.append(signode)
            signode += addnodes.desc_name(loc, loc)

        node.append(uplink_placeholder(self.name))

        if self.name in objects:
            other = objects[self.name]
            self.state_machine.reporter.warning('duplicate object {}, other instance in {}'.format(self.name, self.env.doc2path(other.docname)))
        objects[self.name] = obj

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.env.temp_data['object'] = self.name
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.env.temp_data['object'] = None
        contentnode += self.after_content()
        return [self.indexnode, node]
Ejemplo n.º 36
0
def getMemberContent(Member, *Children):
  Config = Member.Config
  Content = desc_content(*Children)

  doc = Member.Underlying.__doc__
  if doc:
    Content.insert(0, getNodeTreeFromStr(doc)) # add the parsed docstring to the content.

  if 'desc' in Config:
    Content.insert(0, paragraph(text=Config['desc']))

  return Content
Ejemplo n.º 37
0
    def run(self):
        if len(self.arguments) == 1:
            spec = get_obj_from_module(self.arguments[0].strip())
        else:
            spec = json.loads('\n'.join(self.content))

        content = doc_spec(spec)

        # parse the RST text
        node = addnodes.desc_content()
        self.state.nested_parse(StringList(content), self.content_offset, node)

        return [node]
Ejemplo n.º 38
0
    def run(self):
        module_path, member_name = self.arguments[0].rsplit('.', 1)

        member_data = getattr(import_module(module_path), member_name)
        code = pformat(member_data, 2, width=68)

        literal = nodes.literal_block(code, code)
        literal['language'] = 'python'

        # TODO: Make this generate a cross-reference target
        return [
            addnodes.desc_name(text=member_name),
            addnodes.desc_content('', literal)
        ]
Ejemplo n.º 39
0
    def run(self):
        missing_options = set(self.option_spec).difference(self.options)
        if missing_options:
            raise ValueError(f"Missing options: {missing_options!r};"
                             f" content: {list(self.content)!r}")
        try:
            wires = getattr(self.env.app, KEY)
        except AttributeError:
            wires = []
            setattr(self.env.app, KEY, wires)
        wires.append(
            WireInfo(
                value=self.content[0],
                type=self.options["type"],
                runtime=self.options["runtime"],
                config=self.options["config"],
                requirements=self.options["requirements"].split(),
            ))

        node = addnodes.desc()
        node["objtype"] = "wire"
        signode = addnodes.desc_signature("", "")
        signode += addnodes.desc_annotation("type", "type:")
        signode += addnodes.desc_name(self.options["type"],
                                      self.options["type"])
        signode += addnodes.desc_annotation("config", "config:")
        signode += addnodes.pending_xref(
            "",
            addnodes.desc_addname(self.options["config"],
                                  self.options["config"]),
            refdomain="proto",
            reftype="message",
            reftarget=self.options["config"],
        )
        node.append(signode)

        contentnode = addnodes.desc_content()
        if self.options["requirements"]:
            contentnode += nodes.paragraph("", "Requirements:")
            bullet_list = nodes.bullet_list("")
            for requirement in self.options["requirements"].split():
                bullet_list += nodes.list_item("",
                                               nodes.literal("", requirement))
            contentnode += bullet_list
        else:
            contentnode += nodes.paragraph("", "No requirements")
        node.append(contentnode)

        return [node]
Ejemplo n.º 40
0
    def generate(self, all_members=False):
        """
        :rtype: List[nodes.Node]
        """
        objname = self.item.name
        prefixed = (self.item['sourcemodule'].name + '.' +
                    objname) if self.item['sourcemodule'] else None
        objtype = self.objtype
        assert objtype, '%s has no objtype' % type(self)
        root = addnodes.desc(domain='js', desctype=objtype, objtype=objtype)
        with addto(
                root,
                addnodes.desc_signature(
                    module=self.modname or '',
                    fullname=objname,
                )) as s:
            s['class'] = self.classname

            s['ids'] = []
            if objname:
                s['ids'].append(objname)
            if prefixed:
                s['ids'].append(prefixed)

            if objtype:
                s += addnodes.desc_annotation(
                    objtype,
                    objtype,
                    nodes.Text(' '),
                )

                env = self.env
                if objname:
                    env.domaindata['js']['objects'][objname] = (env.docname,
                                                                objtype)
                if prefixed:
                    env.domaindata['js']['objects'][prefixed] = (env.docname,
                                                                 objtype)

            # TODO: linkcode_resolve
            s += self.make_signature()
        with addto(root, addnodes.desc_content()) as c:
            # must be here otherwise nested_parse(self.content) will not have
            # the prefix set
            self.env.temp_data.setdefault('autojs:prefix',
                                          []).append(self.item.name)
            c += self.make_content(all_members=all_members)
            self.env.temp_data['autojs:prefix'].pop()
        return [root]
Ejemplo n.º 41
0
    def run(self):
        if len(self.arguments) == 0:
            types = json.loads('\n'.join(self.content))
        else:
            types = self.iter_types(
                [get_obj_from_module(arg.strip()) for arg in self.arguments])

        content = []
        for typ in types:
            content.extend(doc_type(typ))

        node = addnodes.desc_content()
        self.state.nested_parse(StringList(content), self.content_offset, node)

        return [node]
Ejemplo n.º 42
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env

        obj_name, = self.arguments
        for obj in self.gen_type.instances:
            if obj.name == obj_name:
                break
        else:
            raise ValueError('unknown instance {}'.format(obj_name))

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = False
        node.name = obj.slug
        pobj = GenObjPlaceholder(self.env.docname, obj.brief)

        genobjs = self.env.domaindata['envy']['genobjs']

        signode = addnodes.desc_signature('', '')
        signode['first'] = True
        node.append(signode)
        self.make_signature(obj, signode)
        signode['names'].append(obj.name)
        signode['ids'].append(obj.slug)
        self.state.document.note_explicit_target(signode)

        if obj.slug in genobjs:
            other = genobjs[obj.slug]
            self.state_machine.reporter.warning('duplicate object {}, other instance in {}'.format(obj.slug, self.env.doc2path(other.docname)))
        genobjs[obj.slug] = pobj

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        vl = ViewList()
        doc = prepare_docstring(obj.doc or '')
        for line in doc:
            vl.append(line, obj_name)
        self.state.nested_parse(vl, 0, contentnode)

        return [
            node
        ]
Ejemplo n.º 43
0
    def run(self):
        env = self.state.document.settings.env
        package = env.temp_data.get('el:package')
        keymap_list = DATA.get(package, {}).get('keymap', [])
        keymap_name = self.arguments[0]
        for keymap in keymap_list:
            if keymap['name'] == keymap_name:
                break
        else:
            return [self.state.reporter.warning(
                "Keymap {0} not found".format(keymap_name))]
        nodelist = []

        mapdoc = keymap['doc']
        if mapdoc:
            nd = nodes.paragraph()
            lines = string2lines(doc_to_rst(mapdoc))
            if lines and lines[-1].startswith('(fn '):
                lines = lines[:-1]
            self.state.nested_parse(StringList(lines), 0, nd)
            nodelist.append(nd)

        exclude = self.options.get('exclude', [])
        replace = self.options.get('replace', [])
        for keybind in filter_by_exclude_regexp_list(
                keymap['data'], exclude, lambda x: x['func']):
            desc = addnodes.desc()
            desc['domain'] = 'el'
            desc['objtype'] = 'keybind'
            desc['noindex'] = False
            signode = addnodes.desc_signature()
            # signode += addnodes.desc_annotation("", 'keybind ')
            key = simple_sed(replace, keybind['key'])
            signode += addnodes.desc_name("", key)
            signode += addnodes.desc_addname("", " " + keybind['func'])
            desc += signode
            if keybind['doc']:
                nd = addnodes.desc_content()
                lines = string2lines(doc_to_rst(keybind['doc']))
                if lines and lines[-1].startswith('(fn '):
                    lines = lines[:-1]
                self.state.nested_parse(StringList(lines), 0, nd)
                desc += nodes.definition("", nd)
            nodelist.append(desc)

        return nodelist
Ejemplo n.º 44
0
    def format_operation(self, operations):
        c = n.container()
        for op in operations:

            p = addnodes.desc(objtype='endpoint')
            p += addnodes.desc_signature('nickname', op['nickname'])
            p += addnodes.desc_addname('method', op['httpMethod'])
            p += addnodes.desc_content(text=op['summary'])
            if 'parameters' in op.keys():
                p += addnodes.desc_annotation(text='Parameters: ')
                params = self.format_parameters(op['parameters'])
                p += params
            if op.get('responseClass'):
                response = self.format_response_class(op['responseClass'])
                p += response
            c += p

        return c
Ejemplo n.º 45
0
def transform_module_section(section_node, title_node, env):
    fullmodname = section_node['names'][0]
    where = section_node.first_child_matching_class(section_prelude_end_class)
    content_children = list(ipop_child(section_node, where + 1))
    if title_node is None:
        signature_children = [literal('', fullmodname)]
    else:
        signature_children = list(ipop_child(title_node))
    signature_node = desc_signature('', '', *signature_children,
                                    classes=['title', 'module'],
                                    names=[fullmodname])
    content_node = desc_content('', *content_children)
    desc_node = desc('', signature_node, content_node,
                     desctype='module',
                     objtype='module',
                     classes=['definition'])
    section_node.append(desc_node)
    add_toc(desc_node, env, section_node)
Ejemplo n.º 46
0
    def format_operation(self, operations):
        c = n.container()
        for op in operations:

            p = addnodes.desc(objtype="endpoint")
            p += addnodes.desc_signature("nickname", op["nickname"])
            p += addnodes.desc_addname("method", op["httpMethod"])
            p += addnodes.desc_content(text=op["summary"])
            if "parameters" in op.keys():
                p += addnodes.desc_annotation(text="Parameters: ")
                params = self.format_parameters(op["parameters"])
                p += params
            if op.get("responseClass"):
                response = self.format_response_class(op["responseClass"])
                p += response
            c += p

        return c
Ejemplo n.º 47
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = False

        try:
            signature = self.arguments[0]
            if self.objtype == 'schema':
                signode = addnodes.desc_signature(signature)
                signode['first'] = False
                node += signode
        except:
            signature = None

        headernode = addnodes.desc_name()
        headernode += nodes.inline('', _(self.objtype) + ' ')
        if signature is not None:
            headernode += nodes.emphasis('', signature)
        if _is_compositional(self.options['type']):
            if signature is not None:
                headernode += nodes.inline('', ' -- ')
            _describe_type(self.options['type'], headernode,
                           contains=self.options['contains'])
        node.append(headernode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        type = self.options['type']
        if type in __transformers__:
            __transformers__[type](self).transform_all(contentnode)

        return [addnodes.index(entries=[]), node]
Ejemplo n.º 48
0
    def generate(self, all_members=False):
        """
        :rtype: List[nodes.Node]
        """
        objname = self.item.name
        prefixed = (self.item['sourcemodule'].name + '.' + objname) if self.item['sourcemodule'] else None
        objtype = self.objtype
        assert objtype, '%s has no objtype' % type(self)
        root = addnodes.desc(domain='js', desctype=objtype, objtype=objtype)
        with addto(root, addnodes.desc_signature(
            module=self.modname or '',
            fullname=objname,
        )) as s:
            s['class'] = self.classname

            s['ids'] = []
            if objname:
                s['ids'].append(objname)
            if prefixed:
                s['ids'].append(prefixed)

            if objtype:
                s += addnodes.desc_annotation(
                    objtype, objtype,
                    nodes.Text(' '),
                )

                env = self.env
                if objname:
                    env.domaindata['js']['objects'][objname] = (env.docname, objtype)
                if prefixed:
                    env.domaindata['js']['objects'][prefixed] = (env.docname, objtype)

            # TODO: linkcode_resolve
            s += self.make_signature()
        with addto(root, addnodes.desc_content()) as c:
            # must be here otherwise nested_parse(self.content) will not have
            # the prefix set
            self.env.temp_data.setdefault('autojs:prefix', []).append(self.item.name)
            c += self.make_content(all_members=all_members)
            self.env.temp_data['autojs:prefix'].pop()
        return [root]
Ejemplo n.º 49
0
 def _make_enum_documentation(self, obj):
     def get_entry(node):
         para = addnodes.compact_paragraph()
         para += node
         entry = nodes.entry()
         entry += para
         return entry
     desc = addnodes.desc_signature()
     desc['ids'].append(obj.get_id())
     first = False
     desc += nodes.emphasis(text=u'enum')
     desc += nodes.Text(u' ')
     desc += addnodes.desc_name(text=obj.get_name())
     desc.attributes['first'] = True
     content = addnodes.desc_content()
     if obj.brief():
         para = nodes.paragraph()
         para += nodes.emphasis(text='Brief: ')
         para += nodes.Text(' '.join(obj.brief()))
         content += para
     table, body = nodes.table(), nodes.tbody()
     tgroup = nodes.tgroup(cols=3)
     thead = nodes.thead()
     for it in [20, 10, 70]:
         tgroup += nodes.colspec(colwidth=it)
     tgroup += thead
     tgroup += body
     table += tgroup
     head_row = nodes.row()
     for it in ['Name', 'Value', 'Brief']:
         head_row += get_entry(nodes.Text(it))
     thead += head_row
     for val in sorted(obj.values):
         row = nodes.row()
         row += get_entry(nodes.literal(text=val.name))
         tmp = [val.value if val.value is not None else '',
         ' '.join(val.brief())]
         for it in tmp:
             row += get_entry(nodes.Text(it))
         body += row
     content += table
     return (desc, content)
Ejemplo n.º 50
0
Archivo: c.py Proyecto: Cyofanni/speect
    def add_sig_name(self, signode, name):
        try:
            classname, funcname = name.split('::', 1)
            classname += '::'
            signode += addnodes.desc_addname(classname, classname)
            signode += addnodes.desc_name(funcname, funcname)
            # name (the full name) is still both parts
        except ValueError:
            signode += addnodes.desc_name(name, name)

        if "inheritance" in self.sphinx_directive.options:
            inheritance_node = addnodes.desc_content('')
            self.add_inheritance_diagram(inheritance_node)
            signode += inheritance_node

        # clean up parentheses from canonical name
        m = c_funcptr_name_re.match(name)
        if m:
            name = m.group(1)

        return self.get_full_name(name)
Ejemplo n.º 51
0
    def parse_section(self, node):
        matched = re.search("^(.*?)\s*\((.*)\)\s*$", node[0].astext())
        if not matched:
            return

        objname = matched.group(1).strip()
        typename = matched.group(2).strip()

        desc = sphinxnodes.desc(domain="js", desctype="data", objtype="data")
        sig = sphinxnodes.desc_signature(object="", fullname=objname, first=False)
        sig["names"].append(objname)
        sig["ids"].append(objname.replace("$", "_S_"))
        sig += sphinxnodes.desc_name(text="%s (%s)" % (objname, typename))

        content = sphinxnodes.desc_content()
        node.pop(0)
        transpose_subnodes(node, content)

        node.replace_self(desc)
        desc.append(sig)
        desc.append(content)
Ejemplo n.º 52
0
    def run(self):
        env = self.state.document.settings.env
        package = env.temp_data.get("el:package")
        keymap_list = DATA.get(package, {}).get("keymap", [])
        keymap_name = self.arguments[0]
        for keymap in keymap_list:
            if keymap["name"] == keymap_name:
                break
        else:
            return [self.state.reporter.warning("Keymap {0} not found".format(keymap_name))]
        nodelist = []

        mapdoc = keymap["doc"]
        if mapdoc:
            nd = nodes.paragraph()
            lines = string2lines(doc_to_rst(mapdoc))
            self.state.nested_parse(StringList(lines), 0, nd)
            nodelist.append(nd)

        exclude = self.options.get("exclude", [])
        for keybind in filter_by_exclude_regexp_list(keymap["data"], exclude, lambda x: x["func"]):
            desc = addnodes.desc()
            desc["domain"] = "el"
            desc["objtype"] = "keybind"
            desc["noindex"] = False
            signode = addnodes.desc_signature()
            # signode += addnodes.desc_annotation("", 'keybind ')
            signode += addnodes.desc_name("", keybind["key"])
            signode += addnodes.desc_addname("", " " + keybind["func"])
            desc += signode
            if keybind["doc"]:
                nd = addnodes.desc_content()
                lines = string2lines(doc_to_rst(keybind["doc"]))
                self.state.nested_parse(StringList(lines), 0, nd)
                desc += nodes.definition("", nd)
            nodelist.append(desc)

        return nodelist
    def depart_Action(self, node):
        http_method = node['http_method']
        uri = node['uri']

        self.env.domaindata['http'][http_method.lower()][uri] = (self.env.docname, node['identifier'], False)
        desc = addnodes.desc(domain='http',
                             desctype=http_method.lower(),
                             objtype=http_method.lower())

        sig = addnodes.desc_signature(method=http_method.lower(), path=uri, first=False,
                                      fullname="%s %s" % (http_method, uri))
        sig['ids'].append(http_resource_anchor(http_method, uri))
        if node['identifier']:
            sig += addnodes.desc_name(text="%s %s (%s)" % (http_method, uri, node['identifier']))
        else:
            sig += addnodes.desc_name(text="%s %s" % (http_method, uri))

        content = addnodes.desc_content()
        transpose_subnodes(node, content)

        node.replace_self(desc)
        desc.append(sig)
        desc.append(content)
Ejemplo n.º 54
0
 def run(self):
     result = super(CLsExp, self).run()
     if "nodoc" not in self.options:
         package = self.env.temp_data.get('cl:package')
         node = addnodes.desc_content()
         string = doc_strings.get(package).get(self.names[0][1], "")
         lines = string2lines(string)
         self.state.nested_parse(StringList(lines), 0, node)
         if (result[1][1].children and
             isinstance(result[1][1][0], nodes.field_list)):
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.append(cresult[0])
             target.extend(node)
             target.extend(cresult[1:])
         else:
             cresult = result[1][1].deepcopy()
             target = result[1][1]
             target.clear()
             target.extend(node)
             target.extend(cresult)
     return result
Ejemplo n.º 55
0
    def _build_option(self, parser, action, custom_content):
        """
        Build single program option

        :param parser: pre-configured ArgumentParser instance
        :param action: source Action
        :param custom_content: custom content for options
        :return: node forming program option
        """
        def get_id(progname, name):
            id = 'cmdoption-{}'.format(progname)
            if not name.startswith('-'):
                id += '-arg-'
            id += name
            return id
        fmt = parser._get_formatter()
        result = nodes.container()
        signature = addnodes.desc_signature(ids=[], allnames=[], first=False)
        self.state.document.note_explicit_target(signature)
        description = self._build_option_description(fmt, action, custom_content)
        content = addnodes.desc_content('', description)
        result.append(addnodes.desc('', signature, content, objtype='option'))
        progname = self._get_program_name(parser)
        synopses = []
        for option in self._get_option_group(fmt, action):
            signature['ids'].append(get_id(progname, option['name']))
            signature['allnames'].append(option['name'])
            signature.append(addnodes.desc_name(text=option['name']))
            if 'args' in option:
                signature.append(addnodes.desc_addname(text=option['args']))
            signature.append(addnodes.desc_addname(text=', '))
            synopses.append(option['synopsis'])
        signature.pop()
        index = self._build_option_index(progname, signature['ids'], signature['allnames'], synopses)
        result.append(index)
        return result
Ejemplo n.º 56
0
        if not noindex and name not in names:
            fullname = (module and module + '.' or '') + name
            # note target
            if fullname not in state.document.ids:
                signode['names'].append(fullname)
                signode['ids'].append(fullname)
                signode['first'] = (not names)
                state.document.note_explicit_target(signode)
                env.note_descref(fullname, desctype, lineno)
            names.append(name)

            indextext = desc_index_text(desctype, module, name,
                                        env.config.add_module_names)
            inode['entries'].append(('single', indextext, fullname, fullname))

    subnode = addnodes.desc_content()
    # needed for automatic qualification of members
    clsname_set = False
    if desctype in ('class', 'exception') and names:
        env.currclass = names[0]
        clsname_set = True
    elif desctype in ('method', 'staticmethod', 'attribute') and \
             clsname and not env.currclass:
        env.currclass = clsname.strip('.')
        clsname_set = True
    # needed for association of version{added,changed} directives
    if names:
        env.currdesc = names[0]
    state.nested_parse(content, content_offset, subnode)
    handle_doc_fields(subnode, env)
    if clsname_set:
Ejemplo n.º 57
0
    def run(self):
        filename = self.arguments[0]

        # Load rose configuration.
        try:
            conf = config.load(filename)
        except config.ConfigSyntaxError:
            LOGGER.error(
                'Syntax error in Rose configuration file "%s".' % filename)
            raise

        nodes = []
        nodes.append(addnodes.highlightlang(lang='rose', linenothreshold=20))

        # Append file level comments if present.
        if conf.comments:
            contentnode = addnodes.desc_content()
            contentnode.document = self.state.document
            self.state.nested_parse(
                StringList(conf.comments),
                self.content_offset,
                contentnode
            )
            nodes.append(contentnode)

        # Append configurations.
        section = None
        node = block_quote()
        for key, conf_node in sorted(conf.walk()):
            if isinstance(conf_node.value, str):
                # Configuration setting - "name=arg".
                name = '%s=%s' % (key[-1], conf_node.value or '')
            else:
                # Configuration section - "name"
                name = key[-1]
            # Prepare directive object.
            directive = RoseConfigDirective(
                'rose:conf',
                [name],
                {},
                StringList(conf_node.comments),
                self.lineno,
                self.content_offset,
                self.block_text,
                self.state,
                self.state_machine,
            )
            if isinstance(conf_node.value, dict):
                # Configuration section.
                if section:
                    node.append(section.run()[1])
                section = directive
            elif key[0]:
                # Sub-configuration.
                section.register_subnode(directive)
            else:
                # Top-level configuration
                node.append(directive.run()[1])
        if section:
            node.append(section.run()[1])
        nodes.append(node)

        nodes.append(addnodes.highlightlang(lang='bash', linenothreshold=20))

        return nodes
Ejemplo n.º 58
0
    def run(self):
        """
        Main directive entry function, called by docutils upon encountering the
        directive.

        This directive is meant to be quite easily subclassable, so it delegates
        to several additional methods.  What it does:

        * find out if called as a domain-specific directive, set self.domain
        * create a `desc` node to fit all description inside
        * parse standard options, currently `noindex`
        * create an index node if needed as self.indexnode
        * parse all given signatures (as returned by self.get_signatures())
          using self.handle_signature(), which should either return a name
          or raise ValueError
        * add index entries using self.add_target_and_index()
        * parse the content and handle doc fields in it
        """
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.env = self.state.document.settings.env
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    # only add target and index entry if this is the first
                    # description of the object with this name in this desc block
                    self.add_target_and_index(name, sig, signode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]