aiken-lang / aiken

A modern smart contract platform for Cardano
https://aiken-lang.org
Apache License 2.0
396 stars 82 forks source link

Soft casting with `if/is` #959

Closed rvcas closed 1 month ago

rvcas commented 1 month ago

closes #889

This PR introduces a long awaited feature that I have started calling soft casting.

The main idea is that there are many different payloads of type Data that one may encounter which may not necessarily fit into one big enum style type in Aiken. We needed a syntax that would allow people to check if something is of a certain type or otherwise do something else. Given the conditional nature of this we decided it would make sense to enhance the existing if expressions to be able to attempt casting but without returning an error by using the provided else instead.

CleanShot 2024-06-11 at 19 56 49@2x

CleanShot 2024-06-11 at 19 59 36@2x

Unit tests within aiken passing

test if_soft_cast() {
  let d: Data = Foo { a: 1 }

  if d is Foo {
    d.a == 1
  } else {
    False
  }
}

test if_soft_cast_2() {
  let d: Data = Bazz(1)

  if d is Foo {
    d.a == 1
  } else if d is Bazz(y): Bar {
    y == 1
  } else {
    False
  }
}

test if_soft_cast_3() {
  let d: Data = Bazz(1)
  let x: Data = Buzz(2)

  if d is Foo {
    d.a == 1
  } else if d is Bazz(y): Bar {
    y == 1
  } else if x is Buzz(y): Bar {
    y == 2
  } else {
    False
  }
}

CleanShot 2024-06-11 at 20 03 35@2x