From 662335e91ab72e3e85a2f952108fa852ed95199e Mon Sep 17 00:00:00 2001 From: "Sean T. Allen" Date: Tue, 6 Feb 2024 20:49:41 +0000 Subject: [PATCH] Add constrained_types package to the standard library Implements RFC 79. https://github.com/ponylang/rfcs/blob/main/text/0079-constrained-types.md Closes #4492 --- packages/constrained_types/_test.pony | 8 +++++ packages/constrained_types/constrained.pony | 37 +++++++++++++++++++++ packages/stdlib/_test.pony | 2 ++ 3 files changed, 47 insertions(+) create mode 100644 packages/constrained_types/_test.pony create mode 100644 packages/constrained_types/constrained.pony diff --git a/packages/constrained_types/_test.pony b/packages/constrained_types/_test.pony new file mode 100644 index 0000000000..bf321783a1 --- /dev/null +++ b/packages/constrained_types/_test.pony @@ -0,0 +1,8 @@ +use "pony_test" + +actor \nodoc\ Main is TestList + new create(env: Env) => PonyTest(env, this) + new make() => None + + fun tag tests(test: PonyTest) => + None diff --git a/packages/constrained_types/constrained.pony b/packages/constrained_types/constrained.pony new file mode 100644 index 0000000000..ef1495eaab --- /dev/null +++ b/packages/constrained_types/constrained.pony @@ -0,0 +1,37 @@ +type ValidationResult is (ValidationSuccess | ValidationFailure) + +primitive ValidationSuccess + +class val ValidationFailure + let _errors: Array[String val] = _errors.create() + + new create(e: (String val | None) = None) => + match e + | let s: String val => _errors.push(s) + end + + fun ref apply(e: String val) => + _errors.push(e) + + fun errors(): this->Array[String val] => + _errors + +interface val Validator[T] + new val create() + fun apply(i: T): ValidationResult + +class val Constrained[T: Any val, F: Validator[T]] + let _value: T val + + new val _create(value: T val) => + _value = value + + fun val apply(): T val => + _value + +primitive MakeConstrained[T: Any val, F: Validator[T] val] + fun apply(value: T): (Constrained[T, F] | ValidationFailure) => + match F(value) + | ValidationSuccess => Constrained[T, F]._create(value) + | let e: ValidationFailure => e + end diff --git a/packages/stdlib/_test.pony b/packages/stdlib/_test.pony index 880538ddc4..e7323fe230 100644 --- a/packages/stdlib/_test.pony +++ b/packages/stdlib/_test.pony @@ -24,6 +24,7 @@ use capsicum = "capsicum" use cli = "cli" use collections = "collections" use collections_persistent = "collections/persistent" +use constrained_types = "constrained_types" use debug = "debug" use files = "files" use format = "format" @@ -57,6 +58,7 @@ actor \nodoc\ Main is TestList cli.Main.make().tests(test) collections.Main.make().tests(test) collections_persistent.Main.make().tests(test) + constrained_types.Main.make().tests() files.Main.make().tests(test) format.Main.make().tests(test) ini.Main.make().tests(test)