The code is here:
It's not ready for primetime - it only works for the XML builder, and is designed to generate XLink-based references. But it can be adapted. I'm playing around with it right now and trying to figure it out.
Take a look at build_finished.
master_doc = app.config.master_doc
toctree = TocTree(app.env).get_toctree_for(master_doc, app.builder, False)
if toctree:
visitor = TocVisitor(document, app.builder, app.config.master_doc)
visitor.new['master'] = True
toctree.walkabout(visitor)
document.children.append(
visitor.new)
this code builds the toc tree, transforms it (not in place) and then places it into a new document ('_links'). It isn't what you want but could give you a head start.