From 51615c7592bf8d8b967da7de909716e585e0d660 Mon Sep 17 00:00:00 2001 From: Johannes Coetzee Date: Mon, 6 Jan 2025 13:38:46 +0100 Subject: [PATCH] Add tmp locals for pattern initializers to lambda method bodies (#5204) --- .../expressions/AstForLambdasCreator.scala | 18 ++++++------------ .../querying/PatternExprTests.scala | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/joern-cli/frontends/javasrc2cpg/src/main/scala/io/joern/javasrc2cpg/astcreation/expressions/AstForLambdasCreator.scala b/joern-cli/frontends/javasrc2cpg/src/main/scala/io/joern/javasrc2cpg/astcreation/expressions/AstForLambdasCreator.scala index 3afc16003313..467e938efa4b 100644 --- a/joern-cli/frontends/javasrc2cpg/src/main/scala/io/joern/javasrc2cpg/astcreation/expressions/AstForLambdasCreator.scala +++ b/joern-cli/frontends/javasrc2cpg/src/main/scala/io/joern/javasrc2cpg/astcreation/expressions/AstForLambdasCreator.scala @@ -302,19 +302,13 @@ private[expressions] trait AstForLambdasCreator { this: AstCreator => val bindingsToLocals = defineCapturedVariables(lambdaMethodName, capturedVariables) val capturedLocalAsts = bindingsToLocals.map(_._2).map(Ast(_)) val closureBindingEntries = bindingsToLocals.map(_._1) + val temporaryLocalAsts = scope.enclosingMethod.map(_.getTemporaryLocals).getOrElse(Nil).map(Ast(_)) - body match { - case block: BlockStmt => - val blockAst = Ast(blockNode(block)) - .withChildren(capturedLocalAsts) - .withChildren(stmts) - LambdaBody(blockAst, closureBindingEntries) - case stmt => - val blockAst = Ast(blockNode(stmt)) - .withChildren(capturedLocalAsts) - .withChildren(stmts) - LambdaBody(blockAst, closureBindingEntries) - } + val blockAst = Ast(blockNode(body)) + .withChildren(temporaryLocalAsts) + .withChildren(capturedLocalAsts) + .withChildren(stmts) + LambdaBody(blockAst, closureBindingEntries) } private def genericParamTypeMapForLambda(expectedType: ExpectedType): ResolvedTypeParametersMap = { diff --git a/joern-cli/frontends/javasrc2cpg/src/test/scala/io/joern/javasrc2cpg/querying/PatternExprTests.scala b/joern-cli/frontends/javasrc2cpg/src/test/scala/io/joern/javasrc2cpg/querying/PatternExprTests.scala index ba29c0f6def6..944590d5ca5e 100644 --- a/joern-cli/frontends/javasrc2cpg/src/test/scala/io/joern/javasrc2cpg/querying/PatternExprTests.scala +++ b/joern-cli/frontends/javasrc2cpg/src/test/scala/io/joern/javasrc2cpg/querying/PatternExprTests.scala @@ -18,6 +18,22 @@ import io.shiftleft.semanticcpg.language.* class PatternExprTests extends JavaSrcCode2CpgFixture { + "a pattern initializer in a lambda method" should { + val cpg = code(""" + |import java.util.function.Function; + | + |class Foo { + | Function test() { + | return o -> foo() instanceof String s ? s : null; + | } + |} + |""".stripMargin) + + "not create any orphan locals" in { + cpg.local.exists(_._astIn.isEmpty) shouldBe false + } + } + "a type pattern in an expression in an explicit constructor" should { val cpg = code(""" |class Test {