Try to parse()
the code and see if an error occurs.
valid_syntax(code, silent = TRUE)
TRUE
if the code could be parsed, otherwise FALSE
.
xfun::valid_syntax("1+1")
#> [1] TRUE
xfun::valid_syntax("1+")
#> [1] FALSE
xfun::valid_syntax(c("if(T){1+1}", "else {2+2}"), silent = FALSE)
#> Error in parse(text = code, keep.source = FALSE) :
#> <text>:2:1: unexpected 'else'
#> 1: if(T){1+1}
#> 2: else
#> ^
#> [1] FALSE