'Build a TOC from the doctree and store it in the inventory.'

def build_toc_from(self, docname, document):

    numentries = [0]
    try:
        maxdepth = int(self.metadata[docname].get('tocdepth', 0))
    except ValueError:
        maxdepth = 0
    def traverse_in_section(node, cls):
        'Like    traverse(),    but    stay    within    the    same    section.'
        result = []
        if isinstance(node, cls):
            result.append(node)
        for child in node.children:
            if isinstance(child, nodes.section):
                continue
            result.extend(traverse_in_section(child, cls))
        return result
    def build_toc(node, depth=1):
        entries = []
        for sectionnode in node:
            if (not isinstance(sectionnode, nodes.section)):
                for toctreenode in traverse_in_section(sectionnode, addnodes.toctree):
                    item = toctreenode.copy()
                    entries.append(item)
                    self.note_toctree(docname, toctreenode)
                continue
            title = sectionnode[0]
            visitor = SphinxContentsFilter(document)
            title.walkabout(visitor)
            nodetext = visitor.get_entry_text()
            if (not numentries[0]):
                anchorname = ''
            else:
                anchorname = ('#' + sectionnode['ids'][0])
            numentries[0] += 1
            reference = nodes.reference('', '', refuri=docname, anchorname=anchorname, *nodetext)
            para = addnodes.compact_paragraph('', '', reference)
            item = nodes.list_item('', para)
            if ((maxdepth == 0) or (depth < maxdepth)):
                item += build_toc(sectionnode, (depth + 1))
            entries.append(item)
        if entries:
            return nodes.bullet_list('', *entries)
        return []
    toc = build_toc(document)
    if toc:
        self.tocs[docname] = toc
    else:
        self.tocs[docname] = nodes.bullet_list('')
    self.toc_num_entries[docname] = numentries[0]
