Created
August 8, 2017 15:04
-
-
Save clarkfitzg/861832580a4c527961c11907a88e40de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From wlandau | |
# https://github.com/duncantl/CodeDepends/issues/19 | |
library(CodeDepends) | |
#' Recursively Find Global Variables | |
#' | |
#' TODO: Modify this to work without requiring that the code be evaluated | |
#' Probably means we can't use codetools::findGlobals | |
#' | |
#' fun closure, see codetools::findGlobals | |
#' possible_funs character vector of variable names to recurse into | |
findGlobals_recursive <- function(fun, possible_funs) | |
{ | |
globals <- codetools::findGlobals(fun) | |
for(varname in intersect(globals, possible_funs)){ | |
var = get(varname, envir = .GlobalEnv) | |
if(is.function(var)){ | |
globals <- c(globals, Recall(var, possible_funs)) | |
} | |
} | |
unique(globals) | |
} | |
# Usage | |
############################################################ | |
code = parse(text = " | |
f <- function(x) g(x) | |
g <- function(x) { | |
h(x) | |
} | |
h <- function(x) { | |
sin(x) + cos(x) + my_var | |
} | |
my_var <- 1 | |
") | |
eval(code) | |
info = getInputs(code) | |
findGlobals_recursive(f, possible_funs = info@outputs) | |
g <- function(x) { | |
if(x > 10) | |
h1(x) | |
else | |
h2(x) | |
} | |
getInputs(body(g))@functions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment