collectCallResults: Collect arguments, return values and global variables used in...

collectCallResultsR Documentation

Collect arguments, return values and global variables used in calls to a function

Description

This function traces a given function and arranges to collect all of the arguments and the return value for each call. If the function uses global variables, these can also be collected.

The goal is to be able to use these to test modifications to the function to ensure we get the same results. So these become unit tests.

Usage

collectCallResults(fn, globals = TRUE, len = 1000L, print = FALSE, ...)

Arguments

fn

the function whose calls are to be collected. This should be given by name or symbol (character or name), and not computed as it is passed to trace.

globals

either a scalar logical or a character vector giving the names of global variables to also collect with each call. The function uses findGlobals to identify the global variables. However, this does not always correctly identify global variables (e.g. missing uses before a variable is defined locally, including global functions used in, e.g., lapply calls.) One can use the function getGlobals in CodeAnalysis and pass the names of the global variables it finds.

len

a positive integer which provides a guess as to how many calls we'll see so that we can preallocate the list into which each call will be inserted. # The goal is to avoid growing the list too often which slows down the computations.

print

passed as the value for trace's print argument.

...

additional arguments passed to trace.

Value

A function, which when called, returns the list of the collected call information.

Author(s)

Duncan Temple Lang

See Also

trace

Examples

f = function(a, b = 2) a + b
g = function(x)   c(f(x, 3), f(x))     
h = function(x, y)  c(f(x, 3), g(y))     

funNames = c("f", "g", "h")
envs = lapply(funNames, collectCallResults)
names(envs) = funNames

g(10)
h(11, 201)

calls = lapply(envs, function(f) f())
sapply(calls, length)

#########

global1 = 10
global2 = 3.1415
f3 = function(x, y)
        x + y + global1 + global2

k3 = collectCallResults("f3")
f3(10, 20)
f3(101, 9)

k3calls = k3()

duncantl/CallCounter documentation built on Nov. 23, 2023, 3:38 p.m.