amber-lang / amber

💎 Amber the programming language compiled to Bash
https://amber-lang.com
GNU General Public License v3.0
3.94k stars 89 forks source link

[Feature] Status type #193

Open kosorin opened 5 months ago

kosorin commented 5 months ago

One of the core feature is error handling (failed clause). It would be nice to have named status codes. I think of it as a C# enum. Basically they are just integer constants (Num without fractional part).

Example:

// 7za https://man.archlinux.org/man/7za.1.en#DIAGNOSTICS
status L7zaStatus { // Pascal case as other Amber types
  Success = 0,
  Warning = 1,
  Fatal = 2,
  BadCommandLineParameters = 7,
  NotEnoughMemory = 8,
  UserCancel = 255,
}

main {
    let archive = "path/to/archive.7z"
    $7za x {archive}$? failed {
        if {
            status == L7zaStatus.UserCancel {
                echo "user canceled "
            }
            // ... other exit codes...
            else {
                echo "unknown error {status}"
            }
        }
    }
}

They can be defined in library (pub + import):

// lib.ab
pub status Foo {
...
}

// app.ab
import { Foo } from "lib.ab"

EDIT:

Function could somehow specify its status type:

fun foo_bar(a: Num, b: Num) -> Num fail L7zaStatus {
   // ...
   fail L7zaStatus.Fatal
}

foo_bar(1, 2) failed {
  if status == L7zaStatus.Fatal { // <-- code completion in IDE provides list of L7zaStatus items
    // ...
  }
  if status == 42 {} // <-- it is ok to use Num
}
arapower commented 5 months ago

It may be possible to consider it if the Dictionary Data Type discussed here is implemented.