def lib2to3_to_dictnode(tree):
    """
    Transform a lib2to3 structure into a dictnode, as defined by dictnode_to_lxml.
    """
    from lib2to3.pygram import python_grammar
    from lib2to3.pgen2.token import tok_name
    code2name = tok_name.copy()
    del code2name[256]
    code2name.update(python_grammar.number2symbol)
    root = dict(name='ROOT', children=[], attrs={})
    stack = [(tree, root)]
    prev_node = root
    while stack:
        node, parent = stack.pop()
        node_type = code2name.get(node.type, node.type)
        attrs = {}
        if hasattr(node, 'value'):
            node_text = node.value
        else:
            node_text = ''
        if hasattr(node, '_prefix') and node._prefix:
            if prev_node is parent:
                if parent is root:
                    assert node_text == '', node_text
                    node_text = node._prefix
                else:
                    assert parent['text'] == '', parent
                    prev_node['text'] = node._prefix
            else:
                prev_node['tail'] = node._prefix
        dictnode = dict(name=node_type, text=node_text, attrs=attrs,
            children=[], tail='')
        parent['children'].append(dictnode)
        if hasattr(node, 'children'):
            for child in reversed(node.children):
                stack.append((child, dictnode))
        prev_node = dictnode
    prev_node['tail'] = ''
    assert len(root['children']) == 1, root['children']
    return root['children'][0]
