Add Result

Adds a direct translation of Rust's Result type, for later use in BuildHIR and 
possibly other passes
This commit is contained in:
Lauren Tan committed 2023-01-12 19:35:20 -05:00
1 parent 325987d744
commit 73f09248fb
2 files changed
+374

No files matched your search

@@ -0,0 +1,130 @@
import { Err, Ok, Result } from "../lib/Result";
function addMax10(a: number, b: number): Result<number, string> {
const n = a + b;
return n > 10 ? Err(`${n} is too high`) : Ok(n);
}
function onlyFoo(foo: string): Result<string, string> {
return foo === "foo" ? Ok(foo) : Err(foo);
}
describe("Result", () => {
test(".map", () => {
expect(addMax10(1, 1).map((n) => n * 2)).toEqual(Ok(4));
expect(addMax10(10, 10).map((n) => n * 2)).toEqual(Err("20 is too high"));
});
test(".mapErr", () => {
expect(addMax10(1, 1).mapErr((e) => `not a number: ${e}`)).toEqual(Ok(2));
expect(addMax10(10, 10).mapErr((e) => `couldn't add: ${e}`)).toEqual(
Err("couldn't add: 20 is too high")
);
});
test(".mapOr", () => {
expect(onlyFoo("foo").mapOr(42, (v) => v.length)).toEqual(3);
expect(onlyFoo("bar").mapOr(42, (v) => v.length)).toEqual(42);
});
test(".mapOrElse", () => {
expect(
onlyFoo("foo").mapOrElse(
() => 42,
(v) => v.length
)
).toEqual(3);
expect(
onlyFoo("bar").mapOrElse(
() => 42,
(v) => v.length
)
).toEqual(42);
});
test(".andThen", () => {
expect(addMax10(1, 1).andThen((n) => Ok(n * 2))).toEqual(Ok(4));
expect(addMax10(10, 10).andThen((n) => Ok(n * 2))).toEqual(
Err("20 is too high")
);
});
test(".and", () => {
expect(addMax10(1, 1).and(Ok(4))).toEqual(Ok(4));
expect(addMax10(10, 10).and(Ok(4))).toEqual(Err("20 is too high"));
expect(addMax10(1, 1).and(Err("hehe"))).toEqual(Err("hehe"));
expect(addMax10(10, 10).and(Err("hehe"))).toEqual(Err("20 is too high"));
});
test(".or", () => {
expect(addMax10(1, 1).or(Ok(4))).toEqual(Ok(2));
expect(addMax10(10, 10).or(Ok(4))).toEqual(Ok(4));
expect(addMax10(1, 1).or(Err("hehe"))).toEqual(Ok(2));
expect(addMax10(10, 10).or(Err("hehe"))).toEqual(Err("hehe"));
});
test(".orElse", () => {
expect(addMax10(1, 1).orElse((str) => Err(str.toUpperCase()))).toEqual(
Ok(2)
);
expect(addMax10(10, 10).orElse((str) => Err(str.toUpperCase()))).toEqual(
Err("20 IS TOO HIGH")
);
});
test(".isOk", () => {
expect(addMax10(1, 1).isOk()).toBeTruthy();
expect(addMax10(10, 10).isOk()).toBeFalsy();
});
test(".isErr", () => {
expect(addMax10(1, 1).isErr()).toBeFalsy();
expect(addMax10(10, 10).isErr()).toBeTruthy();
});
test(".expect", () => {
expect(addMax10(1, 1).expect("a number under 10")).toEqual(2);
expect(() => {
addMax10(10, 10).expect("a number under 10");
}).toThrowErrorMatchingInlineSnapshot(
`"a number under 10: 20 is too high"`
);
});
test(".expectErr", () => {
expect(() => {
addMax10(1, 1).expectErr("a number under 10");
}).toThrowErrorMatchingInlineSnapshot(`"a number under 10: 2"`);
expect(addMax10(10, 10).expectErr("a number under 10")).toEqual(
"20 is too high"
);
});
test(".unwrap", () => {
expect(addMax10(1, 1).unwrap()).toEqual(2);
expect(() => {
addMax10(10, 10).unwrap();
}).toThrowErrorMatchingInlineSnapshot(
`"Can't unwrap \`Err\` to \`Ok\`: 20 is too high"`
);
});
test(".unwrapOr", () => {
expect(addMax10(1, 1).unwrapOr(4)).toEqual(2);
expect(addMax10(10, 10).unwrapOr(4)).toEqual(4);
});
test(".unwrapOrElse", () => {
expect(addMax10(1, 1).unwrapOrElse(() => 4)).toEqual(2);
expect(addMax10(10, 10).unwrapOrElse((s) => s.length)).toEqual(14);
});
test(".unwrapErr", () => {
expect(() => {
addMax10(1, 1).unwrapErr();
}).toThrowErrorMatchingInlineSnapshot(
`"Can't unwrap \`Ok\` to \`Err\`: 2"`
);
expect(addMax10(10, 10).unwrapErr()).toEqual("20 is too high");
});
});
+244
View File
@@ -0,0 +1,244 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Direct translation of Rust's Result type, although some ownership related methods are omitted.
export interface Result<T, E> {
/**
* Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a contained `Ok` value,
* leaving an `Err` value untouched.
*
* This function can be used to compose the results of two functions.
*/
map<U>(fn: (val: T) => U): Result<U, E>;
/**
* Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a contained `Err` value,
* leaving an `Ok` value untouched.
*
* This function can be used to pass through a successful result while handling an error.
*/
mapErr<F>(fn: (val: E) => F): Result<T, F>;
/**
* Returns the provided default (if `Err`), or applies a function to the contained value
* (if `Ok`).
*
* Arguments passed to {@link mapOr} are eagerly evaluated; if you are passing the result of a
* function call, it is recommended to use {@link mapOrElse}, which is lazily evaluated.
*/
mapOr<U>(fallback: U, fn: (val: T) => U): U;
/**
* Maps a `Result<T, E>` to `U` by applying fallback function default to a contained `Err` value,
* or function `fn` to a contained `Ok` value.
*
* This function can be used to unpack a successful result while handling an error.
*/
mapOrElse<U>(fallback: () => U, fn: (val: T) => U): U;
/**
* Calls `fn` if the result is `Ok`, otherwise returns the `Err` value of self.
*
* This function can be used for control flow based on Result values.
*/
andThen<U>(fn: (val: T) => Result<U, E>): Result<U, E>;
/**
* Returns res if the result is `Ok`, otherwise returns the `Err` value of self.
*
* Arguments passed to {@link and} are eagerly evaluated; if you are passing the result of a
* function call, it is recommended to use {@link andThen}, which is lazily evaluated.
*/
and<U>(res: Result<U, E>): Result<U, E>;
/**
* Returns `res` if the result is `Err`, otherwise returns the `Ok` value of self.
*
* Arguments passed to {@link or} are eagerly evaluated; if you are passing the result of a
* function call, it is recommended to use {@link orElse}, which is lazily evaluated.
*/
or(res: Result<T, E>): Result<T, E>;
/**
* Calls `fn` if the result is `Err`, otherwise returns the `Ok` value of self.
*
* This function can be used for control flow based on result values.
*/
orElse<F>(fn: (val: E) => Result<T, F>): Result<T, F>;
/**
* Returns `true` if the result is `Ok`.
*/
isOk(): this is OkImpl<T>;
/**
* Returns `true` if the result is `Err`.
*/
isErr(): this is ErrImpl<E>;
/**
* Returns the contained `Ok` value or throws.
*/
expect(msg: string): T;
/**
* Returns the contained `Err` value or throws.
*/
expectErr(msg: string): E;
/**
* Returns the contained `Ok` value.
*/
unwrap(): T;
/**
* Returns the contained `Ok` value or a provided default.
*
* Arguments passed to {@link unwrapOr} are eagerly evaluated; if you are passing the result of a
* function call, it is recommended to use {@link unwrapOrElse}, which is lazily evaluated.
*/
unwrapOr(fallback: T): T;
/**
* Returns the contained `Ok` value or computes it from a closure.
*/
unwrapOrElse(fallback: (val: E) => T): T;
/**
* Returns the contained `Err` value or throws.
*/
unwrapErr(): E;
}
export function Ok<T>(val: T): OkImpl<T> {
return new OkImpl(val);
}
class OkImpl<T> implements Result<T, never> {
constructor(private val: T) {}
map<U>(fn: (val: T) => U): Result<U, never> {
return new OkImpl(fn(this.val));
}
mapErr<F>(_fn: (val: never) => F): Result<T, F> {
return this;
}
mapOr<U>(_fallback: U, fn: (val: T) => U): U {
return fn(this.val);
}
mapOrElse<U>(_fallback: () => U, fn: (val: T) => U): U {
return fn(this.val);
}
andThen<U>(fn: (val: T) => Result<U, never>): Result<U, never> {
return fn(this.val);
}
and<U>(res: Result<U, never>): Result<U, never> {
return res;
}
or(_res: Result<T, never>): Result<T, never> {
return this;
}
orElse<F>(_fn: (val: never) => Result<T, F>): Result<T, F> {
return this;
}
isOk(): boolean {
return true;
}
isErr(): boolean {
return false;
}
expect(_msg: string): T {
return this.val;
}
expectErr(msg: string): never {
throw new Error(`${msg}: ${this.val}`);
}
unwrap(): T {
return this.val;
}
unwrapOr(_fallback: T): T {
return this.val;
}
unwrapOrElse(_fallback: (val: never) => T): T {
return this.val;
}
unwrapErr(): never {
throw new Error(`Can't unwrap \`Ok\` to \`Err\`: ${this.val}`);
}
}
export function Err<E>(val: E): ErrImpl<E> {
return new ErrImpl(val);
}
class ErrImpl<E> implements Result<never, E> {
constructor(private val: E) {}
map<U>(_fn: (val: never) => U): Result<U, E> {
return this;
}
mapErr<F>(fn: (val: E) => F): Result<never, F> {
return new ErrImpl(fn(this.val));
}
mapOr<U>(fallback: U, _fn: (val: never) => U): U {
return fallback;
}
mapOrElse<U>(fallback: () => U, _fn: (val: never) => U): U {
return fallback();
}
andThen<U>(_fn: (val: never) => Result<U, E>): Result<U, E> {
return this;
}
and<U>(_res: Result<U, E>): Result<U, E> {
return this;
}
or(res: Result<never, E>): Result<never, E> {
return res;
}
orElse<F>(fn: (val: E) => ErrImpl<F>): Result<never, F> {
return fn(this.val);
}
isOk(): boolean {
return false;
}
isErr(): boolean {
return true;
}
expect(msg: string): never {
throw new Error(`${msg}: ${this.val}`);
}
expectErr(_msg: string): E {
return this.val;
}
unwrap(): never {
throw new Error(`Can't unwrap \`Err\` to \`Ok\`: ${this.val}`);
}
unwrapOr<T>(fallback: T): T {
return fallback;
}
unwrapOrElse<T>(fallback: (val: E) => T): T {
return fallback(this.val);
}
unwrapErr(): E {
return this.val;
}
}