Skip to content

Commit

Permalink
Optimize if-matches case (#1193)
Browse files Browse the repository at this point in the history
  • Loading branch information
johnynek authored Apr 1, 2024
1 parent 7be2aa4 commit 2394596
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions core/src/main/scala/org/bykn/bosatsu/SourceConverter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,31 @@ final class SourceConverter(
else RecursionKind.NonRecursive
Expr.Let(boundName, lam, in, recursive = rec, decl)
}
case IfElse(NonEmptyList((Matches(a, p), res), tail), elseCase) if p.names.isEmpty =>
// if x matches p: res
// else: elseCase
// same as: match x:
// case p: res
// case _: elseCase
//
// we filter on p.names.isEmpty to ensure this is valid, if it isn't valid
// we want to give the most localized version of Matches to the unusued
// let checker to give the best error message.
val restDecl: OptIndent[Declaration] =
NonEmptyList.fromList(tail) match {
case None => elseCase
case Some(nel) =>
val restRegion = nel.map(_._2.get.region).reduce[Region](_ + _)
// keep the OptIndent from the first item
nel.head._2.map(_ => IfElse(nel, elseCase)(restRegion))
}
loop(Match(
RecursionKind.NonRecursive,
a,
OptIndent.same(NonEmptyList(
(p, res),
(Pattern.WildCard, restDecl) :: Nil
)))(decl.region))
case IfElse(ifCases, elseCase) =>
def loop0(
ifs: NonEmptyList[(Expr[Declaration], Expr[Declaration])],
Expand Down
16 changes: 16 additions & 0 deletions core/src/test/scala/org/bykn/bosatsu/EvaluationTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4004,4 +4004,20 @@ external def foo[b](lst: List[a]) -> a
()
}
}

test("test nested if matches") {
runBosatsuTest(
List("""
package Foo
export fn
def fn(x):
if x matches True: False
elif x matches False: True
else: False
test = Assertion(fn(False), "")
"""), "Foo", 1)
}
}

0 comments on commit 2394596

Please sign in to comment.