Code-Inspect / flowr

A program slicer and dataflow analyzer for the R programming language.
https://github.com/Code-Inspect/flowr/wiki
GNU General Public License v3.0
14 stars 2 forks source link

Dataflow: dead code detection when returning in both if/else branches #816

Closed Ellpeck closed 1 month ago

Ellpeck commented 1 month ago
        assertDataflow(label('return in if',['name-normal', ...OperatorDatabase['<-'].capabilities, 'formals-named', 'newlines', 'numbers', ...OperatorDatabase['*'].capabilities, 'return', 'unnamed-arguments', 'if']),
            shell, `f <- function(x) {
   x <- 3 * x
   if(k)
      return(x)
   else
      return(1)
   x <- 2
   return(x)
}

f(5)`, emptyGraph())

produces this Mermaid diagram. The assignment of x <- 2 is still contained in it, even though it should be considered dead code.

Dead code detection works correctly, however, when a return always occurs (ie outside of an if/else block), like in this example:

f <- function(x) {
   x <- 3 * x
   return(x)
   x <- 2
   return(x)
}

f(5)

Both of these tests are included in #800.

Ellpeck commented 1 month ago

This also occurs when slicing, see this test:

        assertSliced(label('dead code (return in if)', []),
            shell, `f <- function(x) {
   x <- 3 * x
   if(k)
      return(x)
   else
      return(1)
   # alles drunter soll natürlich weg 
   x <- 2
   return(x)
}

f(5)`, ['12@f'], `f <- function(x) {
        x <- 3 * x
        if(k) return(x) else
        return(1)
        x <- 2
        return(x)
    }
f(5)`)
EagleoutIce commented 1 month ago

This should be fixed by the linked PR, please still include the tests as part of #800.