Find Calls to a Function

DESCRIPTION:

Searches a function definition for calls to a given function.

USAGE:

find.calls(definition, name, expressions=T, replace=F) 

REQUIRED ARGUMENTS:

definition
a function definition.
name
character string naming a function.

OPTIONAL ARGUMENTS:

expressions
logical flag specifying whether the found expressions should be returned or just counted.
replace
logical flag: if TRUE, name is sought only in the context of a replacement; that is, as a function call immediately to the left of a <- or <<-. If replace is FALSE, name is sought as a call only in other contexts.

VALUE:

if expressions is TRUE, a list of expressions from definition; the list components are calls to name, or replacement assignments involving name , as replace is FALSE or TRUE. If expressions is FALSE, find.calls just returns the number of such expressions found.

DETAILS:

definition is examined recursively for function calls to name. Generally speaking, a call to f in a function definition would be treated as such by the evaluator. Replacement expressions are an exception. The expression f(x) <- value would conceptually be evaluated as a call to the function f<-, not f, but is represented in a function definition as a call to f on the left hand side of an assignment. The flag replace must be TRUE if find.calls should treat this as a call to f, in which event it will return the entire assignment expression.

Except for the case of replacements, find.calls will return only those expressions which would be evaluated as function calls. This implies that certain expressions which deparse (print) as apparent function calls will not be counted. Examples of these include the interfaces .Internal and .S (but not .C and .Fortran, which are true calls), as well as hardcoded data that may deparse as a call to c, list or structure.

NOTE:

If many functions are going to be searched in a single top-level expression, memory usage can be kept down by setting the keep option to NULL and using immediate=TRUE with the get function. See the help files for options and get.

SEE ALSO:

, , .

EXAMPLES:

  find.calls(f, "[")              # returns [-subscript extractions in f 
  find.calls(f, "[", replace=T)   # returns [-subscript replacements in f 
    
  as.logical(find.calls(f, "g", expr=F))     # returns TRUE if f calls g 
    
# find all functions on working database that call g: 
  old.keep <- options(keep=NULL) 
  for(i in objects()) { 
        obj <- get(i, where=1, immediate=T) 
        if(mode(obj) == "function" && find.calls(obj, "g", expr=F) != 0) 
                cat(i, "calls g\\n") 
       } 
  options(old.keep) 
# find all functions called by f: 
  functions.called <- function(definition) 
        setdiff(all.names(definition, unique = T), all.names(definition,  
                functions = F, unique = T)) 
  functions.called(f)