Skip to content

Instantly share code, notes, and snippets.

@fikovnik
Created June 18, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fikovnik/93fd71f03e1976903e16d546c28c07f2 to your computer and use it in GitHub Desktop.
Save fikovnik/93fd71f03e1976903e16d546c28c07f2 to your computer and use it in GitHub Desktop.
---
title: "R Notebook"
output: html_notebook
---
```{r}
library(readr)
library(devtools)
library(dplyr)
library(stringr)
library(purrr)
library(Rcpp)
```
```{r}
cppFunction(
'
Rcpp::StringVector find_balanced_expression(std::string &s, int start) {
int br = 0;
bool done = false;
int i = start - 1;
if (i < 0 || i > s.length()) throw std::range_error("Invalid start location: " + start);
for (; !done && i < s.length(); i++) {
switch(s[i]) {
case \'(\':
br++;
break;
case \')\':
br--;
done = br == 0;
break;
}
}
Rcpp::StringVector ret = Rcpp::StringVector(NA_STRING);
if (done) {
ret(0) = s.substr(start, i - start - 1);
}
return ret;
}
')
find_evals_in_file <- function(path) {
txt <- read_file(path)
locs <- str_locate_all(txt, "eval\\(")
args <- map_chr(locs[[1]][, 2], ~find_balanced_expression(txt, .))
data_frame(file=path, start=locs[[1]][, 1], args=args)
}
find_evals <- function(path) {
package <- as.package(path)
r_dir <- file.path(path, "R")
r_files <- list.files(r_dir, pattern="\\.[Rr]$", full.names=T, recursive=T)
df <- map_dfr(r_files, ~ find_evals_in_file(.))
bind_cols(data_frame(package=rep(package$package, nrow(df))), df)
}
```
```{r}
test_eval_str <- "asda \n eval(expr=parse(paste0(somefun('A'),\n 'B'))) sdf eval(quote(eval(quote(1+1))))"
find_balanced_expression(test_eval_str, str_locate_all(test_eval_str, "eval\\(")[[1]][1, 2])
find_evals_in_file("R/CRAN-extracted/devtools/R/source.r")
find_evals("R/CRAN-extracted/devtools")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment