Duncan Murdoch wrote on 08/04/2008 08:11 AM:
On 04/08/2008 8:50 AM, Peter Jaeger wrote:
Dear List,
When I try to parse code containing newline characters with
R_ParseVector, I
get a compilation error. How can I compile code that includes comments
and
newlines?
I am using the following:
void* my_compile(char *code)
{
SEXP cmdSexp, cmdExpr = R_NilValue;
ParseStatus status;
PROTECT (cmdSexp = allocVector (STRSXP, 1));
SET_STRING_ELT (cmdSexp, 0, mkChar (code));
PROTECT (cmdExpr = R_ParseVector (cmdSexp,-1,&status,
R_NilValue));
UNPROTECT_PTR (cmdSexp);
if (status != PARSE_OK) {
return (void*)0;
} else {
return (void*)cmdExpr;
}
}
You need to put together a reproducible example if you want help.
parse() uses R_ParseVector, and it handles newlines fine.
As a follow up, it'd be good to know the exact value of your status
variable. You've only tested for PARSE_OK, but there's also
PARSE_INCOMPLETE, PARSE_NULL, PARSE_ERROR, and PARSE_EOF.
Here's a function that I use in rapache that not only parses but
executes the code as well. While it doesn't really help you with your
parsing problem, I suspect that you'll want to do something with the
returned expressions after you've parsed the code, and the point is that
R_ParseVector() can return more than one expression. Thus you'll need to
loop through each expression and eval() it separately. The function
returns 1 when the code was parsed and executed, and 0 on failure.
(it's been awhile since I've had to touch this, and although I do keep
up with R development, my skills at remembering which macros and
functions to use are lacking. Anyone spot something I shouldn't be
doing? like mkChar() or some such? )
static int ExecRCode(const char *code, SEXP env, int *error){
ParseStatus status;
SEXP cmd, expr, fun;
int i, errorOccurred=1, retval = 1;
PROTECT(cmd = allocVector(STRSXP, 1));
SET_STRING_ELT(cmd, 0, mkChar(code));
/* fprintf(stderr,"ExecRCode(%s)\n",code); */
PROTECT(expr = R_ParseVector(cmd, -1, &status,R_NilValue));
switch (status){
case PARSE_OK:
for(i = 0; i < length(expr); i++){
R_tryEval(VECTOR_ELT(expr,
i),env,&errorOccurred);
if (error) *error = errorOccurred;
if (errorOccurred){
retval=0;
break;
}
}
break;
case PARSE_INCOMPLETE:
case PARSE_NULL:
case PARSE_ERROR:
case PARSE_EOF:
default:
retval=0;
break;
}
UNPROTECT(2);
return retval;
}
Duncan Murdoch
______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
--
http://biostat.mc.vanderbilt.edu/JeffreyHorner
______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel