PSA: simple hack to get Rstudio "check syntax on save" to use cmdstanr

Having transitioned to cmdstanr, it irks me that Rstudio’s “check syntax on save” option for .stan files uses rstan, often yielding false alarms thanks to my Stan code using features from newer versions of cmdstan than rstan is using.

Happily there’s a pretty easy workaround whereby you simply run the following (or put it in your .Rprofile so it is run automatically at every R startup):

#dependencies: cmdstanr, fs, stringr, crayon
cmdstan_pedantic_check = function(path){
	stdout = processx::run(
		command = fs::path(cmdstanr::cmdstan_path(),cmdstanr:::stanc_cmd())
		, args = c(
			basename(path)
			, '--include-paths', '.'
			, '--warn-pedantic'
			, '--warn-uninitialized'
			,'--o',tempfile()
		)
		, wd = dirname(path)
		, error_on_status = F
		, stderr_to_stdout = T
	)$stdout
	if(stdout==''){
		cat('\n')
		cat(crayon::blue('No syntax errors detected! :D\n\n'))
	}else{
		stdout = stringr::str_remove_all(stdout,stringr::fixed('./'))
		stdout = stringr::str_replace_all(stdout, 'Info: ', '\nInfo:\n')
		cat(crayon::blue(stdout))
		cat('\n\n')
	}
	invisible(NULL)
}
utils::assignInNamespace("rstudio_stanc", cmdstan_pedantic_check, ns="rstan", envir=as.environment("package:rstan"))

That should work for most simple model-compilation scenarios, as well as those with includes that are in the same dir as the stan file. I haven’t checked it against more advanced compile scenarios (MPI, etc), but it would surprise me if the syntax-checking purposes of this usage of stanc needs anything else.

14 Likes

Great stuff! Also note that you can use Repository for distributing (some) stan-dev R packages | r-packages to install rstan with the latest features, which should solve many of the same issues. Although the appeal of your solution is definitely that any change in installed CmdStan version will immediately affect the syntax check.

3 Likes

Thanks for doing this Mike! Maybe it’s worth including this function in the cmdstanr package until there’s a more permanent solution to this problem (so the function has a home other than the forums). What do you think?

2 Likes

I guess it’s time for me to come clean.

3 Likes