def simplify_tree(tree, unpack_lists=True, in_list=False):
<EOL>if isinstance(tree, BaseNode) and not isinstance(tree, Terminal):<EOL><INDENT>used_fields = [field for field in tree._fields if getattr(tree, field, False)]<EOL>if len(used_fields) == <NUM_LIT:1>:<EOL><INDENT>result = getattr(tree, used_fields[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>result = None<EOL><DEDENT>if (<EOL>len(used_fields) != <NUM_LIT:1><EOL>or isinstance(tree, AliasNode)<EOL>or (in_list and isinstance(result, list))<EOL>):<EOL><INDENT>result = tree<EOL>for field in tree._fields:<EOL><INDENT>old_value = getattr(tree, field, None)<EOL>if old_value:<EOL><INDENT>setattr(<EOL>result,<EOL>field,<EOL>simplify_tree(old_value, unpack_lists=unpack_lists),<EOL>)<EOL><DEDENT><DEDENT>return result<EOL><DEDENT>assert result is not None<EOL><DEDENT>elif isinstance(tree, list) and len(tree) == <NUM_LIT:1> and unpack_lists:<EOL><INDENT>result = tree[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>if isinstance(tree, list):<EOL><INDENT>result = [<EOL>simplify_tree(el, unpack_lists=unpack_lists, in_list=True)<EOL>for el in tree<EOL>]<EOL><DEDENT>else:<EOL><INDENT>result = tree<EOL><DEDENT>return result<EOL><DEDENT>return simplify_tree(result, unpack_lists=unpack_lists)<EOL>
Recursively unpack single-item lists and objects where fields and labels only reference a single child

    :param tree: the tree to simplify (mutating!)
    :param unpack_lists: whether single-item lists should be replaced by that item
    :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists