Skip to content

Commit

Permalink
Refactor receiver with default handling
Browse files Browse the repository at this point in the history
  • Loading branch information
lshala committed Sep 16, 2024
1 parent 01925e0 commit f1e5d78
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -410,20 +410,26 @@ class StatementHandler(frontend: PythonLanguageFrontend) :
result.additionalProblems += newProblemExpression("Expected a receiver", rawNode = args)
} else {
val tpe = recordDeclaration.toType()
val defaultValue =
args.defaults.getOrNull(0)?.let { frontend.expressionHandler.handle(it) }
val recvNode =
newVariableDeclaration(
name = recvPythonNode.arg,
type = tpe,
implicitInitializerAllowed = false,
rawNode = recvPythonNode
)
if (defaultValue != null) {
frontend.scopeManager.addDeclaration(recvNode)
result.additionalProblems +=
newProblemExpression("Receiver with default value", rawNode = args)

// If the number of defaults equals the number of positional arguments, the receiver has
// a default value
if (args.defaults.size == positionalArguments.size) {
val defaultValue =
args.defaults.getOrNull(0)?.let { frontend.expressionHandler.handle(it) }
defaultValue?.let {
frontend.scopeManager.addDeclaration(recvNode)
result.additionalProblems +=
newProblemExpression("Receiver with default value", rawNode = args)
}
}

when (result) {
is ConstructorDeclaration -> result.receiver = recvNode
is MethodDeclaration -> result.receiver = recvNode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import de.fraunhofer.aisec.cpg.TranslationResult
import de.fraunhofer.aisec.cpg.frontends.python.PythonLanguage
import de.fraunhofer.aisec.cpg.graph.*
import de.fraunhofer.aisec.cpg.graph.get
import de.fraunhofer.aisec.cpg.graph.parameters
import de.fraunhofer.aisec.cpg.test.analyze
import java.nio.file.Path
import kotlin.collections.component1
Expand Down Expand Up @@ -148,6 +149,23 @@ class ArgumentsHandlerTest {
}
}

@Test
fun testReceiverWithDefault() {
val func = result.functions["my_method"]
assertNotNull(func, "Function 'my_method' should be found")

assertEquals(2, func.parameters.size)
assertNotNull(func.methods[0].receiver)

val parameterD = func.parameters["d"]
assertNotNull(parameterD?.default, "Expected the parameter `d` to have a default value.")
assertEquals(3.toLong(), parameterD.default?.evaluate())

val parameterE = func.parameters["e"]
assertNotNull(parameterE?.default, "Expected the parameter `e` to have a default value.")
assertEquals(1.toLong(), parameterE.default?.evaluate())
}

@Test
fun testKwArguments() {
val func = result.functions["kw_args"]
Expand Down

0 comments on commit f1e5d78

Please sign in to comment.