Monte Carlo tests with nuisance parameters: A general approach to finite-sample inference and nonstandard asymptotics