'Assign a section number to each heading under a numbered toctree.'

def assign_section_numbers(self):

    rewrite_needed = []
    old_secnumbers = self.toc_secnumbers
    self.toc_secnumbers = {}
    def _walk_toc(node, secnums, titlenode=None):
        for subnode in node.children:
            if isinstance(subnode, nodes.bullet_list):
                numstack.append(0)
                _walk_toc(subnode, secnums, titlenode)
                numstack.pop()
                titlenode = None
            elif isinstance(subnode, nodes.list_item):
                _walk_toc(subnode, secnums, titlenode)
                titlenode = None
            elif isinstance(subnode, addnodes.compact_paragraph):
                numstack[(-1)] += 1
                secnums[subnode[0]['anchorname']] = subnode[0]['secnumber'] = tuple(numstack)
                if titlenode:
                    titlenode['secnumber'] = tuple(numstack)
                    titlenode = None
            elif isinstance(subnode, addnodes.toctree):
                _walk_toctree(subnode)
    def _walk_toctree(toctreenode):
        for (title, ref) in toctreenode['entries']:
            if (url_re.match(ref) or (ref == 'self')):
                continue
            if (ref in self.tocs):
                secnums = self.toc_secnumbers[ref] = {}
                _walk_toc(self.tocs[ref], secnums, self.titles.get(ref))
                if (secnums != old_secnumbers.get(ref)):
                    rewrite_needed.append(ref)
    for docname in self.numbered_toctrees:
        doctree = self.get_doctree(docname)
        for toctreenode in doctree.traverse(addnodes.toctree):
            if toctreenode.get('numbered'):
                numstack = [0]
                _walk_toctree(toctreenode)
    return rewrite_needed
