see the comment below about pushing only sections to the stack. in this case it should be stack = [toc.sections]