findLoops: Find explicit loops in R code

View source: R/findLoops.R View source: R/findLoops.R

findLoopsR Documentation

Find explicit loops in R code

Description

This finds the explicit loops in R code, for, while and repeat loops.

Usage

findLoops(f, nested = TRUE, code = parse(f),
          w = mkLoopWalker(nested, skipIfFalse = skipIfFalse),
          skipIfFalse = TRUE)
numNestedLoops(code, recursive = TRUE)

Arguments

f

either an R language object or the path to a file containing R code which will be parsed

nested

a logical value that controls whether we look for loops inside loops or ignore the code in the body of a loop.

skipIfFalse

a logical value. If TRUE, skip if(FALSE){} code, but do process any else clause. If FALSE, process the body of the if(FALSE) code.

code

the R code, providing a way to pass code already parsed and not necessarily in a file. For numNestedLoops

w

the code walker that collects the loop nodes.

recursive

a logical value, currently ignored

Details

This uses codetools::walkCode to traverse the abstract syntax tree and captures nodes corresponding to these types of loops. One could add criteria to find specific types of loops, e.g., with a loop variable named i, a symbol/name as the third element of the loop (i.e., what is being looped over) or a call to seq, seq_len, etc., or a while condition that is TRUE. One can also post-process the results.

Value

A list of the language objects corresponding to the loop objects found in the R code.

Author(s)

Duncan Temple Lang

See Also

walkCode indexWalkCode

Examples

  fns = getFunctionDefs(getNamespace("tools"))
  loops = lapply(fns, function(x) findLoops(code = x))
  nl = sapply(loops, length)
  table(nl)
  # These include nested loops.
  which.max(nl)


  # Let's look at all the loops and the number of calls in each
  loops2 = unlist(loops, recursive = FALSE)
  length(loops2)
  summary(sapply(loops2, numCalls))

  # number of nested loops.
  nn = sapply(loops2, numNestedLoops)

duncantl/CodeAnalysis documentation built on Feb. 21, 2024, 10:49 p.m.