A nonautonomous chain rule in W^{1,p} and BV