def ToNestedAST(stk, idx=0):
    """
    Assumes a fully valid parse tree with fully bracketed "( .. )" expressions.
    Recursive.

    @param  stk: stack of sly.lex.Tokens
    @param  idx: token index into stk
    @returns:  index to next token in token stack, AST
    """
    ast = []
    i = idx

    while (i < len(stk)):
        if (stk[i].type == 'FUNC_NAME'):
            ast.append(stk[i])
            j, k = ToNestedAST(stk, i+1)
            ast.append(k)
            i = j
        elif (stk[i].type == 'LPAREN'):
            j, k = ToNestedAST(stk, i+1)
            ast.append(k)
            i = j
        elif (stk[i].type == 'RPAREN'):
            # go up recursion 1 level
            return i+1, ast
        elif (stk[i].type == 'COMMA'):
            # skip COMMA
            i = i + 1
        else:
            ast.append(stk[i])
            i = i + 1
    return i, ast