Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1775,15 +1775,24 @@ trait RustVisitor(implicit withSchemaValidation: ValidationMode) { this: AstCrea
Ast(blockNode(matchExpr)).withChildren(Seq(tmpLocalAst, tmpAssignAst, matchExprAst))
}

// TODO: handle guards.
private def lowerMatchArm(matchArm: MatchArm, tmpIdentAst: () => Ast): Seq[Ast] = {
val bindingAsts = createLocalsForBindings(collectPatternBindings(matchArm.pat)) ++ createAssignmentsForPattern(
matchArm.pat,
tmpIdentAst
)
val bodyAst = visitExpr(matchArm.expr)
val bodyAst = matchArm.matchGuard match {
case Some(matchGuard) =>
val conditionAst = visitExpr(matchGuard.expr)
ifThenElseAst(matchGuard, Some(conditionAst), visitExpr(matchArm.expr), None)
case None =>
visitExpr(matchArm.expr)
}
val caseCode = matchArm.matchGuard match {
case Some(matchGuard) => s"${code(matchArm.pat)} ${code(matchGuard)}"
case None => code(matchArm.pat)
}
val matchArmBlock = blockAst(blockNode(matchArm), (bindingAsts :+ bodyAst).toList)
val jumpTargetAst = Ast(jumpTargetNode(matchArm.pat, s"case ${code(matchArm.pat)}", code(matchArm.pat)))
val jumpTargetAst = Ast(jumpTargetNode(matchArm.pat, s"case $caseCode", caseCode))
Seq(jumpTargetAst, matchArmBlock)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,49 @@ class MatchTests extends Rust2CpgSuite(noSysRoot = true) {
}
}

"match with guards" should {
val cpg = code("""
|fn foo(x: (i32, i32)) {
| match x {
| (n, _) if n > 3 => bar(n),
| _ if baz() => qux(),
| _ => 0,
| };
|}
|""".stripMargin)

"have correct jump target names" in {
cpg.jumpTarget.sortBy(_.order).name.l shouldBe List("case (n, _) if n > 3", "case _ if baz()", "case _")
}

"have correct locals" in {
inside(cpg.local.sortBy(_.order).l) { case tmp :: nLocal :: Nil =>
tmp.name shouldBe "<tmp>0"
tmp.typeFullName shouldBe "(i32, i32)"
nLocal.name shouldBe "n"
nLocal.typeFullName shouldBe "i32"
}
}

"have correct local assignments" in {
cpg.method.nameExact("foo").block.assignment.sortBy(_.order).code.l shouldBe List("<tmp>0 = x", "n = <tmp>0.0")
}

"have correct if control structures" in {
inside(cpg.ifBlock.sortBy(_.lineNumber).l) { case guard1 :: guard2 :: Nil =>
guard1.code shouldBe "if n > 3"
guard1.condition.code.l shouldBe List("n > 3")
guard1.whenTrue.code.l shouldBe List("bar(n)")
guard1.whenFalse shouldBe empty

guard2.code shouldBe "if baz()"
guard2.condition.code.l shouldBe List("baz()")
guard2.whenTrue.code.l shouldBe List("qux()")
guard2.whenFalse shouldBe empty
}
}
}

"match with an or-pattern case" should {
val cpg = code("""
|struct Point { x: i32, y: i32 }
Expand Down
Loading