diff --git a/jscomp/ext/config.ml b/jscomp/ext/config.ml index 35040eaa5a..934b5a9166 100644 --- a/jscomp/ext/config.ml +++ b/jscomp/ext/config.ml @@ -14,7 +14,7 @@ let bs_only = ref true let unsafe_empty_array = ref false type uncurried = Legacy | Uncurried | Swap -let uncurried = ref Legacy +let uncurried = ref Uncurried and cmi_magic_number = "Caml1999I022" diff --git a/jscomp/others/js_array.res b/jscomp/others/js_array.res index caf332fdc4..ff469e92cb 100644 --- a/jscomp/others/js_array.res +++ b/jscomp/others/js_array.res @@ -99,7 +99,7 @@ let code = s => Js.String.charCodeAt(0, s) Js.Array.fromMap(strArr, code) == [97.0, 98.0, 99.0, 100.0] ``` */ -external fromMap: (array_like<'a>, @uncurry ('a => 'b)) => array<'b> = "Array.from" +external fromMap: (array_like<'a>, ('a => 'b)) => array<'b> = "Array.from" /* ES2015 */ @@ -127,7 +127,7 @@ external length: array<'a> => int = "length" /* Mutator functions */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Copies from the first element in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN. @@ -143,7 +143,7 @@ external copyWithin: (~to_: int) => 'this = "copyWithin" /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Copies starting at element `~from` in the given array to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN. @@ -159,7 +159,7 @@ external copyWithinFrom: (~to_: int, ~from: int) => 'this = "copyWithin" /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Copies starting at element `~start` in the given array up to but not including `~end_` to the designated `~to_` position, returning the resulting array. *This function modifies the original array.* See [`Array.copyWithin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) on MDN. @@ -175,7 +175,7 @@ external copyWithinFromRange: (~to_: int, ~start: int, ~end_: int) => 'this = "c /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Sets all elements of the given array (the second arumgent) to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. @@ -191,7 +191,7 @@ external fillInPlace: 'a => 'this = "fill" /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Sets all elements of the given array (the last arumgent) from position `~from` to the end to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. @@ -207,7 +207,7 @@ external fillFromInPlace: ('a, ~from: int) => 'this = "fill" /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Sets the elements of the given array (the last arumgent) from position `~start` up to but not including position `~end_` to the designated value (the first argument), returning the resulting array. *This function modifies the original array.* See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. @@ -223,8 +223,8 @@ external fillRangeInPlace: ('a, ~start: int, ~end_: int) => 'this = "fill" /* ES2015 */ -@bs.send.pipe(: t<'a> as 'this) -@return(undefined_to_opt) +@send.pipe(: t<'a> as 'this) +@return(nullable) /** If the array is not empty, removes the last element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN. @@ -241,7 +241,7 @@ Js.Array.pop(empty) == None */ external pop: option<'a> = "pop" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Appends the given value to the array, returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN. @@ -255,7 +255,7 @@ arr == ["ant", "bee", "cat", "dog"] */ external push: 'a => int = "push" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) @variadic /** Appends the values from one array (the first argument) to another (the second argument), returning the number of elements in the updated array. *This function modifies the original array.* See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN. @@ -270,7 +270,7 @@ arr == ["ant", "bee", "cat", "dog", "elk"] */ external pushMany: array<'a> => int = "push" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns an array with the elements of the input array in reverse order. *This function modifies the original array.* See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN. @@ -284,8 +284,8 @@ arr == ["cat", "bee", "ant"] */ external reverseInPlace: 'this = "reverse" -@bs.send.pipe(: t<'a> as 'this) -@return({undefined_to_opt: undefined_to_opt}) +@send.pipe(: t<'a> as 'this) +@return(nullable) /** If the array is not empty, removes the first element and returns it as `Some(value)`; returns `None` if the array is empty. *This function modifies the original array.* See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN. @@ -302,7 +302,7 @@ Js.Array.shift(empty) == None */ external shift: option<'a> = "shift" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Sorts the given array in place and returns the sorted array. JavaScript sorts the array by converting the arguments to UTF-16 strings and sorting them. See the second example with sorting numbers, which does not do a numeric sort. *This function modifies the original array.* See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN. @@ -320,7 +320,7 @@ numbers == [1, 10, 2, 20, 3, 30] */ external sortInPlace: 'this = "sort" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Sorts the given array in place and returns the sorted array. *This function modifies the original array.* @@ -347,9 +347,9 @@ let reverseNumeric = (n1, n2) => n2 - n1 Js.Array.sortInPlaceWith(reverseNumeric, numbers) == [30, 20, 10, 3, 2, 1] ``` */ -external sortInPlaceWith: (@uncurry ('a, 'a) => int) => 'this = "sort" +external sortInPlaceWith: (('a, 'a) => int) => 'this = "sort" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) @variadic /** Starting at position `~pos`, remove `~remove` elements and then add the @@ -376,7 +376,7 @@ arr3 == ["a", "b", "c", "d", "e", "f", "x", "y", "z"] */ external spliceInPlace: (~pos: int, ~remove: int, ~add: array<'a>) => 'this = "splice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Removes elements from the given array starting at position `~pos` to the end of the array, returning the removed elements. *This function modifies the @@ -394,7 +394,7 @@ arr == ["a", "b", "c", "d"] */ external removeFromInPlace: (~pos: int) => 'this = "splice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Removes `~count` elements from the given array starting at position `~pos`, returning the removed elements. *This function modifies the original array.* @@ -412,7 +412,7 @@ arr == ["a", "b", "f"] */ external removeCountInPlace: (~pos: int, ~count: int) => 'this = "splice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Adds the given element to the array, returning the new number of elements in the array. *This function modifies the original array.* See @@ -429,7 +429,7 @@ arr == ["a", "b", "c", "d"] */ external unshift: 'a => int = "unshift" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) @variadic /** Adds the elements in the first array argument at the beginning of the second @@ -450,7 +450,7 @@ external unshiftMany: array<'a> => int = "unshift" /* Accessor functions */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Concatenates the first array argument to the second array argument, returning a new array. The original arrays are not modified. See @@ -465,7 +465,7 @@ Js.Array.concat(["c", "d", "e"], ["a", "b"]) == ["a", "b", "c", "d", "e"] */ external concat: 'this => 'this = "concat" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) @variadic /** The first argument to `concatMany()` is an array of arrays; these are added @@ -491,7 +491,7 @@ Js.Array.concatMany([["d", "e"], ["f", "g", "h"]], ["a", "b", "c"]) == [ external concatMany: array<'this> => 'this = "concat" /* ES2016 */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns true if the given value is in the array, `false` otherwise. See [`Array.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) @@ -506,7 +506,7 @@ Js.Array.includes("x", ["a", "b", "c"]) == false */ external includes: 'a => bool = "includes" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns the index of the first element in the array that has the given value. If the value is not in the array, returns -1. See @@ -522,7 +522,7 @@ Js.Array.indexOf(999, [100, 101, 102, 103]) == -1 */ external indexOf: 'a => int = "indexOf" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns the index of the first element in the array with the given value. The search starts at position `~from`. See @@ -542,7 +542,7 @@ external indexOfFrom: ('a, ~from: int) => int = "indexOf" @send @deprecated("please use joinWith instead") external join: t<'a> => string = "join" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** This function converts each element of the array to a string (via JavaScript) and concatenates them, separated by the string given in the first argument, @@ -561,7 +561,7 @@ Js.Array.joinWith(";", [2.5, 3.6, 3e-2]) == "2.5;3.6;0.03" */ external joinWith: string => string = "join" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns the index of the last element in the array that has the given value. If the value is not in the array, returns -1. See @@ -577,7 +577,7 @@ Js.Array.lastIndexOf("x", ["a", "b", "a", "c"]) == -1 */ external lastIndexOf: 'a => int = "lastIndexOf" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns the index of the last element in the array that has the given value, searching from position `~from` down to the start of the array. If the value @@ -594,7 +594,7 @@ Js.Array.lastIndexOfFrom("c", ~from=2, ["a", "b", "a", "c", "a", "d"]) == -1 */ external lastIndexOfFrom: ('a, ~from: int) => int = "lastIndexOf" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns a shallow copy of the given array from the `~start` index up to but not including the `~end_` position. Negative numbers indicate an offset from @@ -613,7 +613,7 @@ Js.Array.slice(~start=9, ~end_=10, arr) == [] */ external slice: (~start: int, ~end_: int) => 'this = "slice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns a copy of the entire array. Same as `Js.Array.Slice(~start=0, ~end_=Js.Array.length(arr), arr)`. See @@ -622,7 +622,7 @@ on MDN. */ external copy: 'this = "slice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns a shallow copy of the given array from the given index to the end. See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN. @@ -635,7 +635,7 @@ Js.Array.sliceFrom(2, [100, 101, 102, 103, 104]) == [102, 103, 104] */ external sliceFrom: int => 'this = "slice" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Converts the array to a string. Each element is converted to a string using JavaScript. Unlike the JavaScript `Array.toString()`, all elements in a @@ -652,7 +652,7 @@ Js.Array.toString(["a", "b", "c"]) == "a,b,c" */ external toString: string = "toString" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Converts the array to a string using the conventions of the current locale. Each element is converted to a string using JavaScript. Unlike the JavaScript @@ -674,10 +674,10 @@ external toLocaleString: string = "toLocaleString" /* Iteration functions */ /* commented out until bs has a plan for iterators - external entries : (int * 'a) array_iter = "" [@@bs.send.pipe: 'a t as 'this] (* ES2015 *) + external entries : (int * 'a) array_iter = "" [@@send.pipe: 'a t as 'this] (* ES2015 *) */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The first argument to `every()` is a predicate function that returns a boolean. The `every()` function returns `true` if the predicate function is true for all items in the given array. If given an empty array, returns `true`. See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN. @@ -689,9 +689,9 @@ Js.Array.every(isEven, [6, 22, 8, 4]) == true Js.Array.every(isEven, [6, 22, 7, 4]) == false ``` */ -external every: (@uncurry ('a => bool)) => bool = "every" +external every: (('a => bool)) => bool = "every" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The first argument to `everyi()` is a predicate function with two arguments: an array element and that element’s index; it returns a boolean. The `everyi()` function returns `true` if the predicate function is true for all items in the given array. If given an empty array, returns `true`. See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN. @@ -705,9 +705,9 @@ Js.Array.everyi(evenIndexPositive, [6, -3, 5, 8]) == true Js.Array.everyi(evenIndexPositive, [6, 3, -5, 8]) == false ``` */ -external everyi: (@uncurry ('a, int) => bool) => bool = "every" +external everyi: (('a, int) => bool) => bool = "every" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Applies the given predicate function to each element in the array; the result is an array of those elements for which the predicate function returned `true`. See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN. @@ -718,9 +718,9 @@ let nonEmpty = s => s != "" Js.Array.filter(nonEmpty, ["abc", "", "", "def", "ghi"]) == ["abc", "def", "ghi"] ``` */ -external filter: (@uncurry ('a => bool)) => 'this = "filter" +external filter: (('a => bool)) => 'this = "filter" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Each element of the given array are passed to the predicate function. The return value is an array of all those elements for which the predicate @@ -737,10 +737,10 @@ let positiveOddElement = (item, index) => mod(index, 2) == 1 && item > 0 Js.Array.filteri(positiveOddElement, [6, 3, 5, 8, 7, -4, 1]) == [3, 8] ``` */ -external filteri: (@uncurry ('a, int) => bool) => 'this = "filter" +external filteri: (('a, int) => bool) => 'this = "filter" -@bs.send.pipe(: t<'a> as 'this) -@return({undefined_to_opt: undefined_to_opt}) +@send.pipe(: t<'a> as 'this) +@return(nullable) /** Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. @@ -756,10 +756,10 @@ Js.Array.find(x => x < 0, [33, 22, -55, 77, -44]) == Some(-55) Js.Array.find(x => x < 0, [33, 22, 55, 77, 44]) == None ``` */ -external find: (@uncurry ('a => bool)) => option<'a> = "find" +external find: (('a => bool)) => option<'a> = "find" -@bs.send.pipe(: t<'a> as 'this) -@return({undefined_to_opt: undefined_to_opt}) +@send.pipe(: t<'a> as 'this) +@return(nullable) /** Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN. @@ -773,9 +773,9 @@ Js.Array.findi(positiveOddElement, [66, -33, 55, 88, 22]) == Some(88) Js.Array.findi(positiveOddElement, [66, -33, 55, -88, 22]) == None ``` */ -external findi: (@uncurry ('a, int) => bool) => option<'a> = "find" +external findi: (('a, int) => bool) => option<'a> = "find" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns the index of the first element in the array that satisifies the given predicate function, or -1 if no element satisifies the predicate. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN. @@ -786,9 +786,9 @@ Js.Array.findIndex(x => x < 0, [33, 22, -55, 77, -44]) == 2 Js.Array.findIndex(x => x < 0, [33, 22, 55, 77, 44]) == -1 ``` */ -external findIndex: (@uncurry ('a => bool)) => int = "findIndex" +external findIndex: (('a => bool)) => int = "findIndex" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns `Some(value)` for the first element in the array that satisifies the given predicate function, or `None` if no element satisifies the predicate. The predicate function takes an array element and an index as its parameters. See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN. @@ -802,9 +802,9 @@ Js.Array.findIndexi(positiveOddElement, [66, -33, 55, 88, 22]) == 3 Js.Array.findIndexi(positiveOddElement, [66, -33, 55, -88, 22]) == -1 ``` */ -external findIndexi: (@uncurry ('a, int) => bool) => int = "findIndex" +external findIndexi: (('a, int) => bool) => int = "findIndex" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `forEach()` function applies the function given as the first argument to each element in the array. The function you provide returns `unit`, and the `forEach()` function also returns `unit`. You use `forEach()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN. @@ -815,9 +815,9 @@ The `forEach()` function applies the function given as the first argument to eac Js.Array.forEach(x => Js.log(x), ["a", "b", "c"]) == () ``` */ -external forEach: (@uncurry ('a => unit)) => unit = "forEach" +external forEach: (('a => unit)) => unit = "forEach" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `forEachi()` function applies the function given as the first argument to each element in the array. The function you provide takes an item in the array and its index number, and returns `unit`. The `forEachi()` function also returns `unit`. You use `forEachi()` when you need to process each element in the array but not return any new array or value; for example, to print the items in an array. See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN. @@ -828,13 +828,13 @@ The `forEachi()` function applies the function given as the first argument to ea Js.Array.forEachi((item, index) => Js.log2(index + 1, item), ["a", "b", "c"]) == () ``` */ -external forEachi: (@uncurry ('a, int) => unit) => unit = "forEach" +external forEachi: (('a, int) => unit) => unit = "forEach" /* commented out until bs has a plan for iterators - external keys : int array_iter = "" [@@bs.send.pipe: 'a t as 'this] (* ES2015 *) + external keys : int array_iter = "" [@@send.pipe: 'a t as 'this] (* ES2015 *) */ -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Applies the function (given as the first argument) to each item in the array, returning a new array. The result array does not have to have elements of the @@ -849,9 +849,9 @@ Js.Array.map(x => x * x, [12, 4, 8]) == [144, 16, 64] Js.Array.map(Js.String.length, ["animal", "vegetable", "mineral"]) == [6, 9, 7] ``` */ -external map: (@uncurry ('a => 'b)) => t<'b> = "map" +external map: (('a => 'b)) => t<'b> = "map" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Applies the function (given as the first argument) to each item in the array, returning a new array. The function acceps two arguments: an item from the @@ -868,9 +868,9 @@ let product = (item, index) => item * index Js.Array.mapi(product, [10, 11, 12]) == [0, 11, 24] ``` */ -external mapi: (@uncurry ('a, int) => 'b) => t<'b> = "map" +external mapi: (('a, int) => 'b) => t<'b> = "map" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `reduce()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two @@ -902,9 +902,9 @@ Js.Array.reduce( Js.Array.reduce((acc, item) => item /. acc, 1.0, [2.0, 4.0]) == 2.0 // 4.0 / (2.0 / 1.0) ``` */ -external reduce: (@uncurry ('b, 'a) => 'b, 'b) => 'b = "reduce" +external reduce: (('b, 'a) => 'b, 'b) => 'b = "reduce" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `reducei()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three @@ -937,9 +937,9 @@ let sumOfEvens = (accumulator, item, index) => Js.Array.reducei(sumOfEvens, 0, [2, 5, 1, 4, 3]) == 6 ``` */ -external reducei: (@uncurry ('b, 'a, int) => 'b, 'b) => 'b = "reduce" +external reducei: (('b, 'a, int) => 'b, 'b) => 'b = "reduce" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `reduceRight()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has two @@ -967,9 +967,9 @@ Js.Array.reduceRight(sumOfSquares, 0, [10, 2, 4]) == 120 Js.Array.reduceRight((acc, item) => item /. acc, 1.0, [2.0, 4.0]) == 0.5 // 2.0 / (4.0 / 1.0) ``` */ -external reduceRight: (@uncurry ('b, 'a) => 'b, 'b) => 'b = "reduceRight" +external reduceRight: (('b, 'a) => 'b, 'b) => 'b = "reduceRight" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** The `reduceRighti()` function takes three parameters: a *reducer function*, a beginning accumulator value, and an array. The reducer function has three @@ -1004,9 +1004,9 @@ let sumOfEvens = (accumulator, item, index) => Js.Array.reduceRighti(sumOfEvens, 0, [2, 5, 1, 4, 3]) == 6 ``` */ -external reduceRighti: (@uncurry ('b, 'a, int) => 'b, 'b) => 'b = "reduceRight" +external reduceRighti: (('b, 'a, int) => 'b, 'b) => 'b = "reduceRight" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns `true` if the predicate function given as the first argument to `some()` returns `true` for any element in the array; `false` otherwise. @@ -1020,9 +1020,9 @@ Js.Array.some(isEven, [3, 7, 5, 2, 9]) == true Js.Array.some(isEven, [3, 7, 5, 1, 9]) == false ``` */ -external some: (@uncurry ('a => bool)) => bool = "some" +external some: (('a => bool)) => bool = "some" -@bs.send.pipe(: t<'a> as 'this) +@send.pipe(: t<'a> as 'this) /** Returns `true` if the predicate function given as the first argument to `somei()` returns `true` for any element in the array; `false` otherwise. The @@ -1043,10 +1043,10 @@ Js.Array.somei(sameLength, ["ab", "cd", "ef", "gh"]) == true Js.Array.somei(sameLength, ["a", "bc", "def", "gh"]) == false ``` */ -external somei: (@uncurry ('a, int) => bool) => bool = "some" +external somei: (('a, int) => bool) => bool = "some" /* commented out until bs has a plan for iterators - external values : 'a array_iter = "" [@@bs.send.pipe: 'a t as 'this] (* ES2015 *) + external values : 'a array_iter = "" [@@send.pipe: 'a t as 'this] (* ES2015 *) */ /** Returns the value at the given position in the array if the position is in diff --git a/jscomp/others/js_promise.res b/jscomp/others/js_promise.res index 7268e1e37b..9c40ab1851 100644 --- a/jscomp/others/js_promise.res +++ b/jscomp/others/js_promise.res @@ -44,9 +44,7 @@ type error */ @new -external make: ((@uncurry ~resolve: (. 'a) => unit, ~reject: (. exn) => unit) => unit) => promise< - 'a, -> = "Promise" +external make: ((~resolve: 'a => unit, ~reject: exn => unit) => unit) => promise<'a> = "Promise" /* `make (fun resolve reject -> .. )` */ @val @scope("Promise") external resolve: 'a => promise<'a> = "resolve" @@ -83,10 +81,10 @@ external all6: ( @val @scope("Promise") external race: array> => promise<'a> = "race" -@bs.send.pipe(: promise<'a>) external then_: (@uncurry ('a => promise<'b>)) => promise<'b> = "then" +@bs.send.pipe(: promise<'a>) external then_: ('a => promise<'b>) => promise<'b> = "then" @bs.send.pipe(: promise<'a>) -external catch: (@uncurry (error => promise<'a>)) => promise<'a> = "catch" +external catch: (error => promise<'a>) => promise<'a> = "catch" /* ` p|> catch handler` Note in JS the returned promise type is actually runtime dependent, if promise is rejected, it will pick the `handler` otherwise the original promise, diff --git a/jscomp/others/js_promise2.res b/jscomp/others/js_promise2.res index 4fa6778aa3..5b99b9b9f4 100644 --- a/jscomp/others/js_promise2.res +++ b/jscomp/others/js_promise2.res @@ -16,9 +16,7 @@ let catch: (promise<'a>, error => promise<'a>) => promise<'a> = %raw(` `) @new -external make: ((@uncurry ~resolve: (. 'a) => unit, ~reject: (. exn) => unit) => unit) => promise< - 'a, -> = "Promise" +external make: ((~resolve: 'a => unit, ~reject: exn => unit) => unit) => promise<'a> = "Promise" @val @scope("Promise") external resolve: 'a => promise<'a> = "resolve" @val @scope("Promise") external reject: exn => promise<'a> = "reject" diff --git a/jscomp/others/js_string.res b/jscomp/others/js_string.res index 811d1b2b00..a198c9664e 100644 --- a/jscomp/others/js_string.res +++ b/jscomp/others/js_string.res @@ -214,7 +214,7 @@ Js.String.concat("bell", "cow") == "cowbell" */ external concat: t => t = "concat" -@bs.send.pipe(: t) +@send.pipe(: t) @variadic /** `concat(arr, original)` returns a new `string` consisting of each item of an @@ -410,8 +410,8 @@ Js.String.localeCompare("cat", "CAT") > 0.0 */ external localeCompare: t => float = "localeCompare" -@bs.send.pipe(: t) -@return({null_to_opt: null_to_opt}) +@send.pipe(: t) +@return(nullable) /** `match(regexp, str)` matches a `string` against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the g modifier, if @@ -540,7 +540,7 @@ let matchFn = (matchPart, _offset, _wholeString) => Js.String.toUpperCase(matchP Js.String.unsafeReplaceBy0(re, matchFn, str) == "bEAUtIfUl vOwEls" ``` */ -external unsafeReplaceBy0: (Js_re.t, @uncurry (t, int, t) => t) => t = "replace" +external unsafeReplaceBy0: (Js_re.t, (t, int, t) => t) => t = "replace" @bs.send.pipe(: t) /** @@ -565,7 +565,7 @@ let matchFn = (_match, part1, _offset, _wholeString) => { Js.String.unsafeReplaceBy1(re, matchFn, str) == "Jony is 41" ``` */ -external unsafeReplaceBy1: (Js_re.t, @uncurry (t, t, int, t) => t) => t = "replace" +external unsafeReplaceBy1: (Js_re.t, (t, t, int, t) => t) => t = "replace" @bs.send.pipe(: t) /** @@ -593,7 +593,7 @@ let matchFn = (_match, p1, p2, _offset, _wholeString) => { Js.String.unsafeReplaceBy2(re, matchFn, str) == "42" ``` */ -external unsafeReplaceBy2: (Js_re.t, @uncurry (t, t, t, int, t) => t) => t = "replace" +external unsafeReplaceBy2: (Js_re.t, (t, t, t, int, t) => t) => t = "replace" @bs.send.pipe(: t) /** @@ -606,7 +606,7 @@ matched. See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. */ -external unsafeReplaceBy3: (Js_re.t, @uncurry (t, t, t, t, int, t) => t) => t = "replace" +external unsafeReplaceBy3: (Js_re.t, (t, t, t, t, int, t) => t) => t = "replace" @bs.send.pipe(: t) /** diff --git a/jscomp/runtime/caml_obj.res b/jscomp/runtime/caml_obj.res index cd45d644d2..5fb44510b4 100644 --- a/jscomp/runtime/caml_obj.res +++ b/jscomp/runtime/caml_obj.res @@ -283,8 +283,8 @@ and aux_obj_compare = (a: Obj.t, b: Obj.t) => { } } - let do_key_a = do_key((a, b, min_key_rhs)) - let do_key_b = do_key((b, a, min_key_lhs)) + let do_key_a = do_key((a, b, min_key_rhs), ...) + let do_key_b = do_key((b, a, min_key_lhs), ...) O.for_in(a, do_key_a) O.for_in(b, do_key_b) let res = switch (min_key_lhs.contents, min_key_rhs.contents) { diff --git a/jscomp/runtime/curry.res b/jscomp/runtime/curry.res index 7d2fff69ab..7688186dbc 100644 --- a/jscomp/runtime/curry.res +++ b/jscomp/runtime/curry.res @@ -88,13 +88,13 @@ external apply8: ( %%private( let curry_1 = (o, a0, arity) => switch arity { - | 1 => apply1(Obj.magic(o), a0) - | 2 => apply2(Obj.magic(o), a0) - | 3 => apply3(Obj.magic(o), a0) - | 4 => apply4(Obj.magic(o), a0) - | 5 => apply5(Obj.magic(o), a0) - | 6 => apply6(Obj.magic(o), a0) - | 7 => apply7(Obj.magic(o), a0) + | 1 => Obj.magic(apply1)(Obj.magic(o), a0) + | 2 => Obj.magic(apply2)(Obj.magic(o), a0) + | 3 => Obj.magic(apply3)(Obj.magic(o), a0) + | 4 => Obj.magic(apply4)(Obj.magic(o), a0) + | 5 => Obj.magic(apply5)(Obj.magic(o), a0) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0) | _ => Obj.magic(app(o, [a0])) } ) @@ -122,13 +122,13 @@ let __1 = o => { %%private( let curry_2 = (o, a0, a1, arity) => switch arity { - | 1 => app(apply1(Obj.magic(o), a0), [a1]) - | 2 => apply2(Obj.magic(o), a0, a1) - | 3 => apply3(Obj.magic(o), a0, a1) - | 4 => apply4(Obj.magic(o), a0, a1) - | 5 => apply5(Obj.magic(o), a0, a1) - | 6 => apply6(Obj.magic(o), a0, a1) - | 7 => apply7(Obj.magic(o), a0, a1) + | 1 => Obj.magic(app)(apply1(Obj.magic(o), a0), [a1]) + | 2 => Obj.magic(apply2)(Obj.magic(o), a0, a1) + | 3 => Obj.magic(apply3)(Obj.magic(o), a0, a1) + | 4 => Obj.magic(apply4)(Obj.magic(o), a0, a1) + | 5 => Obj.magic(apply5)(Obj.magic(o), a0, a1) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0, a1) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1) | _ => Obj.magic(app(o, [a0, a1])) } ) @@ -139,7 +139,7 @@ let _2 = (o, a0, a1) => { if arity == 2 { apply2(o, a0, a1) } else { - curry_2(o, a0, a1, arity) + Obj.magic(curry_2)(o, a0, a1, arity) } } @@ -159,10 +159,10 @@ let __2 = o => { | 1 => app(apply1(Obj.magic(o), a0), [a1, a2]) | 2 => app(apply2(Obj.magic(o), a0, a1), [a2]) | 3 => apply3(Obj.magic(o), a0, a1, a2) - | 4 => apply4(Obj.magic(o), a0, a1, a2) - | 5 => apply5(Obj.magic(o), a0, a1, a2) - | 6 => apply6(Obj.magic(o), a0, a1, a2) - | 7 => apply7(Obj.magic(o), a0, a1, a2) + | 4 => Obj.magic(apply4)(Obj.magic(o), a0, a1, a2) + | 5 => Obj.magic(apply5)(Obj.magic(o), a0, a1, a2) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0, a1, a2) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1, a2) | _ => Obj.magic(app(o, [a0, a1, a2])) } ) @@ -173,7 +173,7 @@ let _3 = (o, a0, a1, a2) => { if arity == 3 { apply3(o, a0, a1, a2) } else { - curry_3(o, a0, a1, a2, arity) + Obj.magic(curry_3)(o, a0, a1, a2, arity) } } @@ -194,9 +194,9 @@ let __3 = o => { | 2 => app(apply2(Obj.magic(o), a0, a1), [a2, a3]) | 3 => app(apply3(Obj.magic(o), a0, a1, a2), [a3]) | 4 => apply4(Obj.magic(o), a0, a1, a2, a3) - | 5 => apply5(Obj.magic(o), a0, a1, a2, a3) - | 6 => apply6(Obj.magic(o), a0, a1, a2, a3) - | 7 => apply7(Obj.magic(o), a0, a1, a2, a3) + | 5 => Obj.magic(apply5)(Obj.magic(o), a0, a1, a2, a3) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0, a1, a2, a3) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1, a2, a3) | _ => Obj.magic(app(o, [a0, a1, a2, a3])) } ) @@ -207,7 +207,7 @@ let _4 = (o, a0, a1, a2, a3) => { if arity == 4 { apply4(o, a0, a1, a2, a3) } else { - curry_4(o, a0, a1, a2, a3, arity) + Obj.magic(curry_4)(o, a0, a1, a2, a3, arity) } } @@ -228,9 +228,9 @@ let __4 = o => { | 2 => app(apply2(Obj.magic(o), a0, a1), [a2, a3, a4]) | 3 => app(apply3(Obj.magic(o), a0, a1, a2), [a3, a4]) | 4 => app(apply4(Obj.magic(o), a0, a1, a2, a3), [a4]) - | 5 => apply5(Obj.magic(o), a0, a1, a2, a3, a4) - | 6 => apply6(Obj.magic(o), a0, a1, a2, a3, a4) - | 7 => apply7(Obj.magic(o), a0, a1, a2, a3, a4) + | 5 => Obj.magic(apply5)(Obj.magic(o), a0, a1, a2, a3, a4) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0, a1, a2, a3, a4) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1, a2, a3, a4) | _ => Obj.magic(app(o, [a0, a1, a2, a3, a4])) } ) @@ -241,7 +241,7 @@ let _5 = (o, a0, a1, a2, a3, a4) => { if arity == 5 { apply5(o, a0, a1, a2, a3, a4) } else { - curry_5(o, a0, a1, a2, a3, a4, arity) + Obj.magic(curry_5)(o, a0, a1, a2, a3, a4, arity) } } @@ -263,8 +263,8 @@ let __5 = o => { | 3 => app(apply3(Obj.magic(o), a0, a1, a2), [a3, a4, a5]) | 4 => app(apply4(Obj.magic(o), a0, a1, a2, a3), [a4, a5]) | 5 => app(apply5(Obj.magic(o), a0, a1, a2, a3, a4), [a5]) - | 6 => apply6(Obj.magic(o), a0, a1, a2, a3, a4, a5) - | 7 => apply7(Obj.magic(o), a0, a1, a2, a3, a4, a5) + | 6 => Obj.magic(apply6)(Obj.magic(o), a0, a1, a2, a3, a4, a5) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1, a2, a3, a4, a5) | _ => Obj.magic(app(o, [a0, a1, a2, a3, a4, a5])) } ) @@ -275,7 +275,7 @@ let _6 = (o, a0, a1, a2, a3, a4, a5) => { if arity == 6 { apply6(o, a0, a1, a2, a3, a4, a5) } else { - curry_6(o, a0, a1, a2, a3, a4, a5, arity) + Obj.magic(curry_6)(o, a0, a1, a2, a3, a4, a5, arity) } } @@ -298,7 +298,7 @@ let __6 = o => { | 4 => app(apply4(Obj.magic(o), a0, a1, a2, a3), [a4, a5, a6]) | 5 => app(apply5(Obj.magic(o), a0, a1, a2, a3, a4), [a5, a6]) | 6 => app(apply6(Obj.magic(o), a0, a1, a2, a3, a4, a5), [a6]) - | 7 => apply7(Obj.magic(o), a0, a1, a2, a3, a4, a5, a6) + | 7 => Obj.magic(apply7)(Obj.magic(o), a0, a1, a2, a3, a4, a5, a6) | _ => Obj.magic(app(o, [a0, a1, a2, a3, a4, a5, a6])) } ) @@ -309,7 +309,7 @@ let _7 = (o, a0, a1, a2, a3, a4, a5, a6) => { if arity == 7 { apply7(o, a0, a1, a2, a3, a4, a5, a6) } else { - curry_7(o, a0, a1, a2, a3, a4, a5, a6, arity) + Obj.magic(curry_7)(o, a0, a1, a2, a3, a4, a5, a6, arity) } } @@ -343,7 +343,7 @@ let _8 = (o, a0, a1, a2, a3, a4, a5, a6, a7) => { if arity == 8 { apply8(o, a0, a1, a2, a3, a4, a5, a6, a7) } else { - curry_8(o, a0, a1, a2, a3, a4, a5, a6, a7, arity) + Obj.magic(curry_8)(o, a0, a1, a2, a3, a4, a5, a6, a7, arity) } } diff --git a/jscomp/stdlib-406/ArrayBuffer.res b/jscomp/stdlib-406/ArrayBuffer.res new file mode 100644 index 0000000000..0beb684b40 --- /dev/null +++ b/jscomp/stdlib-406/ArrayBuffer.res @@ -0,0 +1,7 @@ +type t = Js.TypedArray2.ArrayBuffer.t + +@new external make: int => t = "ArrayBuffer" +@get external byteLength: t => int = "byteLength" + +@send external slice: (t, ~start: int, ~end: int) => t = "slice" +@send external sliceToEnd: (t, ~start: int) => t = "slice" diff --git a/jscomp/stdlib-406/AsyncIterator.res b/jscomp/stdlib-406/AsyncIterator.res new file mode 100644 index 0000000000..4781fbe755 --- /dev/null +++ b/jscomp/stdlib-406/AsyncIterator.res @@ -0,0 +1,18 @@ +type t<'a> + +type value<'a> = { + done: bool, + value: option<'a>, +} + +@send external next: t<'a> => promise> = "next" + +let forEach = async (iterator, f) => { + let iteratorDone = ref(false) + + while !iteratorDone.contents { + let {done, value} = await iterator->next + f(value) + iteratorDone := done + } +} diff --git a/jscomp/stdlib-406/AsyncIterator.resi b/jscomp/stdlib-406/AsyncIterator.resi new file mode 100644 index 0000000000..5644838b86 --- /dev/null +++ b/jscomp/stdlib-406/AsyncIterator.resi @@ -0,0 +1,80 @@ +/*** +Bindings to async iterators, a way to do async iteration in JavaScript. + +See [async iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) on MDN.*/ + +/** +The type representing an async iterator. +*/ +type t<'a> + +type value<'a> = { + /** + Whether there are more values to iterate on before the iterator is done. + */ + done: bool, + /** + The value of this iteration, if any. + */ + value: option<'a>, +} + +/** +`next(asyncIterator)` + +Returns the next value of the iterator, if any. + +See [async iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) on MDN. + +## Examples +- A simple example, getting the next value: +```rescript +@val external asyncIterator: AsyncIterator.t = "someAsyncIterator" +let {AsyncIterator.done, value} = await asyncIterator->AsyncIterator.next +``` + +- Complete example, including looping over all values: +```rescript +// Let's pretend we get an async iterator returning ints from somewhere. +@val external asyncIterator: AsyncIterator.t = "someAsyncIterator" + + +let processMyAsyncIterator = async () => { + // ReScript doesn't have `for ... of` loops, but it's easy to mimic using a while loop. + let break = ref(false) + + while !break.contents { + // Await the next iterator value + let {value, done} = await asyncIterator->AsyncIterator.next + + // Exit the while loop if the iterator says it's done + break := done + + // This will log the (int) value of the current async iteration, if a value was returned. + Console.log(value) + } +} +``` +*/ +@send +external next: t<'a> => promise> = "next" + +/** +`forEach(iterator, fn)` consumes all values in the async iterator and runs the callback `fn` for each value. + +See [iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. + +## Examples +```rescript +// Let's pretend we get an async iterator returning ints from somewhere. +@val external asyncIterator: AsyncIterator.t = "someAsyncIterator" + +await asyncIterator->AsyncIterator.forEach(value => + switch value { + | Some(value) if value > 10 => Console.log("More than 10!") + | _ => () + } +) +``` +*/ +let forEach: (t<'a>, option<'a> => unit) => promise diff --git a/jscomp/stdlib-406/BigInt.res b/jscomp/stdlib-406/BigInt.res new file mode 100644 index 0000000000..028349fbdb --- /dev/null +++ b/jscomp/stdlib-406/BigInt.res @@ -0,0 +1,97 @@ +@val external asIntN: (~width: int, bigint) => bigint = "BigInt.asIntN" +@val external asUintN: (~width: int, bigint) => bigint = "BigInt.asUintN" + +@val external fromString: string => bigint = "BigInt" + +@val +/** +Parses the given `string` into a `bigint` using JavaScript semantics. Return the +number as a `bigint` if successfully parsed. Uncaught syntax exception otherwise. + +## Examples + +```rescript +/* returns 123n */ +BigInt.fromStringExn("123") + +/* returns 0n */ +BigInt.fromStringExn("") + +/* returns 17n */ +BigInt.fromStringExn("0x11") + +/* returns 3n */ +BigInt.fromStringExn("0b11") + +/* returns 9n */ +BigInt.fromStringExn("0o11") + +/* catch exception */ +try { + BigInt.fromStringExn("a") +} catch { +| Exn.Error(_error) => 0n +} +``` +*/ +external fromStringExn: string => bigint = "BigInt" +@val external fromInt: int => bigint = "BigInt" +@val external fromFloat: float => bigint = "BigInt" + +@send +/** +Formats a `bigint` as a string. Return a `string` representing the given value. +See [`toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) on MDN. + +## Examples + +```rescript +/* prints "123" */ +Js.BigInt.toString(123n)->Js.log +``` +*/ +external toString: (bigint, ~radix: int=?) => string = "toString" + +@deprecated("Use `toString` with `~radix` instead") @send +external toStringWithRadix: (bigint, ~radix: int) => string = "toString" + +@send +/** +Returns a string with a language-sensitive representation of this BigInt value. + +## Examples + +```rescript +/* prints "123" */ +Js.BigInt.toString(123n)->Js.log +``` +*/ +external toLocaleString: bigint => string = "toLocaleString" + +@val external toFloat: bigint => float = "Number" + +let toInt = t => t->toFloat->Core__Int.fromFloat + +external \"+": (bigint, bigint) => bigint = "%addbigint" +external \"-": (bigint, bigint) => bigint = "%subbigint" +external \"*": (bigint, bigint) => bigint = "%mulbigint" +external \"/": (bigint, bigint) => bigint = "%divbigint" +external \"~-": bigint => bigint = "%negbigint" +external \"~+": bigint => bigint = "%identity" +external \"**": (bigint, bigint) => bigint = "%powbigint" + +external add: (bigint, bigint) => bigint = "%addfloat" +external sub: (bigint, bigint) => bigint = "%subfloat" +external mul: (bigint, bigint) => bigint = "%mulfloat" +external div: (bigint, bigint) => bigint = "%divfloat" + +external mod: (bigint, bigint) => bigint = "%modbigint" + +external land: (bigint, bigint) => bigint = "%andbigint" +external lor: (bigint, bigint) => bigint = "%orbigint" +external lxor: (bigint, bigint) => bigint = "%xorbigint" + +external lsl: (bigint, bigint) => bigint = "%lslbigint" +external asr: (bigint, bigint) => bigint = "%asrbigint" + +let lnot = x => lxor(x, -1n) diff --git a/jscomp/stdlib-406/Console.res b/jscomp/stdlib-406/Console.res new file mode 100644 index 0000000000..2c85d0242b --- /dev/null +++ b/jscomp/stdlib-406/Console.res @@ -0,0 +1,67 @@ +@val external assert_: (bool, 'a) => unit = "console.assert" +@val external assert2: (bool, 'a, 'b) => unit = "console.assert" +@val external assert3: (bool, 'a, 'b, 'c) => unit = "console.assert" +@val external assert4: (bool, 'a, 'b, 'c, 'd) => unit = "console.assert" +@val external assert5: (bool, 'a, 'b, 'c, 'd, 'e) => unit = "console.assert" +@val external assert6: (bool, 'a, 'b, 'c, 'd, 'e, 'f) => unit = "console.assert" +@val @variadic external assertMany: (bool, array<_>) => unit = "console.assert" + +@val external clear: unit => unit = "console.clear" + +@val external count: string => unit = "console.count" +@val external countReset: string => unit = "console.countReset" + +@val external debug: 'a => unit = "console.debug" +@val external debug2: ('a, 'b) => unit = "console.debug" +@val external debug3: ('a, 'b, 'c) => unit = "console.debug" +@val external debug4: ('a, 'b, 'c, 'd) => unit = "console.debug" +@val external debug5: ('a, 'b, 'c, 'd, 'e) => unit = "console.debug" +@val external debug6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.debug" +@val @variadic external debugMany: array<_> => unit = "console.debug" + +@val external dir: 'a => unit = "console.dir" +@val external dirxml: 'a => unit = "console.dirxml" + +@val external error: 'a => unit = "console.error" +@val external error2: ('a, 'b) => unit = "console.error" +@val external error3: ('a, 'b, 'c) => unit = "console.error" +@val external error4: ('a, 'b, 'c, 'd) => unit = "console.error" +@val external error5: ('a, 'b, 'c, 'd, 'e) => unit = "console.error" +@val external error6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.error" +@val @variadic external errorMany: array<_> => unit = "console.error" + +@val external group: string => unit = "console.group" +@val external groupCollapsed: string => unit = "console.groupCollapsed" +@val external groupEnd: unit => unit = "console.groupEnd" + +@val external info: 'a => unit = "console.info" +@val external info2: ('a, 'b) => unit = "console.info" +@val external info3: ('a, 'b, 'c) => unit = "console.info" +@val external info4: ('a, 'b, 'c, 'd) => unit = "console.info" +@val external info5: ('a, 'b, 'c, 'd, 'e) => unit = "console.info" +@val external info6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.info" +@val @variadic external infoMany: array<_> => unit = "console.info" + +@val external log: 'a => unit = "console.log" +@val external log2: ('a, 'b) => unit = "console.log" +@val external log3: ('a, 'b, 'c) => unit = "console.log" +@val external log4: ('a, 'b, 'c, 'd) => unit = "console.log" +@val external log5: ('a, 'b, 'c, 'd, 'e) => unit = "console.log" +@val external log6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.log" +@val @variadic external logMany: array<_> => unit = "console.log" + +@val external table: 'a => unit = "console.table" + +@val external time: string => unit = "console.time" +@val external timeEnd: string => unit = "console.timeEnd" +@val external timeLog: string => unit = "console.timeLog" + +@val external trace: unit => unit = "console.trace" + +@val external warn: 'a => unit = "console.warn" +@val external warn2: ('a, 'b) => unit = "console.warn" +@val external warn3: ('a, 'b, 'c) => unit = "console.warn" +@val external warn4: ('a, 'b, 'c, 'd) => unit = "console.warn" +@val external warn5: ('a, 'b, 'c, 'd, 'e) => unit = "console.warn" +@val external warn6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.warn" +@val @variadic external warnMany: array<_> => unit = "console.warn" diff --git a/jscomp/stdlib-406/Console.resi b/jscomp/stdlib-406/Console.resi new file mode 100644 index 0000000000..ec1d757ab3 --- /dev/null +++ b/jscomp/stdlib-406/Console.resi @@ -0,0 +1,786 @@ +/*** +Functions for interacting with JavaScript console. + +See: [`console`](https://developer.mozilla.org/en-US/docs/Web/API/Console). +*/ + +/** +`assert_(assertion, value)` print a message to console if `assertion` evaluates `false`. Does nothing if it's `true`. + +See [`console.assert`](https://developer.mozilla.org/en-US/docs/Web/API/console/assert) +on MDN. + +## Examples + +```rescript +Console.assert_(false, "Hello World!") +Console.assert_(42 == 42, "The answer") +``` +*/ +@val +external assert_: (bool, 'a) => unit = "console.assert" + +/** +`assert2(v1, v2)`. Like `assert_`, but with two arguments. + +## Examples + +```rescript +Console.assert2(false, "Hello", "World") +Console.assert2(42 == 42, [1, 2, 3], '4') +``` +*/ +@val +external assert2: (bool, 'a, 'b) => unit = "console.assert" + +/** +`assert3(v1, v2, v3)`. Like `assert_`, but with three arguments. + +## Examples + +```rescript +Console.assert3(false, "Hello", "World", "ReScript") +Console.assert3(42 == 42, "One", 2, #3) +``` +*/ +@val +external assert3: (bool, 'a, 'b, 'c) => unit = "console.assert" + +/** +`assert4(v1, v2, v3, v4)`. Like `assert_`, but with four arguments. + +## Examples + +```rescript +let value = 42 +Console.assert4(false, "Hello", "World", "ReScript", "!!!") +Console.assert4(value == 42, [1, 2], (3, 4), [#5, #6], #"polyvar") +``` +*/ +@val +external assert4: (bool, 'a, 'b, 'c, 'd) => unit = "console.assert" + +/** +`assert5(v1, v2, v3, v4, v5)`. Like `assert_`, but with five arguments. + +## Examples + +```rescript +let value = 42 +Console.assert5(false, "Hello", "World", "JS", '!', '!') +Console.assert5(value == 42, [1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}) +``` +*/ +@val +external assert5: (bool, 'a, 'b, 'c, 'd, 'e) => unit = "console.assert" + +/** +`assert6(v1, v2)`. Like `assert_`, but with six arguments. + +## Examples + +```rescript +let value = 42 +Console.assert6(false, "Hello", "World", "JS", '!', '!', '?') +Console.assert6(value == 42, [1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external assert6: (bool, 'a, 'b, 'c, 'd, 'e, 'f) => unit = "console.assert" + +/** +`assertMany(assertion, arr)`. Like `assert_`, but variadic. + +## Examples + +```rescript +let value = 42 +Console.assertMany(false, ["Hello", "World"]) +Console.assertMany(value == 42, [1, 2, 3]) +``` +*/ +@val +@variadic +external assertMany: (bool, array<_>) => unit = "console.assert" + +/** +`clear()` clears the console, if allowed. + +See [`console.clear`](https://developer.mozilla.org/en-US/docs/Web/API/console/clear) +on MDN. + +## Examples + +```rescript +Console.clear() +``` +*/ +@val +external clear: unit => unit = "console.clear" + +/** +`count(label)` prints to the console the number of times it's been called with the given label. + +See [`console.count`](https://developer.mozilla.org/en-US/docs/Web/API/console/count) +on MDN. + +## Examples + +```rescript +Console.count("rescript") +``` +*/ +@val +external count: string => unit = "console.count" + +/** +`countReset(label)` resets the count for the given label to 0. + +See [`console.countReset`](https://developer.mozilla.org/en-US/docs/Web/API/console/countReset) +on MDN. + +## Examples + +```rescript +Console.countReset("rescript") +``` +*/ +@val +external countReset: string => unit = "console.countReset" + +/** +`debug(value)` print a debug message to console. + +See [`console.debug`](https://developer.mozilla.org/en-US/docs/Web/API/console/debug) +on MDN. + +## Examples + +```rescript +Console.debug("Hello") +let obj = {"name": "ReScript", "version": 10} +Console.debug(obj) +``` +*/ +@val +external debug: 'a => unit = "console.debug" + +/** +`debug2(v1, v2)`. Like `debug`, but with two arguments. + +## Examples + +```rescript +Console.debug2("Hello", "World") +Console.debug2([1, 2, 3], '4') +``` +*/ +@val +external debug2: ('a, 'b) => unit = "console.debug" + +/** +`debug3(v1, v2, v3)`. Like `debug`, but with three arguments. + +## Examples + +```rescript +Console.debug3("Hello", "World", "ReScript") +Console.debug3("One", 2, #3) +``` +*/ +@val +external debug3: ('a, 'b, 'c) => unit = "console.debug" + +/** +`debug4(v1, v2, v3, v4)`. Like `debug`, but with four arguments. + +## Examples + +```rescript +Console.debug4("Hello", "World", "ReScript", "!!!") +Console.debug4([1, 2], (3, 4), [#5, #6], #"polyvar") +``` +*/ +@val +external debug4: ('a, 'b, 'c, 'd) => unit = "console.debug" + +/** +`debug5(v1, v2, v3, v4, v5)`. Like `debug`, but with five arguments. + +## Examples + +```rescript +Console.debug5("Hello", "World", "JS", '!', '!') +Console.debug5([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}) +``` +*/ +@val +external debug5: ('a, 'b, 'c, 'd, 'e) => unit = "console.debug" + +/** +`debug6(v1, v2, v3, v4, v5, v6)`. Like `debug`, but with six arguments. + +## Examples + +```rescript +Console.debug6("Hello", "World", "JS", '!', '!', '?') +Console.debug6([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external debug6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.debug" + +/** +`debugMany(arr)`. Like `debug`, but variadic. + +## Examples + +```rescript +Console.debugMany(["Hello", "World"]) +Console.debugMany([1, 2, 3]) +``` +*/ +@val +@variadic +external debugMany: array<_> => unit = "console.debug" + +/** +`dir(object)` displays an interactive view of the object in the console. + +See [`console.dir`](https://developer.mozilla.org/en-US/docs/Web/API/console/dir) +on MDN. + +## Examples + +```rescript +Console.dir({"language": "rescript", "version": "10.1.2"}) +``` +*/ +@val +external dir: 'a => unit = "console.dir" + +/** +`dirxml(object)` displays an interactive tree view of an XML/HTML element in the console. + +See [`console.dirxml`](https://developer.mozilla.org/en-US/docs/Web/API/console/dirxml) +on MDN. +*/ +@val +external dirxml: 'a => unit = "console.dirxml" + +/** +`error(value)` prints an error message to console. + +See [`console.error`](https://developer.mozilla.org/en-US/docs/Web/API/console/error) +on MDN. + +## Examples + +```rescript +Console.error("error message") +Console.error(("error", "invalid value")) +``` +*/ +@val +external error: 'a => unit = "console.error" + +/** +`error(v1, v2)`. Like `error`, but two arguments. + +## Examples + +```rescript +Console.error2("Error", "here") +Console.error2(("log", "error"), "message") +``` +*/ +@val +external error2: ('a, 'b) => unit = "console.error" + +/** +`error3(v1, v2, v3)`. Like `error`, but three arguments. + +## Examples + +```rescript +Console.error3("Hello", "World", "!!!") +Console.error3(#first, #second, #third) +``` +*/ +@val +external error3: ('a, 'b, 'c) => unit = "console.error" + +/** +`error4(v1, v2, v3, v4)`. Like `error`, but with four arguments. + +## Examples + +```rescript +Console.error4("Hello", "World", "ReScript", '!') +Console.error4(#first, #second, #third, ("fourth")) +``` +*/ +@val +external error4: ('a, 'b, 'c, 'd) => unit = "console.error" + +/** +`error5(v1, v2, v3, v4, v5)`. Like `error`, but with five arguments. + +## Examples + +```rescript +Console.error5('e', 'r', 'r', 'o', 'r') +Console.error5(1, #second, #third, ("fourth"), 'c') +``` +*/ +@val +external error5: ('a, 'b, 'c, 'd, 'e) => unit = "console.error" + +/** +`error6(v1, v2, v3, v4, v5, v6)`. Like `error`, but with six arguments. + +## Examples + +```rescript +Console.error6("Hello", "World", "from", "JS", "!!!", '!') +Console.error6([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external error6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.error" + +/** +`group(label)` creates a new "group" level with the given label. + +See [`console.group`](https://developer.mozilla.org/en-US/docs/Web/API/console/group) +on MDN. + +## Example + +```rescript +Console.group("first group") +Console.group("second group") +Console.log("a message on the second level") +Console.groupEnd() +Console.log("a message message on the first level") +Console.groupEnd() +``` +*/ +@val +external group: string => unit = "console.group" + +/** +`groupCollapsed(label)`. Like `group` but collapses the group initially. + +See [`console.groupCollapsed`](https://developer.mozilla.org/en-US/docs/Web/API/console/groupCollapsed) +on MDN. +*/ +@val +external groupCollapsed: string => unit = "console.groupCollapsed" + +/** +`groupEnd()` ends the current group. + +See [`console.groupEnd`](https://developer.mozilla.org/en-US/docs/Web/API/console/groupEnd) +on MDN. +*/ +@val +external groupEnd: unit => unit = "console.groupEnd" + +/** +`errorMany(arr)`. Like `error`, but variadic. + +## Examples + +```rescript +Console.errorMany(["Hello", "World"]) +Console.errorMany([1, 2, 3]) +``` +*/ +@val +@variadic +external errorMany: array<_> => unit = "console.error" + +/** +`info(value)` print an informational message to console. + +See [`console.info`](https://developer.mozilla.org/en-US/docs/Web/API/console/info) +on MDN. + +## Examples + +```rescript +Console.info("Information") +Console.info(("Hello", "JS")) +``` +*/ +@val +external info: 'a => unit = "console.info" + +/** +`info2(v1, v2)`. Like `info`, but with two arguments. + +## Examples + +```rescript +Console.info2("Info", "failed to download") +Console.info2(#info, {"name": "ReScript"}) +``` +*/ +@val +external info2: ('a, 'b) => unit = "console.info" + +/** +`info3(v1, v2, v3)`. Like `info`, but with three arguments. + +## Examples + +```rescript +Console.info3("Hello", "World", "ReScript") +Console.info3([1, 2, 3], #4, #5) +``` +*/ +@val +external info3: ('a, 'b, 'c) => unit = "console.info" + +/** +`info4(v1, v2, v3, v4)`. Like `info`, but with four arguments. + +## Examples + +```rescript +Console.info4("Hello", "World", "ReScript", '!') +Console.info4([1, 2, 3], #4, #5, #lastinfo) +``` +*/ +@val +external info4: ('a, 'b, 'c, 'd) => unit = "console.info" + +/** +`info5(v1, v2, v3, v4, v5)`. Like `info`, but with five arguments. + +## Examples + +```rescript +Console.info5("Hello", "World", "from", "JS", "!!!") +Console.info5([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}) +``` +*/ +@val +external info5: ('a, 'b, 'c, 'd, 'e) => unit = "console.info" + +/** +`info6(v1, v2, v3, v4, v5, v6)`. Like `info`, but with six arguments. + +## Examples + +```rescript +Console.info6("Hello", "World", "from", "JS", "!!!", '!') +Console.info6([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external info6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.info" + +/** +`infoMany(arr)`. Like `info`, but variadic. + +## Examples + +```rescript +Console.infoMany(["Hello", "World"]) +Console.infoMany([1, 2, 3]) +``` +*/ +@val +@variadic +external infoMany: array<_> => unit = "console.info" + +/** +`log(value)` print a message to console. + +See [`console.log`](https://developer.mozilla.org/en-US/docs/Web/API/console/log) +on MDN. + +## Examples + +```rescript +Console.log("Hello") +let obj = {"name": "ReScript", "version": 10} +Console.log(obj) +``` +*/ +@val +external log: 'a => unit = "console.log" + +/** +`log2(v1, v2)`. Like `log`, but with two arguments. + +## Examples + +```rescript +Console.log2("Hello", "World") +Console.log2([1, 2, 3], '4') +``` +*/ +@val +external log2: ('a, 'b) => unit = "console.log" + +/** +`log3(v1, v2, v3)`. Like `log`, but with three arguments. + +## Examples + +```rescript +Console.log3("Hello", "World", "ReScript") +Console.log3("One", 2, #3) +``` +*/ +@val +external log3: ('a, 'b, 'c) => unit = "console.log" + +/** +`log4(v1, v2, v3, v4)`. Like `log`, but with four arguments. + +## Examples + +```rescript +Console.log4("Hello", "World", "ReScript", "!!!") +Console.log4([1, 2], (3, 4), [#5, #6], #"polyvar") +``` +*/ +@val +external log4: ('a, 'b, 'c, 'd) => unit = "console.log" + +/** +`log5(v1, v2, v3, v4, v5)`. Like `log`, but with five arguments. + +## Examples + +```rescript +Console.log5("Hello", "World", "JS", '!', '!') +Console.log5([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}) +``` +*/ +@val +external log5: ('a, 'b, 'c, 'd, 'e) => unit = "console.log" + +/** +`log6(v1, v2, v3, v4, v5, v6)`. Like `log`, but with six arguments. + +## Examples + +```rescript +Console.log6("Hello", "World", "JS", '!', '!', '?') +Console.log6([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external log6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.log" + +/** +`logMany(arr)`. Like `log`, but variadic. + +## Examples + +```rescript +Console.logMany(["Hello", "World"]) +Console.logMany([1, 2, 3]) +``` +*/ +@val +@variadic +external logMany: array<_> => unit = "console.log" + +/** +`table(object)` displays an tabular view of the object in the console. + +See [`console.table`](https://developer.mozilla.org/en-US/docs/Web/API/console/table) +on MDN. + +## Examples + +```rescript +Console.table({"language": "rescript", "version": "10.1.2"}) +``` +*/ +@val +external table: 'a => unit = "console.table" + +/** +`time(label)` creates a timer to measure how long an operation takes. `label` +must be a unique name. Call `console.timeEnd` with the same `label` to print +output time. + +See [`console.time`](https://developer.mozilla.org/en-US/docs/Web/API/console/time) +on MDN. + +## Examples + +```rescript +Console.time("for_time") +for x in 3 downto 1 { + Console.log(x) + Console.timeLog("for_time") +} +Console.timeEnd("for_time") +``` +*/ +@val +external time: string => unit = "console.time" + +/** +`timeEnd(label)` stops a timer created by `time`. + +See [`console.timeEnd`](https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd) +on MDN. + +## Examples + +```rescript +Console.time("for_time") +for x in 3 downto 1 { + Console.log(x) + Console.timeLog("for_time") +} +Console.timeEnd("for_time") +``` +*/ +@val +external timeEnd: string => unit = "console.timeEnd" + +/** +`timeLog(label)` prints the current elapsed time of the given timer to the console. + +See [`console.timeLog`](https://developer.mozilla.org/en-US/docs/Web/API/console/timeLog) +on MDN. + +## Examples + +```rescript +Console.time("for_time") +for x in 3 downto 1 { + Console.log(x) + Console.timeLog("for_time") +} +Console.timeEnd("for_time") +``` +*/ +@val +external timeLog: string => unit = "console.timeLog" + +/** +`trace()` print a stack trace to console. + +See [`console.trace`](https://developer.mozilla.org/en-US/docs/Web/API/console/trace) +on MDN. + +## Examples + +```rescript +let main = () => { + Console.trace() +} +main() +// In the console, the following trace will be displayed: +// main +// +``` +*/ +@val +external trace: unit => unit = "console.trace" + +/** +`warn(value)` print a warning message to console. + +See [`console.warn`](https://developer.mozilla.org/en-US/docs/Web/API/console/warn) +on MDN. + +## Examples + +```rescript +Console.warn("Warning") +Console.warn(("Warning", "invalid number")) +``` +*/ +@val +external warn: 'a => unit = "console.warn" + +/** +`warn2(v1, v2)`. Like `warn`, but two arguments. + +## Examples + +```rescript +Console.warn2("Hello", "World") +Console.warn2([1, 2, 3], 4) +``` +*/ +@val +external warn2: ('a, 'b) => unit = "console.warn" + +/** +`warn3(v1, v2, v3)`. Like `warn`, but three arguments. + +## Examples + +```rescript +Console.warn3("Hello", "World", "ReScript") +Console.warn3([1, 2, 3], #4, #5) +``` +*/ +@val +external warn3: ('a, 'b, 'c) => unit = "console.warn" + +/** +`warn4(v1, v2, v3, v4)`. Like `warn`, but with four arguments. + +## Examples + +```rescript +Console.warn4("Hello", "World", "ReScript", "!!!") +Console.warn4(#first, #second, #third, ("fourth")) +``` +*/ +@val +external warn4: ('a, 'b, 'c, 'd) => unit = "console.warn" + +/** +`warn5(v1, v2, v3, v4, v5)`. Like `warn`, but with five arguments. + +## Examples + +```rescript +Console.warn5("Hello", "World", "from", "JS", "!!!") +Console.warn5([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}) +``` +*/ +@val +external warn5: ('a, 'b, 'c, 'd, 'e) => unit = "console.warn" + +/** +`warn6(v1, v2, v3, v4, v5, v6)`. Like `warn`, but with six arguments. + +## Examples + +```rescript +Console.warn6("Hello", "World", "from", "JS", "!!!", '!') +Console.warn6([1, 2], (3, 4), [#5, #6], #"polyvar", {"name": "ReScript"}, 42) +``` +*/ +@val +external warn6: ('a, 'b, 'c, 'd, 'e, 'f) => unit = "console.warn" + +/** +`warnMany(arr)`. Like `warn`, but variadic. + +## Examples + +```rescript +Console.warnMany(["Hello", "World"]) +Console.warnMany([1, 2, 3]) +``` +*/ +@val +@variadic +external warnMany: array<_> => unit = "console.warn" diff --git a/jscomp/stdlib-406/DataView.res b/jscomp/stdlib-406/DataView.res new file mode 100644 index 0000000000..590baffab6 --- /dev/null +++ b/jscomp/stdlib-406/DataView.res @@ -0,0 +1,36 @@ +type t + +@new external fromBuffer: ArrayBuffer.t => t = "DataView" +@new external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "DataView" +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "DataView" + +@get external buffer: t => ArrayBuffer.t = "buffer" +@get external byteLength: t => int = "byteLength" +@get external byteOffset: t => int = "byteOffset" + +@send external getInt8: t => int = "getInt8" +@send external getUint8: t => int = "getUint8" +@send external getInt16: t => int = "getInt16" +@send external getUint16: t => int = "getUint16" +@send external getInt32: t => int = "getInt32" +@send external getUint32: t => int = "getUint32" + +@send external getFloat32: t => float = "getFloat32" +@send external getFloat64: t => float = "getFloat64" + +@send external getBigInt64: t => bigint = "getBigInt64" +@send external getBigUint64: t => bigint = "getBigUint64" + +@send external setInt8: (t, int) => unit = "setInt8" +@send external setUint8: (t, int) => unit = "setUint8" +@send external setInt16: (t, int) => unit = "setInt16" +@send external setUint16: (t, int) => unit = "setUint16" +@send external setInt32: (t, int) => unit = "setInt32" +@send external setUint32: (t, int) => unit = "setUint32" + +@send external setFloat32: (t, float) => unit = "setFloat32" +@send external setFloat64: (t, float) => unit = "setFloat64" + +@send external setBigInt64: (t, bigint) => unit = "setBigInt64" +@send external setBigUint64: (t, bigint) => unit = "setBigUint64" diff --git a/jscomp/stdlib-406/Date.res b/jscomp/stdlib-406/Date.res new file mode 100644 index 0000000000..925afcc190 --- /dev/null +++ b/jscomp/stdlib-406/Date.res @@ -0,0 +1,180 @@ +type t = Js.Date.t + +type msSinceEpoch = float + +type localeOptions = { + dateStyle?: [#full | #long | #medium | #short], + timeStyle?: [#full | #long | #medium | #short], + weekday?: [#long | #short | #narrow], + era?: [#long | #short | #narrow], + year?: [#numeric | #"2-digit"], + month?: [#numeric | #"2-digit" | #long | #short | #narrow], + day?: [#numeric | #"2-digit"], + hour?: [#numeric | #"2-digit"], + minute?: [#numeric | #"2-digit"], + second?: [#numeric | #"2-digit"], + timeZoneName?: [#long | #short], +} + +@new external make: unit => t = "Date" +@new external fromString: string => t = "Date" +@new external fromTime: msSinceEpoch => t = "Date" + +@new external makeWithYM: (~year: int, ~month: int) => t = "Date" +@new external makeWithYMD: (~year: int, ~month: int, ~date: int) => t = "Date" +@new external makeWithYMDH: (~year: int, ~month: int, ~date: int, ~hours: int) => t = "Date" +@new +external makeWithYMDHM: (~year: int, ~month: int, ~date: int, ~hours: int, ~minutes: int) => t = + "Date" +@new +external makeWithYMDHMS: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, +) => t = "Date" +@new +external makeWithYMDHMSM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, +) => t = "Date" + +module UTC = { + @val external makeWithYM: (~year: int, ~month: int) => msSinceEpoch = "Date.UTC" + @val external makeWithYMD: (~year: int, ~month: int, ~date: int) => msSinceEpoch = "Date.UTC" + @val + external makeWithYMDH: (~year: int, ~month: int, ~date: int, ~hours: int) => msSinceEpoch = + "Date.UTC" + @val + external makeWithYMDHM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ) => msSinceEpoch = "Date.UTC" + @val + external makeWithYMDHMS: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ) => msSinceEpoch = "Date.UTC" + @val + external makeWithYMDHMSM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, + ) => msSinceEpoch = "Date.UTC" +} + +@val external now: unit => msSinceEpoch = "Date.now" + +@send external getTime: t => msSinceEpoch = "getTime" +@send external getTimezoneOffset: t => int = "getTimezoneOffset" + +let equal = (a, b) => a->getTime === b->getTime + +let compare = (a, b) => Float.compare(a->getTime, b->getTime) + +// Locale +@send external getFullYear: t => int = "getFullYear" +@send external getMonth: t => int = "getMonth" +@send external getDate: t => int = "getDate" +@send external getHours: t => int = "getHours" +@send external getMinutes: t => int = "getMinutes" +@send external getSeconds: t => int = "getSeconds" +@send external getMilliseconds: t => int = "getMilliseconds" +@send external getDay: t => int = "getDay" + +@send external setFullYear: (t, int) => unit = "setFullYear" +@send external setFullYearM: (t, ~year: int, ~month: int) => unit = "setFullYear" +@send external setFullYearMD: (t, ~year: int, ~month: int, ~date: int) => unit = "setFullYear" +@send external setMonth: (t, int) => unit = "setMonth" +@send external setDate: (t, int) => unit = "setDate" +@send external setHours: (t, int) => unit = "setHours" +@send external setHoursM: (t, ~hours: int, ~minutes: int) => unit = "setHours" +@send external setHoursMS: (t, ~hours: int, ~minutes: int, ~seconds: int) => unit = "setHours" +@send +external setHoursMSMs: (t, ~hours: int, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = + "setHours" +@send external setMinutes: (t, int) => unit = "setMinutes" +@send external setMinutesS: (t, ~minutes: int, ~seconds: int) => unit = "setMinutes" +@send +external setMinutesSMs: (t, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = "setMinutes" +@send external setSeconds: (t, int) => unit = "setSeconds" +@send external setSecondsMs: (t, ~seconds: int, ~milliseconds: int) => unit = "setSeconds" +@send external setMilliseconds: (t, int) => unit = "setMilliseconds" + +// UTC +@send external getUTCFullYear: t => int = "getUTCFullYear" +@send external getUTCMonth: t => int = "getUTCMonth" +@send external getUTCDate: t => int = "getUTCDate" +@send external getUTCHours: t => int = "getUTCHours" +@send external getUTCMinutes: t => int = "getUTCMinutes" +@send external getUTCSeconds: t => int = "getUTCSeconds" +@send external getUTCMilliseconds: t => int = "getUTCMilliseconds" +@send external getUTCDay: t => int = "getUTCDay" + +@send external setUTCFullYear: (t, int) => unit = "setUTCFullYear" +@send external setUTCFullYearM: (t, ~year: int, ~month: int) => unit = "setUTCFullYear" +@send +external setUTCFullYearMD: (t, ~year: int, ~month: int, ~date: int) => unit = "setUTCFullYear" +@send external setUTCMonth: (t, int) => unit = "setUTCMonth" +@send external setUTCDate: (t, int) => unit = "setUTCDate" +@send external setUTCHours: (t, int) => unit = "setUTCHours" +@send external setUTCHoursM: (t, ~hours: int, ~minutes: int) => unit = "setUTCHours" +@send +external setUTCHoursMS: (t, ~hours: int, ~minutes: int, ~seconds: int) => unit = "setUTCHours" +@send +external setUTCHoursMSMs: ( + t, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, +) => unit = "setUTCHours" +@send external setUTCMinutes: (t, int) => unit = "setUTCMinutes" +@send external setUTCMinutesS: (t, ~minutes: int, ~seconds: int) => unit = "setUTCMinutes" +@send +external setUTCMinutesSMs: (t, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = + "setUTCMinutes" +@send external setUTCSeconds: (t, int) => unit = "setUTCSeconds" +@send external setUTCSecondsMs: (t, ~seconds: int, ~milliseconds: int) => unit = "setUTCSeconds" +@send external setUTCMilliseconds: (t, int) => unit = "setUTCMilliseconds" + +@send external toDateString: t => string = "toDateString" +@send external toString: t => string = "toString" +@send external toTimeString: t => string = "toTimeString" + +@send external toLocaleDateString: t => string = "toLocaleDateString" +@send external toLocaleDateStringWithLocale: (t, string) => string = "toLocaleDateString" +@send +external toLocaleDateStringWithLocaleAndOptions: (t, string, localeOptions) => string = + "toLocaleDateString" +@send external toLocaleString: t => string = "toLocaleString" +@send external toLocaleStringWithLocale: (t, string) => string = "toLocaleString" +@send +external toLocaleStringWithLocaleAndOptions: (t, string, localeOptions) => string = "toLocaleString" +@send external toLocaleTimeString: t => string = "toLocaleTimeString" +@send external toLocaleTimeStringWithLocale: (t, string) => string = "toLocaleTimeString" +@send +external toLocaleTimeStringWithLocaleAndOptions: (t, string, localeOptions) => string = + "toLocaleTimeString" + +@send external toISOString: t => string = "toISOString" +@send external toUTCString: t => string = "toUTCString" +@return(nullable) @send external toJSON: t => option = "toJSON" diff --git a/jscomp/stdlib-406/Date.resi b/jscomp/stdlib-406/Date.resi new file mode 100644 index 0000000000..f0d975ba1a --- /dev/null +++ b/jscomp/stdlib-406/Date.resi @@ -0,0 +1,1360 @@ +/*** + Functions for interacting with JavaScript Dates. +*/ + +/** +A type representing a JavaScript date. +*/ +type t = Js.Date.t + +/** +Time, in milliseconds, since / until the UNIX epoch (January 1, 1970 00:00:00 UTC). +Positive numbers represent dates after, negative numbers dates before epoch. +*/ +type msSinceEpoch = float + +/** +A type representing date time format options. + +Note: There are some properties missing: +- fractionalSecondDigits +- dayPeriod +- calendar +- numberingSystem +- localeMatcher +- timeZone +- hour12 +- hourCycle +- formatMatcher + +See full spec at https://tc39.es/ecma402/#datetimeformat-objects +*/ +type localeOptions = { + dateStyle?: [#full | #long | #medium | #short], + timeStyle?: [#full | #long | #medium | #short], + weekday?: [#long | #narrow | #short], + era?: [#long | #narrow | #short], + year?: [#"2-digit" | #numeric], + month?: [#"2-digit" | #long | #narrow | #numeric | #short], + day?: [#"2-digit" | #numeric], + hour?: [#"2-digit" | #numeric], + minute?: [#"2-digit" | #numeric], + second?: [#"2-digit" | #numeric], + timeZoneName?: [#long | #short], +} + +/** +`make()` + +Creates a date object with the current date time as value. + +## Examples +```rescript +Date.make() +``` +*/ +@new +external make: unit => t = "Date" + +/** +`fromString(dateTimeString)` + +Creates a date object from given date time string. +The string has to be in the ISO 8601 format YYYY-MM-DDTHH:mm:ss.sssZ (https://tc39.es/ecma262/#sec-date-time-string-format). + +Invalid date time strings will create invalid dates. +You can use the result like any valid date, but many functions like `toString` will return "Invalid Date" or functions like `Date.getTime` will return NaN. + +## Examples +```rescript +Date.fromString("2023") // 2023-01-01T00:00:00.000Z + +Date.fromString("2023-02-20") // 2023-02-20T00:00:00.000Z + +Date.fromString("2023-02-20T16:40:00.00Z") // 2023-02-20T16:40:00.000Z + +Date.fromString("") // Invalid Date + +Date.fromString("")->Date.getTime // NaN +``` +*/ +@new +external fromString: string => t = "Date" + +/** +`fromTime(msSinceEpoch)` + +Creates a date object from the given time in milliseconds since / until UNIX epoch (January 1, 1970 00:00:00 UTC). +Positive numbers create dates after epoch, negative numbers create dates before epoch. + +## Examples +```rescript +Date.fromTime(0.0) +// 1970-01-01T00:00:00.000Z + +Date.fromTime(-86_400_000.0) +// 1969-12-31T00:00:00.000Z + +Date.fromTime(86_400_000.0) +// 1970-01-02T00:00:00.000Z +``` +*/ +@new +external fromTime: msSinceEpoch => t = "Date" + +/** +Creates a date object with the given year and month. +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYM(~year=2023, ~month=0) +// 2023-01-01T00:00:00.000Z + +Date.makeWithYM(~year=2023, ~month=11) +// 2023-12-01T00:00:00.000Z + +Date.makeWithYM(~year=2023, ~month=12) +// 2024-01-01T00:00:00.000Z + +Date.makeWithYM(~year=2023, ~month=-1) +// 2022-12-01T00:00:00.000Z + +// Note: The output depends on your local time zone. +// In nodejs you can change it by using the TZ env (`export TZ='Europe/London' && node index.bs.js`) + +``` +*/ +@new +external makeWithYM: (~year: int, ~month: int) => t = "Date" + +/** +Creates a date object with the given year, month and date (day of month). +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYMD(~year=2023, ~month=1, ~date=20) +// 2023-02-20T00:00:00.000Z + +Date.makeWithYMD(~year=2023, ~month=1, ~date=-1) +// 2022-11-29T00:00:00.000Z + +Date.makeWithYMD(~year=2023, ~month=1, ~date=29) +// 2023-03-01T00:00:00.000Z +``` +*/ +@new +external makeWithYMD: (~year: int, ~month: int, ~date: int) => t = "Date" + +/** +Creates a date object with the given year, month, date (day of month) and hours. +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=16) +// 2023-02-20T16:00:00.000Z + +Date.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=24) +// 2023-02-21T00:00:00.000Z + +Date.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=-1) +// 2023-02-19T23:00:00.000Z + +// Note: The output depends on your local time zone. +// In nodejs you can change it by using the TZ env (`export TZ='Europe/London' && node index.bs.js`) + +``` +*/ +@new +external makeWithYMDH: (~year: int, ~month: int, ~date: int, ~hours: int) => t = "Date" + +/** +Creates a date object with the given year, month, date (day of month), hours and minutes. +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40) +// 2023-02-20T16:40:00.000Z + +Date.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=60) +// 2023-02-20T17:00:00.000Z + +Date.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=-1) +// 2023-02-20T15:59:00.000Z + +// Note: The output depends on your local time zone. +// In nodejs you can change it by using the TZ env (`export TZ='Europe/London' && node index.bs.js`) + +``` +*/ +@new +external makeWithYMDHM: (~year: int, ~month: int, ~date: int, ~hours: int, ~minutes: int) => t = + "Date" + +/** +Creates a date object with the given year, month, date (day of month), hours, minutes and seconds. +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0) +// 2023-02-20T16:40:00.000Z + +Date.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=60) +// 2023-02-20T16:41:00.000Z + +Date.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=-1) +// 2023-02-20T16:39:59.000Z + +// Note: The output depends on your local time zone. +// In nodejs you can change it by using the TZ env (`export TZ='Europe/London' && node index.bs.js`) + +``` +*/ +@new +external makeWithYMDHMS: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, +) => t = "Date" + +/** +Creates a date object with the given year, month, date (day of month), hours, minutes, seconds and milliseconds. +Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). +Months are 0-indexed (0 = January, 11 = December). +Values, which are out of range, will be carried over to the next bigger unit (s. example). + +## Examples +```rescript +Date.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=0) +// 2023-02-20T16:40:00.000Z + +Date.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=1000) +// 2023-02-20T16:40:01.000Z + +Date.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=-1) +// 2023-02-20T16:39:59.999Z + +// Note: The output depends on your local time zone. +// In nodejs you can change it by using the TZ env (`export TZ='Europe/London' && node index.bs.js`) + +``` +*/ +@new +external makeWithYMDHMSM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, +) => t = "Date" +module UTC: { + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYM(~year=2023, ~month=0) + // 1672531200000 + + Date.UTC.makeWithYM(~year=2023, ~month=11) + // 1701388800000 + + Date.UTC.makeWithYM(~year=2023, ~month=12) + // 1704067200000 + + Date.UTC.makeWithYM(~year=2023, ~month=-1) + // 1669852800000 + ``` + */ + @val + external makeWithYM: (~year: int, ~month: int) => msSinceEpoch = "Date.UTC" + + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYMD(~year=2023, ~month=1, ~date=20) + // 1676851200000 + + Date.UTC.makeWithYMD(~year=2023, ~month=1, ~date=-1) + // 1675036800000 + + Date.UTC.makeWithYMD(~year=2023, ~month=1, ~date=29) + // 1677628800000 + ``` + */ + @val + external makeWithYMD: (~year: int, ~month: int, ~date: int) => msSinceEpoch = "Date.UTC" + + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=16) + // 1676908800000 + + Date.UTC.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=24) + // 1676937600000 + + Date.UTC.makeWithYMDH(~year=2023, ~month=1, ~date=20, ~hours=-1) + // 1676847600000 + ``` + */ + @val + external makeWithYMDH: (~year: int, ~month: int, ~date: int, ~hours: int) => msSinceEpoch = + "Date.UTC" + + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40) + // 1676911200000 + + Date.UTC.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=60) + // 1676912400000 + + Date.UTC.makeWithYMDHM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=-1) + // 1676908740000 + ``` + */ + @val + external makeWithYMDHM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ) => msSinceEpoch = "Date.UTC" + + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0) + // 1676911200000 + + Date.UTC.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=60) + // 1676911260000 + + Date.UTC.makeWithYMDHMS(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=-1) + // 1676911199000 + ``` + */ + @val + external makeWithYMDHMS: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ) => msSinceEpoch = "Date.UTC" + + /** + Returns the time, in milliseconds, since UNIX epoch (January 1, 1970 00:00:00 UTC). + Be aware of using a value for year < 100, because it behaves inconsistent (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#interpretation_of_two-digit_years). + Months are 0-indexed (0 = January, 11 = December). + Values, which are out of range, will be carried over to the next bigger unit (s. example). + + ## Examples + ```rescript + Date.UTC.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=0)->Console.log + // 1676911200000 + + Date.UTC.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=1000)->Console.log + // 1676911201000 + + Date.UTC.makeWithYMDHMSM(~year=2023, ~month=1, ~date=20, ~hours=16, ~minutes=40, ~seconds=0, ~milliseconds=-1)->Console.log + // 1676911199999 + ``` + */ + @val + external makeWithYMDHMSM: ( + ~year: int, + ~month: int, + ~date: int, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, + ) => msSinceEpoch = "Date.UTC" +} + +/** +`now()` + +Returns the time, in milliseconds, between UNIX epoch (January 1, 1970 00:00:00 UTC) and the current date time. +*/ +@val +external now: unit => msSinceEpoch = "Date.now" + +let equal: (t, t) => bool + +let compare: (t, t) => Ordering.t + +/** +`getTime(date)` + +Returns the time, in milliseconds, between UNIX epoch (January 1, 1970 00:00:00 UTC) and the current date time. +Invalid dates will return NaN. +Dates before epoch will return negative numbers. + +## Examples +```rescript +Date.fromString("2023-02-20")->Date.getTime +// 1676851200000 +``` +*/ +@send +external getTime: t => msSinceEpoch = "getTime" + +/** +`getTimezoneOffset(date)` + +Returns the time in minutes between the UTC time and the locale time. +The timezone of the given date doesn't matter. + +## Examples +```rescript +Date.fromString("2023-01-01")->Date.getTimezoneOffset +// -60 with local time zone = Europe/Berlin + +Date.fromString("2023-06-01")->Date.getTimezoneOffset +// -120 with local time zone = Europe/Berlin +``` +*/ +@send +external getTimezoneOffset: t => int = "getTimezoneOffset" + +/** +`getFullYear(date)` + +Returns the year of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20")->Date.getFullYear +// 2023 +``` +*/ +@send +external getFullYear: t => int = "getFullYear" + +/** +`getMonth(date)` + +Returns the month (0-indexed) of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-01-01")->Date.getMonth +// 0 +``` +*/ +@send +external getMonth: t => int = "getMonth" + +/** +`getDate(date)` + +Returns the date (day of month) of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getDate +// 20 +``` +*/ +@send +external getDate: t => int = "getDate" + +/** +`getHours(date)` + +Returns the hours of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getHours +// 16 +``` +*/ +@send +external getHours: t => int = "getHours" + +/** +`getMinutes(date)` + +Returns the minutes of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getMinutes +// 40 +``` +*/ +@send +external getMinutes: t => int = "getMinutes" + +/** +`getSeconds(date)` + +Returns the seconds of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getSeconds +// 0 +``` +*/ +@send +external getSeconds: t => int = "getSeconds" + +/** +`getMilliseconds(date)` + +Returns the milliseconds of a given date (according to local time). + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getMilliseconds +// 0 +``` +*/ +@send +external getMilliseconds: t => int = "getMilliseconds" + +/** +`getDay(date)` + +Returns the day of week of a given date (according to local time). +0 = Sunday, 1 = Monday, ... 6 = Saturday + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.getDay +// 1 +``` +*/ +@send +external getDay: t => int = "getDay" + +/** +`setFullYear(date, year)` + +Sets the year of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setFullYear(2024) +``` +*/ +@send +external setFullYear: (t, int) => unit = "setFullYear" + +/** +`setFullYearM(date, ~year, ~month)` + +Sets the year and month of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setFullYearM(~year=2024, ~month=0) +``` +*/ +@send +external setFullYearM: (t, ~year: int, ~month: int) => unit = "setFullYear" + +/** +`setFullYearMD(date, ~year, ~month, ~date)` + +Sets the year, month and date (day of month) of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setFullYearMD(~year=2024, ~month=0, ~date=1) +``` +*/ +@send +external setFullYearMD: (t, ~year: int, ~month: int, ~date: int) => unit = "setFullYear" + +/** +`setMonth(date, month)` + +Sets the month of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setMonth(0) +``` +*/ +@send +external setMonth: (t, int) => unit = "setMonth" + +/** +`setDate(date, day)` + +Sets the date (day of month) of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setDate(1) +``` +*/ +@send +external setDate: (t, int) => unit = "setDate" + +/** +`setHours(date, hours)` + +Sets the hours of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setHours(0) +``` +*/ +@send +external setHours: (t, int) => unit = "setHours" + +/** +`setHoursM(date, ~hours, ~minutes)` + +Sets the hours and minutes of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setHoursM(~hours=0, ~minutes=0) +``` +*/ +@send +external setHoursM: (t, ~hours: int, ~minutes: int) => unit = "setHours" + +/** +`setHoursMS(date, ~hours, ~minutes, ~seconds)` + +Sets the hours, minutes and seconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setHoursMS(~hours=0, ~minutes=0, ~seconds=0) +``` +*/ +@send +external setHoursMS: (t, ~hours: int, ~minutes: int, ~seconds: int) => unit = "setHours" + +/** +`setHoursMSMs(date, ~hours, ~minutes, ~seconds, ~milliseconds)` + +Sets the hours, minutes, seconds and milliseconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setHoursMSMs(~hours=0, ~minutes=0, ~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setHoursMSMs: (t, ~hours: int, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = + "setHours" + +/** +`setMinutes(date, minutes)` + +Sets the minutes of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setMinutes(0) +``` +*/ +@send +external setMinutes: (t, int) => unit = "setMinutes" + +/** +`setMinutesS(date, ~minutes, ~seconds)` + +Sets the minutes and seconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setMinutesS(~minutes=0, ~seconds=0) +``` +*/ +@send +external setMinutesS: (t, ~minutes: int, ~seconds: int) => unit = "setMinutes" + +/** +`setMinutesSMs(date, ~minutes, ~seconds, ~milliseconds)` + +Sets the minutes, seconds and milliseconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setMinutesSMs(~minutes=0, ~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setMinutesSMs: (t, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = "setMinutes" + +/** +`setSeconds(date, seconds)` + +Sets the seconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setSeconds(0) +``` +*/ +@send +external setSeconds: (t, int) => unit = "setSeconds" + +/** +`setSecondsMs(date, ~seconds, ~milliseconds)` + +Sets the seconds and milliseconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setSecondsMs(~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setSecondsMs: (t, ~seconds: int, ~milliseconds: int) => unit = "setSeconds" + +/** +`setMilliseconds(date, milliseconds)` + +Sets the milliseconds of a date (according to local time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setMilliseconds(0) +``` +*/ +@send +external setMilliseconds: (t, int) => unit = "setMilliseconds" + +/** +`getUTCFullYear(date)` + +Returns the year of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCFullYear // 2022 +``` +*/ +@send +external getUTCFullYear: t => int = "getUTCFullYear" + +/** +`getUTCMonth(date)` + +Returns the month of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCMonth // 11 +``` +*/ +@send +external getUTCMonth: t => int = "getUTCMonth" + +/** +`getUTCDate(date)` + +Returns the date (day of month) of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCDate // 31 +``` +*/ +@send +external getUTCDate: t => int = "getUTCDate" + +/** +`getUTCHours(date)` + +Returns the hours of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCHours // 23 +``` +*/ +@send +external getUTCHours: t => int = "getUTCHours" + +/** +`getUTCMinutes(date)` + +Returns the minutes of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCMinutes // 0 +``` +*/ +@send +external getUTCMinutes: t => int = "getUTCMinutes" + +/** +`getUTCSeconds(date)` + +Returns the seconds of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCSeconds // 0 +``` +*/ +@send +external getUTCSeconds: t => int = "getUTCSeconds" + +/** +`getUTCMilliseconds(date)` + +Returns the milliseconds of a given date (according to UTC time). + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCMilliseconds // 0 +``` +*/ +@send +external getUTCMilliseconds: t => int = "getUTCMilliseconds" + +/** +`getUTCDay(date)` + +Returns the day (day of week) of a given date (according to UTC time). +0 = Sunday, 1 = Monday, ... 6 = Saturday + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.getUTCDay // 6 +``` +*/ +@send +external getUTCDay: t => int = "getUTCDay" + +/** +`setUTCFullYear(date, year)` + +Sets the year of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCFullYear(2024) +``` +*/ +@send +external setUTCFullYear: (t, int) => unit = "setUTCFullYear" + +/** +`setUTCFullYearM(date, ~year, ~month)` + +Sets the year and month of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCFullYearM(~year=2024, ~month=0) +``` +*/ +@send +external setUTCFullYearM: (t, ~year: int, ~month: int) => unit = "setUTCFullYear" + +/** +`setUTCFullYearMD(date, ~year, ~month, ~date)` + +Sets the year, month and date (day of month) of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCFullYearMD(~year=2024, ~month=0, ~date=1) +``` +*/ +@send +external setUTCFullYearMD: (t, ~year: int, ~month: int, ~date: int) => unit = "setUTCFullYear" + +/** +`setUTCMonth(date, month)` + +Sets the month of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCMonth(0) +``` +*/ +@send +external setUTCMonth: (t, int) => unit = "setUTCMonth" + +/** +`setDate(date, day)` + +Sets the date (day of month) of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCDate(1) +``` +*/ +@send +external setUTCDate: (t, int) => unit = "setUTCDate" + +/** +`setUTCHours(date, hours)` + +Sets the hours of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCHours(0) +``` +*/ +@send +external setUTCHours: (t, int) => unit = "setUTCHours" + +/** +`setHoursM(date, ~hours, ~minutes)` + +Sets the hours and minutes of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCHoursM(~hours=0, ~minutes=0) +``` +*/ +@send +external setUTCHoursM: (t, ~hours: int, ~minutes: int) => unit = "setUTCHours" + +/** +`setUTCHoursMS(date, ~hours, ~minutes, ~seconds)` + +Sets the hours, minutes and seconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCHoursMS(~hours=0, ~minutes=0, ~seconds=0) +``` +*/ +@send +external setUTCHoursMS: (t, ~hours: int, ~minutes: int, ~seconds: int) => unit = "setUTCHours" + +/** +`setUTCHoursMSMs(date, ~hours, ~minutes, ~seconds, ~milliseconds)` + +Sets the hours, minutes, seconds and milliseconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCHoursMSMs(~hours=0, ~minutes=0, ~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setUTCHoursMSMs: ( + t, + ~hours: int, + ~minutes: int, + ~seconds: int, + ~milliseconds: int, +) => unit = "setUTCHours" + +/** +`setUTCMinutes(date, minutes)` + +Sets the minutes of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCMinutes(0) +``` +*/ +@send +external setUTCMinutes: (t, int) => unit = "setUTCMinutes" + +/** +`setUTCMinutesS(date, ~minutes, ~seconds)` + +Sets the minutes and seconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCMinutesS(~minutes=0, ~seconds=0) +``` +*/ +@send +external setUTCMinutesS: (t, ~minutes: int, ~seconds: int) => unit = "setUTCMinutes" + +/** +`setUTCMinutesSMs(date, ~minutes, ~seconds, ~milliseconds)` + +Sets the minutes, seconds and milliseconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCMinutesSMs(~minutes=0, ~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setUTCMinutesSMs: (t, ~minutes: int, ~seconds: int, ~milliseconds: int) => unit = + "setUTCMinutes" + +/** +`setUTCSeconds(date, seconds)` + +Sets the seconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCSeconds(0) +``` +*/ +@send +external setUTCSeconds: (t, int) => unit = "setUTCSeconds" + +/** +`setUTCSecondsMs(date, ~seconds, ~milliseconds)` + +Sets the seconds and milliseconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCSecondsMs(~seconds=0, ~milliseconds=0) +``` +*/ +@send +external setUTCSecondsMs: (t, ~seconds: int, ~milliseconds: int) => unit = "setUTCSeconds" + +/** +`setUTCMilliseconds(date, milliseconds)` + +Sets the milliseconds of a date (according to UTC time). +Beware this will *mutate* the date. + +## Examples +```rescript +Date.fromString("2023-02-20T16:40:00.00")->Date.setUTCMilliseconds(0) +``` +*/ +@send +external setUTCMilliseconds: (t, int) => unit = "setUTCMilliseconds" + +/** +`toDateString(date)` + +Converts a JavaScript date to a standard date string. The date will be mapped to the current time zone. +If you want to convert it to a localized string, use `Date.toLocaleDateString` instead. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.toDateString->Console.log +// Sun Jan 01 2023 + +Date.fromString("2023-01-01T00:00:00.00+08:00")->Date.toDateString->Console.log +// Sat Dec 31 2022 +``` +*/ +@send +external toDateString: t => string = "toDateString" + +/** +`toString(date)` + +Converts a JavaScript date to a standard date time string. The date will be mapped to the current time zone. +If you want to convert it to a localized string, use `Date.toLocaleString` instead. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.toString->Console.log +// Sun Jan 01 2023 00:00:00 GMT+0100 (Central European Standard Time) + +Date.fromString("2023-06-01T00:00:00.00+01:00")->Date.toString->Console.log +// Thu Jun 01 2023 01:00:00 GMT+0200 (Central European Summer Time) +``` +*/ +@send +external toString: t => string = "toString" + +/** +`toTimeString(date)` + +Converts a JavaScript date to a standard time string. The date will be mapped to the current time zone. +If you want to convert it to a localized string, use `Date.toLocaleStimeString` instead. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+01:00")->Date.toTimeString->Console.log +// 00:00:00 GMT+0100 (Central European Standard Time) + +Date.fromString("2023-01-01T00:00:00.00+08:00")->Date.toTimeString->Console.log +// 17:00:00 GMT+0100 (Central European Standard Time) +``` +*/ +@send +external toTimeString: t => string = "toTimeString" + +/** +`toLocaleDateString(date)` + +Converts a JavaScript date to a localized date string. It will use the current locale. + +## Examples +```rescript +Date.make()->Date.toLocaleDateString->Console.log +// 2/19/2023 +``` +*/ +@send +external toLocaleDateString: t => string = "toLocaleDateString" + +/** +`toLocaleDateStringWithLocale(date, locale)` + +Converts a JavaScript date to a localized date string. It will use the specified locale. + +## Examples +```rescript +Date.make()->Date.toLocaleDateStringWithLocale("en-US")->Console.log +// 2/19/2023 +``` +*/ +@send +external toLocaleDateStringWithLocale: (t, string) => string = "toLocaleDateString" + +/** +`toLocaleDateStringWithLocaleAndOptions(date, locale, options)` + +Converts a JavaScript date to a localized date string. It will use the specified locale and formatting options. + +## Examples +```rescript +Date.make()->Date.toLocaleDateStringWithLocaleAndOptions("en-US", { dateStyle: #long })->Console.log +// February 19, 2023 + +Date.make()->Date.toLocaleDateStringWithLocaleAndOptions("de", { hour: #"2-digit", minute: #"2-digit" })->Console.log +// 19.2.2023, 15:40 + +Date.make()->Date.toLocaleDateStringWithLocaleAndOptions("de", { year: #numeric })->Console.log +// 2023 +``` +*/ +@send +external toLocaleDateStringWithLocaleAndOptions: (t, string, localeOptions) => string = + "toLocaleDateString" + +/** +`toLocaleString(date)` + +Converts a JavaScript date to a localized date-time string. It will use the current locale. + +## Examples +```rescript +Date.make()->Date.toLocaleString->Console.log +// 2/19/2023, 3:40:00 PM +``` +*/ +@send +external toLocaleString: t => string = "toLocaleString" + +/** +`toLocaleStringWithLocale(date, locale)` + +Converts a JavaScript date to a localized date-time string. It will use the specified locale. + +## Examples +```rescript +Date.make()->Date.toLocaleStringWithLocale("en-US")->Console.log +// 2/19/2023, 3:40:00 PM +``` +*/ +@send +external toLocaleStringWithLocale: (t, string) => string = "toLocaleString" + +/** +`toLocaleStringWithLocaleAndOptions(date, locale, options)` + +Converts a JavaScript date to a localized date-time string. It will use the specified locale and formatting options. + +## Examples +```rescript +Date.make()->Date.toLocaleStringWithLocaleAndOptions("en", { dateStyle: #short, timeStyle: #short })->Console.log +// 2/19/23, 3:40 PM + +Date.make()->Date.toLocaleStringWithLocaleAndOptions("en", { era: #long, year: #numeric, month: #"2-digit", day: #"2-digit", hour: #numeric, timeZoneName: #short })->Console.log +// 02/19/2023 Anno Domini, 3 PM GMT+1 +``` +*/ +@send +external toLocaleStringWithLocaleAndOptions: (t, string, localeOptions) => string = "toLocaleString" + +/** +`toLocaleTimeString(date)` + +Converts a JavaScript date to a localized time string. It will use the current locale. + +## Examples +```rescript +Date.make()->Date.toLocaleTimeString->Console.log +// 3:40:00 PM +``` +*/ +@send +external toLocaleTimeString: t => string = "toLocaleTimeString" + +/** +`toLocaleTimeStringWithLocale(date, locale)` + +Converts a JavaScript date to a localized time string. It will use the specified locale. + +## Examples +```rescript +Date.make()->Date.toLocaleTimeStringWithLocale("en-US")->Console.log +// 3:40:00 PM +``` +*/ +@send +external toLocaleTimeStringWithLocale: (t, string) => string = "toLocaleTimeString" + +/** +`toLocaleTimeStringWithLocaleAndOptions(date, locale, options)` + +Converts a JavaScript date to a localized time string. It will use the specified locale and formatting options. + +## Examples +```rescript +Date.make()->Date.toLocaleTimeStringWithLocaleAndOptions("en-US", { timeStyle: #long })->Console.log +// 3:40:00 PM GMT+1 + +Date.make()->Date.toLocaleTimeStringWithLocaleAndOptions("de", { hour: #"2-digit", minute: #"2-digit" })->Console.log +// 15:40 +``` +*/ +@send +external toLocaleTimeStringWithLocaleAndOptions: (t, string, localeOptions) => string = + "toLocaleTimeString" + +/** +`toISOString(date)` + +Converts a JavaScript date to a ISO 8601 string (YYYY-MM-DDTHH:mm:ss.sssZ). The date will be mapped to the UTC time. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+00:00")->Date.toISOString->Console.log +// 2023-01-01T00:00:00.000Z + +Date.fromString("2023-01-01T00:00:00.00+08:00")->Date.toISOString->Console.log +// 2022-12-31T16:00:00.000Z +``` +*/ +@send +external toISOString: t => string = "toISOString" + +/** +`toUTCString(date)` + +Converts a JavaScript date to date time string. The date will be mapped to the UTC time. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+00:00")->Date.toUTCString->Console.log +// Sun, 01 Jan 2023 00:00:00 GMT + +Date.fromString("2023-01-01T00:00:00.00+08:00")->Date.toUTCString->Console.log +// Sat, 31 Dec 2022 16:00:00 GMT +``` +*/ +@send +external toUTCString: t => string = "toUTCString" + +/** +`toJSON(date)` + +Converts a JavaScript date to a string. +If the date is valid, the function will return the same result as `Date.toISOString`. +Invalid dates will return `None`. + +## Examples +```rescript +Date.fromString("2023-01-01T00:00:00.00+00:00")->Date.toJSON +// Some("2023-01-01T00:00:00.000Z") + +Date.fromString("")->Date.toJSON +// None +``` +*/ +@return(nullable) +@send +external toJSON: t => option = "toJSON" diff --git a/jscomp/stdlib-406/Dict.res b/jscomp/stdlib-406/Dict.res new file mode 100644 index 0000000000..1fb910b3ce --- /dev/null +++ b/jscomp/stdlib-406/Dict.res @@ -0,0 +1,41 @@ +type t<'a> = Js.Dict.t<'a> + +@get_index external getUnsafe: (t<'a>, string) => 'a = "" +@get_index external get: (t<'a>, string) => option<'a> = "" +@set_index external set: (t<'a>, string, 'a) => unit = "" +@val external delete: 'a => unit = "delete" + +let delete = (dict, string) => { + delete(get(dict, string)) +} + +@obj external make: unit => t<'a> = "" + +@val external fromArray: array<(string, 'a)> => t<'a> = "Object.fromEntries" +@val external fromIterator: Iterator.t<(string, 'a)> => t<'a> = "Object.fromEntries" + +@val external toArray: t<'a> => array<(string, 'a)> = "Object.entries" + +@val external keysToArray: t<'a> => array = "Object.keys" + +@val external valuesToArray: t<'a> => array<'a> = "Object.values" + +@val external assign: (t<'a>, t<'a>) => t<'a> = "Object.assign" + +@val external copy: (@as(json`{}`) _, t<'a>) => t<'a> = "Object.assign" + +let forEach = (dict, f) => { + dict->valuesToArray - Array.forEach(value => f(value)) +} + +let forEachWithKey = (dict, f) => { + dict->toArray - Array.forEach(((key, value)) => f(value, key)) +} + +let mapValues = (dict, f) => { + let target = make() + dict->forEachWithKey((value, key) => { + target->set(key, f(value)) + }) + target +} diff --git a/jscomp/stdlib-406/Dict.resi b/jscomp/stdlib-406/Dict.resi new file mode 100644 index 0000000000..2850a12d20 --- /dev/null +++ b/jscomp/stdlib-406/Dict.resi @@ -0,0 +1,234 @@ +/*** +A mutable dictionary with string keys. + +Compiles to a regular JavaScript object.*/ + +/** +Type representing a dictionary of value `'a`. +*/ +type t<'a> = Js.Dict.t<'a> + +/** +`getUnsafe(dict, key)` Returns the `value` at the provided `key`. + +This is _unsafe_, meaning it will return `undefined` value if `key` does not exist in `dict`. + +Use `Dict.getUnsafe` only when you are sure the key exists (i.e. when iterating `Dict.keys` result). + +## Examples +```rescript +let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")]) +let value = dict->Dict.getUnsafe("key1") +Console.log(value) // value1 +``` +*/ +@get_index +external getUnsafe: (t<'a>, string) => 'a = "" + +/** +Returns the value at the provided key, if it exists. Returns an option. + +## Examples +```rescript +let dict = Dict.fromArray([("someKey", "someValue")]) + +switch dict->Dict.get("someKey") { +| None => Console.log("Nope, didn't have the key.") +| Some(value) => Console.log(value) +} +``` +*/ +@get_index +external get: (t<'a>, string) => option<'a> = "" + +/** +`set(dictionary, key, value)` sets the value at the provided key to the provided value. + +## Examples +```rescript +let dict = Dict.make() + +dict->Dict.set("someKey", "someValue") +``` +*/ +@set_index +external set: (t<'a>, string, 'a) => unit = "" + +/** +`delete(dictionary, key)` deletes the value at `key`, if it exists. + +## Examples +```rescript +let dict = Dict.fromArray([("someKey", "someValue")]) + +dict->Dict.delete("someKey") +``` +*/ +let delete: (t<'a>, string) => unit + +/** +`make()` creates a new, empty dictionary. + +## Examples +```rescript +let dict1: Dict.t = Dict.make() // You can annotate the type of the values of your dict yourself if you want + +let dict2 = Dict.make() // Or you can let ReScript infer it via usage. +dict2->Dict.set("someKey", 12) +``` +*/ +@obj +external make: unit => t<'a> = "" + +/** +`fromArray(entries)` creates a new dictionary from the provided array of key/value pairs. + +## Examples +```rescript +let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")]) +``` +*/ +@val +external fromArray: array<(string, 'a)> => t<'a> = "Object.fromEntries" + +/** +`fromIterator(entries)` creates a new dictionary from the provided iterator of key/value pairs. + +## Examples +```rescript +// Pretend we have an iterator of the correct shape +@val external someIterator: Iterator.t<(string, int)> = "someIterator" + +let dict = Dict.fromIterator(someIterator) // Dict.t +``` +*/ +@val +external fromIterator: Iterator.t<(string, 'a)> => t<'a> = "Object.fromEntries" + +/** +`toArray(dictionary)` returns an array of all the key/value pairs of the dictionary. + +## Examples +```rescript +let dict = Dict.make() +dict->Dict.set("someKey", 1) +dict->Dict.set("someKey2", 2) +let asArray = dict->Dict.toArray +Console.log(asArray) // Logs `[["someKey", 1], ["someKey2", 2]]` to the console +``` +*/ +@val +external toArray: t<'a> => array<(string, 'a)> = "Object.entries" + +/** +`keysToArray(dictionary)` returns an array of all the keys of the dictionary. + +## Examples +```rescript +let dict = Dict.make() +dict->Dict.set("someKey", 1) +dict->Dict.set("someKey2", 2) +let keys = dict->Dict.keysToArray +Console.log(keys) // Logs `["someKey", "someKey2"]` to the console +``` +*/ +@val +external keysToArray: t<'a> => array = "Object.keys" + +/** +`valuesToArray(dictionary)` returns an array of all the values of the dictionary. + +## Examples +```rescript +let dict = Dict.make() +dict->Dict.set("someKey", 1) +dict->Dict.set("someKey2", 2) +let values = dict->Dict.valuesToArray +Console.log(values) // Logs `[1, 2]` to the console +``` +*/ +@val +external valuesToArray: t<'a> => array<'a> = "Object.values" + +/** +`assign(dictionary1, dictionary2)` [shallowly](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) merges dictionary2 into dictionary1, and returns dictionary1. + +Beware this will *mutate* dictionary1. If you're looking for a way to copy a dictionary, check out `Dict.copy`. + +## Examples +```rescript +let dict1 = Dict.make() +dict1->Dict.set("firstKey", 1) +Console.log(dict1->Dict.keysToArray) // Logs `["firstKey"]` + +let dict2 = Dict.make() +dict2->Dict.set("someKey", 2) +dict2->Dict.set("someKey2", 3) + +let dict1 = dict1->Dict.assign(dict2) + +Console.log(dict1->Dict.keysToArray) // Logs `["firstKey", "someKey", "someKey2"]` + +``` +*/ +@val +external assign: (t<'a>, t<'a>) => t<'a> = "Object.assign" + +/** +`copy(dictionary)` [shallowly copies](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) the provided dictionary to a new dictionary. + +## Examples +```rescript +let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")]) +let dict2 = dict->Dict.copy + +// Both log `["key1", "key2"]` here. +Console.log2(dict->Dict.keysToArray, dict2->Dict.keysToArray) +``` +*/ +@val +external copy: (@as(json`{}`) _, t<'a>) => t<'a> = "Object.assign" + +/** +`forEach(dictionary, f)` iterates through all values of the dict. + +> Please note that this is *without the keys*, just the values. If you need the key as well, use `Dict.forEachWithKey`. + +## Examples +```rescript +let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")]) + +dict->Dict.forEach(value => { + Console.log(value) +}) +``` +*/ +let forEach: (t<'a>, 'a => unit) => unit + +/** +`forEachWithKey(dictionary, f)` iterates through all values of the dict, including the key for each value. + +## Examples +```rescript +let dict = Dict.fromArray([("key1", "value1"), ("key2", "value2")]) + +dict->Dict.forEachWithKey((value, key) => { + Console.log2(value, key) +}) +``` +*/ +let forEachWithKey: (t<'a>, ('a, string) => unit) => unit + +/** +`mapValues(dictionary, f)` returns a new dictionary with the same keys, and `f` applied to each value in the original dictionary. + +## Examples + +```rescript +let dict = Dict.fromArray([("key1", 1), ("key2", 2)]) + +dict->Dict.mapValues(v => v + 10)->Dict.toArray // [("key1", 11), ("key2", 12)] +dict->Dict.mapValues(v => Int.toString(v))->Dict.toArray // [("key1", "1"), ("key2", "2")] +``` +*/ +let mapValues: (t<'a>, 'a => 'b) => t<'b> diff --git a/jscomp/stdlib-406/Error.res b/jscomp/stdlib-406/Error.res new file mode 100644 index 0000000000..408b08ff56 --- /dev/null +++ b/jscomp/stdlib-406/Error.res @@ -0,0 +1,39 @@ +type t = Js.Exn.t + +external fromException: exn => option = "?as_js_exn" +external toException: t => exn = "%identity" + +@get external stack: t => option = "stack" +@get external message: t => option = "message" +@get external name: t => option = "name" +@get external fileName: t => option = "fileName" + +@new external make: string => t = "Error" + +module EvalError = { + @new external make: string => t = "EvalError" +} + +module RangeError = { + @new external make: string => t = "RangeError" +} + +module ReferenceError = { + @new external make: string => t = "ReferenceError" +} + +module SyntaxError = { + @new external make: string => t = "SyntaxError" +} + +module TypeError = { + @new external make: string => t = "TypeError" +} + +module URIError = { + @new external make: string => t = "URIError" +} + +external raise: t => 'a = "%raise" + +let panic = msg => make(`Panic! ${msg}`)->raise diff --git a/jscomp/stdlib-406/Error.resi b/jscomp/stdlib-406/Error.resi new file mode 100644 index 0000000000..38b6a97334 --- /dev/null +++ b/jscomp/stdlib-406/Error.resi @@ -0,0 +1,172 @@ +/*** +Functions for working with JavaScript exceptions. + +See [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) on MDN. +*/ + +/** Represents a JavaScript exception. */ +type t = Js.Exn.t + +external fromException: exn => option = "?as_js_exn" + +/** +Turns an `Error.t` into an `exn`. + +## Examples +```rescript +let error = Error.make("Something went wrong.") + +let asExn = error->Error.toException // `asExn` is now type `exn` +``` +*/ +external toException: t => exn = "%identity" + +/** +`stack(error)` retrieves the `stack` property of the error, if it exists. The stack is a list of what functions were called, and what files they are defined in, prior to the error happening. + +See [`Error.prototype.stack`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack) on MDN. + +## Example +```rescript +let error = Error.make("error") +Console.log(error->Error.stack) // Logs `stack` if it exists on `someError` +``` +*/ +@get +external stack: t => option = "stack" + +/** +`message(error)` retrieves the `message` property of the error, if it exists. + +See [`Error.prototype.message`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/message) on MDN. + +## Example +```rescript +let error = Error.SyntaxError.make("Some message here") +Console.log(error->Error.message) // Logs "Some message here" to the console +``` +*/ +@get +external message: t => option = "message" + +/** +`name(error)` retrieves the `name` property of the error, if it exists. + +See [`Error.prototype.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name) on MDN. + +## Example +```rescript +let error = Error.SyntaxError.make("Some message here") +Console.log(error->Error.name) // Logs "SyntaxError" to the console +``` +*/ +@get +external name: t => option = "name" + +/** +`fileName(error)` retrieves the `fileName` property of the error, if it exists. + +See [`Error.prototype.fileName`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/fileName) on MDN. +*/ +@get +external fileName: t => option = "fileName" + +/** +`make(message)` creates a new error, setting its `message` to the provided value. + +See [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) on MDN. + +## Example +```rescript +let error = Error.make("Some message here") +Console.log(error->Error.message) // Logs "Some message here" to the console +Console.log(error->Error.name) // Logs "Error" to the console, because this is a regular error +``` +*/ +@new +external make: string => t = "Error" + +module EvalError: { + /** + Creates a new `EvalError` with the provided `message`. + + See [`EvalError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError) on MDN. + */ + @new + external make: string => t = "EvalError" +} +module RangeError: { + /** + Creates a new `RangeError` with the provided `message`. + + See [`RangeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError) on MDN. + */ + @new + external make: string => t = "RangeError" +} +module ReferenceError: { + /** + Creates a new `ReferenceError` with the provided `message`. + + See [`ReferenceError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError) on MDN. + */ + @new + external make: string => t = "ReferenceError" +} +module SyntaxError: { + /** + Creates a new `SyntaxError` with the provided `message`. + + See [`SyntaxError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError) on MDN. + */ + @new + external make: string => t = "SyntaxError" +} +module TypeError: { + /** + Creates a new `TypeError` with the provided `message`. + + See [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) on MDN. + */ + @new + external make: string => t = "TypeError" +} +module URIError: { + /** + Creates a new `URIError` with the provided `message`. + + See [`URIError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError) on MDN. + */ + @new + external make: string => t = "URIError" +} + +/** +Raises (throws in JavaScript language) the provided `Error.t`, which will stop execution. + +## Examples +```rescript +let error = Error.make("Everything is upside down.") + +if 5 > 10 { + error->Error.raise +} else { + Console.log("Phew, sanity still rules.") +} +``` +*/ +external raise: t => 'a = "%raise" + +/** +Raises a panic exception with the given message. + +A panic exception is a native JavaScript exception that is not intended to be caught and +handled. Compared to a ReScript exception this will give a better stack trace and +debugging experience. + +## Examples +```rescript +Error.panic("Uh oh. This was unexpected!") +``` +*/ +let panic: string => 'a diff --git a/jscomp/stdlib-406/Float.res b/jscomp/stdlib-406/Float.res new file mode 100644 index 0000000000..5009cc7c8b --- /dev/null +++ b/jscomp/stdlib-406/Float.res @@ -0,0 +1,60 @@ +module Constants = { + @val external nan: float = "NaN" + @val external epsilon: float = "Number.EPSILON" + @val external positiveInfinity: float = "Number.POSITIVE_INFINITY" + @val external negativeInfinity: float = "Number.NEGATIVE_INFINITY" + @val external minValue: float = "Number.MIN_VALUE" + @val external maxValue: float = "Number.MAX_VALUE" +} + +let equal = (a: float, b: float) => a === b + +let compare = (a: float, b: float) => + a < b ? Ordering.less : a > b ? Ordering.greater : Ordering.equal + +@val external isNaN: float => bool = "isNaN" +@val external isFinite: float => bool = "isFinite" +@val external parseFloat: 'a => float = "parseFloat" +// parseInt's return type is a float because it can be NaN +@val external parseInt: ('a, ~radix: int=?) => float = "parseInt" +@deprecated("Use `parseInt` instead") @val +external parseIntWithRadix: ('a, ~radix: int) => float = "parseInt" + +@send external toExponential: (float, ~digits: int=?) => string = "toExponential" +@deprecated("Use `toExponential` instead") @send +external toExponentialWithPrecision: (float, ~digits: int) => string = "toExponential" + +@send external toFixed: (float, ~digits: int=?) => string = "toFixed" +@deprecated("Use `toFixed` instead") @send +external toFixedWithPrecision: (float, ~digits: int) => string = "toFixed" + +@send external toPrecision: (float, ~digits: int=?) => string = "toPrecision" +@deprecated("Use `toPrecision` instead") @send +external toPrecisionWithPrecision: (float, ~digits: int) => string = "toPrecision" + +@send external toString: (float, ~radix: int=?) => string = "toString" +@deprecated("Use `toString` instead") @send +external toStringWithRadix: (float, ~radix: int) => string = "toString" +@send external toLocaleString: float => string = "toLocaleString" + +let fromString = i => + switch parseFloat(i) { + | i if isNaN(i) => None + | i => Some(i) + } + +external toInt: float => int = "%intoffloat" +external fromInt: int => float = "%identity" + +@unboxed @noalloc external mod: (float, float) => float = "?fmod_float" + +let clamp = (~min=?, ~max=?, value): float => { + let value = switch max { + | Some(max) if max < value => max + | _ => value + } + switch min { + | Some(min) if min > value => min + | _ => value + } +} diff --git a/jscomp/stdlib-406/Float.resi b/jscomp/stdlib-406/Float.resi new file mode 100644 index 0000000000..b00c91ed25 --- /dev/null +++ b/jscomp/stdlib-406/Float.resi @@ -0,0 +1,460 @@ +/* Copyright (C) 2015-2016 Bloomberg Finance L.P. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/*** +Functions for interacting with float. +*/ + +/** +Float constants. +*/ +module Constants: { + /** + The special value "Not a Number" + See [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) on MDN. + + ## Examples + + ```rescript + Float.Constants.nan + ``` + */ + @val + external nan: float = "NaN" + + /** + Represents the difference between 1 and the smallest floating point number greater than 1. + See [`Number.EPSILON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) on MDN. + + ## Examples + + ```rescript + Float.Constants.epsilon + ``` + */ + @val + external epsilon: float = "Number.EPSILON" + + /** + The positive Infinity value + See [`Number.POSITIVE_INFINITY`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY) on MDN. + + ## Examples + + ```rescript + Float.Constants.positiveInfinity + ``` + */ + @val + external positiveInfinity: float = "Number.POSITIVE_INFINITY" + + /** + The negative Infinity value + See [`Number.NEGATIVE_INFINITY`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY) on MDN. + + ## Examples + + ```rescript + Float.Constants.negativeInfinity + ``` + */ + @val + external negativeInfinity: float = "Number.NEGATIVE_INFINITY" + + /** + The smallest positive numeric value representable in JavaScript. + See [`Number.MIN_VALUE`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE) on MDN. + + ## Examples + + ```rescript + Float.Constants.minValue + ``` + */ + @val + external minValue: float = "Number.MIN_VALUE" + + /** + The maximum positive numeric value representable in JavaScript. + See [`Number.MAX_VALUE`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE) on MDN. + + ## Examples + + ```rescript + Float.Constants.minValue + ``` + */ + @val + external maxValue: float = "Number.MAX_VALUE" +} + +let equal: (float, float) => bool + +let compare: (float, float) => Ordering.t + +/** +`isNaN(v)` tests if the given `v` is `NaN`. +See [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) on MDN. + +## Examples + +```rescript +Float.isNaN(3.0) // false +Float.isNaN(Float.Constants.nan) // true +``` +*/ +@val +external isNaN: float => bool = "isNaN" + +/** +`isFinite(v)` tests if the given `v` is finite. +See [`isFinite`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) on MDN. + +## Examples + +```rescript +Float.isFinite(1.0) // true +Float.isFinite(Float.Constants.nan) // false +Float.isFinite(Float.Constants.positiveInfinity) // false +``` +*/ +@val +external isFinite: float => bool = "isFinite" + +/** +`parseFloat(v)` parse the given `v` and returns a float. Leading whitespace in +`v` is ignored. Returns `NaN` if `v` can't be parsed. Use [`fromString`] to +ensure it returns a valid float and not `NaN`. +See [`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) on MDN. + +## Examples + +```rescript +Float.parseFloat("1.0") // 1.0 +Float.parseFloat(" 3.14 ") // 3.14 +Float.parseFloat("3.0") // 3.0 +Float.parseFloat("3.14some non-digit characters") // 3.14 +Float.parseFloat("error")->Float.isNaN // true +``` +*/ +@val +external parseFloat: string => float = "parseFloat" + +/** +`parseInt(v, ~radix=?)` parse the given `v` and returns a float. Leading +whitespace in this argument `v`is ignored. `radix` specifies the radix base to +use for the formatted number. The value must be in the range [2, 36] (inclusive). +Returns `NaN` if `v` can't be parsed and `radix` is smaller than 2 or bigger +than 36. +See [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) on MDN. + +## Examples + +```rescript +Float.parseInt("1.0") // 1.0 +Float.parseInt(" 3.14 ") // 3.0 +Float.parseInt(3) // 3.0 +Float.parseInt("3.14some non-digit characters") // 3.0 +Float.parseInt("error")->Float.isNaN // true +Float.parseInt("10.0", ~radix=2) // 2.0 +Float.parseInt("15 * 3", ~radix=10) // 15.0 +Float.parseInt("12", ~radix=13) // 15.0 +Float.parseInt("17", ~radix=40)->Float.isNaN // true +``` +*/ +@val +external parseInt: ('a, ~radix: int=?) => float = "parseInt" + +/** +`parseIntWithRadix(v, ~radix)` parse the given `v` and returns a float. Leading +whitespace in this argument `v`is ignored. `radix` specifies the radix base to +use for the formatted number. The value must be in the range [2, 36] (inclusive). +Returns `NaN` if `v` can't be parsed and `radix` is smaller than 2 or bigger +than 36. +See [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) on MDN. + +## Examples + +```rescript +Float.parseIntWithRadix("10.0", ~radix=2) // 2.0 +Float.parseIntWithRadix("15 * 3", ~radix=10) // 15.0 +Float.parseIntWithRadix("12", ~radix=13) // 15.0 +Float.parseIntWithRadix("17", ~radix=40)->Float.isNaN // true +``` +*/ +@deprecated("Use `parseInt` instead") +@val +external parseIntWithRadix: ('a, ~radix: int) => float = "parseInt" + +/** +`toExponential(v, ~digits=?)` return a `string` representing the given value in +exponential notation. `digits` specifies how many digits should appear after +the decimal point. +See [`Number.toExponential`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) on MDN. + +## Examples + +```rescript +Float.toExponential(1000.0) // "1e+3" +Float.toExponential(-1000.0) // "-1e+3" +Float.toExponential(77.0, ~digits=2) // "7.70e+1" +Float.toExponential(5678.0, ~digits=2) // "5.68e+3" +``` + +## Exceptions + +- `RangeError`: If `digits` less than 0 or greater than 10. +``` +*/ +@send +external toExponential: (float, ~digits: int=?) => string = "toExponential" + +/** +`toExponential(v, ~digits)` return a `string` representing the given value in +exponential notation. `digits` specifies how many digits should appear after +the decimal point. +See [`Number.toExponential`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) on MDN. + +## Examples + +```rescript +Float.toExponentialWithPrecision(77.0, ~digits=2) // "7.70e+1" +Float.toExponentialWithPrecision(5678.0, ~digits=2) // "5.68e+3" +``` + +## Exceptions + +- `RangeError`: If `digits` less than 0 or greater than 10. +*/ +@deprecated("Use `toExponential` instead") +@send +external toExponentialWithPrecision: (float, ~digits: int) => string = "toExponential" + +/** +`toFixed(v, ~digits=?)` return a `string` representing the given +value using fixed-point notation. `digits` specifies how many digits should +appear after the decimal point. +See [`Number.toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) on MDN. + +## Examples + +```rescript +Float.toFixed(123456.0) // "123456.00" +Float.toFixed(10.0) // "10.00" +Float.toFixed(300.0, ~digits=4) // "300.0000" +Float.toFixed(300.0, ~digits=1) // "300.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is less than 0 or larger than 100. +*/ +@send +external toFixed: (float, ~digits: int=?) => string = "toFixed" + +/** +`toFixedWithPrecision(v, ~digits)` return a `string` representing the given +value using fixed-point notation. `digits` specifies how many digits should +appear after the decimal point. +See [`Number.toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) on MDN. + +## Examples + +```rescript +Float.toFixedWithPrecision(300.0, ~digits=4) // "300.0000" +Float.toFixedWithPrecision(300.0, ~digits=1) // "300.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is less than 0 or larger than 100. +*/ +@deprecated("Use `toFixed` instead") +@send +external toFixedWithPrecision: (float, ~digits: int) => string = "toFixed" + +/** +`toPrecision(v, ~digits=?)` return a `string` representing the giver value with +precision. `digits` specifies the number of significant digits. +See [`Number.toPrecision`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) on MDN. + +## Examples + +```rescript +Float.toPrecision(100.0) // "100" +Float.toPrecision(1.0) // "1" +Float.toPrecision(100.0, ~digits=2) // "1.0e+2" +Float.toPrecision(1.0, ~digits=1) // "1" +``` + +## Exceptions + +- `RangeError`: If `digits` is not between 1 and 100 (inclusive). +Implementations are allowed to support larger and smaller values as well. +ECMA-262 only requires a precision of up to 21 significant digits. +*/ +@send +external toPrecision: (float, ~digits: int=?) => string = "toPrecision" + +/** +`toPrecisionWithPrecision(v, ~digits)` return a `string` representing the giver value with +precision. `digits` specifies the number of significant digits. +See [`Number.toPrecision`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) on MDN. + +## Examples + +```rescript +Float.toPrecisionWithPrecision(100.0, ~digits=2) // "1.0e+2" +Float.toPrecisionWithPrecision(1.0, ~digits=1) // "1" +``` + +## Exceptions + +- `RangeError`: If `digits` is not between 1 and 100 (inclusive). +Implementations are allowed to support larger and smaller values as well. +ECMA-262 only requires a precision of up to 21 significant digits. + +*/ +@deprecated("Use `toPrecision` instead") +@send +external toPrecisionWithPrecision: (float, ~digits: int) => string = "toPrecision" + +/** +`toString(v)` return a `string` representing the given value. +See [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) on MDN. + +## Examples + +```rescript +Float.toString(1000.0) // "1000" +Float.toString(-1000.0) // "-1000" +``` +*/ +@send +external toString: (float, ~radix: int=?) => string = "toString" + +/** +`toStringWithRadix(v, ~radix)` return a `string` representing the given value. +`~radix` specifies the radix base to use for the formatted number. +See [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) on MDN. + +## Examples + +```rescript +Float.toStringWithRadix(6.0, ~radix=2) // "110" +Float.toStringWithRadix(3735928559.0, ~radix=16) // "deadbeef" +Float.toStringWithRadix(123456.0, ~radix=36) // "2n9c" +``` + +## Exceptions + +`RangeError`: if `radix` is less than 2 or greater than 36. +*/ +@deprecated("Use `toString` with `~radix` instead") +@send +external toStringWithRadix: (float, ~radix: int) => string = "toString" + +/** +`toLocaleString(v)` return a `string` with language-sensitive representing the +given value. +See [`Number.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) on MDN. + +## Examples + +```rescript +// If the application uses English as the default language +Float.toLocaleString(1000.0) // "1,000" + +// If the application uses Portuguese Brazil as the default language +Float.toLocaleString(1000.0) // "1.000" +``` +*/ +@send +external toLocaleString: float => string = "toLocaleString" + +/** +`fromString(str)` return an `option` representing the given value `str`. + +## Examples + +```rescript +Float.fromString("0") == Some(0.0) +Float.fromString("NaN") == None +Float.fromString("6") == Some(6.0) +``` +*/ +let fromString: string => option + +/** +`toInt(v)` returns an int to given float `v`. + +## Examples + +```rescript +Float.toInt(2.0) == 2 +Float.toInt(1.0) == 1 +Float.toInt(1.1) == 1 +Float.toInt(1.6) == 1 +``` +*/ +external toInt: float => int = "%intoffloat" + +/** +`fromInt(v)` returns a float to given int `v`. + +## Examples + +```rescript +Float.fromInt(2) == 2.0 +Float.fromInt(1) == 1.0 +``` +*/ +external fromInt: int => float = "%identity" + +/** +`mod(n1, n2)` calculates the modulo (remainder after division) of two floats. + +## Examples + +```rescript +Float.mod(7.0, 4.0) == 3.0 +``` +*/ +external mod: (float, float) => float = "?fmod_float" + +/** +`clamp(~min=?, ~max=?, value)` returns `value`, optionally bounded by `min` and `max`. + +if `max` < `min` returns `min`. + +## Examples + +```rescript +Float.clamp(4.2) == 4.2 +Float.clamp(4.2, ~min=4.3) == 4.3 +Float.clamp(4.2, ~max=4.1) == 4.1 +Float.clamp(4.2, ~min=4.3, ~max=4.1) == 4.3 +``` +*/ +let clamp: (~min: float=?, ~max: float=?, float) => float diff --git a/jscomp/stdlib-406/Global.res b/jscomp/stdlib-406/Global.res new file mode 100644 index 0000000000..0edc87b9ae --- /dev/null +++ b/jscomp/stdlib-406/Global.res @@ -0,0 +1,17 @@ +type timeoutId = Js.Global.timeoutId + +@val external setTimeout: (unit => unit, int) => timeoutId = "setTimeout" +@val external setTimeoutFloat: (unit => unit, float) => timeoutId = "setTimeout" +@val external clearTimeout: timeoutId => unit = "clearTimeout" + +type intervalId = Js.Global.intervalId + +@val external setInterval: (unit => unit, int) => intervalId = "setInterval" +@val external setIntervalFloat: (unit => unit, float) => intervalId = "setInterval" +@val external clearInterval: intervalId => unit = "clearInterval" + +@val external encodeURI: string => string = "encodeURI" +@val external decodeURI: string => string = "decodeURI" + +@val external encodeURIComponent: string => string = "encodeURIComponent" +@val external decodeURIComponent: string => string = "decodeURIComponent" diff --git a/jscomp/stdlib-406/Global.resi b/jscomp/stdlib-406/Global.resi new file mode 100644 index 0000000000..03e0599398 --- /dev/null +++ b/jscomp/stdlib-406/Global.resi @@ -0,0 +1,186 @@ +/*** +Bindings to functions available in the global JavaScript scope. +*/ + +/** +An `id` representing a timeout started via `setTimeout`. + +See [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) on MDN. +*/ +type timeoutId = Js.Global.timeoutId + +/** +`setTimeout(callback, durationInMilliseconds)` starts a timer that will execute `callback` after `durationInMilliseconds`. + +See [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) on MDN. + +## Examples +```rescript +// Log to the console after 2 seconds (2000 milliseconds). +let timeoutId = setTimeout(() => { + Console.log("This prints in 2 seconds.") +}, 2000) +``` +*/ +@val +external setTimeout: (unit => unit, int) => timeoutId = "setTimeout" + +/** +`setTimeoutFloat(callback, durationInMilliseconds)` starts a timer that will execute `callback` after `durationInMilliseconds`. + +The same as `setTimeout`, but allows you to pass a `float` instead of an `int` for the duration. + +See [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) on MDN. + +## Examples +```rescript +// Log to the console after 2 seconds (2000 milliseconds). +let timeoutId = setTimeoutFloat(() => { + Console.log("This prints in 2 seconds.") +}, 2000.) +``` +*/ +@val +external setTimeoutFloat: (unit => unit, float) => timeoutId = "setTimeout" + +/** +`clearTimeout(timeoutId)` clears a scheduled timeout if it hasn't already executed. + +See [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) on MDN. + +## Examples +```rescript +let timeoutId = setTimeout(() => { + Console.log("This prints in 2 seconds.") +}, 2000) + +// Clearing the timeout right away, before 2 seconds has passed, means that the above callback logging to the console will never run. +clearTimeout(timeoutId) +``` +*/ +@val +external clearTimeout: timeoutId => unit = "clearTimeout" + +/** +An `id` representing an interval started via `setInterval`. + +See [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) on MDN. +*/ +type intervalId = Js.Global.intervalId + +/** +`setInterval(callback, intervalInMilliseconds)` starts an interval that will execute `callback` every `durationInMilliseconds` milliseconds. + +See [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) on MDN. + +## Examples +```rescript +// Log to the console ever 2 seconds (2000 milliseconds). +let intervalId = setInterval(() => { + Console.log("This prints every 2 seconds.") +}, 2000) +``` +*/ +@val +external setInterval: (unit => unit, int) => intervalId = "setInterval" + +/** +`setIntervalFloat(callback, intervalInMilliseconds)` starts an interval that will execute `callback` every `durationInMilliseconds` milliseconds. + +The same as `setInterval`, but allows you to pass a `float` instead of an `int` for the duration. + +See [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) on MDN. + +## Examples +```rescript +// Log to the console ever 2 seconds (2000 milliseconds). +let intervalId = setIntervalFloat(() => { + Console.log("This prints every 2 seconds.") +}, 2000.) +``` +*/ +@val +external setIntervalFloat: (unit => unit, float) => intervalId = "setInterval" + +/** +`clearInterval(intervalId)` clears a scheduled interval. + +See [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval) on MDN. + +## Examples +```rescript +let intervalId = setInterval(() => { + Console.log("This prints in 2 seconds.") +}, 2000) + +// Stop the interval after 10 seconds +let timeoutId = setTimeout(() => { + clearInterval(intervalId) +}, 10000) +``` +*/ +@val +external clearInterval: intervalId => unit = "clearInterval" + +/** +Encodes a URI by replacing characters in the provided string that aren't valid in a URL. + +This is intended to operate on full URIs, so it encodes fewer characters than what `encodeURIComponent` does. +If you're looking to encode just parts of a URI, like a query parameter, prefer `encodeURIComponent`. + +See [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) on MDN. + +## Examples +```rescript +Console.log(encodeURI("https://rescript-lang.org?array=[someValue]")) +// Logs "https://rescript-lang.org?array=%5BsomeValue%5D" to the console. +``` + +*/ +@val +external encodeURI: string => string = "encodeURI" + +/** +Decodes a previously encoded URI back to a regular string. + +This is intended to operate on full URIs, so it decodes fewer characters than what `decodeURIComponent` does. +If you're looking to decode just parts of a URI, like a query parameter, prefer `decodeURIComponent`. + +See [`decodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) on MDN. + +## Examples +```rescript +Console.log(decodeURI("https://rescript-lang.org?array=%5BsomeValue%5D")) +// Logs "https://rescript-lang.org?array=[someValue]" to the console. +``` +*/ +@val +external decodeURI: string => string = "decodeURI" + +/** +Encodes a string so it can be used as part of a URI. + +See [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) on MDN. + +## Examples +```rescript +Console.log(encodeURIComponent("array=[someValue]")) +// Logs "array%3D%5BsomeValue%5D" to the console. +``` +*/ +@val +external encodeURIComponent: string => string = "encodeURIComponent" + +/** +Decodes a previously URI encoded string back to its original form. + +See [`decodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) on MDN. + +## Examples +```rescript +Console.log(decodeURIComponent("array%3D%5BsomeValue%5D")) +// Logs "array=[someValue]" to the console. +``` +*/ +@val +external decodeURIComponent: string => string = "decodeURIComponent" diff --git a/jscomp/stdlib-406/Int.res b/jscomp/stdlib-406/Int.res new file mode 100644 index 0000000000..14ca9ab955 --- /dev/null +++ b/jscomp/stdlib-406/Int.res @@ -0,0 +1,84 @@ +module Constants = { + @inline let minValue = -2147483648 + @inline let maxValue = 2147483647 +} + +let equal = (a: int, b: int) => a === b + +let compare = (a: int, b: int) => a < b ? Ordering.less : a > b ? Ordering.greater : Ordering.equal + +@send external toExponential: (int, ~digits: int=?) => string = "toExponential" +@deprecated("Use `toExponential` instead") @send +external toExponentialWithPrecision: (int, ~digits: int) => string = "toExponential" + +@send external toFixed: (int, ~digits: int=?) => string = "toFixed" +@deprecated("Use `toFixed` instead") @send +external toFixedWithPrecision: (int, ~digits: int) => string = "toFixed" + +@send external toPrecision: (int, ~digits: int=?) => string = "toPrecision" +@deprecated("Use `toPrecision` instead") @send +external toPrecisionWithPrecision: (int, ~digits: int) => string = "toPrecision" + +@send external toString: (int, ~radix: int=?) => string = "toString" +@deprecated("Use `toString` instead") @send +external toStringWithRadix: (int, ~radix: int) => string = "toString" +@send external toLocaleString: int => string = "toLocaleString" + +external toFloat: int => float = "%identity" +external fromFloat: float => int = "%intoffloat" + +let fromString = (x, ~radix=?) => { + let maybeInt = switch radix { + | Some(radix) => Float.parseInt(x, ~radix) + | None => Float.parseInt(x) + } + + if Float.isNaN(maybeInt) { + None + } else if maybeInt > Constants.maxValue->toFloat || maybeInt < Constants.minValue->toFloat { + None + } else { + let asInt = fromFloat(maybeInt) + Some(asInt) + } +} + +external mod: (int, int) => int = "%modint" + +type rangeOptions = {step?: int, inclusive?: bool} + +let range = (start, end, ~options: rangeOptions={}) => { + let isInverted = start > end + + let step = switch options.step { + | None => isInverted ? -1 : 1 + | Some(0) if start !== end => Error.raise(Error.RangeError.make("Incorrect range arguments")) + | Some(n) => n + } + + let length = if isInverted === (step >= 0) { + 0 // infinite because step goes in opposite direction of end + } else if step == 0 { + options.inclusive === Some(true) ? 1 : 0 + } else { + let range = isInverted ? start - end : end - start + let range = options.inclusive === Some(true) ? range + 1 : range + ceil(float(range) /. float(abs(step)))->Float.toInt + } + + Array.fromInitializer(~length, i => start + i * step) +} + +@deprecated("Use `range` instead") @send +let rangeWithOptions = (start, end, options) => range(start, end, ~options) + +let clamp = (~min=?, ~max=?, value): int => { + let value = switch max { + | Some(max) if max < value => max + | _ => value + } + switch min { + | Some(min) if min > value => min + | _ => value + } +} diff --git a/jscomp/stdlib-406/Int.resi b/jscomp/stdlib-406/Int.resi new file mode 100644 index 0000000000..19fc4c85d5 --- /dev/null +++ b/jscomp/stdlib-406/Int.resi @@ -0,0 +1,390 @@ +/* Copyright (C) 2015-2016 Bloomberg Finance L.P. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/*** +Functions for interacting with JavaScript Number. +See: [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). +*/ + +module Constants: { + /** + The smallest positive number represented in JavaScript. + See [`Number.MIN_VALUE`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE) + on MDN. + + ## Examples + + ```rescript + Console.log(Int.Constants.minValue) + ``` + */ + @inline + let minValue: int + /** + The largest positive number represented in JavaScript. + See [`Number.MAX_VALUE`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE) + on MDN. + + ## Examples + + ```rescript + Console.log(Int.Constants.maxValue) + ``` + */ + @inline + let maxValue: int +} + +let equal: (int, int) => bool + +let compare: (int, int) => Ordering.t + +/** +`toExponential(n, ~digits=?)` return a `string` representing the given value in +exponential notation. `digits` specifies how many digits should appear after +the decimal point. See [`Number.toExponential`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) + +## Examples + +```rescript +Int.toExponential(1000) // "1e+3" +Int.toExponential(-1000) // "-1e+3" +Int.toExponential(77, ~digits=2) // "7.70e+1" +Int.toExponential(5678, ~digits=2) // "5.68e+3" +``` + +## Exceptions + +- `RangeError`: If `digits` less than 0 or greater than 10. +*/ +@send +external toExponential: (int, ~digits: int=?) => string = "toExponential" + +/** +`toExponential(n, ~digits)` return a `string` representing the given value in +exponential notation. `digits` specifies how many digits should appear after +the decimal point. See [`Number.toExponential`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) +on MDN. + +## Examples + +```rescript +Int.toExponentialWithPrecision(77, ~digits=2) // "7.70e+1" +Int.toExponentialWithPrecision(5678, ~digits=2) // "5.68e+3" +``` + +## Exceptions + +- `RangeError`: If `digits` less than 0 or greater than 10. +*/ +@deprecated("Use `toExponential` instead") +@send +external toExponentialWithPrecision: (int, ~digits: int) => string = "toExponential" + +/** +`toFixed(n, ~digits=?)` return a `string` representing the given +value using fixed-point notation. `digits` specifies how many digits should +appear after the decimal point. See [`Number.toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) +on MDN. + +## Examples + +```rescript +Int.toFixed(123456) // "123456.00" +Int.toFixed(10) // "10.00" +Int.toFixed(300, ~digits=4) // "300.0000" +Int.toFixed(300, ~digits=1) // "300.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is less than 0 or larger than 100. +*/ +@send +external toFixed: (int, ~digits: int=?) => string = "toFixed" + +/** +`toFixedWithPrecision(n, ~digits)` return a `string` representing the given +value using fixed-point notation. `digits` specifies how many digits should +appear after the decimal point. See [`Number.toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) +on MDN. + +## Examples + +```rescript +Int.toFixedWithPrecision(300, ~digits=4) // "300.0000" +Int.toFixedWithPrecision(300, ~digits=1) // "300.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is less than 0 or larger than 100. +*/ +@deprecated("Use `toFixed` instead") +@send +external toFixedWithPrecision: (int, ~digits: int) => string = "toFixed" + +/** +`toPrecision(n, ~digits=?)` return a `string` representing the giver value with +precision. `digits` specifies the number of significant digits. See [`Number.toPrecision`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) on MDN. + +## Examples + +```rescript +Int.toPrecision(100) // "100" +Int.toPrecision(1) // "1" +Int.toPrecision(100, ~digits=2) // "1.0e+2" +Int.toPrecision(1, ~digits=2) // "1.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is not between 1 and 100 (inclusive). +Implementations are allowed to support larger and smaller values as well. +ECMA-262 only requires a precision of up to 21 significant digits. +*/ +@send +external toPrecision: (int, ~digits: int=?) => string = "toPrecision" + +/** +`toPrecisionWithPrecision(n, ~digits)` return a `string` representing the giver value with +precision. `digits` specifies the number of significant digits. See [`Number.toPrecision`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) on MDN. + +## Examples + +```rescript +Int.toPrecisionWithPrecision(100, ~digits=2) // "1.0e+2" +Int.toPrecisionWithPrecision(1, ~digits=2) // "1.0" +``` + +## Exceptions + +- `RangeError`: If `digits` is not between 1 and 100 (inclusive). +Implementations are allowed to support larger and smaller values as well. +ECMA-262 only requires a precision of up to 21 significant digits. + +*/ +@send +@deprecated("Use `toPrecision` instead") +external toPrecisionWithPrecision: (int, ~digits: int) => string = "toPrecision" + +/** +`toString(n, ~radix=?)` return a `string` representing the given value. +`~radix` specifies the radix base to use for the formatted number. +See [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) +on MDN. + +## Examples + +```rescript +Int.toString(1000) // "1000" +Int.toString(-1000) // "-1000" +Int.toString(6, ~radix=2) // "110" +Int.toString(373592855, ~radix=16) // "16449317" +Int.toString(123456, ~radix=36) // "2n9c" +``` + +## Exceptions + +`RangeError`: if `radix` is less than 2 or greater than 36. +*/ +@send +external toString: (int, ~radix: int=?) => string = "toString" + +/** +`toStringWithRadix(n, ~radix)` return a `string` representing the given value. +`~radix` specifies the radix base to use for the formatted number. +See [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) +on MDN. + +## Examples + +```rescript +Int.toStringWithRadix(6, ~radix=2) // "110" +Int.toStringWithRadix(373592855, ~radix=16) // "16449317" +Int.toStringWithRadix(123456, ~radix=36) // "2n9c" +``` + +## Exceptions + +`RangeError`: if `radix` is less than 2 or greater than 36. +*/ +@deprecated("Use `toString` instead") +@send +external toStringWithRadix: (int, ~radix: int) => string = "toString" + +/** +`toLocaleString(n)` return a `string` with language-sensitive representing the +given value. See [`Number.toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) on MDN. + +## Examples + +```rescript +// If the application uses English as the default language +Int.toLocaleString(1000) // "1,000" + +// If the application uses Portuguese Brazil as the default language +Int.toLocaleString(1000) // "1.000" +``` +*/ +@send +external toLocaleString: int => string = "toLocaleString" + +/** +`toFloat(n)` return a `float` representing the given value. + +## Examples + +```rescript +Int.toFloat(100) == 100.0 +Int.toFloat(2) == 2.0 +``` +*/ +external toFloat: int => float = "%identity" + +/** +`fromFloat(n)` return an `int` representing the given value. The conversion is +done by truncating the decimal part. + +## Examples + +```rescript +Int.fromFloat(2.0) == 2 +Int.fromFloat(1.999) == 1 +Int.fromFloat(1.5) == 1 +Int.fromFloat(0.9999) == 0 +``` +*/ +external fromFloat: float => int = "%intoffloat" + +/** +`fromString(str, ~radix=?)` return an `option` representing the given value +`str`. `~radix` specifies the radix base to use for the formatted number. + +## Examples + +```rescript +Int.fromString("0") == Some(0) +Int.fromString("NaN") == None +Int.fromString("6", ~radix=2) == None +``` +*/ +let fromString: (string, ~radix: int=?) => option + +/** +`mod(n1, n2)` calculates the modulo (remainder after division) of two integers. + +## Examples + +```rescript +Int.mod(7, 4) == 3 +``` +*/ +external mod: (int, int) => int = "%modint" + +/** +The options for `range`. +*/ +type rangeOptions = {step?: int, inclusive?: bool} + +/** +`range(start, end, ~options=?)` returns an int array of the sequence of integers in the +range `[start, end)`. That is, including `start` but excluding `end`. + +If `step` is not set and `start < end`, the sequence will be increasing in steps of 1. + +If `step` is not set and `start > end`, the sequence will be decreasing in steps of -1. + +If `step` is set, the sequence will increase or decrease by that amount for each +step. If `start < end` and `step` is negative, or vice versa, an empty array is +returned since the sequence would otherwise never reach or exceed the end value +and hence be infinite. If `step` is `0` and `start !=` end, a `RangeError` is +raised as the sequence would never reach or exceed the end value and hence be +infinite. + +If `inclusive` is set to `true`, the sequence will include `end` if `step` is +set such that the sequence includes it. + +## Examples + +```rescript +Int.range(3, 6) == [3, 4, 5] +Int.range(-3, -1) == [-3, -2] +Int.range(3, 1) == [3, 2] +Int.range(3, 7, ~options={step: 2}) == [3, 5] +Int.range(3, 7, ~options={step: 2, inclusive: true}) == [3, 5, 7] +Int.range(3, 6, ~options={step: -2}) // RangeError +``` + +## Exceptions + +- Raises `RangeError` if `step == 0 && start != end`. +``` +*/ +let range: (int, int, ~options: rangeOptions=?) => array + +/** +`rangeWithOptions(start, end, options)` is like `range`, but with `step` and +`inclusive` options configurable. + +If `step` is set, the sequence will increase or decrease by that amount for each +step. If `start < end` and `step` is negative, or vice versa, an empty array is +returned since the sequence would otherwise never reach or exceed the end value +and hence be infinite. If `step` is `0` and `start !=` end, a `RangeError` is +raised as the sequence would never reach or exceed the end value and hence be +infinite. + +If `inclusive` is set to `true`, the sequence will include `end` if `step` is +set such that the sequence includes it. + +## Examples + +```rescript +Int.rangeWithOptions(3, 7, {step: 2}) == [3, 5] +Int.rangeWithOptions(3, 7, {step: 2, inclusive: true}) == [3, 5, 7] +Int.rangeWithOptions(3, 6, {step: -2}) // RangeError +``` + +## Exceptions + +- Raises `RangeError` if `step == 0 && start != end`. +*/ +@deprecated("Use `range` instead") +let rangeWithOptions: (int, int, rangeOptions) => array + +/** +`clamp(~min=?, ~max=?, value)` returns `value`, optionally bounded by `min` and `max`. + +if `max` < `min` returns `min`. + +## Examples + +```rescript +Int.clamp(42) == 42 +Int.clamp(42, ~min=50) == 50 +Int.clamp(42, ~max=40) == 40 +Int.clamp(42, ~min=50, ~max=40) == 50 +``` +*/ +let clamp: (~min: int=?, ~max: int=?, int) => int diff --git a/jscomp/stdlib-406/Intl.res b/jscomp/stdlib-406/Intl.res new file mode 100644 index 0000000000..fe9ac99cbc --- /dev/null +++ b/jscomp/stdlib-406/Intl.res @@ -0,0 +1,25 @@ +module Common = Intl__Common +module Collator = Intl__Collator +module DateTimeFormat = Intl__DateTimeFormat +module ListFormat = Intl__ListFormat +module Locale = Intl__Locale +module NumberFormat = Intl__NumberFormat +module PluralRules = Intl__PluralRules +module RelativeTimeFormat = Intl__RelativeTimeFormat +module Segmenter = Intl__Segmenter +module Segments = Intl__Segments + +/** +@throws RangeError +*/ +external getCanonicalLocalesExn: string => array = "Intl.getCanonicalLocales" + +/** +@throws RangeError +*/ +external getCanonicalLocalesManyExn: array => array = "Intl.getCanonicalLocales" + +/** +@throws RangeError +*/ +external supportedValuesOfExn: string => array = "Intl.supportedValuesOf" diff --git a/jscomp/stdlib-406/Iterator.res b/jscomp/stdlib-406/Iterator.res new file mode 100644 index 0000000000..80b6829e12 --- /dev/null +++ b/jscomp/stdlib-406/Iterator.res @@ -0,0 +1,20 @@ +type t<'a> + +type value<'a> = { + done: bool, + value: option<'a>, +} + +@send external next: t<'a> => value<'a> = "next" +external toArray: t<'a> => array<'a> = "Array.from" +external toArrayWithMapper: (t<'a>, 'a => 'b) => array<'b> = "Array.from" + +let forEach = (iterator, f) => { + let iteratorDone = ref(false) + + while !iteratorDone.contents { + let {done, value} = iterator->next + f(value) + iteratorDone := done + } +} diff --git a/jscomp/stdlib-406/Iterator.resi b/jscomp/stdlib-406/Iterator.resi new file mode 100644 index 0000000000..300d4fca7b --- /dev/null +++ b/jscomp/stdlib-406/Iterator.resi @@ -0,0 +1,101 @@ +/*** +Bindings to JavaScript iterators. + +See [`iterator protocols`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. +*/ + +/** +The type representing an iterator. +*/ +type t<'a> + +/** +The current value of an iterator. +*/ +type value<'a> = { + /** + Whether there are more values to iterate on before the iterator is done. + */ + done: bool, + /** + The value of this iteration, if any. + */ + value: option<'a>, +} + +/** +Returns the next value of the iterator, if any. + +See [iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. + +## Examples +```rescript +@val external someIterator: Iterator.t = "someIterator" + +// Pulls out the next value of the iterator +let {Iterator.done, value} = someIterator->Iterator.next +``` +*/ +@send +external next: t<'a> => value<'a> = "next" + +/** +Turns an iterator into an array of the remaining values. +Remember that each invocation of `next` of an iterator consumes a value. `Iterator.toArray` will consume all remaining values of the iterator and return them in an array to you. + +See [iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("someKey2", "someValue2") + +// `Map.keys` returns all keys of the map as an iterator. +let mapKeysAsArray = map->Map.keys->Iterator.toArray + +Console.log(mapKeysAsArray) // Logs ["someKey", "someKey2"] to the console. +``` +*/ +external toArray: t<'a> => array<'a> = "Array.from" + +/** +`toArray(iterator)` turns `iterator` into an array of its remaining values, applying the provided mapper function on each item. +Remember that each invocation of `next` of an iterator consumes a value. `Iterator.toArrayWithMapper` will consume all remaining values of the iterator and return them in an array to you. + +See [iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("someKey2", "someValue2") + +// `Map.keys` returns all keys of the map as an iterator. +let mapKeysAsArray = map + ->Map.keys + ->Iterator.toArrayWithMapper(key => key->String.length) + +Console.log(mapKeysAsArray) // Logs [7, 8] to the console. +``` +*/ +external toArrayWithMapper: (t<'a>, 'a => 'b) => array<'b> = "Array.from" + +/** +`forEach(iterator, fn)` consumes all values in the iterator and runs the callback `fn` for each value. + +See [iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) on MDN. + +## Examples +```rescript +@val external someIterator: Iterator.t = "someIterator" + +someIterator->Iterator.forEach(value => + switch value { + | Some(value) if value > 10 => Console.log("More than 10!") + | _ => () + } +) +``` +*/ +let forEach: (t<'a>, option<'a> => unit) => unit diff --git a/jscomp/stdlib-406/JSON.res b/jscomp/stdlib-406/JSON.res new file mode 100644 index 0000000000..b9ee231e8c --- /dev/null +++ b/jscomp/stdlib-406/JSON.res @@ -0,0 +1,94 @@ +@unboxed +type rec t = Js.Json.t = + | Boolean(bool) + | @as(null) Null + | String(string) + | Number(float) + | Object(Dict.t) + | Array(array) + +@unboxed +type replacer = Keys(array) | Replacer((string, t) => t) + +@raises @val external parseExn: (string, ~reviver: (string, t) => t=?) => t = "JSON.parse" +@deprecated("Use `parseExn` with optional parameter instead") @raises @val +external parseExnWithReviver: (string, (string, t) => t) => t = "JSON.parse" + +@val external stringify: (t, ~replacer: replacer=?, ~space: int=?) => string = "JSON.stringify" +@deprecated("Use `stringify` with optional parameter instead") @val +external stringifyWithIndent: (t, @as(json`null`) _, int) => string = "JSON.stringify" +@deprecated("Use `stringify` with optional parameter instead") @val +external stringifyWithReplacer: (t, (string, t) => t) => string = "JSON.stringify" +@deprecated("Use `stringify` with optional parameters instead") @val +external stringifyWithReplacerAndIndent: (t, (string, t) => t, int) => string = "JSON.stringify" +@deprecated("Use `stringify` with optional parameter instead") @val +external stringifyWithFilter: (t, array) => string = "JSON.stringify" +@deprecated("Use `stringify` with optional parameters instead") @val +external stringifyWithFilterAndIndent: (t, array, int) => string = "JSON.stringify" + +@raises @val +external stringifyAny: ('a, ~replacer: replacer=?, ~space: int=?) => option = + "JSON.stringify" +@deprecated("Use `stringifyAny` with optional parameter instead") @raises @val +external stringifyAnyWithIndent: ('a, @as(json`null`) _, int) => option = "JSON.stringify" +@deprecated("Use `stringifyAny` with optional parameter instead") @raises @val +external stringifyAnyWithReplacer: ('a, (string, t) => t) => option = "JSON.stringify" +@deprecated("Use `stringifyAny` with optional parameters instead") @raises @val +external stringifyAnyWithReplacerAndIndent: ('a, (string, t) => t, int) => option = + "JSON.stringify" +@deprecated("Use `stringifyAny` with optional parameter instead") @raises @val +external stringifyAnyWithFilter: ('a, array) => string = "JSON.stringify" +@deprecated("Use `stringifyAny` with optional parameters instead") @raises @val +external stringifyAnyWithFilterAndIndent: ('a, array, int) => string = "JSON.stringify" + +module Classify = { + type t = + | Bool(bool) + | Null + | String(string) + | Number(float) + | Object(Dict.t) + | Array(array) + + @val external _internalClass: 'a => string = "Object.prototype.toString.call" + external _asBool: 'a => bool = "%identity" + external _asString: 'a => string = "%identity" + external _asFloat: 'a => float = "%identity" + external _asArray: 'a => array = "%identity" + external _asDict: 'a => Dict.t = "%identity" + + let classify = value => { + switch _internalClass(value) { + | "[object Boolean]" => Bool(_asBool(value)) + | "[object Null]" => Null + | "[object String]" => String(_asString(value)) + | "[object Number]" => Number(_asFloat(value)) + | "[object Array]" => Array(_asArray(value)) + | _ => Object(_asDict(value)) + } + } +} + +module Encode = { + external bool: bool => t = "%identity" + external null: t = "#null" + external string: string => t = "%identity" + external int: int => t = "%identity" + external float: float => t = "%identity" + external object: Dict.t => t = "%identity" + external array: array => t = "%identity" +} + +module Decode = { + let bool = (json: t) => Type.typeof(json) === #boolean ? Some((Obj.magic(json): bool)) : None + let null = (json: t) => Obj.magic(json) === Null.null ? Some(Null.null) : None + let string = (json: t) => Type.typeof(json) === #string ? Some((Obj.magic(json): string)) : None + let float = (json: t) => Type.typeof(json) === #number ? Some((Obj.magic(json): float)) : None + let object = (json: t) => + if Type.typeof(json) === #object && !Array.isArray(json) && !(Obj.magic(json) === Null.null) { + Some((Obj.magic(json): Dict.t)) + } else { + None + } + let array = (json: t) => Array.isArray(json) ? Some((Obj.magic(json): array)) : None +} diff --git a/jscomp/stdlib-406/JSON.resi b/jscomp/stdlib-406/JSON.resi new file mode 100644 index 0000000000..eeccc56bad --- /dev/null +++ b/jscomp/stdlib-406/JSON.resi @@ -0,0 +1,762 @@ +/*** +Functions for interacting with JSON. +*/ + +/** +A type representing a JSON object. +*/ +@unboxed +type rec t = Js.Json.t = + | Boolean(bool) + | @as(null) Null + | String(string) + | Number(float) + | Object(Dict.t) + | Array(array) + +@unboxed +type replacer = Keys(array) | Replacer((string, t) => t) + +/** +`parseExn(string, ~reviver=?)` + +Parses a JSON string or throws a JavaScript exception (SyntaxError), if the string isn't valid. +The reviver describes how the value should be transformed. It is a function which receives a key and a value. +It returns a JSON type. + +## Examples +```rescript +try { + let _ = JSON.parseExn(`{"foo":"bar","hello":"world"}`) + // { foo: 'bar', hello: 'world' } + + let _ = JSON.parseExn("") + // error +} catch { +| Exn.Error(_) => Console.log("error") +} + +let reviver = (_, value: JSON.t) => + switch value { + | String(string) => string->String.toUpperCase->JSON.Encode.string + | Number(number) => (number *. 2.0)->JSON.Encode.float + | _ => value + } + +let jsonString = `{"hello":"world","someNumber":21}` + +try { + JSON.parseExn(jsonString, ~reviver)->Console.log + // { hello: 'WORLD', someNumber: 42 } + + JSON.parseExn("", ~reviver)->Console.log + // error +} catch { +| Exn.Error(_) => Console.log("error") +} +``` + +## Exceptions + +- Raises a SyntaxError (Exn.t) if the string isn't valid JSON. +*/ +@raises(Exn.t) +@val +external parseExn: (string, ~reviver: (string, t) => t=?) => t = "JSON.parse" + +/** +`parseExnWithReviver(string, reviver)` + +Parses a JSON string or throws a JavaScript exception (SyntaxError), if the string isn't valid. +The reviver describes how the value should be transformed. It is a function which receives a key and a value. +It returns a JSON type. + +## Examples +```rescript +let reviver = (_, value: JSON.t) => + switch value { + | String(string) => string->String.toUpperCase->JSON.Encode.string + | Number(number) => (number *. 2.0)->JSON.Encode.float + | _ => value + } + +let jsonString = `{"hello":"world","someNumber":21}` + +try { + JSON.parseExnWithReviver(jsonString, reviver)->Console.log + // { hello: 'WORLD', someNumber: 42 } + + JSON.parseExnWithReviver("", reviver)->Console.log + // error +} catch { +| Exn.Error(_) => Console.log("error") +} +``` + +## Exceptions + +- Raises a SyntaxError if the string isn't valid JSON. +*/ +@deprecated("Use `parseExn` with optional parameter instead") +@raises(Exn.t) +@val +external parseExnWithReviver: (string, (string, t) => t) => t = "JSON.parse" + +/** +`stringify(json, ~replacer=?, ~space=?)` + +Converts a JSON object to a JSON string. +The replacer describes how the value should be transformed. It is a function which receives a key and a value, +or an array of keys which should be included in the output. +If you want to stringify any type, use `JSON.stringifyAny` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +JSON.stringify(json) +// {"foo":"bar","hello":"world","someNumber":42} + +JSON.stringify(json, ~space=2) +// { +// "foo": "bar", +// "hello": "world", +// "someNumber": 42 +// } + +JSON.stringify(json, ~replacer=Keys(["foo", "someNumber"])) +// {"foo":"bar","someNumber":42} + +let replacer = JSON.Replacer((_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +}) + +JSON.stringify(json, ~replacer) +// {"foo":"BAR","hello":"WORLD","someNumber":42} +``` +*/ +@val +external stringify: (t, ~replacer: replacer=?, ~space: int=?) => string = "JSON.stringify" + +/** +`stringifyWithIndent(json, indentation)` + +Converts a JSON object to a JSON string. The output will be indented. +If you want to stringify any type, use `JSON.stringifyAnyWithIndent` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +JSON.stringifyWithIndent(json, 2) +// { +// "foo": "bar", +// "hello": "world", +// "someNumber": 42 +// } +``` +*/ +@deprecated("Use `stringify` with optional parameter instead") +@val +external stringifyWithIndent: (t, @as(json`null`) _, int) => string = "JSON.stringify" + +/** +`stringifyWithReplacer(json, replacer)` + +Converts a JSON object to a JSON string. +The replacer describes how the value should be transformed. It is a function which receives a key and a value. +If you want to stringify any type, use `JSON.stringifyAnyWithReplacer` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +let replacer = (_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +} + +JSON.stringifyWithReplacer(json, replacer) +// {"foo":"BAR","hello":"WORLD","someNumber":42} +``` +*/ +@deprecated("Use `stringify` with optional parameter instead") +@val +external stringifyWithReplacer: (t, (string, t) => t) => string = "JSON.stringify" + +/** +`stringifyWithReplacerAndIndent(json, replacer, indentation)` + +Converts a JSON object to a JSON string. The output will be indented. +The replacer describes how the value should be transformed. It is a function which receives a key and a value. +If you want to stringify any type, use `JSON.stringifyAnyWithReplacerAndIndent` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +let replacer = (_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +} + +JSON.stringifyWithReplacerAndIndent(json, replacer, 2) +// { +// "foo": "BAR", +// "hello": "WORLD", +// "someNumber": 42 +// } +``` +*/ +@deprecated("Use `stringify` with optional parameters instead") +@val +external stringifyWithReplacerAndIndent: (t, (string, t) => t, int) => string = "JSON.stringify" + +/** +`stringifyWithFilter(json, filter)` + +Converts a JSON object to a JSON string. +The filter is an array of keys, which should be included in the output. +If you want to stringify any type, use `JSON.stringifyAnyWithFilter` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +JSON.stringifyWithFilter(json, ["foo", "someNumber"]) +// {"foo":"bar","someNumber":42} +``` +*/ +@deprecated("Use `stringify` with optional parameter instead") +@val +external stringifyWithFilter: (t, array) => string = "JSON.stringify" + +/** +`stringifyWithFilterAndIndent(json, filter, indentation)` + +Converts a JSON object to a JSON string. The output will be indented. +The filter is an array of keys, which should be included in the output. +If you want to stringify any type, use `JSON.stringifyAnyWithFilterAndIndent` instead. + +## Examples +```rescript +let json = + Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), + ])->JSON.Encode.object + +JSON.stringifyWithFilterAndIndent(json, ["foo", "someNumber"], 2) +// { +// "foo": "bar", +// "someNumber": 42 +// } +``` +*/ +@deprecated("Use `stringify` with optional parameters instead") +@val +external stringifyWithFilterAndIndent: (t, array, int) => string = "JSON.stringify" + +/** +`stringifyAny(any, ~replacer=?, ~space=?)` + +Converts any type to a JSON string. +The replacer describes how the value should be transformed. It is a function which receives a key and a value. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringify` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +JSON.stringifyAny(dict) +// {"foo":"bar","hello":"world","someNumber":42} + +JSON.stringifyAny(dict, ~space=2) +// { +// "foo": "bar", +// "hello": "world", +// "someNumber": 42 +// } + +JSON.stringifyAny(dict, ~replacer=Keys(["foo", "someNumber"])) +// {"foo":"bar","someNumber":42} + +let replacer = JSON.Replacer((_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +}) + +JSON.stringifyAny(dict, ~replacer) +// {"foo":"BAR","hello":"WORLD","someNumber":42} + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@raises(Exn.t) +@val +external stringifyAny: ('a, ~replacer: replacer=?, ~space: int=?) => option = + "JSON.stringify" + +/** +`stringifyAnyWithIndent(any, indentation)` + +Converts any type to a JSON string. The output will be indented. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringifyWithIndent` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +JSON.stringifyAnyWithIndent(dict, 2) +// { +// "foo": "bar", +// "hello": "world", +// "someNumber": 42 +// } + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@deprecated("Use `stringifyAny` with optional parameter instead") +@raises(Exn.t) +@val +external stringifyAnyWithIndent: ('a, @as(json`null`) _, int) => option = "JSON.stringify" + +/** +`stringifyAnyWithReplacer(json, replacer)` + +Converts any type to a JSON string. +The replacer describes how the value should be transformed. It is a function which receives a key and a value. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringifyWithReplacer` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +let replacer = (_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +} + +JSON.stringifyAnyWithReplacer(dict, replacer) +// {"foo":"BAR","hello":"WORLD","someNumber":42} + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@deprecated("Use `stringifyAny` with optional parameter instead") +@raises +@val +external stringifyAnyWithReplacer: ('a, (string, t) => t) => option = "JSON.stringify" + +/** +`stringifyAnyWithReplacerAndIndent(json, replacer, indentation)` + +Converts any type to a JSON string. The output will be indented. +The replacer describes how the value should be transformed. It is a function which receives a key and a value. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringifyWithReplacerAndIndent` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +let replacer = (_, value) => { + let decodedValue = value->JSON.Decode.string + + switch decodedValue { + | Some(string) => string->String.toUpperCase->JSON.Encode.string + | None => value + } +} + +JSON.stringifyAnyWithReplacerAndIndent(dict, replacer, 2) +// { +// "foo": "BAR", +// "hello": "WORLD", +// "someNumber": 42 +// } + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@deprecated("Use `stringifyAny` with optional parameters instead") +@raises +@val +external stringifyAnyWithReplacerAndIndent: ('a, (string, t) => t, int) => option = + "JSON.stringify" + +/** +`stringifyAnyWithFilter(json, filter)` + +Converts any type to a JSON string. +The filter is an array of keys, which should be included in the output. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringifyWithFilter` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +JSON.stringifyAnyWithFilter(dict, ["foo", "someNumber"]) +// {"foo": "bar","someNumber": 42} + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@deprecated("Use `stringifyAny` with optional parameter instead") +@raises +@val +external stringifyAnyWithFilter: ('a, array) => string = "JSON.stringify" + +/** +`stringifyAnyWithFilterAndIndent(json, filter, indentation)` + +Converts any type to a JSON string. The output will be indented. +The filter is an array of keys, which should be included in the output. +Stringifying a function or `undefined` will return `None`. +If the value contains circular references or `BigInt`s, the function will throw a JavaScript exception (TypeError). +If you want to stringify a JSON object, use `JSON.stringifyWithFilterAndIndent` instead. + +## Examples +```rescript +let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ("someNumber", JSON.Encode.int(42)), +]) + +JSON.stringifyAnyWithFilterAndIndent(dict, ["foo", "someNumber"], 2) +// { +// "foo": "bar", +// "someNumber": 42 +// } + +JSON.stringifyAny(() => "hello world") +// None + +BigInt.fromInt(0)->JSON.stringifyAny +// exception +``` + +## Exceptions + +- Raises a TypeError if the value contains circular references. +- Raises a TypeError if the value contains `BigInt`s. +*/ +@deprecated("Use `stringifyAny` with optional parameters instead") +@raises +@val +external stringifyAnyWithFilterAndIndent: ('a, array, int) => string = "JSON.stringify" + +module Classify: { + /** + A type representing a JavaScript type. + */ + type t = + | Bool(bool) + | Null + | String(string) + | Number(float) + | Object(Dict.t) + | Array(array) + + /** + Returns the JSON type of any value. + + ## Examples + ```rescript + JSON.Classify.classify("hello world") + // String("hello world") + + JSON.Classify.classify(42) + // Number(42) + ``` + */ + let classify: 'a => t +} + +module Encode: { + /** + Returns a boolean as a JSON object. + + ## Examples + ```rescript + JSON.Encode.bool(true) + ``` + */ + external bool: bool => t = "%identity" + + /** + Returns null as a JSON object. + + ## Examples + ```rescript + JSON.Encode.null + ``` + */ + external null: t = "#null" + + /** + Returns a string as a JSON object. + + ## Examples + ```rescript + JSON.Encode.string("hello world") + ``` + */ + external string: string => t = "%identity" + + /** + Returns an int as a JSON object. + + ## Examples + ```rescript + JSON.Encode.int(42) + ``` + */ + external int: int => t = "%identity" + + /** + Returns a float as a JSON object. + + ## Examples + ```rescript + JSON.Encode.float(42.0) + ``` + */ + external float: float => t = "%identity" + + /** + Returns a dict as a JSON object. + + ## Examples + ```rescript + let dict = Dict.fromArray([ + ("foo", JSON.Encode.string("bar")), + ("hello", JSON.Encode.string("world")), + ]) + + JSON.Encode.object(dict) + ``` + */ + external object: Dict.t => t = "%identity" + + /** + Returns an array as a JSON object. + + ## Examples + ```rescript + let array = [JSON.Encode.string("hello world"), JSON.Encode.int(42)] + + JSON.Encode.array(array) + ``` + */ + external array: array => t = "%identity" +} + +module Decode: { + /** + Decodes a single JSON value. If the value is a bool, it will return `Some(bool)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`true`)->JSON.Decode.bool + // Some(true) + + JSON.parseExn(`"hello world"`)->JSON.Decode.bool + // None + ``` + */ + let bool: t => option + + /** + Decodes a single JSON value. If the value is null, it will return `Some(Null.t)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`null`)->JSON.Decode.null + // Some(null) + + JSON.parseExn(`"hello world"`)->JSON.Decode.null + // None + ``` + */ + let null: t => option> + + /** + Decodes a single JSON value. If the value is a string, it will return `Some(string)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`"hello world"`)->JSON.Decode.string + // Some("hello world") + + JSON.parseExn(`42`)->JSON.Decode.string + // None + ``` + */ + let string: t => option + + /** + Decodes a single JSON value. If the value is a float, it will return `Some(float)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`42.0`)->JSON.Decode.float + // Some(42.0) + + JSON.parseExn(`"hello world"`)->JSON.Decode.float + // None + ``` + */ + let float: t => option + + /** + Decodes a single JSON value. If the value is an object, it will return `Some(Dict.t)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`{"foo":"bar"}`)->JSON.Decode.object + // Some({ foo: 'bar' }) + + JSON.parseExn(`"hello world"`)->JSON.Decode.object + // None + ``` + */ + let object: t => option> + + /** + Decodes a single JSON value. If the value is an array, it will return `Some(array)` - otherwise it will return `None`. + + ## Examples + ```rescript + JSON.parseExn(`["foo", "bar"]`)->JSON.Decode.array + // Some([ 'foo', 'bar' ]) + + JSON.parseExn(`"hello world"`)->JSON.Decode.array + // None + ``` + */ + let array: t => option> +} diff --git a/jscomp/stdlib-406/Math.res b/jscomp/stdlib-406/Math.res new file mode 100644 index 0000000000..2596b216d3 --- /dev/null +++ b/jscomp/stdlib-406/Math.res @@ -0,0 +1,61 @@ +module Constants = { + @val external e: float = "Math.E" + @val external ln2: float = "Math.LN2" + @val external ln10: float = "Math.LN10" + @val external log2e: float = "Math.LOG2E" + @val external log10e: float = "Math.LOG10E" + @val external pi: float = "Math.PI" + @val external sqrt1_2: float = "Math.SQRT1_2" + @val external sqrt2: float = "Math.SQRT2" +} + +@val external abs: float => float = "Math.abs" +@val external acos: float => float = "Math.acos" +@val external acosh: float => float = "Math.acosh" +@val external asin: float => float = "Math.asin" +@val external asinh: float => float = "Math.asinh" +@val external atan: float => float = "Math.atan" +@val external atanh: float => float = "Math.atanh" +@val external atan2: (~y: float, ~x: float) => float = "Math.atan2" +@val external cbrt: float => float = "Math.cbrt" +@val external ceil: float => float = "Math.ceil" +@val external cos: float => float = "Math.cos" +@val external cosh: float => float = "Math.cosh" +@val external exp: float => float = "Math.exp" +@val external expm1: float => float = "Math.expm1" +@val external floor: float => float = "Math.floor" +@val external fround: float => float = "Math.fround" +@val external hypot: (float, float) => float = "Math.hypot" +@variadic @val external hypotMany: array => float = "Math.hypot" +@val external log: float => float = "Math.log" +@val external log1p: float => float = "Math.log1p" +@val external log10: float => float = "Math.log10" +@val external log2: float => float = "Math.log2" +@val external min: (float, float) => float = "Math.min" +@variadic @val external minMany: array => float = "Math.min" +@val external max: (float, float) => float = "Math.max" +@variadic @val external maxMany: array => float = "Math.max" +@val external pow: (float, ~exp: float) => float = "Math.pow" +@val external random: unit => float = "Math.random" +@val external round: float => float = "Math.round" +@val external sign: float => float = "Math.sign" +@val external sin: float => float = "Math.sin" +@val external sinh: float => float = "Math.sinh" +@val external sqrt: float => float = "Math.sqrt" +@val external tan: float => float = "Math.tan" +@val external tanh: float => float = "Math.tanh" +@val external trunc: float => float = "Math.trunc" + +module Int = { + @val external abs: int => int = "Math.abs" + @val external clz32: int => int = "Math.clz32" + @val external imul: (int, int) => int = "Math.imul" + @val external min: (int, int) => int = "Math.min" + @variadic @val external minMany: array => int = "Math.min" + @val external max: (int, int) => int = "Math.max" + @variadic @val external maxMany: array => int = "Math.max" + @val external pow: (int, ~exp: int) => int = "Math.pow" + @val external sign: int => int = "Math.sign" + let floor: float => int = f => f->floor->Float.toInt + let random: (int, int) => int = (min, max) => floor(random() *. Int.toFloat(max - min)) + min +} diff --git a/jscomp/stdlib-406/Math.resi b/jscomp/stdlib-406/Math.resi new file mode 100644 index 0000000000..9dab2e78fa --- /dev/null +++ b/jscomp/stdlib-406/Math.resi @@ -0,0 +1,880 @@ +/* Copyright (C) 2015-2016 Bloomberg Finance L.P. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/*** +Functions for interacting with JavaScript Math. +See: [`Math`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math). +*/ + +/** +Mathematical Constants +*/ +module Constants: { + /** + `Math.Constants.e` returns Euler's number, ≈ 2.718281828459045. + See [`Math.E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E) on MDN. + + ## Examples + + ```rescript + Math.Constants.e + ``` + */ + @val + external e: float = "Math.E" + + /** + `Math.Constants.ln2` returns Natural logarithm of 2, ≈ 0.6931471805599453. + See [`Math.LN2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN2) on MDN. + + ## Examples + + ```rescript + Math.Constants.ln2 + ``` + */ + @val + external ln2: float = "Math.LN2" + + /** + `Math.Constants.ln10` returns Natural logarithm of 10, ≈ 2.302585092994046. + See [`Math.LN10`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN10) on MDN. + + ## Examples + + ```rescript + Math.Constants.ln10 + ``` + */ + @val + external ln10: float = "Math.LN10" + + /** + `Math.Constants.log2e` returns Base 2 logarithm of E, ≈ 1.4426950408889634. + See [`Math.LOG2E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG2E) on MDN. + + ## Examples + + ```rescript + Math.Constants.log2e + ``` + */ + @val + external log2e: float = "Math.LOG2E" + + /** + `Math.Constants.log10e` returns Base 10 logarithm of E, ≈ 0.4342944819032518. + See [`Math.LOG10E`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG10E) on MDN. + + ## Examples + + ```rescript + Math.Constants.log10e + ``` + */ + @val + external log10e: float = "Math.LOG10E" + /** + `Math.Constants.pi` returns Pi - ratio of the circumference to the diameter + of a circle, ≈ 3.141592653589793. + See [`Math.PI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI) on MDN. + + ## Examples + + ```rescript + Math.Constants.pi + ``` + */ + @val + external pi: float = "Math.PI" + /** + `Math.Constants.sqrt1_2` returns Square root of 1/2, ≈ 0.7071067811865476. + See [`Math.SQRT1_2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2) on MDN. + + ## Examples + + ```rescript + Math.Constants.sqrt1_2 + ``` + */ + @val + external sqrt1_2: float = "Math.SQRT1_2" + /** + `Math.Constants.e` returns Absolute value for integer argument. + See [`Math.abs`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs) on MDN. + + ## Examples + + ```rescript + Math.Constants.sqrt2 + ``` + */ + @val + external sqrt2: float = "Math.SQRT2" +} + +/** +Provide Math utilities for `int` +*/ +module Int: { + /** + `abs(v)` returns absolute value of `v`. + See [`Math.abs`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs) on MDN. + + ## Examples + + ```rescript + Math.Int.abs(-2) // 2 + Math.Int.abs(3) // 3 + ``` + */ + @val + external abs: int => int = "Math.abs" + + /** + `clz32(v)` returns the number of leading zero bits of the argument's 32 bit + int representation. + See [`Math.clz32`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32) on MDN. + + ## Examples + + ```rescript + // 00000000000000000000000000000001 + Math.Int.clz32(1) // 31 + // 00000000000000000000000000000100 + Math.Int.clz32(4) // 29 + ``` + */ + @val + external clz32: int => int = "Math.clz32" + + /** + `imul(a, b)` returns 32-bit integer multiplication. Use this only when you + need to optimize performance of multiplication of numbers stored as 32-bit + integers. + See [`Math.imul`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul) on MDN. + + ## Examples + + ```rescript + Math.Int.imul(3, 4) // 12 + Math.Int.imul(-5, 12) // 60 + ``` + */ + @val + external imul: (int, int) => int = "Math.imul" + + /** + `min(a, b)` returns the minimum of its two integer arguments. + See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN. + + ## Examples + + ```rescript + Math.Int.min(1, 2) // 1 + Math.Int.min(-1, -2) // -2 + ``` + */ + @val + external min: (int, int) => int = "Math.min" + + /** + `minMany(arr)` returns the minimum of the integers in the given array `arr`. + Returns `Infinity` if `arr` is empty. + See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN. + + ## Examples + + ```rescript + Math.Int.minMany([1, 2]) // 1 + Math.Int.minMany([-1, -2]) // -2 + Math.Int.minMany([])->Int.toFloat->Float.isFinite // false + ``` + */ + @variadic + @val + external minMany: array => int = "Math.min" + + /** + `max(a, b)` returns the maximum of its two integer arguments. + See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN. + + ## Examples + + ```rescript + Math.Int.max(1, 2) // 2 + Math.Int.max(-1, -2) // -1 + ``` + */ + @val + external max: (int, int) => int = "Math.max" + + /** + `maxMany(arr)` returns the maximum of the integers in the given array `arr`. + Returns `Infinity` if `arr` is empty. + See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN. + + ## Examples + + ```rescript + Math.Int.maxMany([1, 2]) // 2 + Math.Int.maxMany([-1, -2]) // -1 + Math.Int.maxMany([])->Int.toFloat->Float.isFinite // false + ``` + */ + @variadic + @val + external maxMany: array => int = "Math.max" + + /** + `pow(a, ~exp)` raises the given base `a` to the given exponent `exp`. + See [`Math.pow`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow) on MDN. + + ## Examples + + ```rescript + Math.Int.pow(2, ~exp=4) // 16 + Math.Int.pow(3, ~exp=4) // 81 + ``` + */ + @val + external pow: (int, ~exp: int) => int = "Math.pow" + + /** + `sign(v)` returns the sign of its integer argument: `-1` if negative, `0` if + zero, `1` if positive. + See [`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) on MDN. + + ## Examples + + ```rescript + Math.Int.sign(3) // 1 + Math.Int.sign(-3) // 1 + Math.Int.sign(0) // 0 + ``` + */ + @val + external sign: int => int = "Math.sign" + + /** + floor(v) returns the largest `int` less than or equal to the argument; + the result is pinned to the range of the `int` data type: -2147483648 to 2147483647. + See [`Math.floor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) + on MDN. + + ## Examples + + ```rescript + Math.Int.floor(3.7) == 3 + Math.Int.floor(3.0) == 3 + Math.Int.floor(-3.1) == -4 + Math.Int.floor(-1.0e15) == -2147483648 + Math.Int.floor(1.0e15) == 2147483647 + ``` + */ + let floor: float => int + + /** + `random(minVal, maxVal)` returns a random integer number in the half-closed interval [minVal, maxVal). + See [`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) + on MDN. + + ## Examples + + ```rescript + Math.Int.random(2, 5) == 4 + Math.Int.random(505, 2000) == 1276 + Math.Int.random(-7, -2) == -4 + ``` + */ + let random: (int, int) => int +} + +/** +`abs(v)` returns absolute value of `v`. +See [`Math.abs`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs) on MDN. + +## Examples + +```rescript +Math.abs(-2.0) // 2.0 +Math.abs(3.0) // 3.0 +``` + */ +@val +external abs: float => float = "Math.abs" + +/** +`acos(v)` returns arccosine (in radians) of argument `v`, returns `NaN` if the +argument is outside the range [-1.0, 1.0]. +See [`Math.acos`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos) on MDN. + +## Examples + +```rescript +Math.acos(-1.0) // 3.141592653589793 +Math.acos(-3.0)->Float.isNaN // true +``` +*/ +@val +external acos: float => float = "Math.acos" + +/** +`acosh(v)` returns the inverse hyperbolic arccosine (in radians) of argument `v`, +returns `NaN` if the argument is less than `1.0`. +See [`Math.acosh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acosh) on MDN. + +## Examples + +```rescript +Math.acosh(1.0) // 0.0 +Math.acosh(0.5)->Float.isNaN // true +``` +*/ +@val +external acosh: float => float = "Math.acosh" + +/** +`asin(v)` returns the inverse sine (in radians) of argument `v`, returns `NaN` +if the argument `v` is outside the range [-1.0, 1.0]. +See [`Math.asin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin) on MDN. + +## Examples + +```rescript +Math.asin(-1.0) // -1.5707963267948966 +Math.asin(-2.0)->Float.isNaN // true +``` +*/ +@val +external asin: float => float = "Math.asin" + +/** +`asinh(v)` returns the inverse hyperbolic sine of argument `v`. +See [`Math.asinh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asinh) on MDN. + +## Examples + +```rescript +Math.asinh(-1.0) // -0.881373587019543 +Math.asinh(-0.0) // -0.0 +``` +*/ +@val +external asinh: float => float = "Math.asinh" + +/** +`atan(v)` returns the inverse tangent (in radians) of argument `v`. +See [`Math.atan`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan) on MDN. + +## Examples + +```rescript +Math.atan(-0.0) // -0.0 +Math.atan(0.0) // 0.0 +Math.atan(1.0) // 0.7853981633974483 +``` +*/ +@val +external atan: float => float = "Math.atan" + +/** +`atanh(v)` returns the invert hyperbolic tangent of argument `v`. Returns `NaN` +if the argument `v` is is outside the range [-1.0, 1.0] and `Infinity` if `v` +is `-1.0` or `1.0`. +See [`Math.atanh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atanh) on MDN. + +## Examples + +```rescript +Math.atanh(-2.0)->Float.isNaN // true +Math.atanh(-1.0)->Float.isFinite // false +Math.atanh(-0.0) // -0.0 +Math.atanh(0.0) // 0.0 +Math.atanh(0.5) // 0.5493061443340548 +``` +*/ +@val +external atanh: float => float = "Math.atanh" + +/** +`atan2(~y, ~x)` returns the angle (in radians) of the quotient `y /. x`. It is +also the angle between the *x*-axis and point (*x*, *y*). +See [`Math.atan2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2) on MDN. + +## Examples + +```rescript +Math.atan2(~y=0.0, ~x=10.0) == 0.0 +Math.atan2(~x=5.0, ~y=5.0) == Math.Constants.pi /. 4.0 +Math.atan2(~x=90.0, ~y=15.0) // 1.4056476493802699 +Math.atan2(~x=15.0, ~y=90.0) // 0.16514867741462683 +``` +*/ +@val +external atan2: (~y: float, ~x: float) => float = "Math.atan2" + +/** +`cbrt(v)` returns the cube root of argument `v`. +See [`Math.cbrt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt) on MDN. + +## Examples + +```rescript +Math.cbrt(-1.0) // -1.0 +Math.cbrt(-0.0) // -0.0 +Math.cbrt(0.0) // 0.0 +``` +*/ +@val +external cbrt: float => float = "Math.cbrt" + +/** +`ceil(v)` returns the smallest integral value greater than or equal to the +argument `v`. The result is a `float` and is not restricted to the `int` data +type range. +See [`Math.ceil`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil) on MDN. + +## Examples + +```rescript +Math.ceil(3.1) == 4.0 +Math.ceil(3.0) == 3.0 +Math.ceil(-3.1) == -3.0 +Math.ceil(2_150_000_000.3) == 2_150_000_001.0 +``` +*/ +@val +external ceil: float => float = "Math.ceil" + +/** +`cos(v)` returns the cosine of argument `v`, which must be specified in radians. +See [`Math.cos`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos) on MDN. + +## Examples + +```rescript +Math.cos(-0.0) // 1.0 +Math.cos(0.0) // 1.0 +Math.cos(1.0) // 0.5403023058681398 +``` +*/ +@val +external cos: float => float = "Math.cos" + +/** +`cosh(v)` returns the hyperbolic cosine of argument `v`, which must be specified +in radians. +See [`Math.cosh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cosh) on MDN. + +## Examples + +```rescript +Math.cosh(-1.0) // 1.5430806348152437 +Math.cosh(-0.0) // 1.0 +Math.cosh(0.0) // 1.0 +``` +*/ +@val +external cosh: float => float = "Math.cosh" + +/** +`exp(v)` returns natural exponentional, returns *e* (the base of natural logarithms) +to the power of the given argument `v`. +See [`Math.exp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp) on MDN. + +## Examples + +```rescript +Math.exp(-1.0) // 0.36787944117144233 +Math.exp(0.0) // 1.0 +``` +*/ +@val +external exp: float => float = "Math.exp" + +/** +`expm1(v)` returns *e* (the base of natural logarithms) to the power of the given +argument `v` minus 1. +See [`Math.expm1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1) on MDN. + +## Examples + +```rescript +Math.expm1(-1.0) // -0.6321205588285577 +Math.expm1(-0.0) // -0 +``` +*/ +@val +external expm1: float => float = "Math.expm1" + +/** +`floor(v)` returns the largest integral value less than or equal to the argument +`v`. The result is a `float` and is not restricted to the `int` data type range. +See [`Math.floor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) on MDN. + +## Examples + +```rescript +Math.floor(-45.95) // -46.0 +Math.floor(-45.05) // -46.0 +Math.floor(-0.0) // -0.0 +``` +*/ +@val +external floor: float => float = "Math.floor" + +/** +`fround(v)` returns the nearest single precision float. +See [`Math.fround`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround) on MDN. + +## Examples + +```rescript +Math.fround(5.5) == 5.5 +Math.fround(5.05) == 5.050000190734863 +``` +*/ +@val +external fround: float => float = "Math.fround" + +/** +`hypot(a, b)` returns the square root of the sum of squares of its two arguments +(the Pythagorean formula). +See [`Math.hypot`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot) on MDN. + +## Examples + +```rescript +Math.hypot(3.0, 4.0) // 5.0 +Math.hypot(3.0, 5.0) // 5.8309518948453 +``` +*/ +@val +external hypot: (float, float) => float = "Math.hypot" + +/** +`hypotMany(arr)` returns the square root of the sum of squares of the numbers in +the array argument (generalized Pythagorean equation). Using an array allows you +to have more than two items. If `arr` is an empty array then returns `0.0`. +See [`Math.hypot`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot) on MDN. + +## Examples + +```rescript +Math.hypotMany([3.0, 4.0, 5.0]) // 7.0710678118654755 +Math.hypotMany([]) // 0.0 +``` +*/ +@variadic +@val +external hypotMany: array => float = "Math.hypot" + +/** +`log(v)` returns the natural logarithm of argument `v`, this is the number *x* +such that `e^x` equals the argument. Returns `NaN` for negative arguments and +`Infinity` for `0.0` or `-0.0`. +See [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) on MDN. + +## Examples + +```rescript +Math.log(-1.0)->Float.isNaN // true +Math.log(-0.0)->Float.isFinite // false +Math.log(0.0)->Float.isFinite // false +Math.log(1.0) // 0 +``` +*/ +@val +external log: float => float = "Math.log" + +/** +`log1p(v)` returns the natural logarithm of one plus the argument `v`. +Returns `NaN` for arguments less than `-1` and `Infinity` if `v` is `-1.0`. +See [`Math.log1p`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log1p) on MDN. + +## Examples + +```rescript +Math.log1p(-2.0)->Float.isNaN // true +Math.log1p(-1.0)->Float.isFinite // false +Math.log1p(-0.0) // -0 +``` +*/ +@val +external log1p: float => float = "Math.log1p" + +/** +`log10(v)` returns the base 10 logarithm of argument `v`. Returns `NaN` for +negative `v`. If `v` is `-0.0` or `0.0` returns `Infinity`. +See [`Math.log10`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10) on MDN. + +## Examples + +```rescript +Math.log10(-2.0)->Float.isNaN // true +Math.log10(-0.0)->Float.isFinite // false +Math.log10(0.0)->Float.isFinite // false +Math.log10(1.0) // 0 +``` +*/ +@val +external log10: float => float = "Math.log10" + +/** +`log2(v)` returns the base 2 logarithm of argument `v`. Returns `NaN` for +negative `v` and `Infinity` if `v` is `-0.0` or `0.0`. +See [`Math.log2`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2) on MDN. + +## Examples + +```rescript +Math.log2(-2.0)->Float.isNaN // true +Math.log2(-0.0)->Float.isFinite // false +Math.log2(0.0)->Float.isFinite // false +Math.log2(1.0) // 0.0 +``` +*/ +@val +external log2: float => float = "Math.log2" + +/** +`min(a, b)` returns the minimum of its two float arguments. +See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN. + +## Examples + +```rescript +Math.min(1.0, 2.0) // 1.0 +Math.min(-1.0, -2.0) // -2.0 +``` +*/ +@val +external min: (float, float) => float = "Math.min" + +/** +`minMany(arr)` returns the minimum of the float in the given array `arr`. +Returns `Infinity` if `arr` is empty. +See [`Math.min`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) on MDN. + +## Examples + +```rescript +Math.minMany([1.0, 2.0]) // 1.0 +Math.minMany([-1.0, -2.0]) // -2.0 +Math.minMany([])->Float.isFinite // false +``` +*/ +@variadic +@val +external minMany: array => float = "Math.min" + +/** +`max(a, b)` returns the maximum of its two float arguments. +See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN. + +## Examples + +```rescript +Math.max(1.0, 2.0) // 2.0 +Math.max(-1.0, -2.0) // -1.0 +``` +*/ +@val +external max: (float, float) => float = "Math.max" + +/** +`maxMany(arr)` returns the maximum of the float in the given array `arr`. +Returns `Infinity` if `arr` is empty. +See [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) on MDN. + +## Examples + +```rescript +Math.maxMany([1.0, 2.0]) // 2.0 +Math.maxMany([-1.0, -2.0]) // -1.0 +Math.maxMany([])->Float.isFinite // false +``` +*/ +@variadic +@val +external maxMany: array => float = "Math.max" + +/** +`pow(a, ~exp)` raises the given base `a` to the given exponent `exp`. +See [`Math.pow`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow) on MDN. + +## Examples + +```rescript +Math.pow(2.0, ~exp=4.0) // 16.0 +Math.pow(3.0, ~exp=4.0) // 81.0 +``` +*/ +@val +external pow: (float, ~exp: float) => float = "Math.pow" + +/** +`random()` returns a random number in the half-closed interval [0,1]. +See [`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) on MDN. + +## Examples + +```rescript +Math.random() +``` +*/ +@val +external random: unit => float = "Math.random" + +/** +`round(v)` returns then value of `v` rounded to nearest integral value +(expressed as a float). If the fractional portion of the argument `v` is greater +than `0.5`, the argument `v` is rounded to the float with the next higher +absolute value. +See [`Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) on MDN. + +## Examples + +```rescript +Math.round(-20.5) // -20.0 +Math.round(-0.1) // -0.0 +Math.round(0.0) // 0.0 +Math.round(-0.0) // -0.0 +``` +*/ +@val +external round: float => float = "Math.round" + +/** +`sign(v)` returns the sign of its foat argument: `-1` if negative, `0` if +zero, `1` if positive. +See [`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) on MDN. + +## Examples + +```rescript +Math.sign(3.0) // 1.0 +Math.sign(-3.0) // 1.0 +Math.sign(0.0) // 0.0 +``` +*/ +@val +external sign: float => float = "Math.sign" + +/** +`sin(v)` returns the sine of argument `v`, which must be specified in radians. +See [`Math.sin`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin) on MDN. + +## Examples + +```rescript +Math.sin(-0.0) // -0.0 +Math.sin(0.0) // 0.0 +Math.sin(1.0) // 0.8414709848078965 +``` +*/ +@val +external sin: float => float = "Math.sin" + +/** +`sinh(v)` returns then hyperbolic sine of argument `v`, which must be specified +in radians. +See [`Math.sinh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sinh) on MDN. + +## Examples + +```rescript +Math.sinh(-0.0) // -0.0 +Math.sinh(0.0) // 0.0 +Math.sinh(1.0) // 1.1752011936438014 +``` +*/ +@val +external sinh: float => float = "Math.sinh" + +/** +`sqrt(v)` returns the square root of `v`. If `v` is negative returns `NaN`. +See [`Math.sqrt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt) on MDN. + +## Examples + +```rescript +Math.sqrt(-1.0)->Float.isNaN // true +Math.sqrt(-0.0) // -0.0 +Math.sqrt(0.0) // 0.0 +Math.sqrt(1.0) // 1.0 +Math.sqrt(9.0) // 3.0 +``` +*/ +@val +external sqrt: float => float = "Math.sqrt" + +/** +`tan(v)` returns the tangent of argument `v`, which must be specified in +radians. Returns `NaN` if `v` is positive `Infinity` or negative `Infinity`. +See [`Math.tan`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan) on MDN. + +## Examples + +```rescript +Math.tan(-0.0) // -0.0 +Math.tan(0.0) // 0.0 +Math.tan(1.0) // 1.5574077246549023 +``` +*/ +@val +external tan: float => float = "Math.tan" + +/** +`tanh(v)` returns the hyperbolic tangent of argument `v`, which must be +specified in radians. +See [`Math.tanh`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tanh) on MDN. + +## Examples + +```rescript +Math.tanh(-0.0) // -0.0 +Math.tanh(0.0) // 0.0 +Math.tanh(1.0) // 0.7615941559557649 +``` +*/ +@val +external tanh: float => float = "Math.tanh" + +/** +`trunc(v)` truncates the argument `v`, i.e., removes fractional digits. +See [`Math.trunc`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc) on MDN. + +## Examples + +```rescript +Math.trunc(0.123) // 0.0 +Math.trunc(1.999) // 1.0 +Math.trunc(13.37) // 13.0 +Math.trunc(42.84) // 42.0 +``` +*/ +@val +external trunc: float => float = "Math.trunc" diff --git a/jscomp/stdlib-406/Nullable.res b/jscomp/stdlib-406/Nullable.res new file mode 100644 index 0000000000..b3f6dad440 --- /dev/null +++ b/jscomp/stdlib-406/Nullable.res @@ -0,0 +1,64 @@ +type t<'a> = Js.Nullable.t<'a> = + | Value('a) + | @as(null) Null + | @as(undefined) Undefined + +external null: t<'a> = "#null" + +external undefined: t<'a> = "#undefined" + +external make: 'a => t<'a> = "%identity" + +external toOption: t<'a> => option<'a> = "#nullable_to_opt" + +let fromOption: option<'a> => t<'a> = option => + switch option { + | Some(x) => make(x) + | None => undefined + } + +let equal = (a, b, eq) => Option.equal(a->toOption, b->toOption, eq) + +let compare = (a, b, cmp) => Option.compare(a->toOption, b->toOption, cmp) + +let getOr = (value, default) => + switch value->toOption { + | Some(x) => x + | None => default + } + +let getWithDefault = getOr + +let getExn: t<'a> => 'a = value => + switch value->toOption { + | Some(x) => x + | None => raise(Invalid_argument("Nullable.getExn: value is null or undefined")) + } + +external getUnsafe: t<'a> => 'a = "%identity" + +let forEach = (value, f) => + switch value->toOption { + | Some(x) => f(x) + | None => () + } + +let map = (value, f) => + switch value->toOption { + | Some(x) => make(f(x)) + | None => Obj.magic(value) + } + +let mapOr = (value, default, f) => + switch value->toOption { + | Some(x) => f(x) + | None => default + } + +let mapWithDefault = mapOr + +let flatMap = (value, f) => + switch value->toOption { + | Some(x) => f(x) + | None => Obj.magic(value) + } diff --git a/jscomp/stdlib-406/Nullable.resi b/jscomp/stdlib-406/Nullable.resi new file mode 100644 index 0000000000..bb1fee0c40 --- /dev/null +++ b/jscomp/stdlib-406/Nullable.resi @@ -0,0 +1,210 @@ +/*** +Functions for handling nullable values. + +Primarily useful when interoping with JavaScript when you don't know whether you'll get a value, `null` or `undefined`. +*/ + +/** +Type representing a nullable value. +A nullable value can be the value `'a`, `null` or `undefined`. +*/ +@unboxed +type t<'a> = Js.Nullable.t<'a> = + | Value('a) + | @as(null) Null + | @as(undefined) Undefined + +/** +The value `null`. + +See [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) on MDN. + +## Examples +```rescript +Console.log(Nullable.null) // Logs `null` to the console. +``` +*/ +external null: t<'a> = "#null" + +/** +The value `undefined`. + +See [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/undefined) on MDN. + +## Examples +```rescript +Console.log(undefined) // Logs `undefined` to the console. +``` +*/ +external undefined: t<'a> = "#undefined" + +/** +Creates a new nullable value from the provided value. +This means the compiler will enforce null checks for the new value. + +## Examples +```rescript +let myStr = "Hello" +let asNullable = myStr->Nullable.make + +// Can't do the below because we're now forced to check for nullability +// myStr == asNullable + +// Need to do this +switch asNullable->Nullable.toOption { +| Some(value) if value == myStr => Console.log("Yay, values matched!") +| _ => Console.log("Values did not match.") +} +``` +*/ +external make: 'a => t<'a> = "%identity" + +let equal: (t<'a>, t<'b>, ('a, 'b) => bool) => bool + +let compare: (t<'a>, t<'b>, ('a, 'b) => Ordering.t) => Ordering.t + +/** +Converts a nullable value into an option, so it can be pattern matched on. +Will convert both `null` and `undefined` to `None`, and a present value to `Some(value)`. + +## Examples +```rescript +let nullableString = Nullable.make("Hello") + +switch nullableString->Nullable.toOption { +| Some(str) => Console.log2("Got string:", str) +| None => Console.log("Didn't have a value.") +} +``` +*/ +external toOption: t<'a> => option<'a> = "#nullable_to_opt" + +/** +Turns an `option` into a `Nullable.t`. + +## Examples +```rescript +let optString = Some("Hello") +let asNullable = optString->Nullable.fromOption // Nullable.t +``` +*/ +let fromOption: option<'a> => t<'a> + +/** +`getOr(value, default)` returns `value` if not `null` or `undefined`, +otherwise return `default`. + +## Examples + +```rescript +Nullable.getOr(Nullable.null, "Banana") // Banana +Nullable.getOr(Nullable.make("Apple"), "Banana") // Apple + +let greet = (firstName: option) => + "Greetings " ++ firstName->Option.getOr("Anonymous") + +Nullable.make("Jane")->Nullable.toOption->greet // "Greetings Jane" +Nullable.null->Nullable.toOption->greet // "Greetings Anonymous" +``` +*/ +let getOr: (t<'a>, 'a) => 'a + +@deprecated("Use getOr instead") +let getWithDefault: (t<'a>, 'a) => 'a + +/** +`getExn(value)` raises an exception if `null` or `undefined`, otherwise returns the value. + +```rescript +Nullable.getExn(Nullable.make(3)) // 3 +Nullable.getExn(Nullable.null) /* Raises an Error */ +``` + +## Exceptions + +- Raises `Invalid_argument` if `value` is `null` or `undefined` +*/ +let getExn: t<'a> => 'a + +/** +`getUnsafe(value)` returns `value`. + +## Examples + +```rescript +Nullable.getUnsafe(Nullable.make(3)) == 3 +Nullable.getUnsafe(Nullable.null) // Raises an error +``` + +## Important + +- This is an unsafe operation, it assumes `value` is not `null` or `undefined`. +*/ +external getUnsafe: t<'a> => 'a = "%identity" + +/** +`forEach(value, f)` call `f` on `value`. if `value` is not `null` or `undefined`, +then if calls `f`, otherwise returns `unit`. + +## Examples + +```rescript +Nullable.forEach(Nullable.make("thing"), x => Console.log(x)) // logs "thing" +Nullable.forEach(Nullable.null, x => Console.log(x)) // returns () +Nullable.forEach(undefined, x => Console.log(x)) // returns () +``` +*/ +let forEach: (t<'a>, 'a => unit) => unit + +/** +`map(value, f)` returns `f(value)` if `value` is not `null` or `undefined`, +otherwise returns `value` unchanged. + +## Examples + +```rescript +Nullable.map(Nullable.make(3), x => x * x) // Nullable.make(9) +Nullable.map(undefined, x => x * x) // undefined +``` +*/ +let map: (t<'a>, 'a => 'b) => t<'b> + +/** +`mapOr(value, default, f)` returns `f(value)` if `value` is not `null` +or `undefined`, otherwise returns `default`. + +## Examples + +```rescript +let someValue = Nullable.make(3) +someValue->Nullable.mapOr(0, x => x + 5) // 8 + +let noneValue = Nullable.null +noneValue->Nullable.mapOr(0, x => x + 5) // 0 +``` +*/ +let mapOr: (t<'a>, 'b, 'a => 'b) => 'b + +@deprecated("Use mapOr instead") +let mapWithDefault: (t<'a>, 'b, 'a => 'b) => 'b + +/** +`flatMap(value, f)` returns `f(value)` if `value` is not `null` or `undefined`, +otherwise returns `value` unchanged. + +## Examples + +```rescript +let addIfAboveOne = value => + if (value > 1) { + Nullable.make(value + 1) + } else { + Nullable.null + } + +Nullable.flatMap(Nullable.make(2), addIfAboveOne) // Nullable.make(3) +Nullable.flatMap(Nullable.make(-4), addIfAboveOne) // undefined +Nullable.flatMap(Nullable.null, addIfAboveOne) // undefined +``` +*/ +let flatMap: (t<'a>, 'a => t<'b>) => t<'b> diff --git a/jscomp/stdlib-406/Nulll.res b/jscomp/stdlib-406/Nulll.res new file mode 100644 index 0000000000..70f4730fcd --- /dev/null +++ b/jscomp/stdlib-406/Nulll.res @@ -0,0 +1,64 @@ +@unboxed +type t<'a> = + | Value('a) + | @as(null) Null + +external asNullable: t<'a> => Nullable.t<'a> = "%identity" + +external null: t<'a> = "#null" + +external make: 'a => t<'a> = "%identity" + +external toOption: t<'a> => option<'a> = "#null_to_opt" + +let fromOption: option<'a> => t<'a> = option => + switch option { + | Some(x) => make(x) + | None => null + } + +let equal = (a, b, eq) => Option.equal(a->toOption, b->toOption, eq) + +let compare = (a, b, cmp) => Option.compare(a->toOption, b->toOption, cmp) + +let getOr = (value, default) => + switch value->toOption { + | Some(x) => x + | None => default + } + +let getWithDefault = getOr + +let getExn: t<'a> => 'a = value => + switch value->toOption { + | Some(x) => x + | None => raise(Invalid_argument("Null.getExn: value is null")) + } + +external getUnsafe: t<'a> => 'a = "%identity" + +let forEach = (value, f) => + switch value->toOption { + | Some(x) => f(x) + | None => () + } + +let map = (value, f) => + switch value->toOption { + | Some(x) => make(f(x)) + | None => null + } + +let mapOr = (value, default, f) => + switch value->toOption { + | Some(x) => f(x) + | None => default + } + +let mapWithDefault = mapOr + +let flatMap = (value, f) => + switch value->toOption { + | Some(x) => f(x) + | None => null + } diff --git a/jscomp/stdlib-406/Nulll.resi b/jscomp/stdlib-406/Nulll.resi new file mode 100644 index 0000000000..9cf0d430e6 --- /dev/null +++ b/jscomp/stdlib-406/Nulll.resi @@ -0,0 +1,198 @@ +/*** +Functions for handling values that could be `null`. + +If you also need to cover `undefined`, check out `Nullable` instead. +*/ + +/** +A type representing a value that can be either `'a` or `null`. +*/ +@unboxed +type t<'a> = + | Value('a) + | @as(null) Null + +/** +Converts a `Null.t` into a `Nullable.t`. + +## Examples +```rescript +let nullValue = Null.make("Hello") +let asNullable = nullValue->Null.asNullable // Nullable.t +``` +*/ +external asNullable: t<'a> => Nullable.t<'a> = "%identity" + +/** +The value `null`. + +See [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) on MDN. + +## Examples +```rescript +Console.log(null) // Logs `null` to the console. +``` +*/ +external null: t<'a> = "#null" + +/** +Creates a new `Null.t` from the provided value. +This means the compiler will enforce null checks for the new value. + +## Examples +```rescript +let myStr = "Hello" +let asNullValue = myStr->Null.make // The compiler now thinks this can be `string` or `null`. +``` +*/ +external make: 'a => t<'a> = "%identity" + +let equal: (t<'a>, t<'b>, ('a, 'b) => bool) => bool + +let compare: (t<'a>, t<'b>, ('a, 'b) => Ordering.t) => Ordering.t + +/** +Converts a nullable value into an option, so it can be pattern matched on. +Will convert `null` to `None`, and a present value to `Some(value)`. + +## Examples +```rescript +let nullStr = Null.make("Hello") + +switch nullStr->Null.toOption { +| Some(str) => Console.log2("Got string:", str) +| None => Console.log("Didn't have a value.") +} +``` +*/ +external toOption: t<'a> => option<'a> = "#null_to_opt" + +/** +Turns an `option` into a `Null.t`. `None` will be converted to `null`. + +## Examples +```rescript +let optString: option = None +let asNull = optString->Null.fromOption // Null.t +Console.log(asNull == Null.null) // Logs `true` to the console. +``` +*/ +let fromOption: option<'a> => t<'a> + +/** +`getOr(value, default)` returns `value` if not `null`, otherwise return +`default`. + +## Examples + +```rescript +Null.getOr(Null.null, "Banana") // Banana +Null.getOr(Null.make("Apple"), "Banana") // Apple + +let greet = (firstName: option) => + "Greetings " ++ firstName->Option.getOr("Anonymous") + +Null.make("Jane")->Null.toOption->greet // "Greetings Jane" +Null.null->Null.toOption->greet // "Greetings Anonymous" +``` +*/ +let getOr: (t<'a>, 'a) => 'a + +@deprecated("Use getOr instead") +let getWithDefault: (t<'a>, 'a) => 'a + +/** +`getExn(value)` raises an exception if `null`, otherwise returns the value. + +```rescript +Null.getExn(Null.make(3)) // 3 +Null.getExn(Null.null) /* Raises an Error */ +``` + +## Exceptions + +- Raises `Invalid_argument` if `value` is `null`, +*/ +let getExn: t<'a> => 'a + +/** +`getUnsafe(value)` returns `value`. + +## Examples + +```rescript +Null.getUnsafe(Null.make(3)) == 3 +Null.getUnsafe(Null.null) // Raises an error +``` + +## Important + +- This is an unsafe operation, it assumes `value` is not `null`. +*/ +external getUnsafe: t<'a> => 'a = "%identity" + +/** +`forEach(value, f)` call `f` on `value`. if `value` is not `null`, then if calls +`f`, otherwise returns `unit`. + +## Examples + +```rescript +Null.forEach(Null.make("thing"), x => Console.log(x)) // logs "thing" +Null.forEach(Null.null, x => Console.log(x)) // logs nothing +``` +*/ +let forEach: (t<'a>, 'a => unit) => unit + +/** +`map(value, f)` returns `f(value)` if `value` is not `null`, otherwise returns +`value` unchanged. + +## Examples + +```rescript +Null.map(Null.make(3), x => x * x) // Null.make(9) +Null.map(Null.null, x => x * x) // null +``` +*/ +let map: (t<'a>, 'a => 'b) => t<'b> + +/** +`mapOr(value, default, f)` returns `f(value)` if `value` is not `null`, +otherwise returns `default`. + +## Examples + +```rescript +let someValue = Null.make(3) +someValue->Null.mapOr(0, x => x + 5) // 8 + +let noneValue = Null.null +noneValue->Null.mapOr(0, x => x + 5) // 0 +``` +*/ +let mapOr: (t<'a>, 'b, 'a => 'b) => 'b + +@deprecated("Use mapOr instead") +let mapWithDefault: (t<'a>, 'b, 'a => 'b) => 'b + +/** +`flatMap(value, f)` returns `f(value)` if `value` is not `null`, otherwise +returns `value` unchanged. + +## Examples + +```rescript +let addIfAboveOne = value => + if (value > 1) { + Null.make(value + 1) + } else { + Null.null + } + +Null.flatMap(Null.make(2), addIfAboveOne) // Null.make(3) +Null.flatMap(Null.make(-4), addIfAboveOne) // null +Null.flatMap(Null.null, addIfAboveOne) // null +``` +*/ +let flatMap: (t<'a>, 'a => t<'b>) => t<'b> diff --git a/jscomp/stdlib-406/Object.res b/jscomp/stdlib-406/Object.res new file mode 100644 index 0000000000..434621df86 --- /dev/null +++ b/jscomp/stdlib-406/Object.res @@ -0,0 +1,281 @@ +/** +`make` create a new object that inherits the properties and methods from the standard built-in Object, such as `toString`. See [Object on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) + +## Examples + +```rescript +let x = Object.make() +x->Object.keysToArray->Array.length // 0 +x->Object.get("toString")->Option.isSome // true +``` +*/ +@obj +external make: unit => {..} = "" + +/** +`is` determines if two objects are identical in all contexts. Objects, arrays, records, and other non-primitives are only identical if they reference the **exact** same object in memory. Primitives like ints, floats, and strings are identical if they have the same value. `+0` and `-0` are distinct. NaN is equal to itself. See [Object.is on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) + +In most scenarios use `==` or `===` or the custom `equals` function (if provided) for the type. + +## Examples + +```rescript +Object.is(25, 13) // false +Object.is("abc", "abc") // true +Object.is(undefined, undefined) // true +Object.is(undefined, null) // false +Object.is(-0.0, 0.0) // false +Object.is(list{1, 2}, list{1, 2}) // false + +Object.is([1, 2, 3], [1, 2, 3]) // false +[1, 2, 3] == [1, 2, 3] // true +[1, 2, 3] === [1, 2, 3] // false + +let fruit = {"name": "Apple" } +Object.is(fruit, fruit) // true +Object.is(fruit, {"name": "Apple" }) // false +fruit == {"name": "Apple" } // true +fruit === {"name": "Apple" } // false +``` +*/ +@val +external is: ('a, 'a) => bool = "Object.is" + +/** +`create` creates a new object, using an existing object as the prototype of the new object. See [Object.create on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) + +**Note:** ReScript provides [first-class support for immutable objects](https://rescript-lang.org/docs/manual/latest/object) and [records](https://rescript-lang.org/docs/manual/latest/record). This is often safer and more convenient than using `create` and other functions in this module. + +## Examples + +```rescript +let x = {"fruit": "banana"} +let y = Object.create(x) +y->Object.get("fruit") // Some("banana") +``` +*/ +@val +external create: {..} => {..} = "Object.create" + +@val external createWithProperties: ({..}, {..}) => {..} = "Object.create" + +@val external createWithNull: (@as(json`null`) _, unit) => {..} = "Object.create" + +@val external createWithNullAndProperties: (@as(json`null`) _, {..}) => {..} = "Object.create" + +/** +`assign(target, source)` copies enumerable own properties from the source to the target, overwriting properties with the same name. It returns the modified target object. A deep clone is not created; properties are copied by reference. + +**Warning:** ReScript provides compile-time support for type-safe access to JavaScript objects. This eliminates common errors such as accessing properties that do not exist, or using a property of type x as if it were a y. Using `assign` can bypass these safety checks and lead to run-time errors (if you are not careful). ReScript provides [first-class support for immutable objects](https://rescript-lang.org/docs/manual/latest/object) and [records](https://rescript-lang.org/docs/manual/latest/record). This is often safer and more convenient than using `assign` and other functions in this module. + +See [Object.assign on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) or [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign). + +## Examples + +```rescript +Object.assign({"a": 1}, {"a": 2}) // {"a": 2} +Object.assign({"a": 1, "b": 2}, {"a": 0}) // {"a": 0, "b": 2} +Object.assign({"a": 1}, {"a": null}) // {"a": null} +``` +*/ +@val +external assign: ({..}, {..}) => {..} = "Object.assign" + +/** +`assignMany(target, sources)` copies enumerable own properties from each source to the target, overwriting properties with the same name. Later sources' properties overwrite earlier ones. It returns the modified target object. A deep clone is not created; properties are copied by reference. + +**Note:** ReScript provides [first-class support for immutable objects](https://rescript-lang.org/docs/manual/latest/object), including spreading one object into another. This is often more convenient than using `assign` or `assignMany`. + +See [Object.assign on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) or [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign). +*/ +@variadic +@val +external assignMany: ({..}, array<{..}>) => {..} = "Object.assign" + +@val external copy: (@as(json`{}`) _, {..} as 'a) => 'a = "Object.assign" + +/** +`get` gets the value of a property by name. Returns `None` if the property does not exist or has the value `undefined`. Otherwise returns `Some`, including if the value is `null`. + +## Examples + +```rescript +{"a": 1}->Object.get("a") // Some(1) +{"a": 1}->Object.get("b") // None +{"a": undefined}->Object.get("a") // None +{"a": null}->Object.get("a") // Some(null) +{"a": 1}->Object.get("toString")->Option.isSome // true +``` +*/ +@get_index +external get: ({..}, string) => option<'a> = "" + +/** +`getSymbol` gets the value of a property by symbol. Returns `None` if the property does not exist or has the value `undefined`. Otherwise returns `Some`, including if the value is `null`. + +## Examples + +```rescript +let fruit = Symbol.make("fruit") +let x = Object.make() +x->Object.setSymbol(fruit, "banana") +x->Object.getSymbol(fruit) // Some("banana") +``` +*/ +@get_index +external getSymbol: ({..}, Symbol.t) => option<'a> = "" + +@get_index external getSymbolUnsafe: ({..}, Symbol.t) => 'a = "" + +/** +`set(name, value)` assigns a value to the named object property, overwriting the previous value if any. See [Working with Objects on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#objects_and_properties) + +## Examples + +```rescript +{"a": 1}->Object.set("a", 2) // {"a": 2} +{"a": 1}->Object.set("a", None) // {"a": None} +{"a": 1}->Object.set("b", 2) // {"a": 1, "b": 2} +``` +*/ +@set_index +external set: ({..}, string, 'a) => unit = "" + +@set_index external setSymbol: ({..}, Symbol.t, 'a) => unit = "" + +/** +`keysToArray` returns an array of an object's own enumerable string-keyed property names. See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.keys) +or [Object.keys on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys). + +## Examples + +```rescript +{"a": 1, "b": 2}->Object.keysToArray // ["a", "b"] +{"a": None}->Object.keysToArray // ["a"] +Object.make()->Object.keysToArray // [] +``` +*/ +@val +external keysToArray: {..} => array = "Object.keys" + +/** +`hasOwnProperty` determines whether the object has the specified property as its **own** property, as opposed to inheriting it. See [hasOwnProperty on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) + +## Examples + +```rescript +let point = {"x": 1, "y": 2} +{"a": 1}->Object.hasOwnProperty("a") // true +{"a": 1}->Object.hasOwnProperty("b") // false +{"a": 1}->Object.hasOwnProperty("toString") // false +``` +*/ +@val +external hasOwnProperty: ({..}, string) => bool = "Object.prototype.hasOwnProperty.call" + +/** +`seal` seals an object. Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties. Unlike `freeze`, values of existing properties can still be changed as long as they are writable. + +**Note:** `seal` returns the same object that was passed in; it does not create a copy. Any attempt to delete or add properties to a sealed object will fail, either silently or by throwing an error. + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.seal) and [Object.seal on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal) + +## Examples + +```rescript +let point = {"x": 1, "y": 2} +point->Object.set("x", -7) // succeeds +point->Object.seal->ignore +point->Object.set("z", 9) // fails +point->Object.set("x", 13) // succeeds +``` +*/ +@val +external seal: ({..} as 'a) => 'a = "Object.seal" + +/** +`preventExtensions` prevents new properties from being added to the object. It modifies the object (rather than creating a copy) and returns it. + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.preventextensions) and [Object.preventExtensions on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) + +## Examples + +```rescript +let obj = {"a": 1} +obj->Object.set("b", 2) // succeeds +obj->Object.preventExtensions->ignore +obj->Object.set("c", 3) // fails +``` +*/ +@val +external preventExtensions: ({..} as 'a) => 'a = "Object.preventExtensions" + +/** +`freeze` freezes an object. Freezing an object makes existing properties non-writable and prevents extensions. Once an object is frozen, new properties cannot be be added, existing properties cannot be removed, and their values cannot be changed. + +**Note:** `freeze` returns the same object that was passed in; it does not create a frozen copy. Any attempt to change a frozen object will fail, either silently or by throwing an exception. + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.isfrozen) and [Object.isFrozen on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen). + +## Examples + + ```rescript +let obj = {"a": 1} +obj->Object.set("a", 2) // succeeds +obj->Object.freeze->ignore +obj->Object.set("a", 3) // fails +``` +*/ +@val +external freeze: ({..} as 'a) => 'a = "Object.freeze" + +/** +`isSealed` determines if an object is sealed. A sealed object has a fixed set of properties. + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.issealed) and [Object.isSealed on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed) + +## Examples + +```rescript +let point = {"x": 1, "y": 3}->Object.seal +let pointIsSealed = point->Object.isSealed // true +let fruit = {"name": "Apple" } +let fruitIsSealed = fruit->Object.isSealed // false + ``` +*/ +@val +external isSealed: 'a => bool = "Object.isSealed" + +/** +`isFrozen` determines if an object is frozen. An object is frozen if an only if it is not extensible, all its properties are non-configurable, and all its data properties are non-writable. + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.isfrozen) and [Object.isFrozen on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen). + +## Examples + +```rescript +let point = {"x": 1, "y": 3}->Object.freeze +let pointIsFrozen = point->Object.isFrozen // true +let fruit = {"name": "Apple" } +let fruitIsFrozen = fruit->Object.isFrozen // false + ``` +*/ +@val +external isFrozen: 'a => bool = "Object.isFrozen" + +/** +`isExtensible` determines if an object is extensible (whether it can have new properties added to it). + +See [ECMAScript Language Specification](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.isextensible) and [Object.isExtensible on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible) + +## Examples + +```rescript +let obj = {"a": 1} +obj->Object.isExtensible // true +obj->Object.preventExtensions->ignore +obj->Object.isExtensible // false +``` +*/ +@val +external isExtensible: 'a => bool = "Object.isExtensible" diff --git a/jscomp/stdlib-406/Option.res b/jscomp/stdlib-406/Option.res new file mode 100644 index 0000000000..4fcc8cfbb2 --- /dev/null +++ b/jscomp/stdlib-406/Option.res @@ -0,0 +1,106 @@ +/* Copyright (C) 2017 Hongbo Zhang, Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +let filter = (opt, p) => + switch opt { + | Some(x) as option if p(x) => option + | _ => None + } + +let forEach = (opt, f) => + switch opt { + | Some(x) => f(x) + | None => () + } + +let getExn = (x, ~message=?) => + switch x { + | Some(x) => x + | None => + Error.panic( + switch message { + | None => "Option.getExn called for None value" + | Some(message) => message + }, + ) + } + +external getUnsafe: option<'a> => 'a = "%identity" + +let mapOr = (opt, default, f) => + switch opt { + | Some(x) => f(x) + | None => default + } + +let mapWithDefault = mapOr + +let map = (opt, f) => + switch opt { + | Some(x) => Some(f(x)) + | None => None + } + +let flatMap = (opt, f) => + switch opt { + | Some(x) => f(x) + | None => None + } + +let getOr = (opt, default) => + switch opt { + | Some(x) => x + | None => default + } + +let getWithDefault = getOr + +let orElse = (opt, other) => + switch opt { + | Some(_) as some => some + | None => other + } + +let isSome = x => + switch x { + | Some(_) => true + | None => false + } + +let isNone = x => x == None + +let equal = (a, b, eq) => + switch (a, b) { + | (Some(a), Some(b)) => eq(a, b) + | (None, None) => true + | (None, Some(_)) | (Some(_), None) => false + } + +let compare = (a, b, cmp) => + switch (a, b) { + | (Some(a), Some(b)) => cmp(a, b) + | (None, Some(_)) => Ordering.less + | (Some(_), None) => Ordering.greater + | (None, None) => Ordering.equal + } diff --git a/jscomp/stdlib-406/Option.resi b/jscomp/stdlib-406/Option.resi new file mode 100644 index 0000000000..16efdba52c --- /dev/null +++ b/jscomp/stdlib-406/Option.resi @@ -0,0 +1,255 @@ +/* Copyright (C) 2017 Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/*** +We represent the existence and nonexistence of a value by wrapping it with +the `option` type. In order to make it a bit more convenient to work with +option-types, we provide utility-functions for it. + +The `option` type is a part of the ReScript standard library which is defined +like this: + +```rescript +type option<'a> = None | Some('a) +``` + +```rescript +let someString: option = Some("hello") +``` +*/ + +/** +`filter(opt, f)` applies `f` to `opt`, if `f` returns `true`, then it returns `Some(value)`, otherwise returns `None`. + +## Examples + +```rescript +Option.filter(Some(10), x => x > 5) // Some(10) +Option.filter(Some(4), x => x > 5) // None +Option.filter(None, x => x > 5) // None +``` +*/ +let filter: (option<'a>, 'a => bool) => option<'a> + +/** +`forEach(opt, f)` call `f` on `opt`. if `opt` is `Some(value)`, then if calls +`f`, otherwise returns `unit`. + +## Examples + +```rescript +Option.forEach(Some("thing"), x => Console.log(x)) // logs "thing" +Option.forEach(None, x => Console.log(x)) // returns () +``` +*/ +let forEach: (option<'a>, 'a => unit) => unit + +/** +`getExn(opt, ~message=?)` returns `value` if `opt` is `Some(value)`, otherwise raises an exception with the message provided, or a generic message if no message was provided. + +```rescript +Option.getExn(Some(3)) // 3 +Option.getExn(None) /* Raises an Error */ +Option.getExn(None, ~message="was None!") /* Raises an Error with the message "was None!" */ +``` + +## Exceptions + +- Raises an error if `opt` is `None` +*/ +let getExn: (option<'a>, ~message: string=?) => 'a + +/** +`getUnsafe(opt)` returns `value` if `opt` is `Some(value)`, otherwise `undefined`. + +## Examples + +```rescript +Option.getUnsafe(Some(3)) == 3 +Option.getUnsafe(None: option) // Returns `undefined`, which is not a valid `int` +``` + +## Notes + +- This is an unsafe operation. It assumes `value` is not `None`, and may cause undefined behaviour if it is. +*/ +external getUnsafe: option<'a> => 'a = "%identity" + +/** +`mapOr(opt, default, f)` returns `f(value)` if `opt` is `Some(value)`, otherwise `default`. + +## Examples + +```rescript +let someValue = Some(3) +someValue->Option.mapOr(0, x => x + 5) // 8 + +let noneValue = None +noneValue->Option.mapOr(0, x => x + 5) // 0 +``` +*/ +let mapOr: (option<'a>, 'b, 'a => 'b) => 'b + +@deprecated("Use mapOr instead") +let mapWithDefault: (option<'a>, 'b, 'a => 'b) => 'b + +/** +`map(opt, f)` returns `Some(f(value))` if `opt` is `Some(value)`, otherwise `None`. + +## Examples + +```rescript +Option.map(Some(3), x => x * x) // Some(9) +Option.map(None, x => x * x) // None +``` +*/ +let map: (option<'a>, 'a => 'b) => option<'b> + +/** +`flatMap(opt, f)` returns `f(value)` if `opt` is `Some(value)`, otherwise `None`. + +## Examples + +```rescript +let addIfAboveOne = value => + if (value > 1) { + Some(value + 1) + } else { + None + } + +Option.flatMap(Some(2), addIfAboveOne) // Some(3) +Option.flatMap(Some(-4), addIfAboveOne) // None +Option.flatMap(None, addIfAboveOne) // None +``` +*/ +let flatMap: (option<'a>, 'a => option<'b>) => option<'b> + +/** +`getOr(opt, default)` returns `value` if `opt` is `Some(value)`, otherwise `default`. + +## Examples + +```rescript +Option.getOr(None, "Banana") // Banana +Option.getOr(Some("Apple"), "Banana") // Apple + +let greet = (firstName: option) => + "Greetings " ++ firstName->Option.getOr("Anonymous") + +Some("Jane")->greet // "Greetings Jane" +None->greet // "Greetings Anonymous" +``` +*/ +let getOr: (option<'a>, 'a) => 'a + +@deprecated("Use getOr instead") +let getWithDefault: (option<'a>, 'a) => 'a + +/** +`orElse(opt1, opt2)` returns `opt2` if `opt1` is `None`, otherwise `opt1`. + +## Examples + +```rescript +Option.orElse(Some(1812), Some(1066)) == Some(1812) +Option.orElse(None, Some(1066)) == Some(1066) +Option.orElse(None, None) == None +``` +*/ +let orElse: (option<'a>, option<'a>) => option<'a> + +/** +`isSome(opt)` returns `true` if `opt` is `Some(value)`, otherwise returns `false`. + +## Examples + +```rescript +Option.isSome(None) // false +Option.isSome(Some(1)) // true +``` +*/ +let isSome: option<'a> => bool + +/** +`isNone(opt)` returns `true` if `opt` is `None`, false otherwise. + +## Examples + +```rescript +Option.isNone(None) // true +Option.isNone(Some(1)) // false +``` +*/ +let isNone: option<'a> => bool + +/** +`equal(opt1, opt2, f)` evaluates two optional values for equality with respect to a predicate function `f`. If both `opt1` and `opt2` are `None`, returns `true`. +If one of the arguments is `Some(value)` and the other is `None`, returns +`false`. +If arguments are `Some(value1)` and `Some(value2)`, returns the result of +`f(value1, value2)`, the predicate function `f` must return a bool. + +## Examples + +```rescript +let clockEqual = (a, b) => mod(a, 12) == mod(b, 12) + +open Option + +equal(Some(3), Some(15), clockEqual) // true +equal(Some(3), None, clockEqual) // false +equal(None, Some(3), clockEqual) // false +equal(None, None, clockEqual) // true +``` +*/ +let equal: (option<'a>, option<'b>, ('a, 'b) => bool) => bool + +/** +`compare(opt1, opt2, f)` compares two optional values with respect to given `f`. + +If both `opt1` and `opt2` are `None`, it returns `0.`. If the first argument is `Some(value1)` and the second is `None`, returns `1.` (something is greater than nothing). + +If the first argument is `None` and the second is `Some(value2)`, returns `-1.` +(nothing is less than something). + +If the arguments are `Some(value1)` and `Some(value2)`, returns the result of +`f(value1, value2)`, `f` takes two arguments and returns `-1.` if the first +argument is less than the second, `0.` if the arguments are equal, and `1.` if +the first argument is greater than the second. + +## Examples + +```rescript +let clockCompare = (a, b) => Int.compare(mod(a, 12), mod(b, 12)) + +Option.compare(Some(3), Some(15), clockCompare) // 0. +Option.compare(Some(3), Some(14), clockCompare) // 1. +Option.compare(Some(2), Some(15), clockCompare) // (-1.) +Option.compare(None, Some(15), clockCompare) // (-1.) +Option.compare(Some(14), None, clockCompare) // 1. +Option.compare(None, None, clockCompare) // 0. +``` +*/ +let compare: (option<'a>, option<'b>, ('a, 'b) => Ordering.t) => Ordering.t diff --git a/jscomp/stdlib-406/Ordering.res b/jscomp/stdlib-406/Ordering.res new file mode 100644 index 0000000000..c22a9ec4cb --- /dev/null +++ b/jscomp/stdlib-406/Ordering.res @@ -0,0 +1,13 @@ +type t = float + +@inline let less = -1. +@inline let equal = 0. +@inline let greater = 1. + +let isLess = ord => ord < equal +let isEqual = ord => ord == equal +let isGreater = ord => ord > equal + +let invert = ord => -.ord + +let fromInt = n => n < 0 ? less : n > 0 ? greater : equal diff --git a/jscomp/stdlib-406/Promise.res b/jscomp/stdlib-406/Promise.res new file mode 100644 index 0000000000..8a4418d2fd --- /dev/null +++ b/jscomp/stdlib-406/Promise.res @@ -0,0 +1,112 @@ +type t<+'a> = promise<'a> + +@new +external make: (('a => unit, 'e => unit) => unit) => t<'a> = "Promise" + +type promiseAndResolvers<'a> = { + promise: t<'a>, + resolve: 'a => unit, + reject: exn => unit, +} + +@scope("Promise") @val +external withResolvers: unit => promiseAndResolvers<_> = "withResolvers" + +@scope("Promise") @val +external resolve: 'a => t<'a> = "resolve" + +@send external then: (t<'a>, 'a => t<'b>) => t<'b> = "then" + +@send +external thenResolve: (t<'a>, 'a => 'b) => t<'b> = "then" + +@send external finally: (t<'a>, unit => unit) => t<'a> = "finally" + +@scope("Promise") @val +external reject: exn => t<_> = "reject" + +@scope("Promise") @val +external all: array> => t> = "all" + +@scope("Promise") @val +external all2: ((t<'a>, t<'b>)) => t<('a, 'b)> = "all" + +@scope("Promise") @val +external all3: ((t<'a>, t<'b>, t<'c>)) => t<('a, 'b, 'c)> = "all" + +@scope("Promise") @val +external all4: ((t<'a>, t<'b>, t<'c>, t<'d>)) => t<('a, 'b, 'c, 'd)> = "all" + +@scope("Promise") @val +external all5: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>)) => t<('a, 'b, 'c, 'd, 'e)> = "all" + +@scope("Promise") @val +external all6: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>, t<'f>)) => t<('a, 'b, 'c, 'd, 'e, 'f)> = "all" + +@tag("status") +type settledResult<+'a> = + | @as("fulfilled") Fulfilled({value: 'a}) | @as("rejected") Rejected({reason: exn}) + +@scope("Promise") @val +external allSettled: array> => promise>> = "allSettled" + +@scope("Promise") @val +external allSettled2: ((promise<'a0>, promise<'a1>)) => promise<( + settledResult<'a0>, + settledResult<'a1>, +)> = "allSettled" + +@scope("Promise") @val +external allSettled3: ((promise<'a0>, promise<'a1>, promise<'a2>)) => promise<( + settledResult<'a0>, + settledResult<'a1>, + settledResult<'a2>, +)> = "allSettled" + +@scope("Promise") @val +external allSettled4: ((promise<'a0>, promise<'a1>, promise<'a2>, promise<'a3>)) => promise<( + settledResult<'a0>, + settledResult<'a1>, + settledResult<'a2>, + settledResult<'a3>, +)> = "allSettled" + +@scope("Promise") @val +external allSettled5: ( + (promise<'a0>, promise<'a1>, promise<'a2>, promise<'a3>, promise<'a4>) +) => promise<( + settledResult<'a0>, + settledResult<'a1>, + settledResult<'a2>, + settledResult<'a3>, + settledResult<'a4>, +)> = "allSettled" + +@scope("Promise") @val +external allSettled6: ( + (promise<'a0>, promise<'a1>, promise<'a2>, promise<'a3>, promise<'a4>, promise<'a5>) +) => promise<( + settledResult<'a0>, + settledResult<'a1>, + settledResult<'a2>, + settledResult<'a3>, + settledResult<'a4>, + settledResult<'a5>, +)> = "allSettled" + +@send +external _catch: (t<'a>, exn => t<'a>) => t<'a> = "catch" + +let catch = (promise: promise<'a>, callback: exn => promise<'a>): promise<'a> => { + _catch(promise, err => { + callback(Js.Exn.anyToExnInternal(err)) + }) +} + +@scope("Promise") @val +external race: array> => t<'a> = "race" + +@scope("Promise") @val +external any: array> => t<'a> = "any" + +external done: promise<'a> => unit = "%ignore" diff --git a/jscomp/stdlib-406/Promise.resi b/jscomp/stdlib-406/Promise.resi new file mode 100644 index 0000000000..5468bf9370 --- /dev/null +++ b/jscomp/stdlib-406/Promise.resi @@ -0,0 +1,445 @@ +// The +'a marks the abstract type parameter as covariant, which essentially means that +// a value of type 'a is immutable and may not be used in some mutable context. +// +// This makes sense for promises, since according to their specification, once a promise has +// been resolved (with a specific value), it will never change its resolved value. +// +// More details about polymorphism / invariance / covariance,... can be found here: +// https://caml.inria.fr/pub/docs/manual-ocaml/polymorphism.html#ss:variance:abstract-data-types + +/*** +Functions for interacting with JavaScript Promise. +See: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). +*/ + +type t<+'a> = promise<'a> + +/** +`resolve(value)` creates a resolved Promise with a given `value`. +See [`Promise.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) on MDN. + +## Examples + +```rescript +let p = Promise.resolve(5) // promise +``` +*/ +@val +@scope("Promise") +external resolve: 'a => t<'a> = "resolve" + +/** +`reject(exn)` reject a Promise. +See [`Promise.reject`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject) on MDN. + +## Examples + +```rescript +exception TestError(string) + +let p = Promise.reject(TestError("some rejected value")) +``` +*/ +@scope("Promise") +@val +external reject: exn => t<_> = "reject" + +/** +`make(callback)` creates a new Promise based on a `callback` that receives two +uncurried functions `resolve` and `reject` for defining the Promise's result. + +## Examples + +```rescript +open Promise + +let n = 4 +Promise.make((resolve, reject) => { + if(n < 5) { + resolve(. "success") + } + else { + reject(. "failed") + } +}) +->then(str => { + Console.log(str)->resolve +}) +->catch(_ => { + Console.log("Error occurred") + resolve() +}) +->ignore +``` +*/ +@new +external make: (('a => unit, 'e => unit) => unit) => t<'a> = "Promise" + +type promiseAndResolvers<'a> = { + promise: t<'a>, + resolve: 'a => unit, + reject: exn => unit, +} + +/** +`withResolvers()` returns a object containing a new promise with functions to resolve or reject it. See [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) on MDN. + +## Examples + +```rescript +open Promise + +let {promise, resolve, _} = Promise.withResolvers() + +setTimeout(() => { + resolve(. "success") +}, 1000)->ignore + +promise +->thenResolve(str => { + Console.log(str) +}) +->ignore +``` +*/ +@scope("Promise") +@val +external withResolvers: unit => promiseAndResolvers<_> = "withResolvers" + +/** +`catch(promise, errorCallback)` registers an exception handler in a promise chain. +The `errorCallback` receives an `exn` value that can later be refined into a JS +error or ReScript error. The `errorCallback` needs to return a promise with the +same type as the consumed promise. See [`Promise.catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) on MDN. + +## Examples + +```rescript +open Promise + +exception SomeError(string) + +reject(SomeError("this is an error")) +->then(_ => { + Ok("This result will never be returned")->resolve +}) +->catch(e => { + let msg = switch(e) { + | SomeError(msg) => "ReScript error occurred: " ++ msg + | Exn.Error(obj) => + switch Exn.message(obj) { + | Some(msg) => "JS exception occurred: " ++ msg + | None => "Some other JS value has been thrown" + } + | _ => "Unexpected error occurred" + } + + Error(msg)->resolve +}) +->then(result => { + switch result { + | Ok(r) => Console.log2("Operation successful: ", r) + | Error(msg) => Console.log2("Operation failed: ", msg) + }->resolve +}) +->ignore // Ignore needed for side-effects +``` + +In case you want to return another promise in your `callback`, consider using +`then` instead. +*/ +let catch: (t<'a>, exn => t<'a>) => t<'a> + +/** +`then(promise, callback)` returns a new promise based on the result of `promise`'s +value. The `callback` needs to explicitly return a new promise via `resolve`. +It is **not allowed** to resolve a nested promise (like `resolve(resolve(1))`). +See [`Promise.then`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) on MDN. +## Examples + +```rescript +open Promise +resolve(5) +->then(num => { + resolve(num + 5) +}) +->then(num => { + Console.log2("Your lucky number is: ", num) + resolve() +}) +->ignore +``` +*/ +@send +external then: (t<'a>, 'a => t<'b>) => t<'b> = "then" + +/** +`thenResolve(promise, callback)` converts an encapsulated value of a promise +into another promise wrapped value. It is **not allowed** to return a promise +within the provided callback (e.g. `thenResolve(value => resolve(value))`). + +## Examples + +```rescript +open Promise +resolve("Anna") +->thenResolve(str => { + "Hello " ++ str +}) +->thenResolve(str => { + Console.log(str) +}) +->ignore // Ignore needed for side-effects +``` + +In case you want to return another promise in your `callback`, consider using +`then` instead. +*/ +@send +external thenResolve: (t<'a>, 'a => 'b) => t<'b> = "then" + +/** +`finally(promise, callback)` is used to execute a function that is called no +matter if a promise was resolved or rejected. It will return the same `promise` +it originally received. See [`Promise.finally`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally) on MDN. + +## Examples + +```rescript +open Promise +exception SomeError(string) +let isDone = ref(false) + +resolve(5) +->then(_ => { + reject(SomeError("test")) +}) +->then(v => { + Console.log2("final result", v) + resolve() +}) +->catch(_ => { + Console.log("Error handled") + resolve() +}) +->finally(() => { + Console.log("finally") + isDone := true +}) +->then(() => { + Console.log2("isDone:", isDone.contents) + resolve() +}) +->ignore +``` +*/ +@send +external finally: (t<'a>, unit => unit) => t<'a> = "finally" + +/** +`race(arr)` runs all promises concurrently and returns promise settles with the eventual state of the first promise that settles. See [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) on MDN. + +## Examples + +```rescript +open Promise +let racer = (ms, name) => { + Promise.make((resolve, _) => { + setTimeout(() => { + resolve(name) + }, ms)->ignore + }) +} + +let promises = [racer(1000, "Turtle"), racer(500, "Hare"), racer(100, "Eagle")] + +race(promises)->then(winner => { + Console.log("The winner is " ++ winner) + resolve() +}) +``` +*/ +@scope("Promise") +@val +external race: array> => t<'a> = "race" + +/** +`any(arr)` runs all promises concurrently and returns promise fulfills when any of the input's promises fulfills, with this first fulfillment value. See [`Promise.any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any) on MDN. + +## Examples + +```rescript +open Promise +let racer = (ms, name) => { + Promise.make((resolve, _) => { + setTimeout(() => { + resolve(name) + }, ms)->ignore + }) +} + +let promises = [racer(1000, "Turtle"), racer(500, "Hare"), racer(100, "Eagle")] + +any(promises)->then(winner => { + Console.log("The winner is " ++ winner) + resolve() +}) +``` +*/ +@scope("Promise") +@val +external any: array> => t<'a> = "any" + +/** +`all(promises)` runs all promises concurrently and returns a promise fulfills when all of the input's promises fulfill, with an array of the fulfillment values. See [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) on MDN. + +```rescript +open Promise +let promises = [resolve(1), resolve(2), resolve(3)] + +all(promises) +->then((results) => { + results->Array.forEach(num => { + Console.log2("Number: ", num) + }) + + resolve() +}) +->ignore +``` +*/ +@scope("Promise") +@val +external all: array> => t> = "all" + +/** +`all2((p1, p2))`. Like `all()`, but with a fixed size tuple of 2 +*/ +@scope("Promise") +@val +external all2: ((t<'a>, t<'b>)) => t<('a, 'b)> = "all" + +/** +`all3((p1, p2, p3))`. Like `all()`, but with a fixed size tuple of 3 +*/ +@scope("Promise") +@val +external all3: ((t<'a>, t<'b>, t<'c>)) => t<('a, 'b, 'c)> = "all" + +/** +`all4((p1, p2, p3, p4))`. Like `all()`, but with a fixed size tuple of 4 +*/ +@scope("Promise") +@val +external all4: ((t<'a>, t<'b>, t<'c>, t<'d>)) => t<('a, 'b, 'c, 'd)> = "all" + +/** +`all5((p1, p2, p3, p4, p5))`. Like `all()`, but with a fixed size tuple of 5 +*/ +@scope("Promise") +@val +external all5: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>)) => t<('a, 'b, 'c, 'd, 'e)> = "all" + +/** +`all6((p1, p2, p4, p5, p6))`. Like `all()`, but with a fixed size tuple of 6 +")*/ +@scope("Promise") +@val +external all6: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>, t<'f>)) => t<('a, 'b, 'c, 'd, 'e, 'f)> = "all" + +@tag("status") +type settledResult<+'a> = + | @as("fulfilled") Fulfilled({value: 'a}) | @as("rejected") Rejected({reason: exn}) + +/** +`allSettled(promises)` runs all promises concurrently and returns promise fulfills when all of the input's promises settle with an array of objects that describe the outcome of each promise. See [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) on MDN. + +```rescript +open Promise + +exception TestError(string) + +let promises = [resolve(1), resolve(2), reject(TestError("some rejected promise"))] + +allSettled(promises) +->then((results) => { + results->Array.forEach((result) => { + switch result { + | Fulfilled({value: num}) => + Console.log2("Number: ", num) + | Rejected({reason}) => + Console.log(reason) + } + }) + + resolve() +}) +->ignore +``` +*/ +@scope("Promise") +@val +external allSettled: array> => t>> = "allSettled" + +/** +`allSettled2((p1, p2))`. Like `allSettled()`, but with a fixed size tuple of 2 +*/ +@scope("Promise") +@val +external allSettled2: ((t<'a>, t<'b>)) => t<(settledResult<'a>, settledResult<'b>)> = "allSettled" + +/** +`allSettled3((p1, p2, p3))`. Like `allSettled()`, but with a fixed size tuple of 3 +*/ +@scope("Promise") +@val +external allSettled3: ((t<'a>, t<'b>, t<'c>)) => t<( + settledResult<'a>, + settledResult<'b>, + settledResult<'c>, +)> = "allSettled" + +/** +`allSettled4((p1, p2, p3, p4))`. Like `allSettled()`, but with a fixed size tuple of 4 +*/ +@scope("Promise") +@val +external allSettled4: ((t<'a>, t<'b>, t<'c>, t<'d>)) => t<( + settledResult<'a>, + settledResult<'b>, + settledResult<'c>, + settledResult<'d>, +)> = "allSettled" + +/** +`allSettled5((p1, p2, p3, p4, p5))`. Like `allSettled()`, but with a fixed size tuple of 5 +*/ +@scope("Promise") +@val +external allSettled5: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>)) => t<( + settledResult<'a>, + settledResult<'b>, + settledResult<'c>, + settledResult<'d>, + settledResult<'e>, +)> = "allSettled" + +/** +`allSettled6((p1, p2, p4, p5, p6))`. Like `allSettled()`, but with a fixed size tuple of 6 +")*/ +@scope("Promise") +@val +external allSettled6: ((t<'a>, t<'b>, t<'c>, t<'d>, t<'e>, t<'f>)) => t<( + settledResult<'a>, + settledResult<'b>, + settledResult<'c>, + settledResult<'d>, + settledResult<'e>, + settledResult<'f>, +)> = "allSettled" + +/** +`done(p)` is a safe way to ignore a promise. If a value is anything else than a +promise, it will raise a type error. +*/ +external done: promise<'a> => unit = "%ignore" diff --git a/jscomp/stdlib-406/RegExp.res b/jscomp/stdlib-406/RegExp.res new file mode 100644 index 0000000000..84668ae072 --- /dev/null +++ b/jscomp/stdlib-406/RegExp.res @@ -0,0 +1,23 @@ +type t = Js.Re.t + +module Result = { + type t = array + @get_index external fullMatch: (t, @as(0) _) => string = "" + @send external matches: (t, @as(1) _) => array = "slice" + @get external index: t => int = "index" + @get external input: t => string = "input" +} + +@new external fromString: string => t = "RegExp" +@new external fromStringWithFlags: (string, ~flags: string) => t = "RegExp" + +@send external test: (t, string) => bool = "test" +@return(nullable) @send external exec: (t, string) => option = "exec" + +@get external lastIndex: t => int = "lastIndex" +@get external ignoreCase: t => bool = "ignoreCase" +@get external global: t => bool = "global" +@get external multiline: t => bool = "multiline" +@get external source: t => string = "source" +@get external sticky: t => bool = "sticky" +@get external unicode: t => bool = "unicode" diff --git a/jscomp/stdlib-406/RegExp.resi b/jscomp/stdlib-406/RegExp.resi new file mode 100644 index 0000000000..e16ba1e960 --- /dev/null +++ b/jscomp/stdlib-406/RegExp.resi @@ -0,0 +1,270 @@ +/*** +Functions for handling RegExp's in ReScript. + +See [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) on MDN. +*/ + +/** +Type representing an instantiated `RegExp`. +*/ +type t = Js.Re.t + +module Result: { + /** + Type representing the result of a `RegExp` execution. + */ + type t = array + + /** + `fullMatch(regExpResult)` returns the full string that matched in this result. + + ## Examples + ```rescript + // Match the first two words separated by a space + let regexp = RegExp.fromString("(\\w+) (\\w+)") + + switch regexp->RegExp.exec("ReScript is pretty cool, right?") { + | None => Console.log("Nope, no match...") + | Some(result) => Console.log(result->RegExp.Result.fullMatch) // Prints the full string that matched, "ReScript is" + } + ``` + */ + @get_index + external fullMatch: (t, @as(0) _) => string = "" + + /** + `matches(regExpResult)` returns all matches for `regExpResult`. + + ## Examples + ```rescript + // Match the first two words separated by a space + let regexp = RegExp.fromString("(\\w+) (\\w+)") + + // This below will log "ReScript" and "is" to the console. + switch regexp->RegExp.exec("ReScript is pretty cool, right?") { + | None => Console.log("Nope, no match...") + | Some(result) => switch result->RegExp.Result.matches { + | [firstWord, secondWord] => Console.log2(firstWord, secondWord) + | _ => Console.log("Didn't find exactly two words...") + } + } + ``` + */ + @send + external matches: (t, @as(1) _) => array = "slice" + @get external index: t => int = "index" + + /** + `input(regExpResult)` returns the full input string that was passed to what produced the `RegExp.Result.t`. + + ## Examples + ```rescript + // Match the first two words separated by a space + let regexp = RegExp.fromString("(\\w+) (\\w+)") + + // This below will log the full input string "ReScript is pretty cool, right?" to the console. + switch regexp->RegExp.exec("ReScript is pretty cool, right?") { + | None => Console.log("Nope, no match...") + | Some(result) => Console.log(result->RegExp.Result.input) + } + ``` + */ + @get + external input: t => string = "input" +} + +/** +`fromString(string)` creates a `RegExp.t` from the provided string. This can then be used to match on strings using `RegExp.exec`. + +See [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp) on MDN. + +## Examples +```rescript +// Match the first word in a sentence +let regexp = RegExp.fromString("\\w+") + +switch regexp->RegExp.exec("ReScript is pretty cool, right?") { +| None => Console.log("Nope, no match...") +| Some(result) => Console.log(result->RegExp.Result.fullMatch) // Prints "ReScript" +} +``` +*/ +@new +external fromString: string => t = "RegExp" + +/** +`fromStringWithFlags(string)` creates a `RegExp.t` from the provided string, using the provided `flags`. This can then be used to match on strings using `RegExp.exec`. + +See [`RegExp parameters`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#parameters) on MDN. + +## Examples +```rescript +// Match the first word in a sentence +let regexp = RegExp.fromStringWithFlags("\\w+", ~flags="g") + +switch regexp->RegExp.exec("ReScript is pretty cool, right?") { +| None => Console.log("Nope, no match...") +| Some(result) => Console.log(result->RegExp.Result.fullMatch) // Prints "ReScript" +} +``` +*/ +@new +external fromStringWithFlags: (string, ~flags: string) => t = "RegExp" + +/** +`test(regexp, string)` tests whether the provided `regexp` matches on the provided string. + +See [`RegExp.test`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) on MDN. + +## Examples +```rescript +// Match the first word in a sentence +let regexp = RegExp.fromString("\\w+") + +if regexp->RegExp.test("ReScript is cool!") { + Console.log("Yay, there's a word in there.") +} +``` +*/ +@send +external test: (t, string) => bool = "test" + +/** +`exec(regexp, string)` executes the provided regexp on the provided string, optionally returning a `RegExp.Result.t` if the regexp matches on the string. + +See [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) on MDN. + +## Examples +```rescript +// Match the first word in a sentence +let regexp = RegExp.fromString("\\w+") + +switch regexp->RegExp.exec("ReScript is pretty cool, right?") { +| None => Console.log("Nope, no match...") +| Some(result) => Console.log(result->RegExp.Result.fullMatch) // Prints "ReScript" +} +``` +*/ +@return(nullable) +@send +external exec: (t, string) => option = "exec" + +/** +`lastIndex(regexp)` returns the index the next match will start from. + +See [`RegExp.lastIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) on MDN. + +## Examples +```rescript +// Match the first word in a sentence +let regexp = RegExp.fromString("\\w+") +let someStr = "Many words here." + +Console.log(regexp->RegExp.lastIndex) // Logs `0` to the console + +regexp->RegExp.exec(someStr)->ignore + +Console.log(regexp->RegExp.lastIndex) // Logs `4` to the console +``` +*/ +@get +external lastIndex: t => int = "lastIndex" + +/** +`ignoreCase(regexp)` returns whether the ignore case (`i`) flag is set on this `RegExp`. + +See [`RegExp.ignoreCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase) on MDN. + +## Examples +```rescript +let regexp1 = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp1->RegExp.ignoreCase) // Logs `false`, since `i` is not set + +let regexp2 = RegExp.fromStringWithFlags("\\w+", ~flags="i") +Console.log(regexp2->RegExp.ignoreCase) // Logs `true`, since `i` is set +``` +*/ +@get +external ignoreCase: t => bool = "ignoreCase" + +/** +`global(regexp)` returns whether the global (`g`) flag is set on this `RegExp`. + +See [`RegExp.global`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global) on MDN. + +## Examples +```rescript +let regexp1 = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp1->RegExp.global) // Logs `true`, since `g` is set + +let regexp2 = RegExp.fromStringWithFlags("\\w+", ~flags="i") +Console.log(regexp2->RegExp.global) // Logs `false`, since `g` is not set +``` +*/ +@get +external global: t => bool = "global" + +/** +`multiline(regexp)` returns whether the multiline (`m`) flag is set on this `RegExp`. + +See [`RegExp.multiline`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline) on MDN. + +## Examples +```rescript +let regexp1 = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp1->RegExp.multiline) // Logs `false`, since `m` is not set + +let regexp2 = RegExp.fromStringWithFlags("\\w+", ~flags="mi") +Console.log(regexp2->RegExp.multiline) // Logs `true`, since `m` is set +``` +*/ +@get +external multiline: t => bool = "multiline" + +/** +`source(regexp)` returns the source text for this `RegExp`, without the two forward slashes (if present), and without any set flags. + +See [`RegExp.source`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source) on MDN. + +## Examples +```rescript +let regexp = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp->RegExp.source) // Logs `\w+`, the source text of the `RegExp` +``` +*/ +@get +external source: t => string = "source" + +/** +`sticky(regexp)` returns whether the sticky (`y`) flag is set on this `RegExp`. + +See [`RegExp.sticky`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) on MDN. + +## Examples +```rescript +let regexp1 = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp1->RegExp.unicode) // Logs `false`, since `y` is not set + +let regexp2 = RegExp.fromStringWithFlags("\\w+", ~flags="my") +Console.log(regexp2->RegExp.unicode) // Logs `true`, since `y` is set +``` +*/ +@get +external sticky: t => bool = "sticky" + +/** +`unicode(regexp)` returns whether the unicode (`y`) flag is set on this `RegExp`. + +See [`RegExp.unicode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) on MDN. + +## Examples +```rescript +let regexp1 = RegExp.fromStringWithFlags("\\w+", ~flags="g") +Console.log(regexp1->RegExp.unicode) // Logs `false`, since `u` is not set + +let regexp2 = RegExp.fromStringWithFlags("\\w+", ~flags="mu") +Console.log(regexp2->RegExp.unicode) // Logs `true`, since `u` is set +``` +*/ +@get +external unicode: t => bool = "unicode" diff --git a/jscomp/stdlib-406/Result.res b/jscomp/stdlib-406/Result.res new file mode 100644 index 0000000000..f9307b59f4 --- /dev/null +++ b/jscomp/stdlib-406/Result.res @@ -0,0 +1,97 @@ +/* Copyright (C) 2017 Hongbo Zhang, Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +let getExn = x => + switch x { + | Ok(x) => x + | Error(_) => raise(Not_found) + } + +let mapOr = (opt, default, f) => + switch opt { + | Ok(x) => f(x) + | Error(_) => default + } + +let mapWithDefault = mapOr + +let map = (opt, f) => + switch opt { + | Ok(x) => Ok(f(x)) + | Error(_) as result => result + } + +let flatMap = (opt, f) => + switch opt { + | Ok(x) => f(x) + | Error(_) as result => result + } + +let getOr = (opt, default) => + switch opt { + | Ok(x) => x + | Error(_) => default + } + +let getWithDefault = getOr + +let isOk = x => + switch x { + | Ok(_) => true + | Error(_) => false + } + +let isError = x => + switch x { + | Ok(_) => false + | Error(_) => true + } + +let equal = (a, b, f) => + switch (a, b) { + | (Ok(a), Ok(b)) => f(a, b) + | (Error(_), Ok(_)) + | (Ok(_), Error(_)) => false + | (Error(_), Error(_)) => true + } + +let compare = (a, b, f) => + switch (a, b) { + | (Ok(a), Ok(b)) => f(a, b) + | (Error(_), Ok(_)) => Ordering.less + | (Ok(_), Error(_)) => Ordering.greater + | (Error(_), Error(_)) => Ordering.equal + } + +let forEach = (r, f) => + switch r { + | Ok(ok) => f(ok) + | Error(_) => () + } + +let mapError = (r, f) => + switch r { + | Ok(_) as result => result + | Error(e) => Error(f(e)) + } diff --git a/jscomp/stdlib-406/Result.resi b/jscomp/stdlib-406/Result.resi new file mode 100644 index 0000000000..ac31649e7c --- /dev/null +++ b/jscomp/stdlib-406/Result.resi @@ -0,0 +1,236 @@ +/* Copyright (C) 2017 Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/** + Result types are really useful to describe the result of a certain operation + without relying on exceptions or `option` types. + + This module gives you useful utilities to create and combine `Result` data. +*/ +/** + The type `Result.t(result, err)` describes a variant of two states: + `Ok(someResult)` represents a successful operation, whereby + ``Error(someError)` signals an erronous operation. + + In this concrete example, we are defining our own `Result` type to reflect an HTTP like + query operation: + + ```res example + type responseError = NotAvailable | NotFound + type queryResult = result + + let failQueryUser = (username: string): queryResult => { + Error(NotAvailable) + } +``` +*/ +/** + `getExn(res)`: when `res` is `Ok(n)`, returns `n` when `res` is `Error(m)`, raise an exception + + ```res example + Result.getExn(Result.Ok(42)) == 42 + + Result.getExn(Result.Error("Invalid data")) /* raises exception */ + ``` +*/ +let getExn: result<'a, 'b> => 'a + +/** +`mapOr(res, default, f)`: When res is `Ok(n)`, returns `f(n)`, otherwise `default`. + +## Examples + +```rescript +let ok = Ok(42) +Result.mapOr(ok, 0, (x) => x / 2) == 21 + +let error = Error("Invalid data") +Result.mapOr(error, 0, (x) => x / 2) == 0 +``` +*/ +let mapOr: (result<'a, 'c>, 'b, 'a => 'b) => 'b + +@deprecated("Use mapOr instead") +let mapWithDefault: (result<'a, 'c>, 'b, 'a => 'b) => 'b + +/** +`map(res, f)`: When res is `Ok(n)`, returns `Ok(f(n))`. Otherwise returns res +unchanged. Function `f` takes a value of the same type as `n` and returns an +ordinary value. + +## Examples + +```rescript +let f = (x) => sqrt(Int.toFloat(x)) + +Result.map(Ok(64), f) == Ok(8.0) + +Result.map(Error("Invalid data"), f) == Error("Invalid data") +``` +*/ +let map: (result<'a, 'c>, 'a => 'b) => result<'b, 'c> + +/** +`flatMap(res, f)`: When res is `Ok(n)`, returns `f(n)`. Otherwise, returns res +unchanged. Function `f` takes a value of the same type as `n` and returns a +`Result`. + +## Examples + +```rescript +let recip = (x) => + if (x !== 0.0) { + Ok(1.0 /. x) + } else { + Error("Divide by zero") + } + +Result.flatMap(Ok(2.0), recip) == Ok(0.5) + +Result.flatMap(Ok(0.0), recip) == Error("Divide by zero") + +Result.flatMap(Error("Already bad"), recip) == Error("Already bad") +``` +*/ +let flatMap: (result<'a, 'c>, 'a => result<'b, 'c>) => result<'b, 'c> + +/** +`getOr(res, defaultValue)`: If `res` is `Ok(n)`, returns `n`, otherwise `default` + +## Examples + +```rescript +Result.getOr(Ok(42), 0) == 42 + +Result.getOr(Error("Invalid Data"), 0) == 0 +``` +*/ +let getOr: (result<'a, 'b>, 'a) => 'a + +@deprecated("Use getOr instead") +let getWithDefault: (result<'a, 'b>, 'a) => 'a + +/** +`isOk(res)`: Returns `true` if `res` is of the form `Ok(n)`, `false` if it is the `Error(e)` variant. +*/ +let isOk: result<'a, 'b> => bool + +/** +`isError(res)`: Returns `true` if `res` is of the form `Error(e)`, `false` if it is the `Ok(n)` variant. +*/ +let isError: result<'a, 'b> => bool + +/** +`equal(res1, res2, f)`: Determine if two `Result` variables are equal with +respect to an equality function. If `res1` and `res2` are of the form `Ok(n)` +and `Ok(m)`, return the result of `f(n, m)`. If one of `res1` and `res2` are of +the form `Error(e)`, return false If both `res1` and `res2` are of the form +`Error(e)`, return true + +## Examples + +```rescript +let good1 = Ok(42) + +let good2 = Ok(32) + +let bad1 = Error("invalid") + +let bad2 = Error("really invalid") + +let mod10equal = (a, b) => mod(a, 10) === mod(b, 10) + +Result.equal(good1, good2, mod10equal) == true + +Result.equal(good1, bad1, mod10equal) == false + +Result.equal(bad2, good2, mod10equal) == false + +Result.equal(bad1, bad2, mod10equal) == true +``` +*/ +let equal: (result<'a, 'c>, result<'b, 'd>, ('a, 'b) => bool) => bool + +/** +`compare(res1, res2, f)`: Compare two `Result` variables with respect to a +comparison function. The comparison function returns -1. if the first variable +is "less than" the second, 0. if the two variables are equal, and 1. if the first +is "greater than" the second. + +If `res1` and `res2` are of the form `Ok(n)` and `Ok(m)`, return the result of +`f(n, m)`. If `res1` is of the form `Error(e)` and `res2` of the form `Ok(n)`, +return -1. (nothing is less than something) If `res1` is of the form `Ok(n)` and +`res2` of the form `Error(e)`, return 1. (something is greater than nothing) If +both `res1` and `res2` are of the form `Error(e)`, return 0. (equal) + +## Examples + +```rescript +let good1 = Ok(59) + +let good2 = Ok(37) + +let bad1 = Error("invalid") + +let bad2 = Error("really invalid") + +let mod10cmp = (a, b) => Int.compare(mod(a, 10), mod(b, 10)) + +Result.compare(Ok(39), Ok(57), mod10cmp) == 1. + +Result.compare(Ok(57), Ok(39), mod10cmp) == (-1.) + +Result.compare(Ok(39), Error("y"), mod10cmp) == 1. + +Result.compare(Error("x"), Ok(57), mod10cmp) == (-1.) + +Result.compare(Error("x"), Error("y"), mod10cmp) == 0. +``` +*/ +let compare: (result<'a, 'c>, result<'b, 'd>, ('a, 'b) => Ordering.t) => Ordering.t + +/** +`forEach(res, f)` runs the provided function `f` on the `Ok` value. If `res` is `Error`, nothing happens. + +## Examples + +```rescript +Result.forEach(Ok(3), Console.log) // Logs "3", returns () +Result.forEach(Error("x"), Console.log) // Does nothing, returns () +``` +*/ +let forEach: (result<'a, 'b>, 'a => unit) => unit + +/** +`mapError(r, f)` generates a new `result` by applying the function `f` to the `Error` value. If the source is `Ok`, return it as-is. + +## Examples + +```rescript +let format = n => `Error code: ${n->Int.toString}` +Result.mapError(Error(14), format) // Error("Error code: 14") +Result.mapError(Ok("abc"), format) // Ok("abc") +``` +*/ +let mapError: (result<'a, 'b>, 'b => 'c) => result<'a, 'c> diff --git a/jscomp/stdlib-406/Type.res b/jscomp/stdlib-406/Type.res new file mode 100644 index 0000000000..d29bb28c78 --- /dev/null +++ b/jscomp/stdlib-406/Type.res @@ -0,0 +1,45 @@ +type t = [#undefined | #object | #boolean | #number | #bigint | #string | #symbol | #function] + +external typeof: 'a => t = "#typeof" + +module Classify = { + type function = Js.Types.function_val + type object = Js.Types.obj_val + + type t = + | Bool(bool) + | Null + | Undefined + | String(string) + | Number(float) + | Object(object) + | Function(function) + | Symbol(Symbol.t) + | BigInt(bigint) + + @val external _internalClass: 'a => string = "Object.prototype.toString.call" + external _asBool: 'a => bool = "%identity" + external _asString: 'a => string = "%identity" + external _asFloat: 'a => float = "%identity" + external _asObject: 'a => object = "%identity" + external _asFunction: 'a => function = "%identity" + external _asSymbol: 'a => Symbol.t = "%identity" + external _asBigInt: 'a => bigint = "%identity" + + let classify = value => { + switch _internalClass(value) { + | "[object Boolean]" => Bool(_asBool(value)) + | "[object Null]" => Null + | "[object Undefined]" => Undefined + | "[object String]" => String(_asString(value)) + | "[object Number]" => Number(_asFloat(value)) + | "[object Function]" + | "[object GeneratorFunction]" + | "[object AsyncFunction]" => + Function(_asFunction(value)) + | "[object Symbol]" => Symbol(_asSymbol(value)) + | "[object BigInt]" => BigInt(_asBigInt(value)) + | _ => Object(_asObject(value)) + } + } +} diff --git a/jscomp/stdlib-406/Type.resi b/jscomp/stdlib-406/Type.resi new file mode 100644 index 0000000000..ee6519b653 --- /dev/null +++ b/jscomp/stdlib-406/Type.resi @@ -0,0 +1,77 @@ +/*** +Utilities for classifying the type of JavaScript values at runtime. +*/ + +/** +The possible types of JavaScript values. +*/ +type t = [#undefined | #object | #boolean | #number | #bigint | #string | #symbol | #function] + +/** +`typeof(someValue)` + +Returns the underlying JavaScript type of any runtime value. + +See [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) on MDN. + +## Examples +```rescript +Console.log(Type.typeof("Hello")) // Logs "string" to the console. + +let someVariable = true + +switch someVariable->Type.typeof { +| #boolean => Console.log("This is a bool, yay!") +| _ => Console.log("Oh, not a bool sadly...") +} +``` +*/ +external typeof: 'a => t = "#typeof" + +module Classify: { + /*** + Classifies JavaScript runtime values. + */ + + /** + An abstract type representing a JavaScript function. + + See [`function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) on MDN. + */ + type function + + /** + An abstract type representing a JavaScript object. + + See [`object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) on MDN. + */ + type object + + /** + The type representing a classified JavaScript value. + */ + type t = + | Bool(bool) + | Null + | Undefined + | String(string) + | Number(float) + | Object(object) + | Function(function) + | Symbol(Symbol.t) + | BigInt(bigint) + + /** +`classify(anyValue)` +Classifies a JavaScript value. + +## Examples +```rescript +switch %raw(`null`)->Type.Classify.classify { +| Null => Console.log("Yup, that's null.") +| _ => Console.log("This doesn't actually appear to be null...") +} +``` +*/ + let classify: 'a => t +} diff --git a/jscomp/stdlib-406/WeakMap.res b/jscomp/stdlib-406/WeakMap.res new file mode 100644 index 0000000000..4bc91810da --- /dev/null +++ b/jscomp/stdlib-406/WeakMap.res @@ -0,0 +1,8 @@ +type t<'k, 'v> = Js.WeakMap.t<'k, 'v> + +@new external make: unit => t<'k, 'v> = "WeakMap" + +@send external get: (t<'k, 'v>, 'k) => option<'v> = "get" +@send external has: (t<'k, 'v>, 'k) => bool = "has" +@send external set: (t<'k, 'v>, 'k, 'v) => t<'k, 'v> = "set" +@send external delete: (t<'k, 'v>, 'k) => bool = "delete" diff --git a/jscomp/stdlib-406/WeakSet.res b/jscomp/stdlib-406/WeakSet.res new file mode 100644 index 0000000000..851329c80d --- /dev/null +++ b/jscomp/stdlib-406/WeakSet.res @@ -0,0 +1,7 @@ +type t<'a> = Js.WeakSet.t<'a> + +@new external make: unit => t<'a> = "WeakSet" + +@send external add: (t<'a>, 'a) => t<'a> = "add" +@send external delete: (t<'a>, 'a) => bool = "delete" +@send external has: (t<'a>, 'a) => bool = "has" diff --git a/jscomp/stdlib-406/arg.res b/jscomp/stdlib-406/arg.res deleted file mode 100644 index 7dadf08940..0000000000 --- a/jscomp/stdlib-406/arg.res +++ /dev/null @@ -1,427 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Damien Doligez, projet Para, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -type key = string -type doc = string -type usage_msg = string -type anon_fun = string => unit - -type rec spec = - | Unit(unit => unit) /* Call the function with unit argument */ - | Bool(bool => unit) /* Call the function with a bool argument */ - | Set(ref) /* Set the reference to true */ - | Clear(ref) /* Set the reference to false */ - | String(string => unit) /* Call the function with a string argument */ - | Set_string(ref) /* Set the reference to the string argument */ - | Int(int => unit) /* Call the function with an int argument */ - | Set_int(ref) /* Set the reference to the int argument */ - | Float(float => unit) /* Call the function with a float argument */ - | Set_float(ref) /* Set the reference to the float argument */ - | Tuple(list) /* Take several arguments according to the - spec list */ - - | Symbol(list, string => unit) - /* Take one of the symbols as argument and - call the function with the symbol. */ - | Rest(string => unit) /* Stop interpreting keywords and call the - function with each remaining argument */ - - | Expand( - string => array, - ) /* If the remaining arguments to process - are of the form - [["-foo"; "arg"] @ rest] where "foo" is - registered as [Expand f], then the - arguments [f "arg" @ rest] are - processed. Only allowed in - [parse_and_expand_argv_dynamic]. */ - -exception Bad(string) -exception Help(string) - -type error = - | Unknown(string) - | Wrong(string, string, string) /* option, actual, expected */ - | Missing(string) - | Message(string) - -exception Stop(error) /* used internally */ - -let rec assoc3 = (x, l) => - switch l { - | list{} => raise(Not_found) - | list{(y1, y2, _), ..._} if y1 == x => y2 - | list{_, ...t} => assoc3(x, t) - } - -let split = s => { - let i = String.index(s, '=') - let len = String.length(s) - (String.sub(s, 0, i), String.sub(s, i + 1, len - (i + 1))) -} - -let make_symlist = (prefix, sep, suffix, l) => - switch l { - | list{} => "" - | list{h, ...t} => List.fold_left((x, y) => x ++ (sep ++ y), prefix ++ h, t) ++ suffix - } - -let print_spec = (buf, (key, spec, doc)) => - if String.length(doc) > 0 { - switch spec { - | Symbol(l, _) => - let sym = make_symlist("{", "|", "}", l) - Buffer.add_string(buf, ` ${key} ${sym}${doc}\n`) - | _ => Buffer.add_string(buf, ` ${key} ${doc}\n`) - } - } - -let help_action = () => raise(Stop(Unknown("-help"))) - -let add_help = speclist => { - let add1 = try { - ignore(assoc3("-help", speclist)) - list{} - } catch { - | Not_found => list{("-help", Unit(help_action), " Display this list of options")} - } - and add2 = try { - ignore(assoc3("--help", speclist)) - list{} - } catch { - | Not_found => list{("--help", Unit(help_action), " Display this list of options")} - } - - \"@"(speclist, \"@"(add1, add2)) -} - -let usage_b = (buf, speclist, errmsg) => { - Buffer.add_string(buf, `${errmsg}\n`) - List.iter(print_spec(buf), add_help(speclist)) -} - -let usage_string = (speclist, errmsg) => { - let b = Buffer.create(200) - usage_b(b, speclist, errmsg) - Buffer.contents(b) -} - -let usage = (speclist, errmsg) => Js.log(usage_string(speclist, errmsg)) - -let current = ref(0) - -let bool_of_string_opt = x => - try Some(bool_of_string(x)) catch { - | Invalid_argument(_) => None - } - -let int_of_string_opt = x => - try Some(int_of_string(x)) catch { - | Failure(_) => None - } - -let float_of_string_opt = x => - try Some(float_of_string(x)) catch { - | Failure(_) => None - } - -let parse_and_expand_argv_dynamic_aux = ( - allow_expand, - current, - argv, - speclist, - anonfun, - errmsg, -) => { - let initpos = current.contents - let convert_error = error => { - /* convert an internal error to a Bad/Help exception - *or* add the program name as a prefix and the usage message as a suffix - to an user-raised Bad exception. - */ - let b = Buffer.create(200) - let progname = if initpos < Array.length(argv.contents) { - argv.contents[initpos] - } else { - "(?)" - } - switch error { - | Unknown("-help") => () - | Unknown("--help") => () - | Unknown(s) => Buffer.add_string(b, `${progname}: unknown option '${s}'.\n`) - | Missing(s) => Buffer.add_string(b, `${progname}: option '${s}' needs an argument.\n`) - | Wrong(opt, arg, expected) => - Buffer.add_string( - b, - `${progname}: wrong argument '${arg}'; option '${opt}' expects ${expected}.\n`, - ) - | Message(s) => - /* user error message */ - Buffer.add_string(b, `${progname}: ${s}.\n`) - } - usage_b(b, speclist.contents, errmsg) - if error == Unknown("-help") || error == Unknown("--help") { - Help(Buffer.contents(b)) - } else { - Bad(Buffer.contents(b)) - } - } - - incr(current) - while current.contents < Array.length(argv.contents) { - try { - let s = argv.contents[current.contents] - if String.length(s) >= 1 && String.get(s, 0) == '-' { - let (action, follow) = try (assoc3(s, speclist.contents), None) catch { - | Not_found => - try { - let (keyword, arg) = split(s) - (assoc3(keyword, speclist.contents), Some(arg)) - } catch { - | Not_found => raise(Stop(Unknown(s))) - } - } - - let no_arg = () => - switch follow { - | None => () - | Some(arg) => raise(Stop(Wrong(s, arg, "no argument"))) - } - let get_arg = () => - switch follow { - | None => - if current.contents + 1 < Array.length(argv.contents) { - argv.contents[current.contents + 1] - } else { - raise(Stop(Missing(s))) - } - | Some(arg) => arg - } - - let consume_arg = () => - switch follow { - | None => incr(current) - | Some(_) => () - } - - let rec treat_action = f => - switch f { - | Unit(f) => f() - | Bool(f) => - let arg = get_arg() - switch bool_of_string_opt(arg) { - | None => raise(Stop(Wrong(s, arg, "a boolean"))) - | Some(s) => f(s) - } - consume_arg() - | Set(r) => - no_arg() - r := true - | Clear(r) => - no_arg() - r := false - | String(f) => - let arg = get_arg() - f(arg) - consume_arg() - | Symbol(symb, f) => - let arg = get_arg() - if List.mem(arg, symb) { - f(arg) - consume_arg() - } else { - raise(Stop(Wrong(s, arg, "one of: " ++ make_symlist("", " ", "", symb)))) - } - | Set_string(r) => - r := get_arg() - consume_arg() - | Int(f) => - let arg = get_arg() - switch int_of_string_opt(arg) { - | None => raise(Stop(Wrong(s, arg, "an integer"))) - | Some(x) => f(x) - } - consume_arg() - | Set_int(r) => - let arg = get_arg() - switch int_of_string_opt(arg) { - | None => raise(Stop(Wrong(s, arg, "an integer"))) - | Some(x) => r := x - } - consume_arg() - | Float(f) => - let arg = get_arg() - switch float_of_string_opt(arg) { - | None => raise(Stop(Wrong(s, arg, "a float"))) - | Some(x) => f(x) - } - consume_arg() - | Set_float(r) => - let arg = get_arg() - switch float_of_string_opt(arg) { - | None => raise(Stop(Wrong(s, arg, "a float"))) - | Some(x) => r := x - } - consume_arg() - | Tuple(specs) => List.iter(treat_action, specs) - | Rest(f) => - while current.contents < Array.length(argv.contents) - 1 { - f(argv.contents[current.contents + 1]) - consume_arg() - } - | Expand(f) => - if !allow_expand { - raise( - Invalid_argument( - "Arg.Expand is is only allowed with Arg.parse_and_expand_argv_dynamic", - ), - ) - } - let arg = get_arg() - let newarg = f(arg) - consume_arg() - let before = Array.sub(argv.contents, 0, current.contents + 1) - and after = Array.sub( - argv.contents, - current.contents + 1, - Array.length(argv.contents) - current.contents - 1, - ) - argv := Array.concat(list{before, newarg, after}) - } - - treat_action(action) - } else { - anonfun(s) - } - } catch { - | Bad(m) => raise(convert_error(Message(m))) - | Stop(e) => raise(convert_error(e)) - } - incr(current) - } -} - -let parse_and_expand_argv_dynamic = (current, argv, speclist, anonfun, errmsg) => - parse_and_expand_argv_dynamic_aux(true, current, argv, speclist, anonfun, errmsg) - -let parse_argv_dynamic = (~current=current, argv, speclist, anonfun, errmsg) => - parse_and_expand_argv_dynamic_aux(false, current, ref(argv), speclist, anonfun, errmsg) - -let parse_argv = (~current=current, argv, speclist, anonfun, errmsg) => - parse_argv_dynamic(~current, argv, ref(speclist), anonfun, errmsg) - -let parse = (l, f, msg) => - try parse_argv(Sys.argv, l, f, msg) catch { - | Bad(msg) => - Js.log(msg) - exit(2) - | Help(msg) => - Js.log(msg) - exit(0) - } - -let parse_dynamic = (l, f, msg) => - try parse_argv_dynamic(Sys.argv, l, f, msg) catch { - | Bad(msg) => - Js.log(msg) - exit(2) - | Help(msg) => - Js.log(msg) - exit(0) - } - -let parse_expand = (l, f, msg) => - try { - let argv = ref(Sys.argv) - let spec = ref(l) - let current = ref(current.contents) - parse_and_expand_argv_dynamic(current, argv, spec, f, msg) - } catch { - | Bad(msg) => - Js.log(msg) - exit(2) - | Help(msg) => - Js.log(msg) - exit(0) - } - -let second_word = s => { - let len = String.length(s) - let rec loop = n => - if n >= len { - len - } else if String.get(s, n) == ' ' { - loop(n + 1) - } else { - n - } - - switch String.index(s, '\t') { - | n => loop(n + 1) - | exception Not_found => - switch String.index(s, ' ') { - | n => loop(n + 1) - | exception Not_found => len - } - } -} - -let max_arg_len = (cur, (kwd, spec, doc)) => - switch spec { - | Symbol(_) => max(cur, String.length(kwd)) - | _ => max(cur, String.length(kwd) + second_word(doc)) - } - -let replace_leading_tab = s => { - let seen = ref(false) - String.map(c => - switch c { - | '\t' if !seen.contents => - seen := true - ' ' - | c => c - } - , s) -} - -let add_padding = (len, ksd) => - switch ksd { - | (_, _, "") => /* Do not pad undocumented options, so that they still don't show up when - * run through [usage] or [parse]. */ - ksd - | (kwd, Symbol(_) as spec, msg) => - let cutcol = second_word(msg) - let spaces = String.make(max(0, len - cutcol) + 3, ' ') - (kwd, spec, "\n" ++ (spaces ++ replace_leading_tab(msg))) - | (kwd, spec, msg) => - let cutcol = second_word(msg) - let kwd_len = String.length(kwd) - let diff = len - kwd_len - cutcol - if diff <= 0 { - (kwd, spec, replace_leading_tab(msg)) - } else { - let spaces = String.make(diff, ' ') - let prefix = String.sub(replace_leading_tab(msg), 0, cutcol) - let suffix = String.sub(msg, cutcol, String.length(msg) - cutcol) - (kwd, spec, prefix ++ (spaces ++ suffix)) - } - } - -let align = (~limit=max_int, speclist) => { - let completed = add_help(speclist) - let len = List.fold_left(max_arg_len, 0, completed) - let len = min(len, limit) - List.map(add_padding(len), completed) -} diff --git a/jscomp/stdlib-406/arg.resi b/jscomp/stdlib-406/arg.resi deleted file mode 100644 index e5b69162a1..0000000000 --- a/jscomp/stdlib-406/arg.resi +++ /dev/null @@ -1,186 +0,0 @@ -/*** Parsing of command line arguments. - - This module provides a general mechanism for extracting options and - arguments from the command line to the program. - - Syntax of command lines: - A keyword is a character string starting with a [-]. - An option is a keyword alone or followed by an argument. - The types of keywords are: [Unit], [Bool], [Set], [Clear], - [String], [Set_string], [Int], [Set_int], [Float], [Set_float], - [Tuple], [Symbol], and [Rest]. - [Unit], [Set] and [Clear] keywords take no argument. A [Rest] - keyword takes the remaining of the command line as arguments. - Every other keyword takes the following word on the command line - as argument. For compatibility with GNU getopt_long, [keyword=arg] - is also allowed. - Arguments not preceded by a keyword are called anonymous arguments. - - Examples ([cmd] is assumed to be the command name): -- [cmd -flag ](a unit option) -- [cmd -int 1 ](an int option with argument [1]) -- [cmd -string foobar ](a string option with argument ["foobar"]) -- [cmd -float 12.34 ](a float option with argument [12.34]) -- [cmd a b c ](three anonymous arguments: ["a"], ["b"], and ["c"]) -- [cmd a b -- c d ](two anonymous arguments and a rest option with - two arguments) -*/ - -/** The concrete type describing the behavior associated - with a keyword. */ -type rec spec = - | /** Call the function with unit argument */ Unit(unit => unit) - | /** Call the function with a bool argument */ Bool(bool => unit) - | /** Set the reference to true */ Set(ref) - | /** Set the reference to false */ Clear(ref) - | /** Call the function with a string argument */ String(string => unit) - | /** Set the reference to the string argument */ Set_string(ref) - | /** Call the function with an int argument */ Int(int => unit) - | /** Set the reference to the int argument */ Set_int(ref) - | /** Call the function with a float argument */ Float(float => unit) - | /** Set the reference to the float argument */ Set_float(ref) - | /** Take several arguments according to the - spec list */ - Tuple(list) - - | /** Take one of the symbols as argument and - call the function with the symbol */ - Symbol(list, string => unit) - - | /** Stop interpreting keywords and call the - function with each remaining argument */ - Rest(string => unit) - - | /** If the remaining arguments to process - are of the form - [["-foo"; "arg"] @ rest] where "foo" is - registered as [Expand f], then the - arguments [f "arg" @ rest] are - processed. Only allowed in - [parse_and_expand_argv_dynamic]. */ - Expand(string => array) - -type key = string -type doc = string -type usage_msg = string -type anon_fun = string => unit - -/** [Arg.parse speclist anon_fun usage_msg] parses the command line. - [speclist] is a list of triples [(key, spec, doc)]. - [key] is the option keyword, it must start with a ['-'] character. - [spec] gives the option type and the function to call when this option - is found on the command line. - [doc] is a one-line description of this option. - [anon_fun] is called on anonymous arguments. - The functions in [spec] and [anon_fun] are called in the same order - as their arguments appear on the command line. - - If an error occurs, [Arg.parse] exits the program, after printing - to standard error an error message as follows: -- The reason for the error: unknown option, invalid or missing argument, etc. -- [usage_msg] -- The list of options, each followed by the corresponding [doc] string. - Beware: options that have an empty [doc] string will not be included in the - list. - - For the user to be able to specify anonymous arguments starting with a - [-], include for example [("-", String anon_fun, doc)] in [speclist]. - - By default, [parse] recognizes two unit options, [-help] and [--help], - which will print to standard output [usage_msg] and the list of - options, and exit the program. You can override this behaviour - by specifying your own [-help] and [--help] options in [speclist]. -*/ -let parse: (list<(key, spec, doc)>, anon_fun, usage_msg) => unit - -/** Same as {!Arg.parse}, except that the [speclist] argument is a reference - and may be updated during the parsing. A typical use for this feature - is to parse command lines of the form: -- command subcommand [options] - where the list of options depends on the value of the subcommand argument. - @since 4.01.0 -*/ -let parse_dynamic: (ref>, anon_fun, usage_msg) => unit - -/** [Arg.parse_argv ~current args speclist anon_fun usage_msg] parses - the array [args] as if it were the command line. It uses and updates - the value of [~current] (if given), or {!Arg.current}. You must set - it before calling [parse_argv]. The initial value of [current] - is the index of the program name (argument 0) in the array. - If an error occurs, [Arg.parse_argv] raises {!Arg.Bad} with - the error message as argument. If option [-help] or [--help] is - given, [Arg.parse_argv] raises {!Arg.Help} with the help message - as argument. -*/ -let parse_argv: ( - ~current: ref=?, - array, - list<(key, spec, doc)>, - anon_fun, - usage_msg, -) => unit - -/** Same as {!Arg.parse_argv}, except that the [speclist] argument is a - reference and may be updated during the parsing. - See {!Arg.parse_dynamic}. - @since 4.01.0 -*/ -let parse_argv_dynamic: ( - ~current: ref=?, - array, - ref>, - anon_fun, - string, -) => unit - -/** Same as {!Arg.parse_argv_dynamic}, except that the [argv] argument is a - reference and may be updated during the parsing of [Expand] arguments. - See {!Arg.parse_argv_dynamic}. - @since 4.05.0 -*/ -let parse_and_expand_argv_dynamic: ( - ref, - ref>, - ref>, - anon_fun, - string, -) => unit - -/** Same as {!Arg.parse}, except that the [Expand] arguments are allowed and - the {!current} reference is not updated. - @since 4.05.0 -*/ -let parse_expand: (list<(key, spec, doc)>, anon_fun, usage_msg) => unit - -/** Raised by [Arg.parse_argv] when the user asks for help. */ exception Help(string) - -/** Functions in [spec] or [anon_fun] can raise [Arg.Bad] with an error - message to reject invalid arguments. - [Arg.Bad] is also raised by {!Arg.parse_argv} in case of an error. */ -exception Bad(string) - -/** [Arg.usage speclist usage_msg] prints to standard error - an error message that includes the list of valid options. This is - the same message that {!Arg.parse} prints in case of error. - [speclist] and [usage_msg] are the same as for {!Arg.parse}. */ -let usage: (list<(key, spec, doc)>, usage_msg) => unit - -/** Returns the message that would have been printed by {!Arg.usage}, - if provided with the same parameters. */ -let usage_string: (list<(key, spec, doc)>, usage_msg) => string - -/** Align the documentation strings by inserting spaces at the first alignment - separator (tab or, if tab is not found, space), according to the length of - the keyword. Use a alignment separator as the first character in a doc - string if you want to align the whole string. The doc strings corresponding - to [Symbol] arguments are aligned on the next line. - @param limit options with keyword and message longer than [limit] will not - be used to compute the alignment. */ -let align: (~limit: int=?, list<(key, spec, doc)>) => list<(key, spec, doc)> - -/** Position (in {!Sys.argv}) of the argument being processed. You can - change this value, e.g. to force {!Arg.parse} to skip some arguments. - {!Arg.parse} uses the initial value of {!Arg.current} as the index of - argument 0 (the program name) and starts parsing arguments - at the next element. */ -let current: ref diff --git a/jscomp/stdlib-406/array.res b/jscomp/stdlib-406/array.res index 486217b151..0a2baeba6b 100644 --- a/jscomp/stdlib-406/array.res +++ b/jscomp/stdlib-406/array.res @@ -1,410 +1,257 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Array operations */ - -external length: array<'a> => int = "%array_length" -external get: (array<'a>, int) => 'a = "%array_safe_get" -external set: (array<'a>, int, 'a) => unit = "%array_safe_set" -external unsafe_get: (array<'a>, int) => 'a = "%array_unsafe_get" -external unsafe_set: (array<'a>, int, 'a) => unit = "%array_unsafe_set" -external make: (int, 'a) => array<'a> = "?make_vect" -external create: (int, 'a) => array<'a> = "?make_vect" -external unsafe_sub: (array<'a>, int, int) => array<'a> = "?array_sub" - -@send external append_prim: (array<'a>, array<'a>) => array<'a> = "concat" - -external concat: list> => array<'a> = "?array_concat" -external unsafe_blit: (array<'a>, int, array<'a>, int, int) => unit = "?array_blit" -external create_float: int => array = "?make_float_vect" -let make_float = create_float - -module Floatarray = { - external create: int => floatarray = "?floatarray_create" - external length: floatarray => int = "%floatarray_length" - external get: (floatarray, int) => float = "%floatarray_safe_get" - external set: (floatarray, int, float) => unit = "%floatarray_safe_set" - external unsafe_get: (floatarray, int) => float = "%floatarray_unsafe_get" - external unsafe_set: (floatarray, int, float) => unit = "%floatarray_unsafe_set" -} +@new external makeUninitializedUnsafe: int => array<'a> = "Array" +@set external truncateToLengthUnsafe: (array<'a>, int) => unit = "length" +external getUnsafe: (array<'a>, int) => 'a = "%array_unsafe_get" +external setUnsafe: (array<'a>, int, 'a) => unit = "%array_unsafe_set" -let init = (l, f) => - if l == 0 { - [] - } else if l < 0 { - invalid_arg("Array.init") - } else { - /* See #6575. We could also check for maximum array size, but this depends - on whether we create a float array or a regular one... */ +@val external fromIterator: Iterator.t<'a> => array<'a> = "Array.from" +@val external fromArrayLike: Js.Array2.array_like<'a> => array<'a> = "Array.from" +@val +external fromArrayLikeWithMap: (Js.Array2.array_like<'a>, 'a => 'b) => array<'b> = "Array.from" - let res = create(l, f(0)) - for i in 1 to pred(l) { - unsafe_set(res, i, f(i)) - } - res - } +@send external fillAll: (array<'a>, 'a) => unit = "fill" -let make_matrix = (sx, sy, init) => { - let res = create(sx, []) - for x in 0 to pred(sx) { - unsafe_set(res, x, create(sy, init)) - } - res -} +@send external fillToEnd: (array<'a>, 'a, ~start: int) => unit = "fill" -let create_matrix = make_matrix +@send external fill: (array<'a>, 'a, ~start: int, ~end: int) => unit = "fill" -let copy = a => { - let l = length(a) - if l == 0 { +let make = (~length, x) => + if length <= 0 { [] } else { - unsafe_sub(a, 0, l) + let arr = makeUninitializedUnsafe(length) + arr->fillAll(x) + arr } -} -let append = (a1, a2) => { - let l1 = length(a1) - if l1 == 0 { - copy(a2) - } else if length(a2) == 0 { - unsafe_sub(a1, 0, l1) - } else { - append_prim(a1, a2) - } -} - -let sub = (a, ofs, len) => - if ofs < 0 || (len < 0 || ofs > length(a) - len) { - invalid_arg("Array.sub") - } else { - unsafe_sub(a, ofs, len) - } - -let fill = (a, ofs, len, v) => - if ofs < 0 || (len < 0 || ofs > length(a) - len) { - invalid_arg("Array.fill") +let fromInitializer = (~length, f) => + if length <= 0 { + [] } else { - for i in ofs to ofs + len - 1 { - unsafe_set(a, i, v) + let arr = makeUninitializedUnsafe(length) + for i in 0 to length - 1 { + arr->setUnsafe(i, f(i)) } + arr } -let blit = (a1, ofs1, a2, ofs2, len) => - if len < 0 || (ofs1 < 0 || (ofs1 > length(a1) - len || (ofs2 < 0 || ofs2 > length(a2) - len))) { - invalid_arg("Array.blit") - } else { - unsafe_blit(a1, ofs1, a2, ofs2, len) - } +@val external isArray: 'a => bool = "Array.isArray" -let iter = (f, a) => - for i in 0 to length(a) - 1 { - f(unsafe_get(a, i)) - } +@get external length: array<'a> => int = "length" -let iter2 = (f, a, b) => - if length(a) != length(b) { - invalid_arg("Array.iter2: arrays must have the same length") +let rec equalFromIndex = (a, b, i, eq, len) => + if i === len { + true + } else if eq(a->getUnsafe(i), b->getUnsafe(i)) { + equalFromIndex(a, b, i + 1, eq, len) } else { - for i in 0 to length(a) - 1 { - f(unsafe_get(a, i), unsafe_get(b, i)) - } + false } -let map = (f, a) => { - let l = length(a) - if l == 0 { - [] +let equal = (a, b, eq) => { + let len = a->length + if len === b->length { + equalFromIndex(a, b, 0, eq, len) } else { - let r = create(l, f(unsafe_get(a, 0))) - for i in 1 to l - 1 { - unsafe_set(r, i, f(unsafe_get(a, i))) - } - r + false } } -let map2 = (f, a, b) => { - let la = length(a) - let lb = length(b) - if la != lb { - invalid_arg("Array.map2: arrays must have the same length") - } else if la == 0 { - [] +let rec compareFromIndex = (a, b, i, cmp, len) => + if i === len { + Ordering.equal } else { - let r = create(la, f(unsafe_get(a, 0), unsafe_get(b, 0))) - for i in 1 to la - 1 { - unsafe_set(r, i, f(unsafe_get(a, i), unsafe_get(b, i))) + let c = cmp(a->getUnsafe(i), b->getUnsafe(i)) + if c == Ordering.equal { + compareFromIndex(a, b, i + 1, cmp, len) + } else { + c } - r } + +let compare = (a, b, cmp) => { + let lenA = a->length + let lenB = b->length + lenA < lenB + ? Ordering.less + : lenA > lenB + ? Ordering.greater + : compareFromIndex(a, b, 0, cmp, lenA) } -let iteri = (f, a) => - for i in 0 to length(a) - 1 { - f(i, unsafe_get(a, i)) - } +@send external copyAllWithin: (array<'a>, ~target: int) => array<'a> = "copyWithin" -let mapi = (f, a) => { - let l = length(a) - if l == 0 { - [] - } else { - let r = create(l, f(0, unsafe_get(a, 0))) - for i in 1 to l - 1 { - unsafe_set(r, i, f(i, unsafe_get(a, i))) - } - r - } -} +@send +external copyWithinToEnd: (array<'a>, ~target: int, ~start: int) => array<'a> = "copyWithin" -let to_list = a => { - let rec tolist = (i, res) => - if i < 0 { - res - } else { - tolist(i - 1, list{unsafe_get(a, i), ...res}) - } - tolist(length(a) - 1, list{}) -} +@send +external copyWithin: (array<'a>, ~target: int, ~start: int, ~end: int) => array<'a> = "copyWithin" -/* Cannot use List.length here because the List module depends on Array. */ -let rec list_length = (accu, param) => - switch param { - | list{} => accu - | list{_, ...t} => list_length(succ(accu), t) - } +@send external pop: array<'a> => option<'a> = "pop" -let of_list = param => - switch param { - | list{} => [] - | list{hd, ...tl} as l => - let a = create(list_length(0, l), hd) - let rec fill = (i, param) => - switch param { - | list{} => a - | list{hd, ...tl} => - unsafe_set(a, i, hd) - fill(i + 1, tl) - } - fill(1, tl) - } +@send external push: (array<'a>, 'a) => unit = "push" -let fold_left = (f, x, a) => { - let r = ref(x) - for i in 0 to length(a) - 1 { - r := f(r.contents, unsafe_get(a, i)) - } - r.contents -} +@variadic @send external pushMany: (array<'a>, array<'a>) => unit = "push" -let fold_right = (f, a, x) => { - let r = ref(x) - for i in length(a) - 1 downto 0 { - r := f(unsafe_get(a, i), r.contents) - } - r.contents -} +@send external reverse: array<'a> => unit = "reverse" +@send external toReversed: array<'a> => array<'a> = "toReversed" -let exists = (p, a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if p(unsafe_get(a, i)) { - true - } else { - loop(succ(i)) - } - loop(0) -} +@send external shift: array<'a> => option<'a> = "shift" -let for_all = (p, a) => { - let n = length(a) - let rec loop = i => - if i == n { - true - } else if p(unsafe_get(a, i)) { - loop(succ(i)) - } else { - false - } - loop(0) -} +@variadic @send +external splice: (array<'a>, ~start: int, ~remove: int, ~insert: array<'a>) => unit = "splice" +@variadic @send +external toSpliced: (array<'a>, ~start: int, ~remove: int, ~insert: array<'a>) => array<'a> = + "toSpliced" -let mem = (x, a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if compare(unsafe_get(a, i), x) == 0 { - true - } else { - loop(succ(i)) - } - loop(0) -} +@send external with: (array<'a>, int, 'a) => array<'a> = "with" -let memq = (x, a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if x === unsafe_get(a, i) { - true - } else { - loop(succ(i)) - } - loop(0) -} +@send external unshift: (array<'a>, 'a) => unit = "unshift" -exception Bottom(int) -let sort = (cmp, a) => { - let maxson = (l, i) => { - let i31 = i + i + i + 1 - let x = ref(i31) - if i31 + 2 < l { - if cmp(get(a, i31), get(a, i31 + 1)) < 0 { - x := i31 + 1 - } - if cmp(get(a, x.contents), get(a, i31 + 2)) < 0 { - x := i31 + 2 - } - x.contents - } else if i31 + 1 < l && cmp(get(a, i31), get(a, i31 + 1)) < 0 { - i31 + 1 - } else if i31 < l { - i31 - } else { - raise(Bottom(i)) - } +@variadic @send external unshiftMany: (array<'a>, array<'a>) => unit = "unshift" + +@send external concat: (array<'a>, array<'a>) => array<'a> = "concat" +@variadic @send external concatMany: (array<'a>, array>) => array<'a> = "concat" + +@send external flat: array> => array<'a> = "flat" + +@send external includes: (array<'a>, 'a) => bool = "includes" + +@send external indexOf: (array<'a>, 'a) => int = "indexOf" +let indexOfOpt = (arr, item) => + switch arr->indexOf(item) { + | -1 => None + | index => Some(index) } +@send external indexOfFrom: (array<'a>, 'a, int) => int = "indexOf" - let rec trickledown = (l, i, e) => { - let j = maxson(l, i) - if cmp(get(a, j), e) > 0 { - set(a, i, get(a, j)) - trickledown(l, j, e) - } else { - set(a, i, e) - } +@send external join: (array, string) => string = "join" + +@deprecated("Use `join` instead") @send +external joinWith: (array, string) => string = "join" + +@send external joinUnsafe: (array<'a>, string) => string = "join" + +@deprecated("Use `joinUnsafe` instead") @send +external joinWithUnsafe: (array<'a>, string) => string = "join" + +@send external lastIndexOf: (array<'a>, 'a) => int = "lastIndexOf" +let lastIndexOfOpt = (arr, item) => + switch arr->lastIndexOf(item) { + | -1 => None + | index => Some(index) } +@send external lastIndexOfFrom: (array<'a>, 'a, int) => int = "lastIndexOf" - let trickle = (l, i, e) => - try trickledown(l, i, e) catch { - | Bottom(i) => set(a, i, e) - } - let rec bubbledown = (l, i) => { - let j = maxson(l, i) - set(a, i, get(a, j)) - bubbledown(l, j) +@send external slice: (array<'a>, ~start: int, ~end: int) => array<'a> = "slice" +@send external sliceToEnd: (array<'a>, ~start: int) => array<'a> = "slice" +@send external copy: array<'a> => array<'a> = "slice" + +@send external sort: (array<'a>, ('a, 'a) => Ordering.t) => unit = "sort" +@send external toSorted: (array<'a>, ('a, 'a) => Ordering.t) => array<'a> = "toSorted" + +@send external toString: array<'a> => string = "toString" +@send external toLocaleString: array<'a> => string = "toLocaleString" + +@send external every: (array<'a>, 'a => bool) => bool = "every" +@send external everyWithIndex: (array<'a>, ('a, int) => bool) => bool = "every" + +@send external filter: (array<'a>, 'a => bool) => array<'a> = "filter" +@send external filterWithIndex: (array<'a>, ('a, int) => bool) => array<'a> = "filter" + +@send external find: (array<'a>, 'a => bool) => option<'a> = "find" +@send external findWithIndex: (array<'a>, ('a, int) => bool) => option<'a> = "find" + +@send external findIndex: (array<'a>, 'a => bool) => int = "findIndex" +@send external findIndexWithIndex: (array<'a>, ('a, int) => bool) => int = "findIndex" + +@send external forEach: (array<'a>, 'a => unit) => unit = "forEach" +@send external forEachWithIndex: (array<'a>, ('a, int) => unit) => unit = "forEach" + +@send external map: (array<'a>, 'a => 'b) => array<'b> = "map" +@send external mapWithIndex: (array<'a>, ('a, int) => 'b) => array<'b> = "map" + +@send external reduce: (array<'b>, ('a, 'b) => 'a, 'a) => 'a = "reduce" +let reduce = (arr, init, f) => reduce(arr, f, init) +@send external reduceWithIndex: (array<'b>, ('a, 'b, int) => 'a, 'a) => 'a = "reduce" +let reduceWithIndex = (arr, init, f) => reduceWithIndex(arr, f, init) +@send +external reduceRight: (array<'b>, ('a, 'b) => 'a, 'a) => 'a = "reduceRight" +let reduceRight = (arr, init, f) => reduceRight(arr, f, init) +@send +external reduceRightWithIndex: (array<'b>, ('a, 'b, int) => 'a, 'a) => 'a = "reduceRight" +let reduceRightWithIndex = (arr, init, f) => reduceRightWithIndex(arr, f, init) + +@send external some: (array<'a>, 'a => bool) => bool = "some" +@send external someWithIndex: (array<'a>, ('a, int) => bool) => bool = "some" + +@get_index external get: (array<'a>, int) => option<'a> = "" +@set_index external set: (array<'a>, int, 'a) => unit = "" + +@get_index external getSymbol: (array<'a>, Symbol.t) => option<'b> = "" +@get_index external getSymbolUnsafe: (array<'a>, Symbol.t) => 'b = "" +@set_index external setSymbol: (array<'a>, Symbol.t, 'b) => unit = "" + +let findIndexOpt = (array: array<'a>, finder: 'a => bool): option => + switch findIndex(array, finder) { + | -1 => None + | index => Some(index) } - let bubble = (l, i) => - try bubbledown(l, i) catch { - | Bottom(i) => i - } - let rec trickleup = (i, e) => { - let father = (i - 1) / 3 - assert(i != father) - if cmp(get(a, father), e) < 0 { - set(a, i, get(a, father)) - if father > 0 { - trickleup(father, e) - } else { - set(a, 0, e) - } - } else { - set(a, i, e) - } +let swapUnsafe = (xs, i, j) => { + let tmp = getUnsafe(xs, i) + setUnsafe(xs, i, getUnsafe(xs, j)) + setUnsafe(xs, j, tmp) +} + +let shuffle = xs => { + let len = length(xs) + for i in 0 to len - 1 { + swapUnsafe(xs, i, Js.Math.random_int(i, len)) /* [i,len) */ } +} + +let toShuffled = xs => { + let result = copy(xs) + shuffle(result) + result +} +let filterMap = (a, f) => { let l = length(a) - for i in (l + 1) / 3 - 1 downto 0 { - trickle(l, i, get(a, i)) - } - for i in l - 1 downto 2 { - let e = get(a, i) - set(a, i, get(a, 0)) - trickleup(bubble(i, 0), e) - } - if l > 1 { - let e = get(a, 1) - set(a, 1, get(a, 0)) - set(a, 0, e) + let r = makeUninitializedUnsafe(l) + let j = ref(0) + for i in 0 to l - 1 { + let v = getUnsafe(a, i) + switch f(v) { + | None => () + | Some(v) => + setUnsafe(r, j.contents, v) + j.contents = j.contents + 1 + } } + truncateToLengthUnsafe(r, j.contents) + r } -let cutoff = 5 -let stable_sort = (cmp, a) => { - let merge = (src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs) => { - let src1r = src1ofs + src1len and src2r = src2ofs + src2len - let rec loop = (i1, s1, i2, s2, d) => - if cmp(s1, s2) <= 0 { - set(dst, d, s1) - let i1 = i1 + 1 - if i1 < src1r { - loop(i1, get(a, i1), i2, s2, d + 1) - } else { - blit(src2, i2, dst, d + 1, src2r - i2) - } - } else { - set(dst, d, s2) - let i2 = i2 + 1 - if i2 < src2r { - loop(i1, s1, i2, get(src2, i2), d + 1) - } else { - blit(a, i1, dst, d + 1, src1r - i1) - } - } - loop(src1ofs, get(a, src1ofs), src2ofs, get(src2, src2ofs), dstofs) - } +let keepSome = filterMap(_, x => x) - let isortto = (srcofs, dst, dstofs, len) => - for i in 0 to len - 1 { - let e = get(a, srcofs + i) - let j = ref(dstofs + i - 1) - while j.contents >= dstofs && cmp(get(dst, j.contents), e) > 0 { - set(dst, j.contents + 1, get(dst, j.contents)) - decr(j) - } - set(dst, j.contents + 1, e) - } +@send external flatMap: (array<'a>, 'a => array<'b>) => array<'b> = "flatMap" +@send external flatMapWithIndex: (array<'a>, ('a, int) => array<'b>) => array<'b> = "flatMap" - let rec sortto = (srcofs, dst, dstofs, len) => - if len <= cutoff { - isortto(srcofs, dst, dstofs, len) +let findMap = (arr, f) => { + let rec loop = i => + if i == arr->length { + None } else { - let l1 = len / 2 - let l2 = len - l1 - sortto(srcofs + l1, dst, dstofs + l1, l2) - sortto(srcofs, a, srcofs + l2, l1) - merge(srcofs + l2, l1, dst, dstofs + l1, l2, dst, dstofs) + switch f(getUnsafe(arr, i)) { + | None => loop(i + 1) + | Some(_) as r => r + } } - let l = length(a) - if l <= cutoff { - isortto(0, a, 0, l) - } else { - let l1 = l / 2 - let l2 = l - l1 - let t = make(l2, get(a, 0)) - sortto(l1, t, 0, l2) - sortto(0, a, l2, l1) - merge(l2, l1, t, 0, l2, a, 0) - } + loop(0) } -let fast_sort = stable_sort +@send external at: (array<'a>, int) => option<'a> = "at" + +let last = a => a->get(a->length - 1) diff --git a/jscomp/stdlib-406/array.resi b/jscomp/stdlib-406/array.resi index d16f7bb088..7e9590eb73 100644 --- a/jscomp/stdlib-406/array.resi +++ b/jscomp/stdlib-406/array.resi @@ -1,264 +1,1070 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Array operations. */ - -/** Return the length (number of elements) of the given array. */ -external length: array<'a> => int = "%array_length" - -/** [Array.get a n] returns the element number [n] of array [a]. - The first element has number 0. - The last element has number [Array.length a - 1]. - You can also write [a.(n)] instead of [Array.get a n]. - - Raise [Invalid_argument "index out of bounds"] - if [n] is outside the range 0 to [(Array.length a - 1)]. */ -external get: (array<'a>, int) => 'a = "%array_safe_get" - -/** [Array.set a n x] modifies array [a] in place, replacing - element number [n] with [x]. - You can also write [a.(n) <- x] instead of [Array.set a n x]. - - Raise [Invalid_argument "index out of bounds"] - if [n] is outside the range 0 to [Array.length a - 1]. */ -external set: (array<'a>, int, 'a) => unit = "%array_safe_set" - -/** [Array.make n x] returns a fresh array of length [n], - initialized with [x]. - All the elements of this new array are initially - physically equal to [x] (in the sense of the [==] predicate). - Consequently, if [x] is mutable, it is shared among all elements - of the array, and modifying [x] through one of the array entries - will modify all other entries at the same time. - - Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. - If the value of [x] is a floating-point number, then the maximum - size is only [Sys.max_array_length / 2].*/ -external make: (int, 'a) => array<'a> = "?make_vect" - -@deprecated("Use Array.make instead.") -/** @deprecated [Array.create] is an alias for {!Array.make}. */ -external create: (int, 'a) => array<'a> = "?make_vect" - -/** [Array.create_float n] returns a fresh float array of length [n], - with uninitialized data. - @since 4.03 */ -external create_float: int => array = "?make_float_vect" - -@deprecated("Use Array.create_float instead.") -/** @deprecated [Array.make_float] is an alias for {!Array.create_float}. */ -let make_float: int => array - -/** [Array.init n f] returns a fresh array of length [n], - with element number [i] initialized to the result of [f i]. - In other terms, [Array.init n f] tabulates the results of [f] - applied to the integers [0] to [n-1]. - - Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. - If the return type of [f] is [float], then the maximum - size is only [Sys.max_array_length / 2].*/ -let init: (int, int => 'a) => array<'a> - -/** [Array.make_matrix dimx dimy e] returns a two-dimensional array - (an array of arrays) with first dimension [dimx] and - second dimension [dimy]. All the elements of this new matrix - are initially physically equal to [e]. - The element ([x,y]) of a matrix [m] is accessed - with the notation [m.(x).(y)]. - - Raise [Invalid_argument] if [dimx] or [dimy] is negative or - greater than {!Sys.max_array_length}. - If the value of [e] is a floating-point number, then the maximum - size is only [Sys.max_array_length / 2]. */ -let make_matrix: (int, int, 'a) => array> - -@deprecated("Use Array.make_matrix instead.") -/** @deprecated [Array.create_matrix] is an alias for {!Array.make_matrix}. */ -let create_matrix: (int, int, 'a) => array> - -/** [Array.append v1 v2] returns a fresh array containing the - concatenation of the arrays [v1] and [v2]. */ -let append: (array<'a>, array<'a>) => array<'a> - -/** Same as {!Array.append}, but concatenates a list of arrays. */ -let concat: list> => array<'a> - -/** [Array.sub a start len] returns a fresh array of length [len], - containing the elements number [start] to [start + len - 1] - of array [a]. - - Raise [Invalid_argument "Array.sub"] if [start] and [len] do not - designate a valid subarray of [a]; that is, if - [start < 0], or [len < 0], or [start + len > Array.length a]. */ -let sub: (array<'a>, int, int) => array<'a> - -/** [Array.copy a] returns a copy of [a], that is, a fresh array - containing the same elements as [a]. */ -let copy: array<'a> => array<'a> - -/** [Array.fill a ofs len x] modifies the array [a] in place, - storing [x] in elements number [ofs] to [ofs + len - 1]. - - Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not - designate a valid subarray of [a]. */ -let fill: (array<'a>, int, int, 'a) => unit - -/** [Array.blit v1 o1 v2 o2 len] copies [len] elements - from array [v1], starting at element number [o1], to array [v2], - starting at element number [o2]. It works correctly even if - [v1] and [v2] are the same array, and the source and - destination chunks overlap. - - Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not - designate a valid subarray of [v1], or if [o2] and [len] do not - designate a valid subarray of [v2]. */ -let blit: (array<'a>, int, array<'a>, int, int) => unit - -/** [Array.to_list a] returns the list of all the elements of [a]. */ -let to_list: array<'a> => list<'a> - -/** [Array.of_list l] returns a fresh array containing the elements - of [l]. */ -let of_list: list<'a> => array<'a> - -/* {1 Iterators} */ - -/** [Array.iter f a] applies function [f] in turn to all - the elements of [a]. It is equivalent to - [f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. */ -let iter: ('a => unit, array<'a>) => unit - -/** Same as {!Array.iter}, but the - function is applied with the index of the element as first argument, - and the element itself as second argument. */ -let iteri: ((int, 'a) => unit, array<'a>) => unit - -/** [Array.map f a] applies function [f] to all the elements of [a], - and builds an array with the results returned by [f]: - [[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. */ -let map: ('a => 'b, array<'a>) => array<'b> - -/** Same as {!Array.map}, but the - function is applied to the index of the element as first argument, - and the element itself as second argument. */ -let mapi: ((int, 'a) => 'b, array<'a>) => array<'b> - -/** [Array.fold_left f x a] computes - [f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)], - where [n] is the length of the array [a]. */ -let fold_left: (('a, 'b) => 'a, 'a, array<'b>) => 'a - -/** [Array.fold_right f a x] computes - [f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))], - where [n] is the length of the array [a]. */ -let fold_right: (('b, 'a) => 'a, array<'b>, 'a) => 'a - -/* {1 Iterators on two arrays} */ - -/** [Array.iter2 f a b] applies function [f] to all the elements of [a] - and [b]. - Raise [Invalid_argument] if the arrays are not the same size. - @since 4.03.0 */ -let iter2: (('a, 'b) => unit, array<'a>, array<'b>) => unit - -/** [Array.map2 f a b] applies function [f] to all the elements of [a] - and [b], and builds an array with the results returned by [f]: - [[| f a.(0) b.(0); ...; f a.(Array.length a - 1) b.(Array.length b - 1)|]]. - Raise [Invalid_argument] if the arrays are not the same size. - @since 4.03.0 */ -let map2: (('a, 'b) => 'c, array<'a>, array<'b>) => array<'c> - -/* {1 Array scanning} */ - -/** [Array.for_all p [|a1; ...; an|]] checks if all elements of the array - satisfy the predicate [p]. That is, it returns - [(p a1) && (p a2) && ... && (p an)]. - @since 4.03.0 */ -let for_all: ('a => bool, array<'a>) => bool - -/** [Array.exists p [|a1; ...; an|]] checks if at least one element of - the array satisfies the predicate [p]. That is, it returns - [(p a1) || (p a2) || ... || (p an)]. - @since 4.03.0 */ -let exists: ('a => bool, array<'a>) => bool - -/** [mem a l] is true if and only if [a] is equal - to an element of [l]. - @since 4.03.0 */ -let mem: ('a, array<'a>) => bool - -/** Same as {!Array.mem}, but uses physical equality instead of structural - equality to compare array elements. - @since 4.03.0 */ -let memq: ('a, array<'a>) => bool - -/* {1 Sorting} */ - -/** Sort an array in increasing order according to a comparison - function. The comparison function must return 0 if its arguments - compare as equal, a positive integer if the first is greater, - and a negative integer if the first is smaller (see below for a - complete specification). For example, {!Pervasives.compare} is - a suitable comparison function, provided there are no floating-point - NaN values in the data. After calling [Array.sort], the - array is sorted in place in increasing order. - [Array.sort] is guaranteed to run in constant heap space - and (at most) logarithmic stack space. - - The current implementation uses Heap Sort. It runs in constant - stack space. - - Specification of the comparison function: - Let [a] be the array and [cmp] the comparison function. The following - must be true for all x, y, z in a : -- [cmp x y] > 0 if and only if [cmp y x] < 0 -- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0 - - When [Array.sort] returns, [a] contains the same elements as before, - reordered in such a way that for all i and j valid indices of [a] : -- [cmp a.(i) a.(j)] >= 0 if and only if i >= j -*/ -let sort: (('a, 'a) => int, array<'a>) => unit - -/** Same as {!Array.sort}, but the sorting algorithm is stable (i.e. - elements that compare equal are kept in their original order) and - not guaranteed to run in constant heap space. - - The current implementation uses Merge Sort. It uses [n/2] - words of heap space, where [n] is the length of the array. - It is usually faster than the current implementation of {!Array.sort}. -*/ -let stable_sort: (('a, 'a) => int, array<'a>) => unit - -/** Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster - on typical input. -*/ -let fast_sort: (('a, 'a) => int, array<'a>) => unit - -/* {1 Undocumented functions} */ - -/* The following is for system use only. Do not call directly. */ - -external unsafe_get: (array<'a>, int) => 'a = "%array_unsafe_get" -external unsafe_set: (array<'a>, int, 'a) => unit = "%array_unsafe_set" - -module Floatarray: { - external create: int => floatarray = "?floatarray_create" - external length: floatarray => int = "%floatarray_length" - external get: (floatarray, int) => float = "%floatarray_safe_get" - external set: (floatarray, int, float) => unit = "%floatarray_safe_set" - external unsafe_get: (floatarray, int) => float = "%floatarray_unsafe_get" - external unsafe_set: (floatarray, int, float) => unit = "%floatarray_unsafe_set" +/** + `fromIterator(iterator)` + + Creates an array from the provided `iterator` + + ```res example + let map = Map.fromArray([("foo", 1), ("bar", 2)]) + + Array.fromIterator(map->Map.values) // [1, 2] + ``` + */ +@val +external fromIterator: Iterator.t<'a> => array<'a> = "Array.from" + +// TODO: Docs +@val external fromArrayLike: Js.Array2.array_like<'a> => array<'a> = "Array.from" + +// TODO: Docs +@val +external fromArrayLikeWithMap: (Js.Array2.array_like<'a>, 'a => 'b) => array<'b> = "Array.from" + +/** + `make(~length, init)` + + Creates an array of length `length` initialized with the value of `init`. + + ```res example + Array.make(~length=3, #apple) == [#apple, #apple, #apple] + ``` +*/ +let make: (~length: int, 'a) => array<'a> + +/** + `fromInitializer(~length, f)` + + Creates an array of length `length` initialized with the value returned from `f ` for each index. + + ```res example + Array.fromInitializer(~length=3, i => i + 3) == [3, 4, 5] + ``` +*/ +let fromInitializer: (~length: int, int => 'a) => array<'a> + +let equal: (array<'a>, array<'a>, ('a, 'a) => bool) => bool + +let compare: (array<'a>, array<'a>, ('a, 'a) => Ordering.t) => Ordering.t + +@val external isArray: 'a => bool = "Array.isArray" + +/** +`length(array)` returns the length of (i.e. number of items in) the array. + +See [`Array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] + +Console.log(someArray->Array.length) // 2 +``` +*/ +@get +external length: array<'a> => int = "length" + +// TODO: Docs +@send external copyAllWithin: (array<'a>, ~target: int) => array<'a> = "copyWithin" + +// TODO: Docs +@send +external copyWithinToEnd: (array<'a>, ~target: int, ~start: int) => array<'a> = "copyWithin" + +// TODO: Docs +@send +external copyWithin: (array<'a>, ~target: int, ~start: int, ~end: int) => array<'a> = "copyWithin" + +/** +`fillAll(array, value)` fills the entire `array` with `value`. + +Beware this will *mutate* the array. + +See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. + +## Examples +```rescript +let myArray = [1, 2, 3, 4] +myArray->Array.fillAll(9) + +Console.log(myArray) // [9, 9, 9, 9] +``` +*/ +@send +external fillAll: (array<'a>, 'a) => unit = "fill" + +/** +`fillToEnd(array, value, ~start)` fills `array` with `value` from the `start` index. + +Beware this will *mutate* the array. + +See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. + +## Examples +```rescript +let myArray = [1, 2, 3, 4] +myArray->Array.fillToEnd(9, ~start=1) + +Console.log(myArray) // [1, 9, 9, 9] +``` +*/ +@send +external fillToEnd: (array<'a>, 'a, ~start: int) => unit = "fill" + +/** +`fill(array, value, ~start, ~end)` fills `array` with `value` from `start` to `end`. + +Beware this will *mutate* the array. + +See [`Array.fill`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) on MDN. + +## Examples +```rescript +let myArray = [1, 2, 3, 4] +myArray->Array.fill(9, ~start=1, ~end=2) + +Console.log(myArray) // [1, 9, 9, 4] +``` +*/ +@send +external fill: (array<'a>, 'a, ~start: int, ~end: int) => unit = "fill" + +/** +`pop(array)` removes the last item from `array` and returns it. + +Beware this will *mutate* the array. + +See [`Array.pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +let lastItem = someArray->Array.pop // "hello" + +Console.log(someArray) // ["hi"]. Notice last item is gone. +``` +*/ +@send +external pop: array<'a> => option<'a> = "pop" + +/** +`push(array, item)` appends `item` to the end of `array`. + +Beware this will *mutate* the array. + +See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +someArray->Array.push("yay") + +Console.log(someArray) // ["hi", "hello", "yay"] +``` +*/ +@send +external push: (array<'a>, 'a) => unit = "push" + +/** +`pushMany(array, itemsArray)` appends many new items to the end of the array. + +Beware this will *mutate* the array. + +See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +someArray->Array.pushMany(["yay", "wehoo"]) + +Console.log(someArray) // ["hi", "hello", "yay", "wehoo"] +``` +*/ +@variadic +@send +external pushMany: (array<'a>, array<'a>) => unit = "push" + +/** +`reverse(array)` reverses the order of the items in `array`. + +Beware this will *mutate* the array. + +See [`Array.reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +someArray->Array.reverse + +Console.log(someArray) // ["hello", "h1"] +``` +*/ +@send +external reverse: array<'a> => unit = "reverse" + +/** +`shift(array)` removes the first item in the array, and returns it. + +Beware this will *mutate* the array. + +See [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +let lastItem = someArray->Array.shift // "hi" + +Console.log(someArray) // ["hello"]. Notice first item is gone. +``` +*/ +@send +external shift: array<'a> => option<'a> = "shift" + +/** +`toSorted(array, comparator)` returns a new, sorted array from `array`, using the `comparator` function. + +See [`Array.toSorted`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted) on MDN. + +## Examples +```rescript +let someArray = [3, 2, 1] +let sorted = someArray->Array.toSorted(Int.compare) + +Console.log(sorted) // [1, 2, 3] +Console.log(someArray) // [3, 2, 1]. Original unchanged +``` +*/ +@send +external toSorted: (array<'a>, ('a, 'a) => Ordering.t) => array<'a> = "toSorted" + +/** +`sort(array, comparator)` sorts `array` in-place using the `comparator` function. + +Beware this will *mutate* the array. + +See [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on MDN. + +## Examples +```rescript +let someArray = [3, 2, 1] +someArray->Array.sort((a, b) => float(a - b)) + +Console.log(someArray) // [1, 2, 3] +``` +*/ +@send +external sort: (array<'a>, ('a, 'a) => Ordering.t) => unit = "sort" + +@variadic @send +external splice: (array<'a>, ~start: int, ~remove: int, ~insert: array<'a>) => unit = "splice" + +@variadic @send +external toSpliced: (array<'a>, ~start: int, ~remove: int, ~insert: array<'a>) => array<'a> = + "toSpliced" + +@send external with: (array<'a>, int, 'a) => array<'a> = "with" + +/** +`unshift(array, item)` inserts a new item at the start of the array. + +Beware this will *mutate* the array. + +See [`Array.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +someArray->Array.unshift("yay") + +Console.log(someArray) // ["yay", "hi", "hello"] +``` +*/ +@send +external unshift: (array<'a>, 'a) => unit = "unshift" + +/** +`unshiftMany(array, itemsArray)` inserts many new items to the start of the array. + +Beware this will *mutate* the array. + +See [`Array.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +someArray->Array.unshiftMany(["yay", "wehoo"]) + +Console.log(someArray) // ["yay", "wehoo", "hi", "hello"] +``` +*/ +@variadic +@send +external unshiftMany: (array<'a>, array<'a>) => unit = "unshift" + +/** +`concat(array1, array2)` concatenates the two arrays, creating a new array. + +See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN. + +## Examples +```rescript +let array1 = ["hi", "hello"] +let array2 = ["yay", "wehoo"] + +let someArray = array1->Array.concat(array2) + +Console.log(someArray) // ["hi", "hello", "yay", "wehoo"] +``` +*/ +@send +external concat: (array<'a>, array<'a>) => array<'a> = "concat" + +/** +`concatMany(array1, arrays)` concatenates array1 with several other arrays, creating a new array. + +See [`Array.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) on MDN. + +## Examples +```rescript +let array1 = ["hi", "hello"] +let array2 = ["yay"] +let array3 = ["wehoo"] + +let someArray = array1->Array.concatMany([array2, array3]) + +Console.log(someArray) // ["hi", "hello", "yay", "wehoo"] +``` +*/ +@variadic +@send +external concatMany: (array<'a>, array>) => array<'a> = "concat" + +/** +`flat(arrays)` concatenates an array of arrays into a single array. + +See [`Array.flat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) on MDN. + +## Examples +```rescript +Console.log([[1], [2], [3, 4]]->Array.flat) // [1, 2, 3, 4] +``` +*/ +@send +external flat: array> => array<'a> = "flat" + +/** +`includes(array, item)` checks whether `array` includes `item`, by doing a [strict check for equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality). + +See [`Array.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) on MDN. + +## Examples +```rescript +Console.log([1, 2]->Array.includes(1)) // true +Console.log([1, 2]->Array.includes(3)) // false +Console.log([{"language": "ReScript"}]->Array.includes({"language": "ReScript"})) // false, because of strict equality +``` +*/ +@send +external includes: (array<'a>, 'a) => bool = "includes" + +/** +`indexOf(array, item)` returns the index of the provided `item` in `array`. Uses [strict check for equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) when comparing items. + +Returns `-1` if the item doesn not exist. Check out `Array.indexOfOpt` for a version that returns `None` instead of `-1` if the item does not exist. + +See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN. + +## Examples +```rescript +Console.log([1, 2]->Array.indexOf(2)) // 1 +Console.log([1, 2]->Array.indexOf(3)) // -1 +Console.log([{"language": "ReScript"}]->Array.indexOf({"language": "ReScript"})) // -1, because of strict equality +``` +*/ +@send +external indexOf: (array<'a>, 'a) => int = "indexOf" + +/** +`indexOfOpt(array, item)` returns an option of the index of the provided `item` in `array`. Uses [strict check for equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) when comparing items. + +See [`Array.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) on MDN. + +## Examples +```rescript +Console.log([1, 2]->Array.indexOfOpt(2)) // Some(1) +Console.log([1, 2]->Array.indexOfOpt(3)) // None +Console.log([{"language": "ReScript"}]->Array.indexOfOpt({"language": "ReScript"})) // None, because of strict equality +``` +*/ +let indexOfOpt: (array<'a>, 'a) => option +@send external indexOfFrom: (array<'a>, 'a, int) => int = "indexOf" + +/** +`join(array, separator)` produces a string where all items of `array` are printed, separated by `separator`. Array items must be strings, to join number or other arrays, use `joinUnsafe`. Under the hood this will run JavaScript's `toString` on all the array items. + +See [Array.join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) + +## Examples +```rescript +let array = ["One", "Two", "Three"] + +Console.log(array->Array.join(" -- ")) // One -- Two -- Three +``` +*/ +@send +external join: (array, string) => string = "join" + +/** +`joinWith(array, separator)` produces a string where all items of `array` are printed, separated by `separator`. Array items must be strings, to join number or other arrays, use `joinWithUnsafe`. Under the hood this will run JavaScript's `toString` on all the array items. + +## Examples +```rescript +let array = ["One", "Two", "Three"] + +Console.log(array->Array.joinWith(" -- ")) // One -- Two -- Three +``` +*/ +@deprecated("Use `join` instead") +@send +external joinWith: (array, string) => string = "join" + +/** +`joinUnsafe(array, separator)` produces a string where all items of `array` are printed, separated by `separator`. Under the hood this will run JavaScript's `toString` on all the array items. + +See [Array.join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) + +## Examples +```rescript +let array = [1, 2, 3] + +Console.log(array->Array.joinUnsafe(" -- ")) // 1 -- 2 -- 3 +``` +*/ +@send +external joinUnsafe: (array<'a>, string) => string = "join" + +/** +`joinWithUnsafe(array, separator)` produces a string where all items of `array` are printed, separated by `separator`. Under the hood this will run JavaScript's `toString` on all the array items. + +## Examples +```rescript +let array = [1, 2, 3] + +Console.log(array->Array.joinWithUnsafe(" -- ")) // 1 -- 2 -- 3 +``` +*/ +@deprecated("Use `joinUnsafe` instead") +@send +external joinWithUnsafe: (array<'a>, string) => string = "join" +@send external lastIndexOf: (array<'a>, 'a) => int = "lastIndexOf" +let lastIndexOfOpt: (array<'a>, 'a) => option +@send external lastIndexOfFrom: (array<'a>, 'a, int) => int = "lastIndexOf" + +/** +`slice(array, ~start, ~end)` creates a new array of items copied from `array` from `start` until (but not including) `end`. + +See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN. + +## Examples +```rescript +let myArray = [1, 2, 3, 4] + +Console.log(myArray->Array.slice(~start=1, ~end=3)) // [2, 3] +``` +*/ +@send +external slice: (array<'a>, ~start: int, ~end: int) => array<'a> = "slice" + +/** +`sliceToEnd(array, start)` creates a new array from `array`, with all items from `array` starting from `start`. + +See [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) on MDN. + +## Examples +```rescript +let myArray = [1, 2, 3, 4] + +Console.log(myArray->Array.sliceToEnd(~start=1)) // [2, 3, 4] +``` +*/ +@send +external sliceToEnd: (array<'a>, ~start: int) => array<'a> = "slice" +/** +`copy(array)` makes a copy of the array with the items in it, but does not make copies of the items themselves. + +## Examples +```rescript +let myArray = [1, 2, 3] +let copyOfMyArray = myArray->Array.copy + +Console.log(copyOfMyArray) // [1, 2, 3] +Console.log(myArray === copyOfMyArray) // false +``` +*/ +@send +external copy: array<'a> => array<'a> = "slice" + +/** +`toString(array)` stringifies `array` by running `toString` on all of the array elements and joining them with ",". + +See [`Array.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) on MDN. + +## Examples +```rescript +let array = [1, 2, 3, 4] + +Console.log(array->Array.toString) // "1,2,3,4" +``` +*/ +@send +external toString: array<'a> => string = "toString" + +@send external toLocaleString: array<'a> => string = "toLocaleString" + +/** +`every(array, predicate)` returns true if `predicate` returns true for all items in `array`. + +See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN. + +## Examples +```rescript +let array = [1, 2, 3, 4] + +Console.log(array->Array.every(num => num > 4)) // true +Console.log(array->Array.every(num => num === 1)) // false +``` +*/ +@send +external every: (array<'a>, 'a => bool) => bool = "every" + +/** +`everyWithIndex(array, checker)` returns true if all items in `array` returns true when running the provided `checker` function. + +See [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) on MDN. + +## Examples +```rescript +let array = [1, 2, 3, 4] + +Console.log(array->Array.everyWithIndex((num, index) => index < 2 && num <= 2)) // true +Console.log(array->Array.everyWithIndex((num, index) => index < 2 && num >= 2)) // false +``` +*/ +@send +external everyWithIndex: (array<'a>, ('a, int) => bool) => bool = "every" + +/** +`filter(array, checker)` returns a new array containing all elements from `array` for which the provided `checker` function returns true. + +See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN. + +## Examples +```rescript +let array = [1, 2, 3, 4] + +Console.log(array->Array.filter(num => num > 2)) // [3, 4] +``` +*/ +@send +external filter: (array<'a>, 'a => bool) => array<'a> = "filter" + +/** +`filterWithIndex(array, checker)` returns a new array containing all elements from `array` for which the provided `checker` function returns true. + +See [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) on MDN. + +## Examples +```rescript +let array = [1, 2, 3, 4] + +Console.log(array->Array.filterWithIndex((num, index) => index === 0 || num === 2)) // [1, 2] +``` +*/ +@send +external filterWithIndex: (array<'a>, ('a, int) => bool) => array<'a> = "filter" + +/** +`find(array, checker)` returns the first element of `array` where the provided `checker` function returns true. + +See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN. + +## Examples +```rescript +type languages = ReScript | TypeScript | JavaScript + +let array = [ReScript, TypeScript, JavaScript] + +switch array->Array.find(item => item == ReScript) { +| None => Console.log("No item...") +| Some(_) => Console.log("Yay, ReScript!") } +``` +*/ +@send +external find: (array<'a>, 'a => bool) => option<'a> = "find" + +/** +`findWithIndex(array, checker)` returns the first element of `array` where the provided `checker` function returns true. + +See [`Array.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) on MDN. + +## Examples +```rescript +type languages = ReScript | TypeScript | JavaScript + +let array = [TypeScript, JavaScript, ReScript] + +switch array->Array.findWithIndex((item, index) => index > 1 && item == ReScript) { +| None => Console.log("No item...") +| Some(_) => Console.log("Yay, ReScript exists in a later position!") +} +``` +*/ +@send +external findWithIndex: (array<'a>, ('a, int) => bool) => option<'a> = "find" + +/** +`findIndex(array, checker)` returns the index of the first element of `array` where the provided `checker` function returns true. + +Returns `-1` if the item does not exist. Consider using `Array.findIndexOpt` if you want an option instead (where `-1` would be `None`). + +See [`Array.findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) on MDN. + +## Examples +```rescript +type languages = ReScript | TypeScript | JavaScript + +let array = [ReScript, JavaScript] + +Console.log(array->Array.findIndex(item => item == ReScript)) // 0 +Console.log(array->Array.findIndex(item => item == TypeScript)) // -1 +``` +*/ +@send +external findIndex: (array<'a>, 'a => bool) => int = "findIndex" + +/** +`findIndexWithIndex(array, checker)` returns the index of the first element of `array` where the provided `checker` function returns true. + +Returns `-1` if the item does not exist. Consider using `Array.findIndexOpt` if you want an option instead (where `-1` would be `None`). + +See [`Array.findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) on MDN. + +## Examples +```rescript +type languages = ReScript | TypeScript | JavaScript + +let array = [ReScript, JavaScript] + +let isReScriptFirst = array->Array.findIndexWithIndex((item, index) => index === 0 && item == ReScript) +let isTypeScriptFirst = array->Array.findIndexWithIndex((item, index) => index === 0 && item == TypeScript) + +Console.log(isReScriptFirst) // 0 +Console.log(isTypeScriptFirst) // -1 +``` +*/ +@send +external findIndexWithIndex: (array<'a>, ('a, int) => bool) => int = "findIndex" + +/** +`forEach(array, fn)` runs the provided `fn` on every element of `array`. + +See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +array->Array.forEach(item => { + Console.log(item) +}) +``` +*/ +@send +external forEach: (array<'a>, 'a => unit) => unit = "forEach" + +/** +`forEachWithIndex(array, fn)` runs the provided `fn` on every element of `array`. + +See [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +array->Array.forEachWithIndex((item, index) => { + Console.log("At item " ++ Int.toString(index) ++ ": " ++ item) +}) +``` +*/ +@send +external forEachWithIndex: (array<'a>, ('a, int) => unit) => unit = "forEach" + +/** +`map(array, fn)` returns a new array with all elements from `array`, each element transformed using the provided `fn`. + +See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +let mappedArray = array->Array.map(greeting => greeting ++ " to you") + +Console.log(mappedArray) // ["Hello to you", "Hi to you", "Good bye to you"] +``` +*/ +@send +external map: (array<'a>, 'a => 'b) => array<'b> = "map" + +/** +`mapWithIndex(array, fn)` returns a new array with all elements from `array`, each element transformed using the provided `fn`. + +See [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +let mappedArray = + array->Array.mapWithIndex((greeting, index) => + greeting ++ " at position " ++ Int.toString(index) + ) + +Console.log(mappedArray) // ["Hello at position 0", "Hi at position 1", "Good bye at position 2"] +``` +*/ +@send +external mapWithIndex: (array<'a>, ('a, int) => 'b) => array<'b> = "map" + +/** + `reduce(xs, init, fn)` + + Applies `fn` to each element of `xs` from beginning to end. Function `fn` has two parameters: the item from the list and an “accumulator”; which starts with a value of `init`. `reduce` returns the final value of the accumulator. + + ```res example + Array.reduce([2, 3, 4], 1, (a, b) => a + b) == 10 + + Array.reduce(["a", "b", "c", "d"], "", (a, b) => a ++ b) == "abcd" + ``` +*/ +let reduce: (array<'a>, 'b, ('b, 'a) => 'b) => 'b + +/** + `reduceWithIndex(x, init, fn)` + + Applies `fn` to each element of `xs` from beginning to end. Function `fn` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. + + ```res example + Array.reduceWithIndex([1, 2, 3, 4], 0, (acc, x, i) => acc + x + i) == 16 + ``` +*/ +let reduceWithIndex: (array<'a>, 'b, ('b, 'a, int) => 'b) => 'b + +/** + `reduceRight(xs, init, fn)` + + Works like `Array.reduce`; except that function `fn` is applied to each item of `xs` from the last back to the first. + + ```res example + Array.reduceRight(["a", "b", "c", "d"], "", (a, b) => a ++ b) == "dcba" + ``` +*/ +let reduceRight: (array<'a>, 'b, ('b, 'a) => 'b) => 'b + +/** + `reduceRightWithIndex(xs, init, fn)` + + Like `reduceRight`, but with an additional index argument on the callback function. + + ```res example + Array.reduceRightWithIndex([1, 2, 3, 4], 0, (acc, x, i) => acc + x + i) == 16 + ``` +*/ +let reduceRightWithIndex: (array<'a>, 'b, ('b, 'a, int) => 'b) => 'b + +/** +`some(array, predicate)` returns true if `predicate` returns true for any element in `array`. + +See [`Array.some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +Console.log(array->Array.some(greeting => greeting === "Hello")) // true +``` +*/ +@send +external some: (array<'a>, 'a => bool) => bool = "some" + +/** +`someWithIndex(array, checker)` returns true if running the provided `checker` function on any element in `array` returns true. + +See [`Array.some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) on MDN. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +Console.log(array->Array.someWithIndex((greeting, index) => greeting === "Hello" && index === 0)) // true +``` +*/ +@send +external someWithIndex: (array<'a>, ('a, int) => bool) => bool = "some" + +/** +`get(array, index)` returns the element at `index` of `array`. + +Returns `None` if the index does not exist in the array. Equivalent to doing `array[index]` in JavaScript. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +array->Array.get(0) == Some("Hello") // true +array->Array.get(3) == None // true +``` +*/ +@get_index +external get: (array<'a>, int) => option<'a> = "" + +/** +`set(array, index, item)` sets the provided `item` at `index` of `array`. + +Beware this will *mutate* the array. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +array->Array.set(1, "Hello") + +Console.log(array[1]) // "Hello" +``` +*/ +@set_index +external set: (array<'a>, int, 'a) => unit = "" +@get_index external getSymbol: (array<'a>, Symbol.t) => option<'b> = "" +@get_index external getSymbolUnsafe: (array<'a>, Symbol.t) => 'b = "" +@set_index external setSymbol: (array<'a>, Symbol.t, 'b) => unit = "" + +/** +`getUnsafe(array, index)` returns the element at `index` of `array`. + +This is _unsafe_, meaning it will return `undefined` value if `index` does not exist in `array`. + +Use `Array.getUnsafe` only when you are sure the `index` exists (i.e. when using for-loop). + +## Examples +```rescript +let array = [1, 2, 3] +for index in 0 to array->Array.length - 1 { + let value = array->Array.getUnsafe(index) + Console.log(value) +} +``` +*/ +external getUnsafe: (array<'a>, int) => 'a = "%array_unsafe_get" + +/** +`setUnsafe(array, index, item)` sets the provided `item` at `index` of `array`. + +Beware this will *mutate* the array, and is *unsafe*. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +array->Array.setUnsafe(1, "Hello") + +Console.log(array[1]) // "Hello" +``` +*/ +external setUnsafe: (array<'a>, int, 'a) => unit = "%array_unsafe_set" + +/** +`findIndexOpt(array, checker)` returns the index of the first element of `array` where the provided `checker` function returns true. + +Returns `None` if no item matches. + +See [`Array.findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) on MDN. + +## Examples +```rescript +type languages = ReScript | TypeScript | JavaScript + +let array = [ReScript, TypeScript, JavaScript] + +switch array->Array.findIndexOpt(item => item == ReScript) { +| None => Console.log("Ahh, no ReScript...") +| Some(index) => Console.log("Yay, ReScript at index " ++ Int.toString(index)) +} +``` +*/ +let findIndexOpt: (array<'a>, 'a => bool) => option + +/** +`toReversed(array)` creates a new array with all items from `array` in reversed order. + +See [`Array.toReversed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed) on MDN. + +## Examples +```rescript +let someArray = ["hi", "hello"] +let reversed = someArray->Array.toReversed + +Console.log(reversed) // ["hello", "h1"] +Console.log(someArray) // ["h1", "hello"]. Original unchanged +``` +*/ +@send +external toReversed: array<'a> => array<'a> = "toReversed" + +/** +`filterMap(array, fn)` + +Calls `fn` for each element and returns a new array containing results of the `fn` calls which are not `None`. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +Console.log( + array->Array.filterMap(item => + switch item { + | "Hello" => Some(item->String.length) + | _ => None + } + ), +) // [5] +``` +*/ +let filterMap: (array<'a>, 'a => option<'b>) => array<'b> + +/** + `keepSome(arr)` + + Returns a new array containing `value` for all elements that are `Some(value)` + and ignoring every value that is `None` + + ```res example + Array.keepSome([Some(1), None, Some(3)]) == [1, 3] + ``` +*/ +let keepSome: array> => array<'a> + +/** +`toShuffled(array)` returns a new array with all items in `array` in a random order. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +let shuffledArray = array->Array.toShuffled + +Console.log(shuffledArray) +``` +*/ +let toShuffled: array<'a> => array<'a> + +/** +`shuffle(array)` randomizes the position of all items in `array`. + +Beware this will *mutate* the array. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] +array->Array.shuffle + +Console.log(array) +``` +*/ +let shuffle: array<'a> => unit + +/** +`flatMap(array, mapper)` returns a new array concatenating the arrays returned from running `mapper` on all items in `array`. + +## Examples +```rescript +type language = ReScript | TypeScript | JavaScript + +let array = [ReScript, TypeScript, JavaScript] + +Console.log( + array->Array.flatMap(item => + switch item { + | ReScript => [1, 2, 3] + | TypeScript => [4, 5, 6] + | JavaScript => [7, 8, 9] + } + ), +) +// [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` +*/ +@send +external flatMap: (array<'a>, 'a => array<'b>) => array<'b> = "flatMap" + +/** +`flatMapWithIndex(array, mapper)` returns a new array concatenating the arrays returned from running `mapper` on all items in `array`. + +## Examples +```rescript +type language = ReScript | TypeScript | JavaScript + +let array = [ReScript, TypeScript, JavaScript] + +Console.log( + array->Array.flatMapWithIndex((item, index) => + switch item { + | ReScript => [index] + | TypeScript => [index, index + 1] + | JavaScript => [index, index + 1, index + 2] + } + ), +) +// [0, 1, 2, 2, 3, 4] +``` +*/ +@send +external flatMapWithIndex: (array<'a>, ('a, int) => array<'b>) => array<'b> = "flatMap" + +/** + `findMap(arr, fn)` + + Calls `fn` for each element and returns the first value from `fn` that is `Some(_)`. + Otherwise returns `None` + + ```res example + Array.findMap([1, 2, 3], n => mod(n, 2) == 0 ? Some(n - 2) : None) == Some(0) // true + ``` +*/ +let findMap: (array<'a>, 'a => option<'b>) => option<'b> + +/** + `at(array, index)` + + Get an element by its index. Negative indices count backwards from the last item. + + ## Examples + ```rescript + ["a", "b", "c"]->Array.at(0) // Some("a") + ["a", "b", "c"]->Array.at(2) // Some("c") + ["a", "b", "c"]->Array.at(3) // None + ["a", "b", "c"]->Array.at(-1) // Some("c") + ["a", "b", "c"]->Array.at(-3) // Some("a") + ["a", "b", "c"]->Array.at(-4) // None + ``` +*/ +@send +external at: (array<'a>, int) => option<'a> = "at" + +/** +`last(array)` returns the last element of `array`. + +Returns `None` if the array is empty. + +## Examples +```rescript +let array = ["Hello", "Hi", "Good bye"] + +array->Array.last == Some("Good bye") // true +[]->Array.last == None // true +``` +*/ +let last: array<'a> => option<'a> diff --git a/jscomp/stdlib-406/arrayLabels.res b/jscomp/stdlib-406/arrayLabels.res deleted file mode 100644 index e67752553b..0000000000 --- a/jscomp/stdlib-406/arrayLabels.res +++ /dev/null @@ -1,410 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Array operations */ - -external length: array<'a> => int = "%array_length" -external get: (array<'a>, int) => 'a = "%array_safe_get" -external set: (array<'a>, int, 'a) => unit = "%array_safe_set" -external unsafe_get: (array<'a>, int) => 'a = "%array_unsafe_get" -external unsafe_set: (array<'a>, int, 'a) => unit = "%array_unsafe_set" -external make: (int, 'a) => array<'a> = "?make_vect" -external create: (int, 'a) => array<'a> = "?make_vect" -external unsafe_sub: (array<'a>, int, int) => array<'a> = "?array_sub" - -@send external append_prim: (array<'a>, array<'a>) => array<'a> = "concat" - -external concat: list> => array<'a> = "?array_concat" -external unsafe_blit: (array<'a>, int, array<'a>, int, int) => unit = "?array_blit" -external create_float: int => array = "?make_float_vect" -let make_float = create_float - -module Floatarray = { - external create: int => floatarray = "?floatarray_create" - external length: floatarray => int = "%floatarray_length" - external get: (floatarray, int) => float = "%floatarray_safe_get" - external set: (floatarray, int, float) => unit = "%floatarray_safe_set" - external unsafe_get: (floatarray, int) => float = "%floatarray_unsafe_get" - external unsafe_set: (floatarray, int, float) => unit = "%floatarray_unsafe_set" -} - -let init = (l, ~f) => - if l == 0 { - [] - } else if l < 0 { - invalid_arg("Array.init") - } else { - /* See #6575. We could also check for maximum array size, but this depends - on whether we create a float array or a regular one... */ - - let res = create(l, f(0)) - for i in 1 to pred(l) { - unsafe_set(res, i, f(i)) - } - res - } - -let make_matrix = (~dimx as sx, ~dimy as sy, init) => { - let res = create(sx, []) - for x in 0 to pred(sx) { - unsafe_set(res, x, create(sy, init)) - } - res -} - -let create_matrix = make_matrix - -let copy = a => { - let l = length(a) - if l == 0 { - [] - } else { - unsafe_sub(a, 0, l) - } -} - -let append = (a1, a2) => { - let l1 = length(a1) - if l1 == 0 { - copy(a2) - } else if length(a2) == 0 { - unsafe_sub(a1, 0, l1) - } else { - append_prim(a1, a2) - } -} - -let sub = (a, ~pos as ofs, ~len) => - if ofs < 0 || (len < 0 || ofs > length(a) - len) { - invalid_arg("Array.sub") - } else { - unsafe_sub(a, ofs, len) - } - -let fill = (a, ~pos as ofs, ~len, v) => - if ofs < 0 || (len < 0 || ofs > length(a) - len) { - invalid_arg("Array.fill") - } else { - for i in ofs to ofs + len - 1 { - unsafe_set(a, i, v) - } - } - -let blit = (~src as a1, ~src_pos as ofs1, ~dst as a2, ~dst_pos as ofs2, ~len) => - if len < 0 || (ofs1 < 0 || (ofs1 > length(a1) - len || (ofs2 < 0 || ofs2 > length(a2) - len))) { - invalid_arg("Array.blit") - } else { - unsafe_blit(a1, ofs1, a2, ofs2, len) - } - -let iter = (~f, a) => - for i in 0 to length(a) - 1 { - f(unsafe_get(a, i)) - } - -let iter2 = (~f, a, b) => - if length(a) != length(b) { - invalid_arg("Array.iter2: arrays must have the same length") - } else { - for i in 0 to length(a) - 1 { - f(unsafe_get(a, i), unsafe_get(b, i)) - } - } - -let map = (~f, a) => { - let l = length(a) - if l == 0 { - [] - } else { - let r = create(l, f(unsafe_get(a, 0))) - for i in 1 to l - 1 { - unsafe_set(r, i, f(unsafe_get(a, i))) - } - r - } -} - -let map2 = (~f, a, b) => { - let la = length(a) - let lb = length(b) - if la != lb { - invalid_arg("Array.map2: arrays must have the same length") - } else if la == 0 { - [] - } else { - let r = create(la, f(unsafe_get(a, 0), unsafe_get(b, 0))) - for i in 1 to la - 1 { - unsafe_set(r, i, f(unsafe_get(a, i), unsafe_get(b, i))) - } - r - } -} - -let iteri = (~f, a) => - for i in 0 to length(a) - 1 { - f(i, unsafe_get(a, i)) - } - -let mapi = (~f, a) => { - let l = length(a) - if l == 0 { - [] - } else { - let r = create(l, f(0, unsafe_get(a, 0))) - for i in 1 to l - 1 { - unsafe_set(r, i, f(i, unsafe_get(a, i))) - } - r - } -} - -let to_list = a => { - let rec tolist = (i, res) => - if i < 0 { - res - } else { - tolist(i - 1, list{unsafe_get(a, i), ...res}) - } - tolist(length(a) - 1, list{}) -} - -/* Cannot use List.length here because the List module depends on Array. */ -let rec list_length = (accu, param) => - switch param { - | list{} => accu - | list{_, ...t} => list_length(succ(accu), t) - } - -let of_list = param => - switch param { - | list{} => [] - | list{hd, ...tl} as l => - let a = create(list_length(0, l), hd) - let rec fill = (i, param) => - switch param { - | list{} => a - | list{hd, ...tl} => - unsafe_set(a, i, hd) - fill(i + 1, tl) - } - fill(1, tl) - } - -let fold_left = (~f, ~init as x, a) => { - let r = ref(x) - for i in 0 to length(a) - 1 { - r := f(r.contents, unsafe_get(a, i)) - } - r.contents -} - -let fold_right = (~f, a, ~init as x) => { - let r = ref(x) - for i in length(a) - 1 downto 0 { - r := f(unsafe_get(a, i), r.contents) - } - r.contents -} - -let exists = (~f as p, a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if p(unsafe_get(a, i)) { - true - } else { - loop(succ(i)) - } - loop(0) -} - -let for_all = (~f as p, a) => { - let n = length(a) - let rec loop = i => - if i == n { - true - } else if p(unsafe_get(a, i)) { - loop(succ(i)) - } else { - false - } - loop(0) -} - -let mem = (x, ~set as a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if compare(unsafe_get(a, i), x) == 0 { - true - } else { - loop(succ(i)) - } - loop(0) -} - -let memq = (x, ~set as a) => { - let n = length(a) - let rec loop = i => - if i == n { - false - } else if x === unsafe_get(a, i) { - true - } else { - loop(succ(i)) - } - loop(0) -} - -exception Bottom(int) -let sort = (~cmp, a) => { - let maxson = (l, i) => { - let i31 = i + i + i + 1 - let x = ref(i31) - if i31 + 2 < l { - if cmp(get(a, i31), get(a, i31 + 1)) < 0 { - x := i31 + 1 - } - if cmp(get(a, x.contents), get(a, i31 + 2)) < 0 { - x := i31 + 2 - } - x.contents - } else if i31 + 1 < l && cmp(get(a, i31), get(a, i31 + 1)) < 0 { - i31 + 1 - } else if i31 < l { - i31 - } else { - raise(Bottom(i)) - } - } - - let rec trickledown = (l, i, e) => { - let j = maxson(l, i) - if cmp(get(a, j), e) > 0 { - set(a, i, get(a, j)) - trickledown(l, j, e) - } else { - set(a, i, e) - } - } - - let trickle = (l, i, e) => - try trickledown(l, i, e) catch { - | Bottom(i) => set(a, i, e) - } - let rec bubbledown = (l, i) => { - let j = maxson(l, i) - set(a, i, get(a, j)) - bubbledown(l, j) - } - - let bubble = (l, i) => - try bubbledown(l, i) catch { - | Bottom(i) => i - } - let rec trickleup = (i, e) => { - let father = (i - 1) / 3 - assert(i != father) - if cmp(get(a, father), e) < 0 { - set(a, i, get(a, father)) - if father > 0 { - trickleup(father, e) - } else { - set(a, 0, e) - } - } else { - set(a, i, e) - } - } - - let l = length(a) - for i in (l + 1) / 3 - 1 downto 0 { - trickle(l, i, get(a, i)) - } - for i in l - 1 downto 2 { - let e = get(a, i) - set(a, i, get(a, 0)) - trickleup(bubble(i, 0), e) - } - if l > 1 { - let e = get(a, 1) - set(a, 1, get(a, 0)) - set(a, 0, e) - } -} - -let cutoff = 5 -let stable_sort = (~cmp, a) => { - let merge = (src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs) => { - let src1r = src1ofs + src1len and src2r = src2ofs + src2len - let rec loop = (i1, s1, i2, s2, d) => - if cmp(s1, s2) <= 0 { - set(dst, d, s1) - let i1 = i1 + 1 - if i1 < src1r { - loop(i1, get(a, i1), i2, s2, d + 1) - } else { - blit(~src=src2, ~src_pos=i2, ~dst, ~dst_pos=d + 1, ~len=src2r - i2) - } - } else { - set(dst, d, s2) - let i2 = i2 + 1 - if i2 < src2r { - loop(i1, s1, i2, get(src2, i2), d + 1) - } else { - blit(~src=a, ~src_pos=i1, ~dst, ~dst_pos=d + 1, ~len=src1r - i1) - } - } - loop(src1ofs, get(a, src1ofs), src2ofs, get(src2, src2ofs), dstofs) - } - - let isortto = (srcofs, dst, dstofs, len) => - for i in 0 to len - 1 { - let e = get(a, srcofs + i) - let j = ref(dstofs + i - 1) - while j.contents >= dstofs && cmp(get(dst, j.contents), e) > 0 { - set(dst, j.contents + 1, get(dst, j.contents)) - decr(j) - } - set(dst, j.contents + 1, e) - } - - let rec sortto = (srcofs, dst, dstofs, len) => - if len <= cutoff { - isortto(srcofs, dst, dstofs, len) - } else { - let l1 = len / 2 - let l2 = len - l1 - sortto(srcofs + l1, dst, dstofs + l1, l2) - sortto(srcofs, a, srcofs + l2, l1) - merge(srcofs + l2, l1, dst, dstofs + l1, l2, dst, dstofs) - } - - let l = length(a) - if l <= cutoff { - isortto(0, a, 0, l) - } else { - let l1 = l / 2 - let l2 = l - l1 - let t = make(l2, get(a, 0)) - sortto(l1, t, 0, l2) - sortto(0, a, l2, l1) - merge(l2, l1, t, 0, l2, a, 0) - } -} - -let fast_sort = stable_sort diff --git a/jscomp/stdlib-406/arrayLabels.resi b/jscomp/stdlib-406/arrayLabels.resi deleted file mode 100644 index 1a211691d3..0000000000 --- a/jscomp/stdlib-406/arrayLabels.resi +++ /dev/null @@ -1,264 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Array operations. */ - -/** Return the length (number of elements) of the given array. */ -external length: array<'a> => int = "%array_length" - -/** [Array.get a n] returns the element number [n] of array [a]. - The first element has number 0. - The last element has number [Array.length a - 1]. - You can also write [a.(n)] instead of [Array.get a n]. - - Raise [Invalid_argument "index out of bounds"] - if [n] is outside the range 0 to [(Array.length a - 1)]. */ -external get: (array<'a>, int) => 'a = "%array_safe_get" - -/** [Array.set a n x] modifies array [a] in place, replacing - element number [n] with [x]. - You can also write [a.(n) <- x] instead of [Array.set a n x]. - - Raise [Invalid_argument "index out of bounds"] - if [n] is outside the range 0 to [Array.length a - 1]. */ -external set: (array<'a>, int, 'a) => unit = "%array_safe_set" - -/** [Array.make n x] returns a fresh array of length [n], - initialized with [x]. - All the elements of this new array are initially - physically equal to [x] (in the sense of the [==] predicate). - Consequently, if [x] is mutable, it is shared among all elements - of the array, and modifying [x] through one of the array entries - will modify all other entries at the same time. - - Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. - If the value of [x] is a floating-point number, then the maximum - size is only [Sys.max_array_length / 2].*/ -external make: (int, 'a) => array<'a> = "?make_vect" - -@deprecated("Use Array.make instead.") -/** @deprecated [Array.create] is an alias for {!Array.make}. */ -external create: (int, 'a) => array<'a> = "?make_vect" - -/** [Array.init n f] returns a fresh array of length [n], - with element number [i] initialized to the result of [f i]. - In other terms, [Array.init n f] tabulates the results of [f] - applied to the integers [0] to [n-1]. - - Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length]. - If the return type of [f] is [float], then the maximum - size is only [Sys.max_array_length / 2].*/ -let init: (int, ~f: int => 'a) => array<'a> - -/** [Array.make_matrix dimx dimy e] returns a two-dimensional array - (an array of arrays) with first dimension [dimx] and - second dimension [dimy]. All the elements of this new matrix - are initially physically equal to [e]. - The element ([x,y]) of a matrix [m] is accessed - with the notation [m.(x).(y)]. - - Raise [Invalid_argument] if [dimx] or [dimy] is negative or - greater than {!Sys.max_array_length}. - If the value of [e] is a floating-point number, then the maximum - size is only [Sys.max_array_length / 2]. */ -let make_matrix: (~dimx: int, ~dimy: int, 'a) => array> - -@deprecated("Use Array.make_matrix instead.") -/** @deprecated [Array.create_matrix] is an alias for - {!Array.make_matrix}. */ -let create_matrix: (~dimx: int, ~dimy: int, 'a) => array> - -/** [Array.append v1 v2] returns a fresh array containing the - concatenation of the arrays [v1] and [v2]. */ -let append: (array<'a>, array<'a>) => array<'a> - -/** Same as {!Array.append}, but concatenates a list of arrays. */ -let concat: list> => array<'a> - -/** [Array.sub a start len] returns a fresh array of length [len], - containing the elements number [start] to [start + len - 1] - of array [a]. - - Raise [Invalid_argument "Array.sub"] if [start] and [len] do not - designate a valid subarray of [a]; that is, if - [start < 0], or [len < 0], or [start + len > Array.length a]. */ -let sub: (array<'a>, ~pos: int, ~len: int) => array<'a> - -/** [Array.copy a] returns a copy of [a], that is, a fresh array - containing the same elements as [a]. */ -let copy: array<'a> => array<'a> - -/** [Array.fill a ofs len x] modifies the array [a] in place, - storing [x] in elements number [ofs] to [ofs + len - 1]. - - Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not - designate a valid subarray of [a]. */ -let fill: (array<'a>, ~pos: int, ~len: int, 'a) => unit - -/** [Array.blit v1 o1 v2 o2 len] copies [len] elements - from array [v1], starting at element number [o1], to array [v2], - starting at element number [o2]. It works correctly even if - [v1] and [v2] are the same array, and the source and - destination chunks overlap. - - Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not - designate a valid subarray of [v1], or if [o2] and [len] do not - designate a valid subarray of [v2]. */ -let blit: (~src: array<'a>, ~src_pos: int, ~dst: array<'a>, ~dst_pos: int, ~len: int) => unit - -/** [Array.to_list a] returns the list of all the elements of [a]. */ -let to_list: array<'a> => list<'a> - -/** [Array.of_list l] returns a fresh array containing the elements - of [l]. */ -let of_list: list<'a> => array<'a> - -/** [Array.iter f a] applies function [f] in turn to all - the elements of [a]. It is equivalent to - [f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. */ -let iter: (~f: 'a => unit, array<'a>) => unit - -/** [Array.map f a] applies function [f] to all the elements of [a], - and builds an array with the results returned by [f]: - [[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. */ -let map: (~f: 'a => 'b, array<'a>) => array<'b> - -/** Same as {!Array.iter}, but the - function is applied to the index of the element as first argument, - and the element itself as second argument. */ -let iteri: (~f: (int, 'a) => unit, array<'a>) => unit - -/** Same as {!Array.map}, but the - function is applied to the index of the element as first argument, - and the element itself as second argument. */ -let mapi: (~f: (int, 'a) => 'b, array<'a>) => array<'b> - -/** [Array.fold_left f x a] computes - [f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)], - where [n] is the length of the array [a]. */ -let fold_left: (~f: ('a, 'b) => 'a, ~init: 'a, array<'b>) => 'a - -/** [Array.fold_right f a x] computes - [f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))], - where [n] is the length of the array [a]. */ -let fold_right: (~f: ('b, 'a) => 'a, array<'b>, ~init: 'a) => 'a - -/* {6 Iterators on two arrays} */ - -/** [Array.iter2 f a b] applies function [f] to all the elements of [a] - and [b]. - Raise [Invalid_argument] if the arrays are not the same size. - @since 4.05.0 */ -let iter2: (~f: ('a, 'b) => unit, array<'a>, array<'b>) => unit - -/** [Array.map2 f a b] applies function [f] to all the elements of [a] - and [b], and builds an array with the results returned by [f]: - [[| f a.(0) b.(0); ...; f a.(Array.length a - 1) b.(Array.length b - 1)|]]. - Raise [Invalid_argument] if the arrays are not the same size. - @since 4.05.0 */ -let map2: (~f: ('a, 'b) => 'c, array<'a>, array<'b>) => array<'c> - -/* {6 Array scanning} */ - -/** [Array.exists p [|a1; ...; an|]] checks if at least one element of - the array satisfies the predicate [p]. That is, it returns - [(p a1) || (p a2) || ... || (p an)]. - @since 4.03.0 */ -let exists: (~f: 'a => bool, array<'a>) => bool - -/** [Array.for_all p [|a1; ...; an|]] checks if all elements of the array - satisfy the predicate [p]. That is, it returns - [(p a1) && (p a2) && ... && (p an)]. - @since 4.03.0 */ -let for_all: (~f: 'a => bool, array<'a>) => bool - -/** [mem x a] is true if and only if [x] is equal - to an element of [a]. - @since 4.03.0 */ -let mem: ('a, ~set: array<'a>) => bool - -/** Same as {!Array.mem}, but uses physical equality instead of structural - equality to compare list elements. - @since 4.03.0 */ -let memq: ('a, ~set: array<'a>) => bool - -/** [Array.create_float n] returns a fresh float array of length [n], - with uninitialized data. - @since 4.03 */ -external create_float: int => array = "?make_float_vect" - -@deprecated("Use Array.create_float instead.") -/** @deprecated [Array.make_float] is an alias for - {!Array.create_float}. */ -let make_float: int => array - -/* {1 Sorting} */ - -/** Sort an array in increasing order according to a comparison - function. The comparison function must return 0 if its arguments - compare as equal, a positive integer if the first is greater, - and a negative integer if the first is smaller (see below for a - complete specification). For example, {!Pervasives.compare} is - a suitable comparison function, provided there are no floating-point - NaN values in the data. After calling [Array.sort], the - array is sorted in place in increasing order. - [Array.sort] is guaranteed to run in constant heap space - and (at most) logarithmic stack space. - - The current implementation uses Heap Sort. It runs in constant - stack space. - - Specification of the comparison function: - Let [a] be the array and [cmp] the comparison function. The following - must be true for all x, y, z in a : -- [cmp x y] > 0 if and only if [cmp y x] < 0 -- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0 - - When [Array.sort] returns, [a] contains the same elements as before, - reordered in such a way that for all i and j valid indices of [a] : -- [cmp a.(i) a.(j)] >= 0 if and only if i >= j -*/ -let sort: (~cmp: ('a, 'a) => int, array<'a>) => unit - -/** Same as {!Array.sort}, but the sorting algorithm is stable (i.e. - elements that compare equal are kept in their original order) and - not guaranteed to run in constant heap space. - - The current implementation uses Merge Sort. It uses [n/2] - words of heap space, where [n] is the length of the array. - It is usually faster than the current implementation of {!Array.sort}. -*/ -let stable_sort: (~cmp: ('a, 'a) => int, array<'a>) => unit - -/** Same as {!Array.sort} or {!Array.stable_sort}, whichever is - faster on typical input. -*/ -let fast_sort: (~cmp: ('a, 'a) => int, array<'a>) => unit - -/* {1 Undocumented functions} */ - -/* The following is for system use only. Do not call directly. */ - -external unsafe_get: (array<'a>, int) => 'a = "%array_unsafe_get" -external unsafe_set: (array<'a>, int, 'a) => unit = "%array_unsafe_set" - -module Floatarray: { - external create: int => floatarray = "?floatarray_create" - external length: floatarray => int = "%floatarray_length" - external get: (floatarray, int) => float = "%floatarray_safe_get" - external set: (floatarray, int, float) => unit = "%floatarray_safe_set" - external unsafe_get: (floatarray, int) => float = "%floatarray_unsafe_get" - external unsafe_set: (floatarray, int, float) => unit = "%floatarray_unsafe_set" -} diff --git a/jscomp/stdlib-406/buffer.res b/jscomp/stdlib-406/buffer.res deleted file mode 100644 index 6d9db8c24d..0000000000 --- a/jscomp/stdlib-406/buffer.res +++ /dev/null @@ -1,307 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Pierre Weis and Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1999 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Extensible buffers */ - -type t = { - mutable buffer: bytes, - mutable position: int, - mutable length: int, - initial_buffer: bytes, -} - -let create = n => { - let n = if n < 1 { - 1 - } else { - n - } - let s = Bytes.create(n) - {buffer: s, position: 0, length: n, initial_buffer: s} -} - -let contents = b => Bytes.sub_string(b.buffer, 0, b.position) -let to_bytes = b => Bytes.sub(b.buffer, 0, b.position) - -let sub = (b, ofs, len) => - if ofs < 0 || (len < 0 || ofs > b.position - len) { - invalid_arg("Buffer.sub") - } else { - Bytes.sub_string(b.buffer, ofs, len) - } - -let blit = (src, srcoff, dst, dstoff, len) => - if ( - len < 0 || - (srcoff < 0 || - (srcoff > src.position - len || (dstoff < 0 || dstoff > Bytes.length(dst) - len))) - ) { - invalid_arg("Buffer.blit") - } else { - Bytes.blit(src.buffer, srcoff, dst, dstoff, len) - } - -let nth = (b, ofs) => - if ofs < 0 || ofs >= b.position { - invalid_arg("Buffer.nth") - } else { - Bytes.unsafe_get(b.buffer, ofs) - } - -let length = b => b.position - -let clear = b => b.position = 0 - -let reset = b => { - b.position = 0 - b.buffer = b.initial_buffer - b.length = Bytes.length(b.buffer) -} - -let resize = (b, more) => { - let len = b.length - let new_len = ref(len) - while b.position + more > new_len.contents { - new_len := 2 * new_len.contents - } - let new_buffer = Bytes.create(new_len.contents) - /* PR#6148: let's keep using [blit] rather than [unsafe_blit] in - this tricky function that is slow anyway. */ - Bytes.blit(b.buffer, 0, new_buffer, 0, b.position) - b.buffer = new_buffer - b.length = new_len.contents -} - -let add_char = (b, c) => { - let pos = b.position - if pos >= b.length { - resize(b, 1) - } - Bytes.unsafe_set(b.buffer, pos, c) - b.position = pos + 1 -} - -let add_utf_8_uchar = (b, u) => - switch Uchar.to_int(u) { - | u if u < 0 => assert(false) - | u if u <= 0x007F => add_char(b, Char.unsafe_chr(u)) - | u if u <= 0x07FF => - let pos = b.position - if pos + 2 > b.length { - resize(b, 2) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(lor(0xC0, lsr(u, 6)))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(lor(0x80, land(u, 0x3F)))) - b.position = pos + 2 - | u if u <= 0xFFFF => - let pos = b.position - if pos + 3 > b.length { - resize(b, 3) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(lor(0xE0, lsr(u, 12)))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(lor(0x80, land(lsr(u, 6), 0x3F)))) - Bytes.unsafe_set(b.buffer, pos + 2, Char.unsafe_chr(lor(0x80, land(u, 0x3F)))) - b.position = pos + 3 - | u if u <= 0x10FFFF => - let pos = b.position - if pos + 4 > b.length { - resize(b, 4) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(lor(0xF0, lsr(u, 18)))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(lor(0x80, land(lsr(u, 12), 0x3F)))) - Bytes.unsafe_set(b.buffer, pos + 2, Char.unsafe_chr(lor(0x80, land(lsr(u, 6), 0x3F)))) - Bytes.unsafe_set(b.buffer, pos + 3, Char.unsafe_chr(lor(0x80, land(u, 0x3F)))) - b.position = pos + 4 - | _ => assert(false) - } - -let add_utf_16be_uchar = (b, u) => - switch Uchar.to_int(u) { - | u if u < 0 => assert(false) - | u if u <= 0xFFFF => - let pos = b.position - if pos + 2 > b.length { - resize(b, 2) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(lsr(u, 8))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(land(u, 0xFF))) - b.position = pos + 2 - | u if u <= 0x10FFFF => - let u' = u - 0x10000 - let hi = lor(0xD800, lsr(u', 10)) - let lo = lor(0xDC00, land(u', 0x3FF)) - let pos = b.position - if pos + 4 > b.length { - resize(b, 4) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(lsr(hi, 8))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(land(hi, 0xFF))) - Bytes.unsafe_set(b.buffer, pos + 2, Char.unsafe_chr(lsr(lo, 8))) - Bytes.unsafe_set(b.buffer, pos + 3, Char.unsafe_chr(land(lo, 0xFF))) - b.position = pos + 4 - | _ => assert(false) - } - -let add_utf_16le_uchar = (b, u) => - switch Uchar.to_int(u) { - | u if u < 0 => assert(false) - | u if u <= 0xFFFF => - let pos = b.position - if pos + 2 > b.length { - resize(b, 2) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(land(u, 0xFF))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(lsr(u, 8))) - b.position = pos + 2 - | u if u <= 0x10FFFF => - let u' = u - 0x10000 - let hi = lor(0xD800, lsr(u', 10)) - let lo = lor(0xDC00, land(u', 0x3FF)) - let pos = b.position - if pos + 4 > b.length { - resize(b, 4) - } - Bytes.unsafe_set(b.buffer, pos, Char.unsafe_chr(land(hi, 0xFF))) - Bytes.unsafe_set(b.buffer, pos + 1, Char.unsafe_chr(lsr(hi, 8))) - Bytes.unsafe_set(b.buffer, pos + 2, Char.unsafe_chr(land(lo, 0xFF))) - Bytes.unsafe_set(b.buffer, pos + 3, Char.unsafe_chr(lsr(lo, 8))) - b.position = pos + 4 - | _ => assert(false) - } - -let add_substring = (b, s, offset, len) => { - if offset < 0 || (len < 0 || offset > String.length(s) - len) { - invalid_arg("Buffer.add_substring/add_subbytes") - } - let new_position = b.position + len - if new_position > b.length { - resize(b, len) - } - Bytes.blit_string(s, offset, b.buffer, b.position, len) - b.position = new_position -} - -let add_subbytes = (b, s, offset, len) => add_substring(b, Bytes.unsafe_to_string(s), offset, len) - -let add_string = (b, s) => { - let len = String.length(s) - let new_position = b.position + len - if new_position > b.length { - resize(b, len) - } - Bytes.blit_string(s, 0, b.buffer, b.position, len) - b.position = new_position -} - -let add_bytes = (b, s) => add_string(b, Bytes.unsafe_to_string(s)) - -let add_buffer = (b, bs) => add_subbytes(b, bs.buffer, 0, bs.position) - -let closing = param => - switch param { - | '(' => ')' - | '{' => '}' - | _ => assert(false) - } - -/* opening and closing: open and close characters, typically ( and ) - k: balance of opening and closing chars - s: the string where we are searching - start: the index where we start the search. */ -let advance_to_closing = (opening, closing, k, s, start) => { - let rec advance = (k, i, lim) => - if i >= lim { - raise(Not_found) - } else if String.get(s, i) == opening { - advance(k + 1, i + 1, lim) - } else if String.get(s, i) == closing { - if k == 0 { - i - } else { - advance(k - 1, i + 1, lim) - } - } else { - advance(k, i + 1, lim) - } - advance(k, start, String.length(s)) -} - -let advance_to_non_alpha = (s, start) => { - let rec advance = (i, lim) => - if i >= lim { - lim - } else { - switch String.get(s, i) { - | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' => advance(i + 1, lim) - | _ => i - } - } - advance(start, String.length(s)) -} - -/* We are just at the beginning of an ident in s, starting at start. */ -let find_ident = (s, start, lim) => - if start >= lim { - raise(Not_found) - } else { - switch String.get(s, start) { - /* Parenthesized ident ? */ - | ('(' | '{') as c => - let new_start = start + 1 - let stop = advance_to_closing(c, closing(c), 0, s, new_start) - (String.sub(s, new_start, stop - start - 1), stop + 1) - /* Regular ident */ - | _ => - let stop = advance_to_non_alpha(s, start + 1) - (String.sub(s, start, stop - start), stop) - } - } - -/* Substitute $ident, $(ident), or ${ident} in s, - according to the function mapping f. */ -let add_substitute = (b, f, s) => { - let lim = String.length(s) - let rec subst = (previous, i) => - if i < lim { - switch String.get(s, i) { - | '$' as current if previous == '\\' => - add_char(b, current) - subst(' ', i + 1) - | '$' => - let j = i + 1 - let (ident, next_i) = find_ident(s, j, lim) - add_string(b, f(ident)) - subst(' ', next_i) - | current if previous === '\\' => - add_char(b, '\\') - add_char(b, current) - subst(' ', i + 1) - | '\\' as current => subst(current, i + 1) - | current => - add_char(b, current) - subst(current, i + 1) - } - } else if previous == '\\' { - add_char(b, previous) - } - subst(' ', 0) -} - -let truncate = (b, len) => - if len < 0 || len > length(b) { - invalid_arg("Buffer.truncate") - } else { - b.position = len - } diff --git a/jscomp/stdlib-406/buffer.resi b/jscomp/stdlib-406/buffer.resi deleted file mode 100644 index 9929a1d2ff..0000000000 --- a/jscomp/stdlib-406/buffer.resi +++ /dev/null @@ -1,148 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Pierre Weis and Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1999 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Extensible buffers. - - This module implements buffers that automatically expand - as necessary. It provides accumulative concatenation of strings - in quasi-linear time (instead of quadratic time when strings are - concatenated pairwise). -*/ - -/** The abstract type of buffers. */ -type t - -/** [create n] returns a fresh buffer, initially empty. - The [n] parameter is the initial size of the internal byte sequence - that holds the buffer contents. That byte sequence is automatically - reallocated when more than [n] characters are stored in the buffer, - but shrinks back to [n] characters when [reset] is called. - For best performance, [n] should be of the same order of magnitude - as the number of characters that are expected to be stored in - the buffer (for instance, 80 for a buffer that holds one output - line). Nothing bad will happen if the buffer grows beyond that - limit, however. In doubt, take [n = 16] for instance. - If [n] is not between 1 and {!Sys.max_string_length}, it will - be clipped to that interval. */ -let create: int => t - -/** Return a copy of the current contents of the buffer. - The buffer itself is unchanged. */ -let contents: t => string - -/** Return a copy of the current contents of the buffer. - The buffer itself is unchanged. - @since 4.02 */ -let to_bytes: t => bytes - -/** [Buffer.sub b off len] returns a copy of [len] bytes from the - current contents of the buffer [b], starting at offset [off]. - - Raise [Invalid_argument] if [srcoff] and [len] do not designate a valid - range of [b]. */ -let sub: (t, int, int) => string - -/** [Buffer.blit src srcoff dst dstoff len] copies [len] characters from - the current contents of the buffer [src], starting at offset [srcoff] - to [dst], starting at character [dstoff]. - - Raise [Invalid_argument] if [srcoff] and [len] do not designate a valid - range of [src], or if [dstoff] and [len] do not designate a valid - range of [dst]. - @since 3.11.2 -*/ -let blit: (t, int, bytes, int, int) => unit - -/** Get the n-th character of the buffer. Raise [Invalid_argument] if - index out of bounds */ -let nth: (t, int) => char - -/** Return the number of characters currently contained in the buffer. */ -let length: t => int - -/** Empty the buffer. */ -let clear: t => unit - -/** Empty the buffer and deallocate the internal byte sequence holding the - buffer contents, replacing it with the initial internal byte sequence - of length [n] that was allocated by {!Buffer.create} [n]. - For long-lived buffers that may have grown a lot, [reset] allows - faster reclamation of the space used by the buffer. */ -let reset: t => unit - -/** [add_char b c] appends the character [c] at the end of buffer [b]. */ -let add_char: (t, char) => unit - -/** [add_utf_8_uchar b u] appends the {{:https://tools.ietf.org/html/rfc3629} - UTF-8} encoding of [u] at the end of buffer [b]. - - @since 4.06.0 */ -let add_utf_8_uchar: (t, Uchar.t) => unit - -/** [add_utf_16le_uchar b u] appends the - {{:https://tools.ietf.org/html/rfc2781}UTF-16LE} encoding of [u] - at the end of buffer [b]. - - @since 4.06.0 */ -let add_utf_16le_uchar: (t, Uchar.t) => unit - -/** [add_utf_16be_uchar b u] appends the - {{:https://tools.ietf.org/html/rfc2781}UTF-16BE} encoding of [u] - at the end of buffer [b]. - - @since 4.06.0 */ -let add_utf_16be_uchar: (t, Uchar.t) => unit - -/** [add_string b s] appends the string [s] at the end of buffer [b]. */ -let add_string: (t, string) => unit - -/** [add_bytes b s] appends the byte sequence [s] at the end of buffer [b]. - @since 4.02 */ -let add_bytes: (t, bytes) => unit - -/** [add_substring b s ofs len] takes [len] characters from offset - [ofs] in string [s] and appends them at the end of buffer [b]. */ -let add_substring: (t, string, int, int) => unit - -/** [add_subbytes b s ofs len] takes [len] characters from offset - [ofs] in byte sequence [s] and appends them at the end of buffer [b]. - @since 4.02 */ -let add_subbytes: (t, bytes, int, int) => unit - -/** [add_substitute b f s] appends the string pattern [s] at the end - of buffer [b] with substitution. - The substitution process looks for variables into - the pattern and substitutes each variable name by its value, as - obtained by applying the mapping [f] to the variable name. Inside the - string pattern, a variable name immediately follows a non-escaped - [$] character and is one of the following: - - a non empty sequence of alphanumeric or [_] characters, - - an arbitrary sequence of characters enclosed by a pair of - matching parentheses or curly brackets. - An escaped [$] character is a [$] that immediately follows a backslash - character; it then stands for a plain [$]. - Raise [Not_found] if the closing character of a parenthesized variable - cannot be found. */ -let add_substitute: (t, string => string, string) => unit - -/** [add_buffer b1 b2] appends the current contents of buffer [b2] - at the end of buffer [b1]. [b2] is not modified. */ -let add_buffer: (t, t) => unit - -/** [truncate b len] truncates the length of [b] to [len] - Note: the internal byte sequence is not shortened. - Raise [Invalid_argument] if [len < 0] or [len > length b]. - @since 4.05.0 */ -let truncate: (t, int) => unit diff --git a/jscomp/stdlib-406/bytes.res b/jscomp/stdlib-406/bytes.res deleted file mode 100644 index d7f9c5cb7b..0000000000 Binary files a/jscomp/stdlib-406/bytes.res and /dev/null differ diff --git a/jscomp/stdlib-406/bytes.resi b/jscomp/stdlib-406/bytes.resi deleted file mode 100644 index 2b65cb4695..0000000000 --- a/jscomp/stdlib-406/bytes.resi +++ /dev/null @@ -1,427 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Byte sequence operations. - - A byte sequence is a mutable data structure that contains a - fixed-length sequence of bytes. Each byte can be indexed in - constant time for reading or writing. - - Given a byte sequence [s] of length [l], we can access each of the - [l] bytes of [s] via its index in the sequence. Indexes start at - [0], and we will call an index valid in [s] if it falls within the - range [[0...l-1]] (inclusive). A position is the point between two - bytes or at the beginning or end of the sequence. We call a - position valid in [s] if it falls within the range [[0...l]] - (inclusive). Note that the byte at index [n] is between positions - [n] and [n+1]. - - Two parameters [start] and [len] are said to designate a valid - range of [s] if [len >= 0] and [start] and [start+len] are valid - positions in [s]. - - Byte sequences can be modified in place, for instance via the [set] - and [blit] functions described below. See also strings (module - {!String}), which are almost the same data structure, but cannot be - modified in place. - - Bytes are represented by the OCaml type [char]. - - @since 4.02.0 -*/ - -/** Return the length (number of bytes) of the argument. */ -external length: bytes => int = "%bytes_length" - -/** [get s n] returns the byte at index [n] in argument [s]. - - Raise [Invalid_argument] if [n] is not a valid index in [s]. */ -external get: (bytes, int) => char = "%bytes_safe_get" - -/** [set s n c] modifies [s] in place, replacing the byte at index [n] - with [c]. - - Raise [Invalid_argument] if [n] is not a valid index in [s]. */ -external set: (bytes, int, char) => unit = "%bytes_safe_set" - -/** [create n] returns a new byte sequence of length [n]. The - sequence is uninitialized and contains arbitrary bytes. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -external create: int => bytes = "?create_bytes" - -/** [make n c] returns a new byte sequence of length [n], filled with - the byte [c]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let make: (int, char) => bytes - -/** [Bytes.init n f] returns a fresh byte sequence of length [n], with - character [i] initialized to the result of [f i] (in increasing - index order). - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let init: (int, int => char) => bytes - -/** A byte sequence of size 0. */ -let empty: bytes - -/** Return a new byte sequence that contains the same bytes as the - argument. */ -let copy: bytes => bytes - -/** Return a new byte sequence that contains the same bytes as the - given string. */ -let of_string: string => bytes - -/** Return a new string that contains the same bytes as the given byte - sequence. */ -let to_string: bytes => string - -/** [sub s start len] returns a new byte sequence of length [len], - containing the subsequence of [s] that starts at position [start] - and has length [len]. - - Raise [Invalid_argument] if [start] and [len] do not designate a - valid range of [s]. */ -let sub: (bytes, int, int) => bytes - -/** Same as [sub] but return a string instead of a byte sequence. */ -let sub_string: (bytes, int, int) => string - -/** [extend s left right] returns a new byte sequence that contains - the bytes of [s], with [left] uninitialized bytes prepended and - [right] uninitialized bytes appended to it. If [left] or [right] - is negative, then bytes are removed (instead of appended) from - the corresponding side of [s]. - - Raise [Invalid_argument] if the result length is negative or - longer than {!Sys.max_string_length} bytes. */ -let extend: (bytes, int, int) => bytes - -/** [fill s start len c] modifies [s] in place, replacing [len] - characters with [c], starting at [start]. - - Raise [Invalid_argument] if [start] and [len] do not designate a - valid range of [s]. */ -let fill: (bytes, int, int, char) => unit - -/** [blit src srcoff dst dstoff len] copies [len] bytes from sequence - [src], starting at index [srcoff], to sequence [dst], starting at - index [dstoff]. It works correctly even if [src] and [dst] are the - same byte sequence, and the source and destination intervals - overlap. - - Raise [Invalid_argument] if [srcoff] and [len] do not - designate a valid range of [src], or if [dstoff] and [len] - do not designate a valid range of [dst]. */ -let blit: (bytes, int, bytes, int, int) => unit - -/** [blit src srcoff dst dstoff len] copies [len] bytes from string - [src], starting at index [srcoff], to byte sequence [dst], - starting at index [dstoff]. - - Raise [Invalid_argument] if [srcoff] and [len] do not - designate a valid range of [src], or if [dstoff] and [len] - do not designate a valid range of [dst]. */ -let blit_string: (string, int, bytes, int, int) => unit - -/** [concat sep sl] concatenates the list of byte sequences [sl], - inserting the separator byte sequence [sep] between each, and - returns the result as a new byte sequence. - - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. */ -let concat: (bytes, list) => bytes - -/** [cat s1 s2] concatenates [s1] and [s2] and returns the result - as new byte sequence. - - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. */ -let cat: (bytes, bytes) => bytes - -/** [iter f s] applies function [f] in turn to all the bytes of [s]. - It is equivalent to [f (get s 0); f (get s 1); ...; f (get s - (length s - 1)); ()]. */ -let iter: (char => unit, bytes) => unit - -/** Same as {!Bytes.iter}, but the function is applied to the index of - the byte as first argument and the byte itself as second - argument. */ -let iteri: ((int, char) => unit, bytes) => unit - -/** [map f s] applies function [f] in turn to all the bytes of [s] - (in increasing index order) and stores the resulting bytes in - a new sequence that is returned as the result. */ -let map: (char => char, bytes) => bytes - -/** [mapi f s] calls [f] with each character of [s] and its - index (in increasing index order) and stores the resulting bytes - in a new sequence that is returned as the result. */ -let mapi: ((int, char) => char, bytes) => bytes - -/** Return a copy of the argument, without leading and trailing - whitespace. The bytes regarded as whitespace are the ASCII - characters [' '], ['\x0c'], ['\n'], ['\r'], and ['\t']. */ -let trim: bytes => bytes - -/** Return a copy of the argument, with special characters represented - by escape sequences, following the lexical conventions of OCaml. - All characters outside the ASCII printable range (32..126) are - escaped, as well as backslash and double-quote. - - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. */ -let escaped: bytes => bytes - -/** [index s c] returns the index of the first occurrence of byte [c] - in [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let index: (bytes, char) => int - -/** [index_opt s c] returns the index of the first occurrence of byte [c] - in [s] or [None] if [c] does not occur in [s]. - @since 4.05 */ -let index_opt: (bytes, char) => option - -/** [rindex s c] returns the index of the last occurrence of byte [c] - in [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let rindex: (bytes, char) => int - -/** [rindex_opt s c] returns the index of the last occurrence of byte [c] - in [s] or [None] if [c] does not occur in [s]. - @since 4.05 */ -let rindex_opt: (bytes, char) => option - -/** [index_from s i c] returns the index of the first occurrence of - byte [c] in [s] after position [i]. [Bytes.index s c] is - equivalent to [Bytes.index_from s 0 c]. - - Raise [Invalid_argument] if [i] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] after position [i]. */ -let index_from: (bytes, int, char) => int - -/** [index_from _opts i c] returns the index of the first occurrence of - byte [c] in [s] after position [i] or [None] if [c] does not occur in [s] after position [i]. - [Bytes.index_opt s c] is equivalent to [Bytes.index_from_opt s 0 c]. - - Raise [Invalid_argument] if [i] is not a valid position in [s]. - @since 4.05 */ -let index_from_opt: (bytes, int, char) => option - -/** [rindex_from s i c] returns the index of the last occurrence of - byte [c] in [s] before position [i+1]. [rindex s c] is equivalent - to [rindex_from s (Bytes.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] before position [i+1]. */ -let rindex_from: (bytes, int, char) => int - -/** [rindex_from_opt s i c] returns the index of the last occurrence - of byte [c] in [s] before position [i+1] or [None] if [c] does not - occur in [s] before position [i+1]. [rindex_opt s c] is equivalent to - [rindex_from s (Bytes.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - @since 4.05 */ -let rindex_from_opt: (bytes, int, char) => option - -/** [contains s c] tests if byte [c] appears in [s]. */ -let contains: (bytes, char) => bool - -/** [contains_from s start c] tests if byte [c] appears in [s] after - position [start]. [contains s c] is equivalent to [contains_from - s 0 c]. - - Raise [Invalid_argument] if [start] is not a valid position in [s]. */ -let contains_from: (bytes, int, char) => bool - -/** [rcontains_from s stop c] tests if byte [c] appears in [s] before - position [stop+1]. - - Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid - position in [s]. */ -let rcontains_from: (bytes, int, char) => bool - -/** Return a copy of the argument, with all lowercase letters - translated to uppercase, using the US-ASCII character set. - @since 4.03.0 */ -let uppercase_ascii: bytes => bytes - -/** Return a copy of the argument, with all uppercase letters - translated to lowercase, using the US-ASCII character set. - @since 4.03.0 */ -let lowercase_ascii: bytes => bytes - -/** Return a copy of the argument, with the first character set to uppercase, - using the US-ASCII character set. - @since 4.03.0 */ -let capitalize_ascii: bytes => bytes - -/** Return a copy of the argument, with the first character set to lowercase, - using the US-ASCII character set. - @since 4.03.0 */ -let uncapitalize_ascii: bytes => bytes - -/** An alias for the type of byte sequences. */ -type t = bytes - -/** The comparison function for byte sequences, with the same - specification as {!Pervasives.compare}. Along with the type [t], - this function [compare] allows the module [Bytes] to be passed as - argument to the functors {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int - -/** The equality function for byte sequences. - @since 4.03.0 */ -let equal: (t, t) => bool - -/* {3 Unsafe conversions (for advanced users)} - - This section describes unsafe, low-level conversion functions - between [bytes] and [string]. They do not copy the internal data; - used improperly, they can break the immutability invariant on - strings provided by the [-safe-string] option. They are available for - expert library authors, but for most purposes you should use the - always-correct {!Bytes.to_string} and {!Bytes.of_string} instead. -*/ - -/** Unsafely convert a byte sequence into a string. - - To reason about the use of [unsafe_to_string], it is convenient to - consider an "ownership" discipline. A piece of code that - manipulates some data "owns" it; there are several disjoint ownership - modes, including: - - Unique ownership: the data may be accessed and mutated - - Shared ownership: the data has several owners, that may only - access it, not mutate it. - - Unique ownership is linear: passing the data to another piece of - code means giving up ownership (we cannot write the - data again). A unique owner may decide to make the data shared - (giving up mutation rights on it), but shared data may not become - uniquely-owned again. - - [unsafe_to_string s] can only be used when the caller owns the byte - sequence [s] -- either uniquely or as shared immutable data. The - caller gives up ownership of [s], and gains ownership of the - returned string. - - There are two valid use-cases that respect this ownership - discipline: - - 1. Creating a string by initializing and mutating a byte sequence - that is never changed after initialization is performed. - - {[ -let string_init len f : string = - let s = Bytes.create len in - for i = 0 to len - 1 do Bytes.set s i (f i) done; - Bytes.unsafe_to_string s - ]} - - This function is safe because the byte sequence [s] will never be - accessed or mutated after [unsafe_to_string] is called. The - [string_init] code gives up ownership of [s], and returns the - ownership of the resulting string to its caller. - - Note that it would be unsafe if [s] was passed as an additional - parameter to the function [f] as it could escape this way and be - mutated in the future -- [string_init] would give up ownership of - [s] to pass it to [f], and could not call [unsafe_to_string] - safely. - - We have provided the {!String.init}, {!String.map} and - {!String.mapi} functions to cover most cases of building - new strings. You should prefer those over [to_string] or - [unsafe_to_string] whenever applicable. - - 2. Temporarily giving ownership of a byte sequence to a function - that expects a uniquely owned string and returns ownership back, so - that we can mutate the sequence again after the call ended. - - {[ -let bytes_length (s : bytes) = - String.length (Bytes.unsafe_to_string s) - ]} - - In this use-case, we do not promise that [s] will never be mutated - after the call to [bytes_length s]. The {!String.length} function - temporarily borrows unique ownership of the byte sequence - (and sees it as a [string]), but returns this ownership back to - the caller, which may assume that [s] is still a valid byte - sequence after the call. Note that this is only correct because we - know that {!String.length} does not capture its argument -- it could - escape by a side-channel such as a memoization combinator. - - The caller may not mutate [s] while the string is borrowed (it has - temporarily given up ownership). This affects concurrent programs, - but also higher-order functions: if {!String.length} returned - a closure to be called later, [s] should not be mutated until this - closure is fully applied and returns ownership. -*/ -let unsafe_to_string: bytes => string - -/** Unsafely convert a shared string to a byte sequence that should - not be mutated. - - The same ownership discipline that makes [unsafe_to_string] - correct applies to [unsafe_of_string]: you may use it if you were - the owner of the [string] value, and you will own the return - [bytes] in the same mode. - - In practice, unique ownership of string values is extremely - difficult to reason about correctly. You should always assume - strings are shared, never uniquely owned. - - For example, string literals are implicitly shared by the - compiler, so you never uniquely own them. - - {[ -let incorrect = Bytes.unsafe_of_string "hello" -let s = Bytes.of_string "hello" - ]} - - The first declaration is incorrect, because the string literal - ["hello"] could be shared by the compiler with other parts of the - program, and mutating [incorrect] is a bug. You must always use - the second version, which performs a copy and is thus correct. - - Assuming unique ownership of strings that are not string - literals, but are (partly) built from string literals, is also - incorrect. For example, mutating [unsafe_of_string ("foo" ^ s)] - could mutate the shared string ["foo"] -- assuming a rope-like - representation of strings. More generally, functions operating on - strings will assume shared ownership, they do not preserve unique - ownership. It is thus incorrect to assume unique ownership of the - result of [unsafe_of_string]. - - The only case we have reasonable confidence is safe is if the - produced [bytes] is shared -- used as an immutable byte - sequence. This is possibly useful for incremental migration of - low-level programs that manipulate immutable sequences of bytes - (for example {!Marshal.from_bytes}) and previously used the - [string] type for this purpose. -*/ -let unsafe_of_string: string => bytes - -/* The following is for system use only. Do not call directly. */ - -external unsafe_get: (bytes, int) => char = "%bytes_unsafe_get" -external unsafe_set: (bytes, int, char) => unit = "%bytes_unsafe_set" diff --git a/jscomp/stdlib-406/bytesLabels.res b/jscomp/stdlib-406/bytesLabels.res deleted file mode 100644 index 527d76a20a..0000000000 Binary files a/jscomp/stdlib-406/bytesLabels.res and /dev/null differ diff --git a/jscomp/stdlib-406/bytesLabels.resi b/jscomp/stdlib-406/bytesLabels.resi deleted file mode 100644 index 411f939e20..0000000000 --- a/jscomp/stdlib-406/bytesLabels.resi +++ /dev/null @@ -1,269 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Byte sequence operations. - @since 4.02.0 -*/ - -/** Return the length (number of bytes) of the argument. */ -external length: bytes => int = "%bytes_length" - -/** [get s n] returns the byte at index [n] in argument [s]. - - Raise [Invalid_argument] if [n] is not a valid index in [s]. */ -external get: (bytes, int) => char = "%bytes_safe_get" - -/** [set s n c] modifies [s] in place, replacing the byte at index [n] - with [c]. - - Raise [Invalid_argument] if [n] is not a valid index in [s]. */ -external set: (bytes, int, char) => unit = "%bytes_safe_set" - -/** [create n] returns a new byte sequence of length [n]. The - sequence is uninitialized and contains arbitrary bytes. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -external create: int => bytes = "?create_bytes" - -/** [make n c] returns a new byte sequence of length [n], filled with - the byte [c]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let make: (int, char) => bytes - -/** [init n f] returns a fresh byte sequence of length [n], - with character [i] initialized to the result of [f i]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let init: (int, ~f: int => char) => bytes - -/** A byte sequence of size 0. */ -let empty: bytes - -/** Return a new byte sequence that contains the same bytes as the - argument. */ -let copy: bytes => bytes - -/** Return a new byte sequence that contains the same bytes as the - given string. */ -let of_string: string => bytes - -/** Return a new string that contains the same bytes as the given byte - sequence. */ -let to_string: bytes => string - -/** [sub s start len] returns a new byte sequence of length [len], - containing the subsequence of [s] that starts at position [start] - and has length [len]. - - Raise [Invalid_argument] if [start] and [len] do not designate a - valid range of [s]. */ -let sub: (bytes, ~pos: int, ~len: int) => bytes - -/** Same as [sub] but return a string instead of a byte sequence. */ -let sub_string: (bytes, ~pos: int, ~len: int) => string - -/** [extend s left right] returns a new byte sequence that contains - the bytes of [s], with [left] uninitialized bytes prepended and - [right] uninitialized bytes appended to it. If [left] or [right] - is negative, then bytes are removed (instead of appended) from - the corresponding side of [s]. - - Raise [Invalid_argument] if the result length is negative or - longer than {!Sys.max_string_length} bytes. - @since 4.05.0 */ -let extend: (bytes, ~left: int, ~right: int) => bytes - -/** [fill s start len c] modifies [s] in place, replacing [len] - characters with [c], starting at [start]. - - Raise [Invalid_argument] if [start] and [len] do not designate a - valid range of [s]. */ -let fill: (bytes, ~pos: int, ~len: int, char) => unit - -/** [blit src srcoff dst dstoff len] copies [len] bytes from sequence - [src], starting at index [srcoff], to sequence [dst], starting at - index [dstoff]. It works correctly even if [src] and [dst] are the - same byte sequence, and the source and destination intervals - overlap. - - Raise [Invalid_argument] if [srcoff] and [len] do not - designate a valid range of [src], or if [dstoff] and [len] - do not designate a valid range of [dst]. */ -let blit: (~src: bytes, ~src_pos: int, ~dst: bytes, ~dst_pos: int, ~len: int) => unit - -/** [blit src srcoff dst dstoff len] copies [len] bytes from string - [src], starting at index [srcoff], to byte sequence [dst], - starting at index [dstoff]. - - Raise [Invalid_argument] if [srcoff] and [len] do not - designate a valid range of [src], or if [dstoff] and [len] - do not designate a valid range of [dst]. - @since 4.05.0 */ -let blit_string: (~src: string, ~src_pos: int, ~dst: bytes, ~dst_pos: int, ~len: int) => unit - -/** [concat sep sl] concatenates the list of byte sequences [sl], - inserting the separator byte sequence [sep] between each, and - returns the result as a new byte sequence. */ -let concat: (~sep: bytes, list) => bytes - -/** [cat s1 s2] concatenates [s1] and [s2] and returns the result - as new byte sequence. - - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. - @since 4.05.0 */ -let cat: (bytes, bytes) => bytes - -/** [iter f s] applies function [f] in turn to all the bytes of [s]. - It is equivalent to [f (get s 0); f (get s 1); ...; f (get s - (length s - 1)); ()]. */ -let iter: (~f: char => unit, bytes) => unit - -/** Same as {!Bytes.iter}, but the function is applied to the index of - the byte as first argument and the byte itself as second - argument. */ -let iteri: (~f: (int, char) => unit, bytes) => unit - -/** [map f s] applies function [f] in turn to all the bytes of [s] and - stores the resulting bytes in a new sequence that is returned as - the result. */ -let map: (~f: char => char, bytes) => bytes - -/** [mapi f s] calls [f] with each character of [s] and its - index (in increasing index order) and stores the resulting bytes - in a new sequence that is returned as the result. */ -let mapi: (~f: (int, char) => char, bytes) => bytes - -/** Return a copy of the argument, without leading and trailing - whitespace. The bytes regarded as whitespace are the ASCII - characters [' '], ['\x0c'], ['\n'], ['\r'], and ['\t']. */ -let trim: bytes => bytes - -/** Return a copy of the argument, with special characters represented - by escape sequences, following the lexical conventions of OCaml. */ -let escaped: bytes => bytes - -/** [index s c] returns the index of the first occurrence of byte [c] - in [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let index: (bytes, char) => int - -/** [index_opt s c] returns the index of the first occurrence of byte [c] - in [s] or [None] if [c] does not occur in [s]. - @since 4.05 */ -let index_opt: (bytes, char) => option - -/** [rindex s c] returns the index of the last occurrence of byte [c] - in [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let rindex: (bytes, char) => int - -/** [rindex_opt s c] returns the index of the last occurrence of byte [c] - in [s] or [None] if [c] does not occur in [s]. - @since 4.05 */ -let rindex_opt: (bytes, char) => option - -/** [index_from s i c] returns the index of the first occurrence of - byte [c] in [s] after position [i]. [Bytes.index s c] is - equivalent to [Bytes.index_from s 0 c]. - - Raise [Invalid_argument] if [i] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] after position [i]. */ -let index_from: (bytes, int, char) => int - -/** [index_from _opts i c] returns the index of the first occurrence of - byte [c] in [s] after position [i] or [None] if [c] does not occur in [s] after position [i]. - [Bytes.index_opt s c] is equivalent to [Bytes.index_from_opt s 0 c]. - - Raise [Invalid_argument] if [i] is not a valid position in [s]. - @since 4.05 */ -let index_from_opt: (bytes, int, char) => option - -/** [rindex_from s i c] returns the index of the last occurrence of - byte [c] in [s] before position [i+1]. [rindex s c] is equivalent - to [rindex_from s (Bytes.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] before position [i+1]. */ -let rindex_from: (bytes, int, char) => int - -/** [rindex_from_opt s i c] returns the index of the last occurrence - of byte [c] in [s] before position [i+1] or [None] if [c] does not - occur in [s] before position [i+1]. [rindex_opt s c] is equivalent to - [rindex_from s (Bytes.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - @since 4.05 */ -let rindex_from_opt: (bytes, int, char) => option - -/** [contains s c] tests if byte [c] appears in [s]. */ -let contains: (bytes, char) => bool - -/** [contains_from s start c] tests if byte [c] appears in [s] after - position [start]. [contains s c] is equivalent to [contains_from - s 0 c]. - - Raise [Invalid_argument] if [start] is not a valid position in [s]. */ -let contains_from: (bytes, int, char) => bool - -/** [rcontains_from s stop c] tests if byte [c] appears in [s] before - position [stop+1]. - - Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid - position in [s]. */ -let rcontains_from: (bytes, int, char) => bool - -/** Return a copy of the argument, with all lowercase letters - translated to uppercase, using the US-ASCII character set. - @since 4.05.0 */ -let uppercase_ascii: bytes => bytes - -/** Return a copy of the argument, with all uppercase letters - translated to lowercase, using the US-ASCII character set. - @since 4.05.0 */ -let lowercase_ascii: bytes => bytes - -/** Return a copy of the argument, with the first character set to uppercase, - using the US-ASCII character set. - @since 4.05.0 */ -let capitalize_ascii: bytes => bytes - -/** Return a copy of the argument, with the first character set to lowercase, - using the US-ASCII character set. - @since 4.05.0 */ -let uncapitalize_ascii: bytes => bytes - -/** An alias for the type of byte sequences. */ -type t = bytes - -/** The comparison function for byte sequences, with the same - specification as {!Pervasives.compare}. Along with the type [t], - this function [compare] allows the module [Bytes] to be passed as - argument to the functors {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int - -/** The equality function for byte sequences. - @since 4.05.0 */ -let equal: (t, t) => bool - -/* The following is for system use only. Do not call directly. */ - -external unsafe_get: (bytes, int) => char = "%bytes_unsafe_get" -external unsafe_set: (bytes, int, char) => unit = "%bytes_unsafe_set" -let unsafe_to_string: bytes => string -let unsafe_of_string: string => bytes diff --git a/jscomp/stdlib-406/callback.res b/jscomp/stdlib-406/callback.res deleted file mode 100644 index 89d44b6368..0000000000 --- a/jscomp/stdlib-406/callback.res +++ /dev/null @@ -1,19 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ -@@config({flags: ["-bs-no-cross-module-opt"]}) -/* Registering OCaml values with the C runtime for later callbacks */ - -let register = (_, _) => () -let register_exception = (_, _) => () diff --git a/jscomp/stdlib-406/callback.resi b/jscomp/stdlib-406/callback.resi deleted file mode 100644 index bff728306d..0000000000 --- a/jscomp/stdlib-406/callback.resi +++ /dev/null @@ -1,34 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Registering OCaml values with the C runtime. - - This module allows OCaml values to be registered with the C runtime - under a symbolic name, so that C code can later call back registered - OCaml functions, or raise registered OCaml exceptions. -*/ - -/** [Callback.register n v] registers the value [v] under - the name [n]. C code can later retrieve a handle to [v] - by calling [caml_named_value(n)]. */ -let register: (string, 'a) => unit - -/** [Callback.register_exception n exn] registers the - exception contained in the exception value [exn] - under the name [n]. C code can later retrieve a handle to - the exception by calling [caml_named_value(n)]. The exception - value thus obtained is suitable for passing as first argument - to [raise_constant] or [raise_with_arg]. */ -let register_exception: (string, exn) => unit diff --git a/jscomp/stdlib-406/complex.res b/jscomp/stdlib-406/complex.res deleted file mode 100644 index 4b0561011f..0000000000 --- a/jscomp/stdlib-406/complex.res +++ /dev/null @@ -1,112 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 2002 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Complex numbers */ - -type t = {re: float, im: float} - -let zero = {re: 0.0, im: 0.0} -let one = {re: 1.0, im: 0.0} -let i = {re: 0.0, im: 1.0} - -let add = (x, y) => {re: x.re +. y.re, im: x.im +. y.im} - -let sub = (x, y) => {re: x.re -. y.re, im: x.im -. y.im} - -let neg = x => {re: -.x.re, im: -.x.im} - -let conj = x => {re: x.re, im: -.x.im} - -let mul = (x, y) => { - re: x.re *. y.re -. x.im *. y.im, - im: x.re *. y.im +. x.im *. y.re, -} - -let div = (x, y) => - if abs_float(y.re) >= abs_float(y.im) { - let r = y.im /. y.re - let d = y.re +. r *. y.im - { - re: (x.re +. r *. x.im) /. d, - im: (x.im -. r *. x.re) /. d, - } - } else { - let r = y.re /. y.im - let d = y.im +. r *. y.re - { - re: (r *. x.re +. x.im) /. d, - im: (r *. x.im -. x.re) /. d, - } - } - -let inv = x => div(one, x) - -let norm2 = x => x.re *. x.re +. x.im *. x.im - -let norm = x => { - /* Watch out for overflow in computing re^2 + im^2 */ - let r = abs_float(x.re) - and i = abs_float(x.im) - if r == 0.0 { - i - } else if i == 0.0 { - r - } else if r >= i { - let q = i /. r - r *. sqrt(1.0 +. q *. q) - } else { - let q = r /. i - i *. sqrt(1.0 +. q *. q) - } -} - -let arg = x => atan2(x.im, x.re) - -let polar = (n, a) => {re: cos(a) *. n, im: sin(a) *. n} - -let sqrt = x => - if x.re == 0.0 && x.im == 0.0 { - {re: 0.0, im: 0.0} - } else { - let r = abs_float(x.re) and i = abs_float(x.im) - let w = if r >= i { - let q = i /. r - sqrt(r) *. sqrt(0.5 *. (1.0 +. sqrt(1.0 +. q *. q))) - } else { - let q = r /. i - sqrt(i) *. sqrt(0.5 *. (q +. sqrt(1.0 +. q *. q))) - } - if x.re >= 0.0 { - {re: w, im: 0.5 *. x.im /. w} - } else { - { - re: 0.5 *. i /. w, - im: if x.im >= 0.0 { - w - } else { - -.w - }, - } - } - } - -let exp = x => { - let e = exp(x.re) - {re: e *. cos(x.im), im: e *. sin(x.im)} -} - -let log = x => {re: log(norm(x)), im: atan2(x.im, x.re)} - -let pow = (x, y) => exp(mul(y, log(x))) diff --git a/jscomp/stdlib-406/complex.resi b/jscomp/stdlib-406/complex.resi deleted file mode 100644 index bacdc477d5..0000000000 --- a/jscomp/stdlib-406/complex.resi +++ /dev/null @@ -1,86 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 2002 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Complex numbers. - - This module provides arithmetic operations on complex numbers. - Complex numbers are represented by their real and imaginary parts - (cartesian representation). Each part is represented by a - double-precision floating-point number (type [float]). */ - -/** The type of complex numbers. [re] is the real part and [im] the - imaginary part. */ -type t = {re: float, im: float} - -/** The complex number [0]. */ -let zero: t - -/** The complex number [1]. */ -let one: t - -/** The complex number [i]. */ -let i: t - -/** Unary negation. */ -let neg: t => t - -/** Conjugate: given the complex [x + i.y], returns [x - i.y]. */ -let conj: t => t - -/** Addition */ -let add: (t, t) => t - -/** Subtraction */ -let sub: (t, t) => t - -/** Multiplication */ -let mul: (t, t) => t - -/** Multiplicative inverse ([1/z]). */ -let inv: t => t - -/** Division */ -let div: (t, t) => t - -/** Square root. The result [x + i.y] is such that [x > 0] or - [x = 0] and [y >= 0]. - This function has a discontinuity along the negative real axis. */ -let sqrt: t => t - -/** Norm squared: given [x + i.y], returns [x^2 + y^2]. */ -let norm2: t => float - -/** Norm: given [x + i.y], returns [sqrt(x^2 + y^2)]. */ -let norm: t => float - -/** Argument. The argument of a complex number is the angle - in the complex plane between the positive real axis and a line - passing through zero and the number. This angle ranges from - [-pi] to [pi]. This function has a discontinuity along the - negative real axis. */ -let arg: t => float - -/** [polar norm arg] returns the complex having norm [norm] - and argument [arg]. */ -let polar: (float, float) => t - -/** Exponentiation. [exp z] returns [e] to the [z] power. */ -let exp: t => t - -/** Natural logarithm (in base [e]). */ -let log: t => t - -/** Power function. [pow z1 z2] returns [z1] to the [z2] power. */ -let pow: (t, t) => t diff --git a/jscomp/stdlib-406/digest.res b/jscomp/stdlib-406/digest.res deleted file mode 100644 index d922290395..0000000000 --- a/jscomp/stdlib-406/digest.res +++ /dev/null @@ -1,78 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Message digest (MD5) */ - -type t = string - -let compare = String.compare -let equal = String.equal - -external unsafe_string: (string, int, int) => t = "?md5_string" - -let string = str => unsafe_string(str, 0, String.length(str)) - -let bytes = b => string(Bytes.unsafe_to_string(b)) - -let substring = (str, ofs, len) => - if ofs < 0 || (len < 0 || ofs > String.length(str) - len) { - invalid_arg("Digest.substring") - } else { - unsafe_string(str, ofs, len) - } - -let subbytes = (b, ofs, len) => substring(Bytes.unsafe_to_string(b), ofs, len) - -let char_hex = n => - Char.unsafe_chr( - n + if n < 10 { - Char.code('0') - } else { - Char.code('a') - 10 - }, - ) - -let to_hex = d => { - if String.length(d) != 16 { - invalid_arg("Digest.to_hex") - } - let result = Bytes.create(32) - for i in 0 to 15 { - let x = Char.code(String.get(d, i)) - Bytes.unsafe_set(result, i * 2, char_hex(lsr(x, 4))) - Bytes.unsafe_set(result, i * 2 + 1, char_hex(land(x, 0x0f))) - } - Bytes.unsafe_to_string(result) -} - -let from_hex = s => { - if String.length(s) != 32 { - invalid_arg("Digest.from_hex") - } - let digit = c => - switch c { - | '0' .. '9' => Char.code(c) - Char.code('0') - | 'A' .. 'F' => Char.code(c) - Char.code('A') + 10 - | 'a' .. 'f' => Char.code(c) - Char.code('a') + 10 - | _ => raise(Invalid_argument("Digest.from_hex")) - } - - let byte = i => lsl(digit(String.get(s, i)), 4) + digit(String.get(s, i + 1)) - let result = Bytes.create(16) - for i in 0 to 15 { - Bytes.set(result, i, Char.chr(byte(2 * i))) - } - Bytes.unsafe_to_string(result) -} diff --git a/jscomp/stdlib-406/digest.resi b/jscomp/stdlib-406/digest.resi deleted file mode 100644 index bcedb527e5..0000000000 --- a/jscomp/stdlib-406/digest.resi +++ /dev/null @@ -1,67 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** MD5 message digest. - - This module provides functions to compute 128-bit 'digests' of - arbitrary-length strings or files. The digests are of cryptographic - quality: it is very hard, given a digest, to forge a string having - that digest. The algorithm used is MD5. This module should not be - used for secure and sensitive cryptographic applications. For these - kind of applications more recent and stronger cryptographic - primitives should be used instead. -*/ - -/** The type of digests: 16-character strings. */ -type t = string - -/** The comparison function for 16-character digest, with the same - specification as {!Pervasives.compare} and the implementation - shared with {!String.compare}. Along with the type [t], this - function [compare] allows the module [Digest] to be passed as - argument to the functors {!Set.Make} and {!Map.Make}. - @since 4.00.0 */ -let compare: (t, t) => int - -/** The equal function for 16-character digest. - @since 4.03.0 */ -let equal: (t, t) => bool - -/** Return the digest of the given string. */ -let string: string => t - -/** Return the digest of the given byte sequence. - @since 4.02.0 */ -let bytes: bytes => t - -/** [Digest.substring s ofs len] returns the digest of the substring - of [s] starting at index [ofs] and containing [len] characters. */ -let substring: (string, int, int) => t - -/** [Digest.subbytes s ofs len] returns the digest of the subsequence - of [s] starting at index [ofs] and containing [len] bytes. - @since 4.02.0 */ -let subbytes: (bytes, int, int) => t - -/** Return the printable hexadecimal representation of the given digest. - Raise [Invalid_argument] if the argument is not exactly 16 bytes. - */ -let to_hex: t => string - -/** Convert a hexadecimal representation back into the corresponding digest. - Raise [Invalid_argument] if the argument is not exactly 32 hexadecimal - characters. - @since 4.00.0 */ -let from_hex: string => t diff --git a/jscomp/stdlib-406/filename.res b/jscomp/stdlib-406/filename.res deleted file mode 100644 index 0dcb014b31..0000000000 --- a/jscomp/stdlib-406/filename.res +++ /dev/null @@ -1,353 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -let generic_quote = (quotequote, s) => { - let l = String.length(s) - let b = Buffer.create(l + 20) - Buffer.add_char(b, '\'') - for i in 0 to l - 1 { - if String.get(s, i) == '\'' { - Buffer.add_string(b, quotequote) - } else { - Buffer.add_char(b, String.get(s, i)) - } - } - Buffer.add_char(b, '\'') - Buffer.contents(b) -} - -/* This function implements the Open Group specification found here: - [[1]] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html - In step 1 of [[1]], we choose to return "." for empty input. - (for compatibility with previous versions of OCaml) - In step 2, we choose to process "//" normally. - Step 6 is not implemented: we consider that the [suffix] operand is - always absent. Suffixes are handled by [chop_suffix] and [chop_extension]. -*/ -let generic_basename = (is_dir_sep, current_dir_name, name) => { - let rec find_end = n => - if n < 0 { - String.sub(name, 0, 1) - } else if is_dir_sep(name, n) { - find_end(n - 1) - } else { - find_beg(n, n + 1) - } - and find_beg = (n, p) => - if n < 0 { - String.sub(name, 0, p) - } else if is_dir_sep(name, n) { - String.sub(name, n + 1, p - n - 1) - } else { - find_beg(n - 1, p) - } - - if name == "" { - current_dir_name - } else { - find_end(String.length(name) - 1) - } -} - -/* This function implements the Open Group specification found here: - [[2]] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html - In step 6 of [[2]], we choose to process "//" normally. -*/ -let generic_dirname = (is_dir_sep, current_dir_name, name) => { - let rec trailing_sep = n => - if n < 0 { - String.sub(name, 0, 1) - } else if is_dir_sep(name, n) { - trailing_sep(n - 1) - } else { - base(n) - } - and base = n => - if n < 0 { - current_dir_name - } else if is_dir_sep(name, n) { - intermediate_sep(n) - } else { - base(n - 1) - } - and intermediate_sep = n => - if n < 0 { - String.sub(name, 0, 1) - } else if is_dir_sep(name, n) { - intermediate_sep(n - 1) - } else { - String.sub(name, 0, n + 1) - } - - if name == "" { - current_dir_name - } else { - trailing_sep(String.length(name) - 1) - } -} - -module Unix = { - let current_dir_name = "." - let parent_dir_name = ".." - let dir_sep = "/" - let is_dir_sep = (s, i) => String.get(s, i) == '/' - let is_relative = n => String.length(n) < 1 || String.get(n, 0) != '/' - let is_implicit = n => - is_relative(n) && - ((String.length(n) < 2 || String.sub(n, 0, 2) != "./") && - (String.length(n) < 3 || String.sub(n, 0, 3) != "../")) - let check_suffix = (name, suff) => - String.length(name) >= String.length(suff) && - String.sub(name, String.length(name) - String.length(suff), String.length(suff)) == suff - let temp_dir_name = try Sys.getenv("TMPDIR") catch { - | Not_found => "/tmp" - } - let quote = generic_quote("'\\''") - let basename = generic_basename(is_dir_sep, current_dir_name) - let dirname = generic_dirname(is_dir_sep, current_dir_name) -} - -module Win32 = { - let current_dir_name = "." - let parent_dir_name = ".." - let dir_sep = "\\" - let is_dir_sep = (s, i) => { - let c = String.get(s, i) - c == '/' || (c == '\\' || c == ':') - } - let is_relative = n => - (String.length(n) < 1 || String.get(n, 0) != '/') && - ((String.length(n) < 1 || String.get(n, 0) != '\\') && - (String.length(n) < 2 || String.get(n, 1) != ':')) - let is_implicit = n => - is_relative(n) && - ((String.length(n) < 2 || String.sub(n, 0, 2) != "./") && - ((String.length(n) < 2 || String.sub(n, 0, 2) != ".\\") && - ((String.length(n) < 3 || String.sub(n, 0, 3) != "../") && - (String.length(n) < 3 || String.sub(n, 0, 3) != "..\\")))) - let check_suffix = (name, suff) => - String.length(name) >= String.length(suff) && { - let s = String.sub(name, String.length(name) - String.length(suff), String.length(suff)) - String.lowercase_ascii(s) == String.lowercase_ascii(suff) - } - let temp_dir_name = try Sys.getenv("TEMP") catch { - | Not_found => "." - } - let quote = s => { - let l = String.length(s) - let b = Buffer.create(l + 20) - Buffer.add_char(b, '"') - let rec loop = i => - if i == l { - Buffer.add_char(b, '"') - } else { - switch String.get(s, i) { - | '"' => loop_bs(0, i) - | '\\' => loop_bs(0, i) - | c => - Buffer.add_char(b, c) - loop(i + 1) - } - } - and loop_bs = (n, i) => - if i == l { - Buffer.add_char(b, '"') - add_bs(n) - } else { - switch String.get(s, i) { - | '"' => - add_bs(2 * n + 1) - Buffer.add_char(b, '"') - loop(i + 1) - | '\\' => loop_bs(n + 1, i + 1) - | _ => - add_bs(n) - loop(i) - } - } - and add_bs = n => - for _j in 1 to n { - Buffer.add_char(b, '\\') - } - - loop(0) - Buffer.contents(b) - } - let has_drive = s => { - let is_letter = param => - switch param { - | 'A' .. 'Z' | 'a' .. 'z' => true - | _ => false - } - - String.length(s) >= 2 && (is_letter(String.get(s, 0)) && String.get(s, 1) == ':') - } - let drive_and_path = s => - if has_drive(s) { - (String.sub(s, 0, 2), String.sub(s, 2, String.length(s) - 2)) - } else { - ("", s) - } - let dirname = s => { - let (drive, path) = drive_and_path(s) - let dir = generic_dirname(is_dir_sep, current_dir_name, path) - drive ++ dir - } - let basename = s => { - let (_drive, path) = drive_and_path(s) - generic_basename(is_dir_sep, current_dir_name, path) - } -} - -module Cygwin = { - let current_dir_name = "." - let parent_dir_name = ".." - let dir_sep = "/" - let is_dir_sep = Win32.is_dir_sep - let is_relative = Win32.is_relative - let is_implicit = Win32.is_implicit - let check_suffix = Win32.check_suffix - let temp_dir_name = Unix.temp_dir_name - let quote = Unix.quote - let basename = generic_basename(is_dir_sep, current_dir_name) - let dirname = generic_dirname(is_dir_sep, current_dir_name) -} - -let ( - current_dir_name, - parent_dir_name, - dir_sep, - is_dir_sep, - is_relative, - is_implicit, - check_suffix, - temp_dir_name, - quote, - basename, - dirname, -) = switch Sys.os_type { -| "Win32" => ( - Win32.current_dir_name, - Win32.parent_dir_name, - Win32.dir_sep, - Win32.is_dir_sep, - Win32.is_relative, - Win32.is_implicit, - Win32.check_suffix, - Win32.temp_dir_name, - Win32.quote, - Win32.basename, - Win32.dirname, - ) -| "Cygwin" => ( - Cygwin.current_dir_name, - Cygwin.parent_dir_name, - Cygwin.dir_sep, - Cygwin.is_dir_sep, - Cygwin.is_relative, - Cygwin.is_implicit, - Cygwin.check_suffix, - Cygwin.temp_dir_name, - Cygwin.quote, - Cygwin.basename, - Cygwin.dirname, - ) -| _ => /* normally "Unix" */ - ( - Unix.current_dir_name, - Unix.parent_dir_name, - Unix.dir_sep, - Unix.is_dir_sep, - Unix.is_relative, - Unix.is_implicit, - Unix.check_suffix, - Unix.temp_dir_name, - Unix.quote, - Unix.basename, - Unix.dirname, - ) -} - -let concat = (dirname, filename) => { - let l = String.length(dirname) - if l == 0 || is_dir_sep(dirname, l - 1) { - dirname ++ filename - } else { - dirname ++ (dir_sep ++ filename) - } -} - -let chop_suffix = (name, suff) => { - let n = String.length(name) - String.length(suff) - if n < 0 { - invalid_arg("Filename.chop_suffix") - } else { - String.sub(name, 0, n) - } -} - -let extension_len = name => { - let rec check = (i0, i) => - if i < 0 || is_dir_sep(name, i) { - 0 - } else if String.get(name, i) == '.' { - check(i0, i - 1) - } else { - String.length(name) - i0 - } - - let rec search_dot = i => - if i < 0 || is_dir_sep(name, i) { - 0 - } else if String.get(name, i) == '.' { - check(i, i - 1) - } else { - search_dot(i - 1) - } - - search_dot(String.length(name) - 1) -} - -let extension = name => { - let l = extension_len(name) - if l == 0 { - "" - } else { - String.sub(name, String.length(name) - l, l) - } -} - -let chop_extension = name => { - let l = extension_len(name) - if l == 0 { - invalid_arg("Filename.chop_extension") - } else { - String.sub(name, 0, String.length(name) - l) - } -} - -let remove_extension = name => { - let l = extension_len(name) - if l == 0 { - name - } else { - String.sub(name, 0, String.length(name) - l) - } -} - -let current_temp_dir_name = ref(temp_dir_name) - -let set_temp_dir_name = s => current_temp_dir_name := s -let get_temp_dir_name = () => current_temp_dir_name.contents diff --git a/jscomp/stdlib-406/filename.resi b/jscomp/stdlib-406/filename.resi deleted file mode 100644 index e9da0f7634..0000000000 --- a/jscomp/stdlib-406/filename.resi +++ /dev/null @@ -1,132 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Operations on file names. */ - -/** The conventional name for the current directory (e.g. [.] in Unix). */ -let current_dir_name: string - -/** The conventional name for the parent of the current directory - (e.g. [..] in Unix). */ -let parent_dir_name: string - -/** The directory separator (e.g. [/] in Unix). @since 3.11.2 */ -let dir_sep: string - -/** [concat dir file] returns a file name that designates file - [file] in directory [dir]. */ -let concat: (string, string) => string - -/** Return [true] if the file name is relative to the current - directory, [false] if it is absolute (i.e. in Unix, starts - with [/]). */ -let is_relative: string => bool - -/** Return [true] if the file name is relative and does not start - with an explicit reference to the current directory ([./] or - [../] in Unix), [false] if it starts with an explicit reference - to the root directory or the current directory. */ -let is_implicit: string => bool - -/** [check_suffix name suff] returns [true] if the filename [name] - ends with the suffix [suff]. */ -let check_suffix: (string, string) => bool - -/** [chop_suffix name suff] removes the suffix [suff] from - the filename [name]. The behavior is undefined if [name] does not - end with the suffix [suff]. */ -let chop_suffix: (string, string) => string - -/** [extension name] is the shortest suffix [ext] of [name0] where: - - - [name0] is the longest suffix of [name] that does not - contain a directory separator; - - [ext] starts with a period; - - [ext] is preceded by at least one non-period character - in [name0]. - - If such a suffix does not exist, [extension name] is the empty - string. - - @since 4.04 -*/ -let extension: string => string - -/** Return the given file name without its extension, as defined - in {!Filename.extension}. If the extension is empty, the function - returns the given file name. - - The following invariant holds for any file name [s]: - - [remove_extension s ^ extension s = s] - - @since 4.04 -*/ -let remove_extension: string => string - -/** Same as {!Filename.remove_extension}, but raise [Invalid_argument] - if the given name has an empty extension. */ -let chop_extension: string => string - -/** Split a file name into directory name / base file name. - If [name] is a valid file name, then [concat (dirname name) (basename name)] - returns a file name which is equivalent to [name]. Moreover, - after setting the current directory to [dirname name] (with {!Sys.chdir}), - references to [basename name] (which is a relative file name) - designate the same file as [name] before the call to {!Sys.chdir}. - - This function conforms to the specification of POSIX.1-2008 for the - [basename] utility. */ -let basename: string => string - -/** See {!Filename.basename}. - This function conforms to the specification of POSIX.1-2008 for the - [dirname] utility. */ -let dirname: string => string - -/** The name of the temporary directory: - Under Unix, the value of the [TMPDIR] environment variable, or "/tmp" - if the variable is not set. - Under Windows, the value of the [TEMP] environment variable, or "." - if the variable is not set. - The temporary directory can be changed with {!Filename.set_temp_dir_name}. - @since 4.00.0 -*/ -let get_temp_dir_name: unit => string - -/** Change the temporary directory returned by {!Filename.get_temp_dir_name} - and used by {!Filename.temp_file} and {!Filename.open_temp_file}. - @since 4.00.0 -*/ -let set_temp_dir_name: string => unit - -@deprecated("Use Filename.get_temp_dir_name instead") -/** The name of the initial temporary directory: - Under Unix, the value of the [TMPDIR] environment variable, or "/tmp" - if the variable is not set. - Under Windows, the value of the [TEMP] environment variable, or "." - if the variable is not set. - @deprecated You should use {!Filename.get_temp_dir_name} instead. - @since 3.09.1 -*/ -let temp_dir_name: string - -/** Return a quoted version of a file name, suitable for use as - one argument in a command line, escaping all meta-characters. - Warning: under Windows, the output is only suitable for use - with programs that follow the standard Windows quoting - conventions. - */ -let quote: string => string diff --git a/jscomp/stdlib-406/genlex.res b/jscomp/stdlib-406/genlex.res deleted file mode 100644 index bb6ef2409a..0000000000 --- a/jscomp/stdlib-406/genlex.res +++ /dev/null @@ -1,353 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -type token = - | Kwd(string) - | Ident(string) - | Int(int) - | Float(float) - | String(string) - | Char(char) - -/* The string buffering machinery */ - -let initial_buffer = Bytes.create(32) - -let buffer = ref(initial_buffer) -let bufpos = ref(0) - -let reset_buffer = () => { - buffer := initial_buffer - bufpos := 0 -} - -let store = c => { - if bufpos.contents >= Bytes.length(buffer.contents) { - let newbuffer = Bytes.create(2 * bufpos.contents) - Bytes.blit(buffer.contents, 0, newbuffer, 0, bufpos.contents) - buffer := newbuffer - } - Bytes.set(buffer.contents, bufpos.contents, c) - incr(bufpos) -} - -let get_string = () => { - let s = Bytes.sub_string(buffer.contents, 0, bufpos.contents) - buffer := initial_buffer - s -} - -/* The lexer */ - -let make_lexer = keywords => { - let kwd_table = Hashtbl.create(17) - List.iter(s => Hashtbl.add(kwd_table, s, Kwd(s)), keywords) - let ident_or_keyword = id => - try Hashtbl.find(kwd_table, id) catch { - | Not_found => Ident(id) - } - and keyword_or_error = c => { - let s = String.make(1, c) - try Hashtbl.find(kwd_table, s) catch { - | Not_found => raise(Stream.Error("Illegal character " ++ s)) - } - } - - let rec next_token = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some(' ' | '\n' | '\r' | '\t' | '' | ' ') => - Stream.junk(strm__) - next_token(strm__) - | Some(('A' .. 'Z' | 'a' .. 'z' | '_' | 'À' .. 'ÿ') as c) => - Stream.junk(strm__) - let s = strm__ - reset_buffer() - store(c) - ident(s) - | Some( - ('!' - | '%' - | '&' - | '$' - | '#' - | '+' - | '/' - | ':' - | '<' - | '=' - | '>' - | '?' - | '@' - | '\\' - | '~' - | '^' - | '|' - | '*') as c, - ) => - Stream.junk(strm__) - let s = strm__ - reset_buffer() - store(c) - ident2(s) - | Some('0' .. '9' as c) => - Stream.junk(strm__) - let s = strm__ - reset_buffer() - store(c) - number(s) - | Some('\'') => - Stream.junk(strm__) - let c = try char(strm__) catch { - | Stream.Failure => raise(Stream.Error("")) - } - - switch Stream.peek(strm__) { - | Some('\'') => - Stream.junk(strm__) - Some(Char(c)) - | _ => raise(Stream.Error("")) - } - | Some('"') => - Stream.junk(strm__) - let s = strm__ - reset_buffer() - Some(String(string(s))) - | Some('-') => - Stream.junk(strm__) - neg_number(strm__) - | Some('(') => - Stream.junk(strm__) - maybe_comment(strm__) - | Some(c) => - Stream.junk(strm__) - Some(keyword_or_error(c)) - | _ => None - } - and ident = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some(('A' .. 'Z' | 'a' .. 'z' | 'À' .. 'ÿ' | '0' .. '9' | '_' | '\'') as c) => - Stream.junk(strm__) - let s = strm__ - store(c) - ident(s) - | _ => Some(ident_or_keyword(get_string())) - } - and ident2 = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some( - ('!' - | '%' - | '&' - | '$' - | '#' - | '+' - | '-' - | '/' - | ':' - | '<' - | '=' - | '>' - | '?' - | '@' - | '\\' - | '~' - | '^' - | '|' - | '*') as c, - ) => - Stream.junk(strm__) - let s = strm__ - store(c) - ident2(s) - | _ => Some(ident_or_keyword(get_string())) - } - and neg_number = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('0' .. '9' as c) => - Stream.junk(strm__) - let s = strm__ - reset_buffer() - store('-') - store(c) - number(s) - | _ => - let s = strm__ - reset_buffer() - store('-') - ident2(s) - } - and number = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('0' .. '9' as c) => - Stream.junk(strm__) - let s = strm__ - store(c) - number(s) - | Some('.') => - Stream.junk(strm__) - let s = strm__ - store('.') - decimal_part(s) - | Some('e' | 'E') => - Stream.junk(strm__) - let s = strm__ - store('E') - exponent_part(s) - | _ => Some(Int(int_of_string(get_string()))) - } - and decimal_part = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('0' .. '9' as c) => - Stream.junk(strm__) - let s = strm__ - store(c) - decimal_part(s) - | Some('e' | 'E') => - Stream.junk(strm__) - let s = strm__ - store('E') - exponent_part(s) - | _ => Some(Float(float_of_string(get_string()))) - } - and exponent_part = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some(('+' | '-') as c) => - Stream.junk(strm__) - let s = strm__ - store(c) - end_exponent_part(s) - | _ => end_exponent_part(strm__) - } - and end_exponent_part = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('0' .. '9' as c) => - Stream.junk(strm__) - let s = strm__ - store(c) - end_exponent_part(s) - | _ => Some(Float(float_of_string(get_string()))) - } - and string = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('"') => - Stream.junk(strm__) - get_string() - | Some('\\') => - Stream.junk(strm__) - let c = try escape(strm__) catch { - | Stream.Failure => raise(Stream.Error("")) - } - - let s = strm__ - store(c) - string(s) - | Some(c) => - Stream.junk(strm__) - let s = strm__ - store(c) - string(s) - | _ => raise(Stream.Failure) - } - and char = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('\\') => - Stream.junk(strm__) - try escape(strm__) catch { - | Stream.Failure => raise(Stream.Error("")) - } - | Some(c) => - Stream.junk(strm__) - c - | _ => raise(Stream.Failure) - } - and escape = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('n') => - Stream.junk(strm__) - '\n' - | Some('r') => - Stream.junk(strm__) - '\r' - | Some('t') => - Stream.junk(strm__) - '\t' - | Some('0' .. '9' as c1) => - Stream.junk(strm__) - switch Stream.peek(strm__) { - | Some('0' .. '9' as c2) => - Stream.junk(strm__) - switch Stream.peek(strm__) { - | Some('0' .. '9' as c3) => - Stream.junk(strm__) - Char.chr((Char.code(c1) - 48) * 100 + (Char.code(c2) - 48) * 10 + (Char.code(c3) - 48)) - | _ => raise(Stream.Error("")) - } - | _ => raise(Stream.Error("")) - } - | Some(c) => - Stream.junk(strm__) - c - | _ => raise(Stream.Failure) - } - and maybe_comment = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('*') => - Stream.junk(strm__) - let s = strm__ - comment(s) - next_token(s) - | _ => Some(keyword_or_error('(')) - } - and comment = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('(') => - Stream.junk(strm__) - maybe_nested_comment(strm__) - | Some('*') => - Stream.junk(strm__) - maybe_end_comment(strm__) - | Some(_) => - Stream.junk(strm__) - comment(strm__) - | _ => raise(Stream.Failure) - } - and maybe_nested_comment = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some('*') => - Stream.junk(strm__) - let s = strm__ - comment(s) - comment(s) - | Some(_) => - Stream.junk(strm__) - comment(strm__) - | _ => raise(Stream.Failure) - } - and maybe_end_comment = (strm__: Stream.t<_>) => - switch Stream.peek(strm__) { - | Some(')') => - Stream.junk(strm__) - () - | Some('*') => - Stream.junk(strm__) - maybe_end_comment(strm__) - | Some(_) => - Stream.junk(strm__) - comment(strm__) - | _ => raise(Stream.Failure) - } - - input => Stream.from(_count => next_token(input)) -} diff --git a/jscomp/stdlib-406/genlex.resi b/jscomp/stdlib-406/genlex.resi deleted file mode 100644 index 48dc4f9927..0000000000 --- a/jscomp/stdlib-406/genlex.resi +++ /dev/null @@ -1,73 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** A generic lexical analyzer. - - - This module implements a simple 'standard' lexical analyzer, presented - as a function from character streams to token streams. It implements - roughly the lexical conventions of OCaml, but is parameterized by the - set of keywords of your language. - - - Example: a lexer suitable for a desk calculator is obtained by - {[ let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"] ]} - - The associated parser would be a function from [token stream] - to, for instance, [int], and would have rules such as: - - {[ - let rec parse_expr = parser - | [< n1 = parse_atom; n2 = parse_remainder n1 >] -> n2 - and parse_atom = parser - | [< 'Int n >] -> n - | [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n - and parse_remainder n1 = parser - | [< 'Kwd "+"; n2 = parse_expr >] -> n1+n2 - | [< >] -> n1 - ]} - - One should notice that the use of the [parser] keyword and associated - notation for streams are only available through camlp4 extensions. This - means that one has to preprocess its sources {i e. g.} by using the - ["-pp"] command-line switch of the compilers. -*/ - -/** The type of tokens. The lexical classes are: [Int] and [Float] - for integer and floating-point numbers; [String] for - string literals, enclosed in double quotes; [Char] for - character literals, enclosed in single quotes; [Ident] for - identifiers (either sequences of letters, digits, underscores - and quotes, or sequences of 'operator characters' such as - [+], [*], etc); and [Kwd] for keywords (either identifiers or - single 'special characters' such as [(], [}], etc). */ -type token = - | Kwd(string) - | Ident(string) - | Int(int) - | Float(float) - | String(string) - | Char(char) - -/** Construct the lexer function. The first argument is the list of - keywords. An identifier [s] is returned as [Kwd s] if [s] - belongs to this list, and as [Ident s] otherwise. - A special character [s] is returned as [Kwd s] if [s] - belongs to this list, and cause a lexical error (exception - {!Stream.Error} with the offending lexeme as its parameter) otherwise. - Blanks and newlines are skipped. Comments delimited by [(*] and [*)] - are skipped as well, and can be nested. A {!Stream.Failure} exception - is raised if end of stream is unexpectedly reached.*/ -let make_lexer: (list, Stream.t) => Stream.t diff --git a/jscomp/stdlib-406/hashtbl.res b/jscomp/stdlib-406/hashtbl.res deleted file mode 100644 index 58c3ac9735..0000000000 --- a/jscomp/stdlib-406/hashtbl.res +++ /dev/null @@ -1,679 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Hash tables */ - -@noalloc external seeded_hash_param: (int, int, int, 'a) => int = "?hash" -/* external old_hash_param : - int -> int -> 'a -> int = "caml_hash_univ_param" [@@noalloc] */ - -let hash = x => seeded_hash_param(10, 100, 0, x) -let hash_param = (n1, n2, x) => seeded_hash_param(n1, n2, 0, x) -let seeded_hash = (seed, x) => seeded_hash_param(10, 100, seed, x) - -/* We do dynamic hashing, and resize the table and rehash the elements - when buckets become too long. */ - -type rec t<'a, 'b> = { - mutable size: int /* number of entries */, - mutable data: array> /* the buckets */, - mutable seed: int /* for randomization */, - mutable initial_size: int /* initial array size */, -} - -and bucketlist<'a, 'b> = - | Empty - | Cons({mutable key: 'a, mutable data: 'b, mutable next: bucketlist<'a, 'b>}) - -/* The sign of initial_size encodes the fact that a traversal is - ongoing or not. - - This disables the efficient in place implementation of resizing. -*/ - -let ongoing_traversal = h => h.initial_size < 0 - -let flip_ongoing_traversal = h => h.initial_size = -h.initial_size - -/* To pick random seeds if requested */ - -let randomized_default = false - -let randomized = ref(randomized_default) - -let randomize = () => randomized := true -let is_randomized = () => randomized.contents - -let prng = Lazy.from_fun(() => Random.State.make_self_init()) - -/* Creating a fresh, empty table */ - -let rec power_2_above = (x, n) => - if x >= n { - x - } else if x * 2 < x { - x /* overflow */ - } else { - power_2_above(x * 2, n) - } - -let create = (~random=randomized.contents, initial_size) => { - let s = power_2_above(16, initial_size) - let seed = if random { - Random.State.bits(Lazy.force(prng)) - } else { - 0 - } - {initial_size: s, size: 0, seed, data: Array.make(s, Empty)} -} - -let clear = h => { - h.size = 0 - let len = Array.length(h.data) - for i in 0 to len - 1 { - h.data[i] = Empty - } -} - -let reset = h => { - let len = Array.length(h.data) - if len == abs(h.initial_size) { - clear(h) - } else { - h.size = 0 - h.data = Array.make(abs(h.initial_size), Empty) - } -} - -let copy_bucketlist = param => - switch param { - | Empty => Empty - | Cons({key, data, next}) => - let rec loop = (prec, param) => - switch param { - | Empty => () - | Cons({key, data, next}) => - let r = Cons({key, data, next}) - switch prec { - | Empty => assert(false) - | Cons(prec) => prec.next = r - } - loop(r, next) - } - - let r = Cons({key, data, next}) - loop(r, next) - r - } - -let copy = h => {...h, data: Array.map(copy_bucketlist, h.data)} - -let length = h => h.size - -let resize = (indexfun, h) => { - let odata = h.data - let osize = Array.length(odata) - let nsize = osize * 2 - if nsize >= osize { - let ndata = Array.make(nsize, Empty) - let ndata_tail = Array.make(nsize, Empty) - let inplace = !ongoing_traversal(h) - h.data = ndata /* so that indexfun sees the new bucket count */ - let rec insert_bucket = param => - switch param { - | Empty => () - | Cons({key, data, next}) as cell => - let cell = if inplace { - cell - } else { - Cons({key, data, next: Empty}) - } - - let nidx = indexfun(h, key) - switch ndata_tail[nidx] { - | Empty => ndata[nidx] = cell - | Cons(tail) => tail.next = cell - } - ndata_tail[nidx] = cell - insert_bucket(next) - } - - for i in 0 to osize - 1 { - insert_bucket(odata[i]) - } - if inplace { - for i in 0 to nsize - 1 { - switch ndata_tail[i] { - | Empty => () - | Cons(tail) => tail.next = Empty - } - } - } - } -} - -let key_index = (h, key) => - /* compatibility with old hash tables */ - land(seeded_hash_param(10, 100, h.seed, key), Array.length(h.data) - 1) - -let add = (h, key, data) => { - let i = key_index(h, key) - let bucket = Cons({key, data, next: h.data[i]}) - h.data[i] = bucket - h.size = h.size + 1 - if h.size > lsl(Array.length(h.data), 1) { - resize(key_index, h) - } -} - -let rec remove_bucket = (h, i, key, prec, param) => - switch param { - | Empty => () - | Cons({key: k, next}) as c => - if compare(k, key) == 0 { - h.size = h.size - 1 - switch prec { - | Empty => h.data[i] = next - | Cons(c) => c.next = next - } - } else { - remove_bucket(h, i, key, c, next) - } - } - -let remove = (h, key) => { - let i = key_index(h, key) - remove_bucket(h, i, key, Empty, h.data[i]) -} - -let rec find_rec = (key, param) => - switch param { - | Empty => raise(Not_found) - | Cons({key: k, data, next}) => - if compare(key, k) == 0 { - data - } else { - find_rec(key, next) - } - } - -let find = (h, key) => - switch h.data[key_index(h, key)] { - | Empty => raise(Not_found) - | Cons({key: k1, data: d1, next: next1}) => - if compare(key, k1) == 0 { - d1 - } else { - switch next1 { - | Empty => raise(Not_found) - | Cons({key: k2, data: d2, next: next2}) => - if compare(key, k2) == 0 { - d2 - } else { - switch next2 { - | Empty => raise(Not_found) - | Cons({key: k3, data: d3, next: next3}) => - if compare(key, k3) == 0 { - d3 - } else { - find_rec(key, next3) - } - } - } - } - } - } - -let rec find_rec_opt = (key, param) => - switch param { - | Empty => None - | Cons({key: k, data, next}) => - if compare(key, k) == 0 { - Some(data) - } else { - find_rec_opt(key, next) - } - } - -let find_opt = (h, key) => - switch h.data[key_index(h, key)] { - | Empty => None - | Cons({key: k1, data: d1, next: next1}) => - if compare(key, k1) == 0 { - Some(d1) - } else { - switch next1 { - | Empty => None - | Cons({key: k2, data: d2, next: next2}) => - if compare(key, k2) == 0 { - Some(d2) - } else { - switch next2 { - | Empty => None - | Cons({key: k3, data: d3, next: next3}) => - if compare(key, k3) == 0 { - Some(d3) - } else { - find_rec_opt(key, next3) - } - } - } - } - } - } - -let find_all = (h, key) => { - let rec find_in_bucket = param => - switch param { - | Empty => list{} - | Cons({key: k, data, next}) => - if compare(k, key) == 0 { - list{data, ...find_in_bucket(next)} - } else { - find_in_bucket(next) - } - } - find_in_bucket(h.data[key_index(h, key)]) -} - -let rec replace_bucket = (key, data, param) => - switch param { - | Empty => true - | Cons({key: k, next} as slot) => - if compare(k, key) == 0 { - slot.key = key - slot.data = data - false - } else { - replace_bucket(key, data, next) - } - } - -let replace = (h, key, data) => { - let i = key_index(h, key) - let l = h.data[i] - if replace_bucket(key, data, l) { - h.data[i] = Cons({key, data, next: l}) - h.size = h.size + 1 - if h.size > lsl(Array.length(h.data), 1) { - resize(key_index, h) - } - } -} - -let mem = (h, key) => { - let rec mem_in_bucket = param => - switch param { - | Empty => false - | Cons({key: k, next}) => compare(k, key) == 0 || mem_in_bucket(next) - } - mem_in_bucket(h.data[key_index(h, key)]) -} - -let iter = (f, h) => { - let rec do_bucket = param => - switch param { - | Empty => () - | Cons({key, data, next}) => - f(key, data) - do_bucket(next) - } - let old_trav = ongoing_traversal(h) - if !old_trav { - flip_ongoing_traversal(h) - } - try { - let d = h.data - for i in 0 to Array.length(d) - 1 { - do_bucket(d[i]) - } - if !old_trav { - flip_ongoing_traversal(h) - } - } catch { - | exn if !old_trav => - flip_ongoing_traversal(h) - raise(exn) - } -} - -let rec filter_map_inplace_bucket = (f, h, i, prec, param) => - switch param { - | Empty => - switch prec { - | Empty => h.data[i] = Empty - | Cons(c) => c.next = Empty - } - | Cons({key, data, next} as c) as slot => - switch f(key, data) { - | None => - h.size = h.size - 1 - filter_map_inplace_bucket(f, h, i, prec, next) - | Some(data) => - switch prec { - | Empty => h.data[i] = slot - | Cons(c) => c.next = slot - } - c.data = data - filter_map_inplace_bucket(f, h, i, slot, next) - } - } - -let filter_map_inplace = (f, h) => { - let d = h.data - let old_trav = ongoing_traversal(h) - if !old_trav { - flip_ongoing_traversal(h) - } - try for i in 0 to Array.length(d) - 1 { - filter_map_inplace_bucket(f, h, i, Empty, h.data[i]) - } catch { - | exn if !old_trav => - flip_ongoing_traversal(h) - raise(exn) - } -} - -let fold = (f, h, init) => { - let rec do_bucket = (b, accu) => - switch b { - | Empty => accu - | Cons({key, data, next}) => do_bucket(next, f(key, data, accu)) - } - let old_trav = ongoing_traversal(h) - if !old_trav { - flip_ongoing_traversal(h) - } - try { - let d = h.data - let accu = ref(init) - for i in 0 to Array.length(d) - 1 { - accu := do_bucket(d[i], accu.contents) - } - if !old_trav { - flip_ongoing_traversal(h) - } - accu.contents - } catch { - | exn if !old_trav => - flip_ongoing_traversal(h) - raise(exn) - } -} - -type statistics = { - num_bindings: int, - num_buckets: int, - max_bucket_length: int, - bucket_histogram: array, -} - -let rec bucket_length = (accu, param) => - switch param { - | Empty => accu - | Cons({next}) => bucket_length(accu + 1, next) - } - -let stats = h => { - let mbl = Array.fold_left((m, b) => max(m, bucket_length(0, b)), 0, h.data) - let histo = Array.make(mbl + 1, 0) - Array.iter(b => { - let l = bucket_length(0, b) - histo[l] = histo[l] + 1 - }, h.data) - { - num_bindings: h.size, - num_buckets: Array.length(h.data), - max_bucket_length: mbl, - bucket_histogram: histo, - } -} - -/* Functorial interface */ - -module type HashedType = { - type t - let equal: (t, t) => bool - let hash: t => int -} - -module type SeededHashedType = { - type t - let equal: (t, t) => bool - let hash: (int, t) => int -} - -module type S = { - type key - type t<'a> - let create: int => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, key, 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, key, 'a) => unit - let mem: (t<'a>, key) => bool - let iter: ((key, 'a) => unit, t<'a>) => unit - let filter_map_inplace: ((key, 'a) => option<'a>, t<'a>) => unit - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics -} - -module type SeededS = { - type key - type t<'a> - let create: (~random: bool=?, int) => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, key, 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, key, 'a) => unit - let mem: (t<'a>, key) => bool - let iter: ((key, 'a) => unit, t<'a>) => unit - let filter_map_inplace: ((key, 'a) => option<'a>, t<'a>) => unit - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics -} - -module MakeSeeded = (H: SeededHashedType): (SeededS with type key = H.t) => { - type key = H.t - type hashtbl<'a> = t - type t<'a> = hashtbl<'a> - let create = create - let clear = clear - let reset = reset - let copy = copy - - let key_index = (h, key) => land(H.hash(h.seed, key), Array.length(h.data) - 1) - - let add = (h, key, data) => { - let i = key_index(h, key) - let bucket = Cons({key, data, next: h.data[i]}) - h.data[i] = bucket - h.size = h.size + 1 - if h.size > lsl(Array.length(h.data), 1) { - resize(key_index, h) - } - } - - let rec remove_bucket = (h, i, key, prec, param) => - switch param { - | Empty => () - | Cons({key: k, next}) as c => - if H.equal(k, key) { - h.size = h.size - 1 - switch prec { - | Empty => h.data[i] = next - | Cons(c) => c.next = next - } - } else { - remove_bucket(h, i, key, c, next) - } - } - - let remove = (h, key) => { - let i = key_index(h, key) - remove_bucket(h, i, key, Empty, h.data[i]) - } - - let rec find_rec = (key, param) => - switch param { - | Empty => raise(Not_found) - | Cons({key: k, data, next}) => - if H.equal(key, k) { - data - } else { - find_rec(key, next) - } - } - - let find = (h, key) => - switch h.data[key_index(h, key)] { - | Empty => raise(Not_found) - | Cons({key: k1, data: d1, next: next1}) => - if H.equal(key, k1) { - d1 - } else { - switch next1 { - | Empty => raise(Not_found) - | Cons({key: k2, data: d2, next: next2}) => - if H.equal(key, k2) { - d2 - } else { - switch next2 { - | Empty => raise(Not_found) - | Cons({key: k3, data: d3, next: next3}) => - if H.equal(key, k3) { - d3 - } else { - find_rec(key, next3) - } - } - } - } - } - } - - let rec find_rec_opt = (key, param) => - switch param { - | Empty => None - | Cons({key: k, data, next}) => - if H.equal(key, k) { - Some(data) - } else { - find_rec_opt(key, next) - } - } - - let find_opt = (h, key) => - switch h.data[key_index(h, key)] { - | Empty => None - | Cons({key: k1, data: d1, next: next1}) => - if H.equal(key, k1) { - Some(d1) - } else { - switch next1 { - | Empty => None - | Cons({key: k2, data: d2, next: next2}) => - if H.equal(key, k2) { - Some(d2) - } else { - switch next2 { - | Empty => None - | Cons({key: k3, data: d3, next: next3}) => - if H.equal(key, k3) { - Some(d3) - } else { - find_rec_opt(key, next3) - } - } - } - } - } - } - - let find_all = (h, key) => { - let rec find_in_bucket = param => - switch param { - | Empty => list{} - | Cons({key: k, data: d, next}) => - if H.equal(k, key) { - list{d, ...find_in_bucket(next)} - } else { - find_in_bucket(next) - } - } - find_in_bucket(h.data[key_index(h, key)]) - } - - let rec replace_bucket = (key, data, param) => - switch param { - | Empty => true - | Cons({key: k, next} as slot) => - if H.equal(k, key) { - slot.key = key - slot.data = data - false - } else { - replace_bucket(key, data, next) - } - } - - let replace = (h, key, data) => { - let i = key_index(h, key) - let l = h.data[i] - if replace_bucket(key, data, l) { - h.data[i] = Cons({key, data, next: l}) - h.size = h.size + 1 - if h.size > lsl(Array.length(h.data), 1) { - resize(key_index, h) - } - } - } - - let mem = (h, key) => { - let rec mem_in_bucket = param => - switch param { - | Empty => false - | Cons({key: k, next}) => H.equal(k, key) || mem_in_bucket(next) - } - mem_in_bucket(h.data[key_index(h, key)]) - } - - let iter = iter - let filter_map_inplace = filter_map_inplace - let fold = fold - let length = length - let stats = stats -} - -module Make = (H: HashedType): (S with type key = H.t) => { - include MakeSeeded({ - type t = H.t - let equal = H.equal - let hash = (_seed: int, x) => H.hash(x) - }) - let create = sz => create(~random=false, sz) -} diff --git a/jscomp/stdlib-406/hashtbl.resi b/jscomp/stdlib-406/hashtbl.resi deleted file mode 100644 index 5acfde280f..0000000000 --- a/jscomp/stdlib-406/hashtbl.resi +++ /dev/null @@ -1,406 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Hash tables and hash functions. - - Hash tables are hashed association tables, with in-place modification. -*/ - -/* {1 Generic interface} */ - -/** The type of hash tables from type ['a] to type ['b]. */ -type t<'a, 'b> - -/** [Hashtbl.create n] creates a new, empty hash table, with - initial size [n]. For best results, [n] should be on the - order of the expected number of elements that will be in - the table. The table grows as needed, so [n] is just an - initial guess. - - The optional [random] parameter (a boolean) controls whether - the internal organization of the hash table is randomized at each - execution of [Hashtbl.create] or deterministic over all executions. - - A hash table that is created with [~random:false] uses a - fixed hash function ({!Hashtbl.hash}) to distribute keys among - buckets. As a consequence, collisions between keys happen - deterministically. In Web-facing applications or other - security-sensitive applications, the deterministic collision - patterns can be exploited by a malicious user to create a - denial-of-service attack: the attacker sends input crafted to - create many collisions in the table, slowing the application down. - - A hash table that is created with [~random:true] uses the seeded - hash function {!Hashtbl.seeded_hash} with a seed that is randomly - chosen at hash table creation time. In effect, the hash function - used is randomly selected among [2^{30}] different hash functions. - All these hash functions have different collision patterns, - rendering ineffective the denial-of-service attack described above. - However, because of randomization, enumerating all elements of the - hash table using {!Hashtbl.fold} or {!Hashtbl.iter} is no longer - deterministic: elements are enumerated in different orders at - different runs of the program. - - If no [~random] parameter is given, hash tables are created - in non-random mode by default. This default can be changed - either programmatically by calling {!Hashtbl.randomize} or by - setting the [R] flag in the [OCAMLRUNPARAM] environment variable. - - @before 4.00.0 the [random] parameter was not present and all - hash tables were created in non-randomized mode. */ -let create: (~random: bool=?, int) => t<'a, 'b> - -/** Empty a hash table. Use [reset] instead of [clear] to shrink the - size of the bucket table to its initial size. */ -let clear: t<'a, 'b> => unit - -/** Empty a hash table and shrink the size of the bucket table - to its initial size. - @since 4.00.0 */ -let reset: t<'a, 'b> => unit - -/** Return a copy of the given hashtable. */ -let copy: t<'a, 'b> => t<'a, 'b> - -/** [Hashtbl.add tbl x y] adds a binding of [x] to [y] in table [tbl]. - Previous bindings for [x] are not removed, but simply - hidden. That is, after performing {!Hashtbl.remove}[ tbl x], - the previous binding for [x], if any, is restored. - (Same behavior as with association lists.) */ -let add: (t<'a, 'b>, 'a, 'b) => unit - -/** [Hashtbl.find tbl x] returns the current binding of [x] in [tbl], - or raises [Not_found] if no such binding exists. */ -let find: (t<'a, 'b>, 'a) => 'b - -/** [Hashtbl.find_opt tbl x] returns the current binding of [x] in [tbl], - or [None] if no such binding exists. - @since 4.05 */ -let find_opt: (t<'a, 'b>, 'a) => option<'b> - -/** [Hashtbl.find_all tbl x] returns the list of all data - associated with [x] in [tbl]. - The current binding is returned first, then the previous - bindings, in reverse order of introduction in the table. */ -let find_all: (t<'a, 'b>, 'a) => list<'b> - -/** [Hashtbl.mem tbl x] checks if [x] is bound in [tbl]. */ -let mem: (t<'a, 'b>, 'a) => bool - -/** [Hashtbl.remove tbl x] removes the current binding of [x] in [tbl], - restoring the previous binding if it exists. - It does nothing if [x] is not bound in [tbl]. */ -let remove: (t<'a, 'b>, 'a) => unit - -/** [Hashtbl.replace tbl x y] replaces the current binding of [x] - in [tbl] by a binding of [x] to [y]. If [x] is unbound in [tbl], - a binding of [x] to [y] is added to [tbl]. - This is functionally equivalent to {!Hashtbl.remove}[ tbl x] - followed by {!Hashtbl.add}[ tbl x y]. */ -let replace: (t<'a, 'b>, 'a, 'b) => unit - -/** [Hashtbl.iter f tbl] applies [f] to all bindings in table [tbl]. - [f] receives the key as first argument, and the associated value - as second argument. Each binding is presented exactly once to [f]. - - The order in which the bindings are passed to [f] is unspecified. - However, if the table contains several bindings for the same key, - they are passed to [f] in reverse order of introduction, that is, - the most recent binding is passed first. - - If the hash table was created in non-randomized mode, the order - in which the bindings are enumerated is reproducible between - successive runs of the program, and even between minor versions - of OCaml. For randomized hash tables, the order of enumeration - is entirely random. - - The behavior is not defined if the hash table is modified - by [f] during the iteration. -*/ -let iter: (('a, 'b) => unit, t<'a, 'b>) => unit - -/** [Hashtbl.filter_map_inplace f tbl] applies [f] to all bindings in - table [tbl] and update each binding depending on the result of - [f]. If [f] returns [None], the binding is discarded. If it - returns [Some new_val], the binding is update to associate the key - to [new_val]. - - Other comments for {!Hashtbl.iter} apply as well. - @since 4.03.0 */ -let filter_map_inplace: (('a, 'b) => option<'b>, t<'a, 'b>) => unit - -/** [Hashtbl.fold f tbl init] computes - [(f kN dN ... (f k1 d1 init)...)], - where [k1 ... kN] are the keys of all bindings in [tbl], - and [d1 ... dN] are the associated values. - Each binding is presented exactly once to [f]. - - The order in which the bindings are passed to [f] is unspecified. - However, if the table contains several bindings for the same key, - they are passed to [f] in reverse order of introduction, that is, - the most recent binding is passed first. - - If the hash table was created in non-randomized mode, the order - in which the bindings are enumerated is reproducible between - successive runs of the program, and even between minor versions - of OCaml. For randomized hash tables, the order of enumeration - is entirely random. - - The behavior is not defined if the hash table is modified - by [f] during the iteration. -*/ -let fold: (('a, 'b, 'c) => 'c, t<'a, 'b>, 'c) => 'c - -/** [Hashtbl.length tbl] returns the number of bindings in [tbl]. - It takes constant time. Multiple bindings are counted once each, so - [Hashtbl.length] gives the number of times [Hashtbl.iter] calls its - first argument. */ -let length: t<'a, 'b> => int - -/** After a call to [Hashtbl.randomize()], hash tables are created in - randomized mode by default: {!Hashtbl.create} returns randomized - hash tables, unless the [~random:false] optional parameter is given. - The same effect can be achieved by setting the [R] parameter in - the [OCAMLRUNPARAM] environment variable. - - It is recommended that applications or Web frameworks that need to - protect themselves against the denial-of-service attack described - in {!Hashtbl.create} call [Hashtbl.randomize()] at initialization - time. - - Note that once [Hashtbl.randomize()] was called, there is no way - to revert to the non-randomized default behavior of {!Hashtbl.create}. - This is intentional. Non-randomized hash tables can still be - created using [Hashtbl.create ~random:false]. - - @since 4.00.0 */ -let randomize: unit => unit - -/** return if the tables are currently created in randomized mode by default - - @since 4.03.0 */ -let is_randomized: unit => bool - -/** @since 4.00.0 */ -type statistics = { - /** Number of bindings present in the table. - Same value as returned by {!Hashtbl.length}. */ - num_bindings: int, - /** Number of buckets in the table. */ - num_buckets: int, - /** Maximal number of bindings per bucket. */ - max_bucket_length: int, - /** Histogram of bucket sizes. This array [histo] has - length [max_bucket_length + 1]. The value of - [histo.(i)] is the number of buckets whose size is [i]. */ - bucket_histogram: array, -} - -/** [Hashtbl.stats tbl] returns statistics about the table [tbl]: - number of buckets, size of the biggest bucket, distribution of - buckets by size. - @since 4.00.0 */ -let stats: t<'a, 'b> => statistics - -/* {1 Functorial interface} - -The functorial interface allows the use of specific comparison - and hash functions, either for performance/security concerns, - or because keys are not hashable/comparable with the polymorphic builtins. - - For instance, one might want to specialize a table for integer keys: - {[ - module IntHash = - struct - type t = int - let equal i j = i=j - let hash i = i land max_int - end - - module IntHashtbl = Hashtbl.Make(IntHash) - - let h = IntHashtbl.create 17 in - IntHashtbl.add h 12 "hello" - ]} - - This creates a new module [IntHashtbl], with a new type ['a - IntHashtbl.t] of tables from [int] to ['a]. In this example, [h] - contains [string] values so its type is [string IntHashtbl.t]. - - Note that the new type ['a IntHashtbl.t] is not compatible with - the type [('a,'b) Hashtbl.t] of the generic interface. For - example, [Hashtbl.length h] would not type-check, you must use - [IntHashtbl.length]. -*/ - -/** The input signature of the functor {!Hashtbl.Make}. */ -module type HashedType = { - /** The type of the hashtable keys. */ - type t - - /** The equality predicate used to compare keys. */ - let equal: (t, t) => bool - - /** A hashing function on keys. It must be such that if two keys are - equal according to [equal], then they have identical hash values - as computed by [hash]. - Examples: suitable ([equal], [hash]) pairs for arbitrary key - types include -- ([(=)], {!Hashtbl.hash}) for comparing objects by structure - (provided objects do not contain floats) -- ([(fun x y -> compare x y = 0)], {!Hashtbl.hash}) - for comparing objects by structure - and handling {!Pervasives.nan} correctly -- ([(==)], {!Hashtbl.hash}) for comparing objects by physical - equality (e.g. for mutable or cyclic objects). */ - let hash: t => int -} - -/** The output signature of the functor {!Hashtbl.Make}. */ -module type S = { - type key - type t<'a> - let create: int => t<'a> - let clear: t<'a> => unit - /** @since 4.00.0 */ - let reset: t<'a> => unit - - let copy: t<'a> => t<'a> - let add: (t<'a>, key, 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - /** @since 4.05.0 */ - let find_opt: (t<'a>, key) => option<'a> - - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, key, 'a) => unit - let mem: (t<'a>, key) => bool - let iter: ((key, 'a) => unit, t<'a>) => unit - /** @since 4.03.0 */ - let filter_map_inplace: ((key, 'a) => option<'a>, t<'a>) => unit - - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - let length: t<'a> => int - /** @since 4.00.0 */ - let stats: t<'a> => statistics -} - -/** Functor building an implementation of the hashtable structure. - The functor [Hashtbl.Make] returns a structure containing - a type [key] of keys and a type ['a t] of hash tables - associating data of type ['a] to keys of type [key]. - The operations perform similarly to those of the generic - interface, but use the hashing and equality functions - specified in the functor argument [H] instead of generic - equality and hashing. Since the hash function is not seeded, - the [create] operation of the result structure always returns - non-randomized hash tables. */ -module Make: (H: HashedType) => (S with type key = H.t) - -/** The input signature of the functor {!Hashtbl.MakeSeeded}. - @since 4.00.0 */ -module type SeededHashedType = { - /** The type of the hashtable keys. */ - type t - - /** The equality predicate used to compare keys. */ - let equal: (t, t) => bool - - /** A seeded hashing function on keys. The first argument is - the seed. It must be the case that if [equal x y] is true, - then [hash seed x = hash seed y] for any value of [seed]. - A suitable choice for [hash] is the function {!Hashtbl.seeded_hash} - below. */ - let hash: (int, t) => int -} - -/** The output signature of the functor {!Hashtbl.MakeSeeded}. - @since 4.00.0 */ -module type SeededS = { - type key - type t<'a> - let create: (~random: bool=?, int) => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, key, 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - /** @since 4.05.0 */ - let find_opt: (t<'a>, key) => option<'a> - - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, key, 'a) => unit - let mem: (t<'a>, key) => bool - let iter: ((key, 'a) => unit, t<'a>) => unit - /** @since 4.03.0 */ - let filter_map_inplace: ((key, 'a) => option<'a>, t<'a>) => unit - - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics -} - -/** Functor building an implementation of the hashtable structure. - The functor [Hashtbl.MakeSeeded] returns a structure containing - a type [key] of keys and a type ['a t] of hash tables - associating data of type ['a] to keys of type [key]. - The operations perform similarly to those of the generic - interface, but use the seeded hashing and equality functions - specified in the functor argument [H] instead of generic - equality and hashing. The [create] operation of the - result structure supports the [~random] optional parameter - and returns randomized hash tables if [~random:true] is passed - or if randomization is globally on (see {!Hashtbl.randomize}). - @since 4.00.0 */ -module MakeSeeded: (H: SeededHashedType) => (SeededS with type key = H.t) - -/* {1 The polymorphic hash functions} */ - -/** [Hashtbl.hash x] associates a nonnegative integer to any value of - any type. It is guaranteed that - if [x = y] or [Pervasives.compare x y = 0], then [hash x = hash y]. - Moreover, [hash] always terminates, even on cyclic structures. */ -let hash: 'a => int - -/** A variant of {!Hashtbl.hash} that is further parameterized by - an integer seed. - @since 4.00.0 */ -let seeded_hash: (int, 'a) => int - -/** [Hashtbl.hash_param meaningful total x] computes a hash value for [x], - with the same properties as for [hash]. The two extra integer - parameters [meaningful] and [total] give more precise control over - hashing. Hashing performs a breadth-first, left-to-right traversal - of the structure [x], stopping after [meaningful] meaningful nodes - were encountered, or [total] nodes (meaningful or not) were - encountered. If [total] as specified by the user exceeds a certain - value, currently 256, then it is capped to that value. - Meaningful nodes are: integers; floating-point - numbers; strings; characters; booleans; and constant - constructors. Larger values of [meaningful] and [total] means that - more nodes are taken into account to compute the final hash value, - and therefore collisions are less likely to happen. However, - hashing takes longer. The parameters [meaningful] and [total] - govern the tradeoff between accuracy and speed. As default - choices, {!Hashtbl.hash} and {!Hashtbl.seeded_hash} take - [meaningful = 10] and [total = 100]. */ -let hash_param: (int, int, 'a) => int - -/** A variant of {!Hashtbl.hash_param} that is further parameterized by - an integer seed. Usage: - [Hashtbl.seeded_hash_param meaningful total seed x]. - @since 4.00.0 */ -let seeded_hash_param: (int, int, int, 'a) => int diff --git a/jscomp/stdlib-406/hashtblLabels.res b/jscomp/stdlib-406/hashtblLabels.res deleted file mode 100644 index e9fe63a1fa..0000000000 --- a/jscomp/stdlib-406/hashtblLabels.res +++ /dev/null @@ -1,129 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Hash tables */ - -type t<'a, 'b> = Hashtbl.t<'a, 'b> - -let { - create, - clear, - reset, - copy, - add, - find, - find_opt, - find_all, - mem, - remove, - replace, - iter, - filter_map_inplace, - fold, - length, - randomize, - is_randomized, - stats, - hash, - seeded_hash, - hash_param, - seeded_hash_param, -} = module(Hashtbl) - -let add = (tbl, ~key, ~data) => add(tbl, key, data) - -let replace = (tbl, ~key, ~data) => replace(tbl, key, data) - -let iter = (~f, tbl) => iter((key, data) => f(~key, ~data), tbl) - -let filter_map_inplace = (~f, tbl) => filter_map_inplace((key, data) => f(~key, ~data), tbl) - -let fold = (~f, tbl, ~init) => fold((key, data, acc) => f(~key, ~data, acc), tbl, init) - -type statistics = Hashtbl.statistics = { - num_bindings: int, - num_buckets: int, - max_bucket_length: int, - bucket_histogram: array, -} - -/* Functorial interface */ - -module type HashedType = Hashtbl.HashedType - -module type SeededHashedType = Hashtbl.SeededHashedType - -module type S = { - type rec key - and t<'a> - let create: int => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, ~key: key, ~data: 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, ~key: key, ~data: 'a) => unit - let mem: (t<'a>, key) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let filter_map_inplace: (~f: (~key: key, ~data: 'a) => option<'a>, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics -} - -module type SeededS = { - type rec key - and t<'a> - let create: (~random: bool=?, int) => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, ~key: key, ~data: 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, ~key: key, ~data: 'a) => unit - let mem: (t<'a>, key) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let filter_map_inplace: (~f: (~key: key, ~data: 'a) => option<'a>, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics -} - -module MakeSeeded = (H: SeededHashedType): (SeededS with type key = H.t) => { - include Hashtbl.MakeSeeded(H) - let add = (tbl, ~key, ~data) => add(tbl, key, data) - let replace = (tbl, ~key, ~data) => replace(tbl, key, data) - - let iter = (~f, tbl) => iter((key, data) => f(~key, ~data), tbl) - - let filter_map_inplace = (~f, tbl) => filter_map_inplace((key, data) => f(~key, ~data), tbl) - - let fold = (~f, tbl, ~init) => fold((key, data, acc) => f(~key, ~data, acc), tbl, init) -} - -module Make = (H: HashedType): (S with type key = H.t) => { - include MakeSeeded({ - type t = H.t - let equal = H.equal - let hash = (_seed: int, x) => H.hash(x) - }) - let create = sz => create(~random=false, sz) -} diff --git a/jscomp/stdlib-406/int32.res b/jscomp/stdlib-406/int32.res deleted file mode 100644 index d3a53dbbdf..0000000000 --- a/jscomp/stdlib-406/int32.res +++ /dev/null @@ -1,64 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ -type t = int -/* Module [t]: 32-bit integers */ - -external neg: t => t = "%negint" -external add: (t, t) => t = "%addint" -external sub: (t, t) => t = "%subint" -external mul: (t, t) => t = "%mulint" -external div: (t, t) => t = "%divint" -external rem: (t, t) => t = "%modint" -external logand: (t, t) => t = "%andint" -external logor: (t, t) => t = "%orint" -external logxor: (t, t) => t = "%xorint" -external shift_left: (t, int) => t = "%lslint" -external shift_right: (t, int) => t = "%asrint" -external shift_right_logical: (t, int) => t = "%lsrint" -external of_int: int => t = "%identity" -external to_int: t => int = "%identity" -external of_float: float => t = "?int_of_float" -external to_float: t => float = "?int_to_float" -external bits_of_float: float => t = "?int_bits_of_float" -external float_of_bits: t => float = "?int_float_of_bits" - -let zero = 0l -let one = 1l -let minus_one = -1l -let succ = n => add(n, 1l) -let pred = n => sub(n, 1l) -let abs = n => - if n >= 0l { - n - } else { - neg(n) - } -let min_int = 0x80000000l -let max_int = 0x7FFFFFFFl -let lognot = n => logxor(n, -1l) - -external format: (string, t) => string = "?format_int" -let to_string = n => format("%d", n) - -external of_string: string => t = "?int_of_string" - -let of_string_opt = s => - /* TODO: expose a non-raising primitive directly. */ - try Some(of_string(s)) catch { - | Failure(_) => None - } - -let compare = (x: t, y: t) => Pervasives.compare(x, y) -let equal = (x: t, y: t) => compare(x, y) == 0 diff --git a/jscomp/stdlib-406/int32.resi b/jscomp/stdlib-406/int32.resi deleted file mode 100644 index 174036f240..0000000000 --- a/jscomp/stdlib-406/int32.resi +++ /dev/null @@ -1,176 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/** 32-bit integers. - - This module provides operations on the type [t] - of signed 32-bit integers. Unlike the built-in [int] type, - the type [t] is guaranteed to be exactly 32-bit wide on all - platforms. All arithmetic operations over [t] are taken - modulo 2{^32}. - - Performance notice: values of type [t] occupy more memory - space than values of type [int], and arithmetic operations on - [t] are generally slower than those on [int]. Use [t] - only when the application requires exact 32-bit arithmetic. */ -/** An alias for the type of 32-bit integers. */ -type t = int - -/** The 32-bit integer 0. */ -let zero: t - -/** The 32-bit integer 1. */ -let one: t - -/** The 32-bit integer -1. */ -let minus_one: t - -/** Unary negation. */ -external neg: t => t = "%negint" - -/** Addition. */ -external add: (t, t) => t = "%addint" - -/** Subtraction. */ -external sub: (t, t) => t = "%subint" - -/** Multiplication. */ -external mul: (t, t) => t = "%mulint" - -/** Integer division. Raise [Division_by_zero] if the second - argument is zero. This division rounds the real quotient of - its arguments towards zero, as specified for {!Pervasives.(/)}. */ -external div: (t, t) => t = "%divint" - -/** Integer remainder. If [y] is not zero, the result - of [Int32.rem x y] satisfies the following property: - [x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)]. - If [y = 0], [Int32.rem x y] raises [Division_by_zero]. */ -external rem: (t, t) => t = "%modint" - -/** Successor. [Int32.succ x] is [Int32.add x Int32.one]. */ -let succ: t => t - -/** Predecessor. [Int32.pred x] is [Int32.sub x Int32.one]. */ -let pred: t => t - -/** Return the absolute value of its argument. */ -let abs: t => t - -/** The greatest representable 32-bit integer, 2{^31} - 1. */ -let max_int: t - -/** The smallest representable 32-bit integer, -2{^31}. */ -let min_int: t - -/** Bitwise logical and. */ -external logand: (t, t) => t = "%andint" - -/** Bitwise logical or. */ -external logor: (t, t) => t = "%orint" - -/** Bitwise logical exclusive or. */ -external logxor: (t, t) => t = "%xorint" - -/** Bitwise logical negation. */ -let lognot: t => t - -/** [Int32.shift_left x y] shifts [x] to the left by [y] bits. - The result is unspecified if [y < 0] or [y >= 32]. */ -external shift_left: (t, int) => t = "%lslint" - -/** [Int32.shift_right x y] shifts [x] to the right by [y] bits. - This is an arithmetic shift: the sign bit of [x] is replicated - and inserted in the vacated bits. - The result is unspecified if [y < 0] or [y >= 32]. */ -external shift_right: (t, int) => t = "%asrint" - -/** [Int32.shift_right_logical x y] shifts [x] to the right by [y] bits. - This is a logical shift: zeroes are inserted in the vacated bits - regardless of the sign of [x]. - The result is unspecified if [y < 0] or [y >= 32]. */ -external shift_right_logical: (t, int) => t = "%lsrint" - -/** Convert the given integer (type [int]) to a 32-bit integer - (type [t]). */ -external of_int: int => t = "%identity" - -/** Convert the given 32-bit integer (type [t]) to an - integer (type [int]). On 32-bit platforms, the 32-bit integer - is taken modulo 2{^31}, i.e. the high-order bit is lost - during the conversion. On 64-bit platforms, the conversion - is exact. */ -external to_int: t => int = "%identity" - -/** Convert the given floating-point number to a 32-bit integer, - discarding the fractional part (truncate towards 0). - The result of the conversion is undefined if, after truncation, - the number is outside the range \[{!Int32.min_int}, {!Int32.max_int}\]. */ -external of_float: float => t = "?int_of_float" - -/** Convert the given 32-bit integer to a floating-point number. */ -external to_float: t => float = "?int_to_float" - -/** Convert the given string to a 32-bit integer. - The string is read in decimal (by default, or if the string - begins with [0u]) or in hexadecimal, octal or binary if the - string begins with [0x], [0o] or [0b] respectively. - - The [0u] prefix reads the input as an unsigned integer in the range - [[0, 2*Int32.max_int+1]]. If the input exceeds {!Int32.max_int} - it is converted to the signed integer - [Int32.min_int + input - Int32.max_int - 1]. - - The [_] (underscore) character can appear anywhere in the string - and is ignored. - Raise [Failure "Int32.of_string"] if the given string is not - a valid representation of an integer, or if the integer represented - exceeds the range of integers representable in type [t]. */ -external of_string: string => t = "?int_of_string" - -/** Same as [of_string], but return [None] instead of raising. - @since 4.05 */ -let of_string_opt: string => option - -/** Return the string representation of its argument, in signed decimal. */ -let to_string: t => string - -/** Return the internal representation of the given float according - to the IEEE 754 floating-point 'single format' bit layout. - Bit 31 of the result represents the sign of the float; - bits 30 to 23 represent the (biased) exponent; bits 22 to 0 - represent the mantissa. */ -external bits_of_float: float => t = "?int_bits_of_float" - -/** Return the floating-point number whose internal representation, - according to the IEEE 754 floating-point 'single format' bit layout, - is the given [t]. */ -external float_of_bits: t => float = "?int_float_of_bits" - -/** The comparison function for 32-bit integers, with the same specification as - {!Pervasives.compare}. Along with the type [t], this function [compare] - allows the module [Int32] to be passed as argument to the functors - {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int - -/** The equal function for int32s. - @since 4.03.0 */ -let equal: (t, t) => bool - -/* {1 Deprecated functions} */ - -/** Do not use this deprecated function. Instead, - used {!Printf.sprintf} with a [%l...] format. */ -external format: (string, t) => string = "?format_int" diff --git a/jscomp/stdlib-406/int64.res b/jscomp/stdlib-406/int64.res deleted file mode 100644 index 032a1c4aa4..0000000000 --- a/jscomp/stdlib-406/int64.res +++ /dev/null @@ -1,71 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Module [Int64]: 64-bit integers */ - -external neg: int64 => int64 = "%int64_neg" -external add: (int64, int64) => int64 = "%int64_add" -external sub: (int64, int64) => int64 = "%int64_sub" -external mul: (int64, int64) => int64 = "%int64_mul" -external div: (int64, int64) => int64 = "%int64_div" -external rem: (int64, int64) => int64 = "%int64_mod" -external logand: (int64, int64) => int64 = "%int64_and" -external logor: (int64, int64) => int64 = "%int64_or" -external logxor: (int64, int64) => int64 = "%int64_xor" -external shift_left: (int64, int) => int64 = "%int64_lsl" -external shift_right: (int64, int) => int64 = "%int64_asr" -external shift_right_logical: (int64, int) => int64 = "%int64_lsr" -external of_int: int => int64 = "%int64_of_int" -external to_int: int64 => int = "%int64_to_int" -external of_float: float => int64 = "?int64_of_float" -external to_float: int64 => float = "?int64_to_float" -external of_int32: int => int64 = "%int64_of_int32" -external to_int32: int64 => int = "%int64_to_int32" - -let zero = 0L -let one = 1L -let minus_one = -1L -/* let succ n = add n 1L */ -external succ: int64 => int64 = "?int64_succ" -let pred = n => sub(n, 1L) -let abs = n => - if n >= 0L { - n - } else { - neg(n) - } -let min_int = 0x8000000000000000L -let max_int = 0x7FFFFFFFFFFFFFFFL -let lognot = n => logxor(n, -1L) - -external format: (string, int64) => string = "?int64_format" -external to_string: int64 => string = "?int64_to_string" - -external of_string: string => int64 = "?int64_of_string" - -let of_string_opt = s => - /* TODO: expose a non-raising primitive directly. */ - try Some(of_string(s)) catch { - | Failure(_) => None - } - -external bits_of_float: float => int64 = "?int64_bits_of_float" - -external float_of_bits: int64 => float = "?int64_float_of_bits" - -type t = int64 - -let compare = (x: t, y: t) => Pervasives.compare(x, y) -let equal = (x: t, y: t) => compare(x, y) == 0 diff --git a/jscomp/stdlib-406/int64.resi b/jscomp/stdlib-406/int64.resi deleted file mode 100644 index aeb0588c0f..0000000000 --- a/jscomp/stdlib-406/int64.resi +++ /dev/null @@ -1,189 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** 64-bit integers. - - This module provides operations on the type [int64] of - signed 64-bit integers. Unlike the built-in [int] type, - the type [int64] is guaranteed to be exactly 64-bit wide on all - platforms. All arithmetic operations over [int64] are taken - modulo 2{^64} - - Performance notice: values of type [int64] occupy more memory - space than values of type [int], and arithmetic operations on - [int64] are generally slower than those on [int]. Use [int64] - only when the application requires exact 64-bit arithmetic. -*/ - -/** The 64-bit integer 0. */ -let zero: int64 - -/** The 64-bit integer 1. */ -let one: int64 - -/** The 64-bit integer -1. */ -let minus_one: int64 - -/** Unary negation. */ -external neg: int64 => int64 = "%int64_neg" - -/** Addition. */ -external add: (int64, int64) => int64 = "%int64_add" - -/** Subtraction. */ -external sub: (int64, int64) => int64 = "%int64_sub" - -/** Multiplication. */ -external mul: (int64, int64) => int64 = "%int64_mul" - -/** Integer division. Raise [Division_by_zero] if the second - argument is zero. This division rounds the real quotient of - its arguments towards zero, as specified for {!Pervasives.(/)}. */ -external div: (int64, int64) => int64 = "%int64_div" - -/** Integer remainder. If [y] is not zero, the result - of [Int64.rem x y] satisfies the following property: - [x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)]. - If [y = 0], [Int64.rem x y] raises [Division_by_zero]. */ -external rem: (int64, int64) => int64 = "%int64_mod" - -/** Successor. [Int64.succ x] is [Int64.add x Int64.one]. */ -let succ: int64 => int64 - -/** Predecessor. [Int64.pred x] is [Int64.sub x Int64.one]. */ -let pred: int64 => int64 - -/** Return the absolute value of its argument. */ -let abs: int64 => int64 - -/** The greatest representable 64-bit integer, 2{^63} - 1. */ -let max_int: int64 - -/** The smallest representable 64-bit integer, -2{^63}. */ -let min_int: int64 - -/** Bitwise logical and. */ -external logand: (int64, int64) => int64 = "%int64_and" - -/** Bitwise logical or. */ -external logor: (int64, int64) => int64 = "%int64_or" - -/** Bitwise logical exclusive or. */ -external logxor: (int64, int64) => int64 = "%int64_xor" - -/** Bitwise logical negation. */ -let lognot: int64 => int64 - -/** [Int64.shift_left x y] shifts [x] to the left by [y] bits. - The result is unspecified if [y < 0] or [y >= 64]. */ -external shift_left: (int64, int) => int64 = "%int64_lsl" - -/** [Int64.shift_right x y] shifts [x] to the right by [y] bits. - This is an arithmetic shift: the sign bit of [x] is replicated - and inserted in the vacated bits. - The result is unspecified if [y < 0] or [y >= 64]. */ -external shift_right: (int64, int) => int64 = "%int64_asr" - -/** [Int64.shift_right_logical x y] shifts [x] to the right by [y] bits. - This is a logical shift: zeroes are inserted in the vacated bits - regardless of the sign of [x]. - The result is unspecified if [y < 0] or [y >= 64]. */ -external shift_right_logical: (int64, int) => int64 = "%int64_lsr" - -/** Convert the given integer (type [int]) to a 64-bit integer - (type [int64]). */ -external of_int: int => int64 = "%int64_of_int" - -/** Convert the given 64-bit integer (type [int64]) to an - integer (type [int]). On 64-bit platforms, the 64-bit integer - is taken modulo 2{^63}, i.e. the high-order bit is lost - during the conversion. On 32-bit platforms, the 64-bit integer - is taken modulo 2{^31}, i.e. the top 33 bits are lost - during the conversion. */ -external to_int: int64 => int = "%int64_to_int" - -/** Convert the given floating-point number to a 64-bit integer, - discarding the fractional part (truncate towards 0). - The result of the conversion is undefined if, after truncation, - the number is outside the range \[{!Int64.min_int}, {!Int64.max_int}\]. */ -external of_float: float => int64 = "?int64_of_float" - -/** Convert the given 64-bit integer to a floating-point number. */ -external to_float: int64 => float = "?int64_to_float" - -/** Convert the given 32-bit integer (type [int]) - to a 64-bit integer (type [int64]). */ -external of_int32: int => int64 = "%int64_of_int32" - -/** Convert the given 64-bit integer (type [int64]) to a - 32-bit integer (type [int]). The 64-bit integer - is taken modulo 2{^32}, i.e. the top 32 bits are lost - during the conversion. */ -external to_int32: int64 => int = "%int64_to_int32" - -/** Convert the given string to a 64-bit integer. - The string is read in decimal (by default, or if the string - begins with [0u]) or in hexadecimal, octal or binary if the - string begins with [0x], [0o] or [0b] respectively. - - The [0u] prefix reads the input as an unsigned integer in the range - [[0, 2*Int64.max_int+1]]. If the input exceeds {!Int64.max_int} - it is converted to the signed integer - [Int64.min_int + input - Int64.max_int - 1]. - - The [_] (underscore) character can appear anywhere in the string - and is ignored. - Raise [Failure "Int64.of_string"] if the given string is not - a valid representation of an integer, or if the integer represented - exceeds the range of integers representable in type [int64]. */ -external of_string: string => int64 = "?int64_of_string" - -/** Same as [of_string], but return [None] instead of raising. - @since 4.05 */ -let of_string_opt: string => option - -/** Return the string representation of its argument, in decimal. */ -let to_string: int64 => string - -/** Return the internal representation of the given float according - to the IEEE 754 floating-point 'double format' bit layout. - Bit 63 of the result represents the sign of the float; - bits 62 to 52 represent the (biased) exponent; bits 51 to 0 - represent the mantissa. */ -external bits_of_float: float => int64 = "?int64_bits_of_float" - -/** Return the floating-point number whose internal representation, - according to the IEEE 754 floating-point 'double format' bit layout, - is the given [int64]. */ -external float_of_bits: int64 => float = "?int64_float_of_bits" - -/** An alias for the type of 64-bit integers. */ -type t = int64 - -/** The comparison function for 64-bit integers, with the same specification as - {!Pervasives.compare}. Along with the type [t], this function [compare] - allows the module [Int64] to be passed as argument to the functors - {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int - -/** The equal function for int64s. - @since 4.03.0 */ -let equal: (t, t) => bool - -/* {1 Deprecated functions} */ - -/** Do not use this deprecated function. Instead, - used {!Printf.sprintf} with a [%L...] format. */ -external format: (string, int64) => string = "?int64_format" diff --git a/jscomp/stdlib-406/intl/Intl__Collator.res b/jscomp/stdlib-406/intl/Intl__Collator.res new file mode 100644 index 0000000000..2ed6dbe2f3 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__Collator.res @@ -0,0 +1,36 @@ +type t + +type usage = [#sort | #search] +type sensitivity = [#base | #accent | #case | #variant] +type caseFirst = [#upper | #lower | #"false"] + +type options = { + localeMatcher?: Intl__Common.localeMatcher, + usage?: usage, + sensitivity?: sensitivity, + ignorePunctuation?: bool, + numeric?: bool, + caseFirst?: caseFirst, +} + +type resolvedOptions = { + locale: string, + usage: usage, + sensitivity: sensitivity, + ignorePunctuation: bool, + collation: [Intl__Common.collation | #default], + numeric?: bool, + caseFirst?: caseFirst, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.Collator" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.Collator.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external compare: (t, string, string) => int = "compare" diff --git a/jscomp/stdlib-406/intl/Intl__Common.res b/jscomp/stdlib-406/intl/Intl__Common.res new file mode 100644 index 0000000000..e0cea141a5 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__Common.res @@ -0,0 +1,156 @@ +type localeMatcher = [#lookup | @as("best fit") #bestFit] + +type calendar = [ + | #buddhist + | #chinese + | #coptic + | #dangi + | #ethioaa + | #ethiopic + | #gregory + | #hebrew + | #indian + | #islamic + | #"islamic-umalqura" + | #"islamic-tbla" + | #"islamic-civil" + | #"islamic-rgsa" + | #iso8601 + | #japanese + | #persian + | #roc +] + +type collation = [ + | #compat // (Arabic) + | #dict // (Sinhala) + | #emoji // (root) + | #eor // (root) + | #phonebk // (German) + | #phonetic // (Lingala) + | #pinyin // (Chinese) + | #stroke // (Chinese) + | #trad + | #unihan // (Chinese, Japanese, and Korean; not available in Chrome or Edge) + | #zhuyin +] // (Chinese) + +type numberingSystem = [ + | #adlm + | #ahom + | #arab + | #arabext + | #bali + | #beng + | #bhks + | #brah + | #cakm + | #cham + | #deva + | #diak + | #fullwide + | #gong + | #gonm + | #gujr + | #guru + | #hanidec + | #hmng + | #hmnp + | #java + | #kali + | #kawi + | #khmr + | #knda + | #lana + | #lanatham + | #laoo + | #latn + | #lepc + | #limb + | #mathbold + | #mathdbl + | #mathmono + | #mathsanb + | #mathsans + | #mlym + | #modi + | #mong + | #mroo + | #mtei + | #mymr + | #mymrshan + | #mymrtlng + | #nagm + | #newa + | #nkoo + | #olck + | #orya + | #osma + | #rohg + | #saur + | #segment + | #shrd + | #sind + | #sinh + | #sora + | #sund + | #takr + | #talu + | #tamldec + | #telu + | #thai + | #tibt + | #tirh + | #tnsa + | #vaii + | #wara + | #wcho +] + +type oneTo21 = [ + | #1 + | #2 + | #3 + | #4 + | #5 + | #6 + | #7 + | #8 + | #9 + | #10 + | #11 + | #12 + | #13 + | #14 + | #15 + | #16 + | #17 + | #18 + | #19 + | #20 + | #21 +] + +type zeroTo20 = [ + | #0 + | #1 + | #2 + | #3 + | #4 + | #5 + | #6 + | #7 + | #8 + | #9 + | #10 + | #11 + | #12 + | #13 + | #14 + | #15 + | #16 + | #17 + | #18 + | #19 + | #20 +] diff --git a/jscomp/stdlib-406/intl/Intl__DateTimeFormat.res b/jscomp/stdlib-406/intl/Intl__DateTimeFormat.res new file mode 100644 index 0000000000..8d048bdc01 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__DateTimeFormat.res @@ -0,0 +1,125 @@ +type t + +type dateStyle = [#full | #long | #medium | #short] +type timeStyle = [#full | #long | #medium | #short] +type dayPeriod = [#narrow | #short | #long] +type weekday = [#narrow | #short | #long] +type era = [#narrow | #short | #long] +type year = [#numeric | #"2-digit"] +type month = [#numeric | #"2-digit" | #narrow | #short | #long] +type day = [#numeric | #"2-digit"] +type hour = [#numeric | #"2-digit"] +type minute = [#numeric | #"2-digit"] +type second = [#numeric | #"2-digit"] + +/** +Firefox also supports IANA time zone names here +Node v19+ supports "shortOffset", "shortGeneric", "longOffset", and "longGeneric". +*/ +type timeZoneName = [ + | #short + | #long + | #shortOffset + | #shortGeneric + | #longOffset + | #longGeneric +] + +type hourCycle = [#h11 | #h12 | #h23 | #h24] +type formatMatcher = [#basic | @as("best fit") #bestFit] +type fractionalSecondDigits = [#0 | #1 | #2 | #3] + +type options = { + dateStyle?: dateStyle, // can be used with timeStyle, but not other options + timeStyle?: timeStyle, // can be used with dateStyle, but not other options + calendar?: Intl__Common.calendar, + dayPeriod?: dayPeriod, // only has an effect if a 12-hour clock is used + numberingSystem?: Intl__Common.numberingSystem, + localeMatcher?: Intl__Common.localeMatcher, + timeZone?: string, + hour12?: bool, + hourCycle?: hourCycle, + formatMatcher?: formatMatcher, + // date-time components + weekday?: weekday, + era?: era, + year?: year, + month?: month, + day?: day, + hour?: hour, + minute?: minute, + second?: second, + fractionalSecondDigits?: fractionalSecondDigits, + timeZoneName?: timeZoneName, +} + +type resolvedOptions = { + dateStyle?: dateStyle, + timeStyle?: timeStyle, + weekday?: weekday, + era?: era, + year?: year, + month?: month, + day?: day, + hour?: hour, + minute?: minute, + second?: second, + fractionalSecondDigits?: fractionalSecondDigits, + timeZoneName?: timeZoneName, + calendar: Intl__Common.calendar, + hour12: bool, + hourCycle: hourCycle, + locale: string, + numberingSystem: Intl__Common.numberingSystem, + timeZone: string, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +type dateTimeComponent = [ + | #day + | #dayPeriod + | #era + | #fractionalSecond + | #hour + | #literal + | #minute + | #month + | #relatedYear + | #second + | #timeZone + | #weekday + | #year + | #yearName +] + +type dateTimePart = { + \"type": dateTimeComponent, + value: string, +} + +type dateTimeRangeSource = [#startRange | #shared | #endRange] +type dateTimeRangePart = { + \"type": dateTimeComponent, + value: string, + source: dateTimeRangeSource, +} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.DateTimeFormat" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.DateTimeFormat.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external format: (t, Date.t) => string = "format" +@send +external formatToParts: (t, Date.t) => array = "formatToParts" + +@send +external formatRange: (t, ~startDate: Date.t, ~endDate: Date.t) => string = "formatRange" + +@send +external formatRangeToParts: (t, ~startDate: Date.t, ~endDate: Date.t) => array = + "formatRangeToParts" diff --git a/jscomp/stdlib-406/intl/Intl__ListFormat.res b/jscomp/stdlib-406/intl/Intl__ListFormat.res new file mode 100644 index 0000000000..973e1bd96f --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__ListFormat.res @@ -0,0 +1,47 @@ +type t + +type listType = [ + | #conjunction + | #disjunction + | #unit +] +type style = [ + | #long + | #short + | #narrow +] + +type options = { + localeMatcher?: Intl__Common.localeMatcher, + \"type"?: listType, + style?: style, +} + +type listPartComponentType = [ + | #element + | #literal +] + +type listPart = { + \"type": listPartComponentType, + value: string, +} + +type resolvedOptions = { + locale: string, + style: style, + \"type": listType, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.ListFormat" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.ListFormat.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external format: (t, array) => string = "format" +@send external formatToParts: (t, array) => array = "formatToParts" diff --git a/jscomp/stdlib-406/intl/Intl__Locale.res b/jscomp/stdlib-406/intl/Intl__Locale.res new file mode 100644 index 0000000000..88d55bad4a --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__Locale.res @@ -0,0 +1,30 @@ +type t + +type options = { + baseName?: string, + calendar?: Intl__Common.calendar, + collation?: Intl__Common.collation, + hourCycle?: [#h11 | #h12 | #h23 | #h24], + caseFirst?: [#upper | #lower | #"false"], + numberingSystem?: Intl__Common.numberingSystem, + numeric?: bool, + language?: string, + script?: string, + region?: string, +} + +@new external make: (string, ~options: options=?) => t = "Intl.Locale" + +@get external baseName: t => string = "baseName" +@get external calendar: t => option = "calendar" +@get external caseFirst: t => option = "caseFirst" +@get external collation: t => option = "collation" +@get external hourCycle: t => option = "hourCycle" +@get external language: t => string = "language" +@get external numberingSystem: t => option = "numberingSystem" +@get external numeric: t => bool = "numeric" +@get external region: t => option = "region" +@get external script: t => option = "script" + +@send external maximize: t => t = "maximize" +@send external minimize: t => t = "minimize" diff --git a/jscomp/stdlib-406/intl/Intl__NumberFormat.res b/jscomp/stdlib-406/intl/Intl__NumberFormat.res new file mode 100644 index 0000000000..e002400f54 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__NumberFormat.res @@ -0,0 +1,211 @@ +module Grouping = Intl__NumberFormat__Grouping + +type t + +/** +An ISO 4217 currency code. e.g. USD, EUR, CNY +*/ +type currency = string +type currencyDisplay = [#symbol | #narrowSymbol | #code | #name] +type currencySign = [#accounting | #standard] +type notation = [#scientific | #standard | #engineering | #compact] + +/** +Used only when notation is #compact +*/ +type compactDisplay = [#short | #long] + +type signDisplay = [ + | #auto + | #always + | #exceptZero + | #never + | #negative +] + +type style = [#decimal | #currency | #percent | #unit] + +/** +Defined in https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier +Only used when style is #unit +*/ +type unitSystem = string + +/** +Only used when style is #unit +*/ +type unitDisplay = [#long | #short | #narrow] + +type rounding = [ + | #ceil + | #floor + | #expand + | #trunc + | #halfCeil + | #halfFloor + | #halfExpand + | #halfTrunc + | #halfEven +] + +type roundingPriority = [#auto | #morePrecision | #lessPrecision] + +type roundingIncrement = [ + | #1 + | #2 + | #5 + | #10 + | #20 + | #25 + | #50 + | #100 + | #200 + | #250 + | #500 + | #1000 + | #2000 + | #2500 + | #5000 +] + +type trailingZeroDisplay = [#auto | #stripIfInteger | #lessPrecision] + +type options = { + compactDisplay?: compactDisplay, + numberingSystem?: Intl__Common.numberingSystem, + currency?: currency, + currencyDisplay?: currencyDisplay, + currencySign?: currencySign, + localeMatcher?: Intl__Common.localeMatcher, + notation?: notation, + signDisplay?: signDisplay, + style?: style, + /** + required if style == #unit + */ + unit?: unitSystem, + unitDisplay?: unitDisplay, + useGrouping?: Grouping.t, + roundingMode?: rounding, // not available in firefox v110 + roundingPriority?: roundingPriority, // not available in firefox v110 + roundingIncrement?: roundingIncrement, // not available in firefox v110 + /** + Supported everywhere but Firefox as of v110 + */ + trailingZeroDisplay?: trailingZeroDisplay, + // use either this group + minimumIntegerDigits?: Intl__Common.oneTo21, + minimumFractionDigits?: Intl__Common.zeroTo20, + maximumFractionDigits?: Intl__Common.zeroTo20, + // OR these + minimumSignificantDigits?: Intl__Common.oneTo21, + maximumSignificantDigits?: Intl__Common.oneTo21, +} + +type resolvedOptions = { + // only when style == "currency" + currency?: currency, + currencyDisplay?: currencyDisplay, + currencySign?: currencySign, + // only when notation == "compact" + compactDisplay?: compactDisplay, + // only when style == "unit" + unit: unitSystem, + unitDisplay: unitDisplay, + roundingMode?: rounding, // not available in firefox v110 + roundingPriority?: roundingPriority, // not available in firefox v110 + roundingIncrement?: roundingIncrement, // not available in firefox v110 + // either this group + minimumIntegerDigits?: Intl__Common.oneTo21, + minimumFractionDigits?: Intl__Common.zeroTo20, + maximumFractionDigits?: Intl__Common.zeroTo20, + // OR these + minimumSignificantDigits?: Intl__Common.oneTo21, + maximumSignificantDigits?: Intl__Common.oneTo21, + // always present + locale: string, + notation: notation, + numberingSystem: Intl__Common.numberingSystem, + signDisplay: signDisplay, + style: style, + useGrouping: Grouping.t, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +type numberFormatPartType = [ + | #compact + | #currency + | #decimal + | #exponentInteger + | #exponentMinusSign + | #exponentSeparator + | #fraction + | #group + | #infinity + | #integer + | #literal + | #minusSign + | #nan + | #plusSign + | #percentSign + | #unit + | #unknown +] + +type numberFormatPart = { + \"type": numberFormatPartType, + value: string, +} + +type rangeSource = [#startRange | #endRange | #shared] + +type numberFormatRangePart = { + \"type": numberFormatPartType, + value: string, + source: rangeSource, +} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.NumberFormat" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.NumberFormat.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external format: (t, float) => string = "format" +@send +external formatRange: (t, ~start: float, ~end: float) => array = "formatRange" +@send +external formatToParts: (t, float) => array = "formatToParts" +@send +external formatRangeToParts: (t, ~start: float, ~end: float) => array = + "formatRange" + +@send external formatInt: (t, int) => string = "format" + +@send +external formatIntRange: (t, ~start: int, ~end: int) => array = "formatRange" +@send +external formatIntToParts: (t, int) => array = "formatToParts" + +@send +external formatIntRangeToParts: (t, ~start: int, ~end: int) => array = + "formatRange" + +@send external formatBigInt: (t, bigint) => string = "format" + +@send +external formatBigIntRange: (t, ~start: bigint, ~end: bigint) => array = "formatRange" +@send +external formatBigIntToParts: (t, bigint) => array = "formatToParts" + +@send +external formatBigIntRangeToParts: (t, ~start: bigint, ~end: bigint) => array = + "formatRange" + +@send external formatString: (t, string) => string = "format" + +@send +external formatStringToParts: (t, string) => array = "formatToParts" diff --git a/jscomp/stdlib-406/intl/Intl__NumberFormat__Grouping.res b/jscomp/stdlib-406/intl/Intl__NumberFormat__Grouping.res new file mode 100644 index 0000000000..600b06ba1e --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__NumberFormat__Grouping.res @@ -0,0 +1,15 @@ +type t + +type parsed = [#bool(bool) | #always | #auto | #min2] + +external fromBool: bool => t = "%identity" +external fromString: [#always | #auto | #min2] => t = "%identity" + +let parseJsValue = value => + switch Type.Classify.classify(value) { + | String("always") => Some(#always) + | String("auto") => Some(#auto) + | String("min2") => Some(#min2) + | Bool(value) => Some(#bool(value)) + | _ => None + } diff --git a/jscomp/stdlib-406/intl/Intl__PluralRules.res b/jscomp/stdlib-406/intl/Intl__PluralRules.res new file mode 100644 index 0000000000..0634a3c504 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__PluralRules.res @@ -0,0 +1,62 @@ +type t + +type localeType = [#cardinal | #ordinal] + +type options = { + localeMatcher?: Intl__Common.localeMatcher, + \"type"?: localeType, + // use either this group + minimumIntegerDigits?: Intl__Common.oneTo21, + minimumFractionDigits?: Intl__Common.zeroTo20, + maximumFractionDigits?: Intl__Common.zeroTo20, + // OR this group + minimumSignificantDigits?: Intl__Common.oneTo21, + maximumSignificantDigits?: Intl__Common.oneTo21, +} + +type pluralCategories = [ + | #zero + | #one + | #two + | #few + | #many + | #other +] + +type resolvedOptions = { + locale: string, + pluralCategories: array, + \"type": localeType, + // either this group + minimumIntegerDigits?: Intl__Common.oneTo21, + minimumFractionDigits?: Intl__Common.zeroTo20, + maximumFractionDigits?: Intl__Common.zeroTo20, + // OR this group + minimumSignificantDigits?: Intl__Common.oneTo21, + maximumSignificantDigits?: Intl__Common.oneTo21, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.PluralRules" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.PluralRules.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +type rule = [#zero | #one | #two | #few | #many | #other] + +@send external select: (t, float) => rule = "select" +@send external selectInt: (t, int) => rule = "select" +@send external selectBigInt: (t, bigint) => rule = "select" + +@send +external selectRange: (t, ~start: float, ~end: float) => rule = "selectRange" + +@send +external selectRangeInt: (t, ~start: int, ~end: int) => rule = "selectRange" + +@send +external selectRangeBigInt: (t, ~start: bigint, ~end: bigint) => rule = "selectRange" diff --git a/jscomp/stdlib-406/intl/Intl__RelativeTimeFormat.res b/jscomp/stdlib-406/intl/Intl__RelativeTimeFormat.res new file mode 100644 index 0000000000..e2d4dc9adb --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__RelativeTimeFormat.res @@ -0,0 +1,40 @@ +type t + +type numeric = [#always | #auto] +type style = [#long | #short | #narrow] +type timeUnit = [#year | #quarter | #month | #week | #day | #hour | #minute | #second] + +type options = { + localeMatcher?: Intl__Common.localeMatcher, + numeric?: numeric, + style?: style, +} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +type resolvedOptions = { + locale: string, + numeric: numeric, + style: style, + numberingSystem: string, +} + +type relativeTimePartComponent = [#literal | #integer] +type relativeTimePart = { + \"type": relativeTimePartComponent, + value: string, + unit?: timeUnit, +} + +@new +external make: (~locales: array=?, ~options: options=?) => t = "Intl.RelativeTimeFormat" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.RelativeTimeFormat.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external format: (t, int, timeUnit) => string = "format" +@send +external formatToParts: (t, int, timeUnit) => array = "formatToParts" diff --git a/jscomp/stdlib-406/intl/Intl__Segmenter.res b/jscomp/stdlib-406/intl/Intl__Segmenter.res new file mode 100644 index 0000000000..f7018d6c2e --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__Segmenter.res @@ -0,0 +1,34 @@ +/*** +Not supported in Firefox +*/ +type t + +type granularity = [#grapheme | #word | #sentence] + +type options = { + localeMatcher?: Intl__Common.localeMatcher, + granularity?: granularity, +} + +type pluralCategories = [ + | #zero + | #one + | #two + | #few + | #many + | #other +] + +type resolvedOptions = {locale: string, granularity: granularity} + +type supportedLocalesOptions = {localeMatcher: Intl__Common.localeMatcher} + +@new external make: (~locales: array=?, ~options: options=?) => t = "Intl.Segmenter" + +@val +external supportedLocalesOf: (array, ~options: supportedLocalesOptions=?) => t = + "Intl.Segmenter.supportedLocalesOf" + +@send external resolvedOptions: t => resolvedOptions = "resolvedOptions" + +@send external segment: (t, string) => Intl__Segments.t = "segment" diff --git a/jscomp/stdlib-406/intl/Intl__Segments.res b/jscomp/stdlib-406/intl/Intl__Segments.res new file mode 100644 index 0000000000..33b06ea177 --- /dev/null +++ b/jscomp/stdlib-406/intl/Intl__Segments.res @@ -0,0 +1,18 @@ +/*** + A Segments instance is an object that represents the segments of a specific string, subject to the locale and options of its constructing Intl.Segmenter instance. +https://tc39.es/ecma402/#sec-segments-objects +*/ +type t + +type segmentData = { + segment: string, + index: int, + isWordLike: option, + input: string, +} + +@send +external containing: t => segmentData = "containing" + +@send +external containingWithIndex: (t, int) => segmentData = "containing" diff --git a/jscomp/stdlib-406/lexing.res b/jscomp/stdlib-406/lexing.res deleted file mode 100644 index 2773ecb4cf..0000000000 --- a/jscomp/stdlib-406/lexing.res +++ /dev/null @@ -1,245 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* The run-time library for lexers generated by camllex */ - -type position = { - pos_fname: string, - pos_lnum: int, - pos_bol: int, - pos_cnum: int, -} - -let dummy_pos = { - pos_fname: "", - pos_lnum: 0, - pos_bol: 0, - pos_cnum: -1, -} - -type rec lexbuf = { - refill_buff: lexbuf => unit, - mutable lex_buffer: bytes, - mutable lex_buffer_len: int, - mutable lex_abs_pos: int, - mutable lex_start_pos: int, - mutable lex_curr_pos: int, - mutable lex_last_pos: int, - mutable lex_last_action: int, - mutable lex_eof_reached: bool, - mutable lex_mem: array, - mutable lex_start_p: position, - mutable lex_curr_p: position, -} - -type lex_tables = { - lex_base: string, - lex_backtrk: string, - lex_default: string, - lex_trans: string, - lex_check: string, - lex_base_code: string, - lex_backtrk_code: string, - lex_default_code: string, - lex_trans_code: string, - lex_check_code: string, - lex_code: string, -} - -external c_engine: (lex_tables, int, lexbuf) => int = "?lex_engine" -external c_new_engine: (lex_tables, int, lexbuf) => int = "?new_lex_engine" - -let engine = (tbl, state, buf) => { - let result = c_engine(tbl, state, buf) - if result >= 0 { - buf.lex_start_p = buf.lex_curr_p - buf.lex_curr_p = { - ...buf.lex_curr_p, - pos_cnum: buf.lex_abs_pos + buf.lex_curr_pos, - } - } - result -} - -let new_engine = (tbl, state, buf) => { - let result = c_new_engine(tbl, state, buf) - if result >= 0 { - buf.lex_start_p = buf.lex_curr_p - buf.lex_curr_p = { - ...buf.lex_curr_p, - pos_cnum: buf.lex_abs_pos + buf.lex_curr_pos, - } - } - result -} - -let lex_refill = (read_fun, aux_buffer, lexbuf) => { - let read = read_fun(aux_buffer, Bytes.length(aux_buffer)) - let n = if read > 0 { - read - } else { - lexbuf.lex_eof_reached = true - 0 - } - - /* Current state of the buffer: - <-------|---------------------|-----------> - | junk | valid data | junk | - ^ ^ ^ ^ - 0 start_pos buffer_end Bytes.length buffer - */ - if lexbuf.lex_buffer_len + n > Bytes.length(lexbuf.lex_buffer) { - /* There is not enough space at the end of the buffer */ - if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n <= Bytes.length(lexbuf.lex_buffer) { - /* But there is enough space if we reclaim the junk at the beginning - of the buffer */ - Bytes.blit( - lexbuf.lex_buffer, - lexbuf.lex_start_pos, - lexbuf.lex_buffer, - 0, - lexbuf.lex_buffer_len - lexbuf.lex_start_pos, - ) - } else { - /* We must grow the buffer. Doubling its size will provide enough - space since n <= String.length aux_buffer <= String.length buffer. - Watch out for string length overflow, though. */ - let newlen = 2 * Bytes.length(lexbuf.lex_buffer) - - if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n > newlen { - failwith("Lexing.lex_refill: cannot grow buffer") - } - let newbuf = Bytes.create(newlen) - /* Copy the valid data to the beginning of the new buffer */ - Bytes.blit( - lexbuf.lex_buffer, - lexbuf.lex_start_pos, - newbuf, - 0, - lexbuf.lex_buffer_len - lexbuf.lex_start_pos, - ) - lexbuf.lex_buffer = newbuf - } - /* Reallocation or not, we have shifted the data left by - start_pos characters; update the positions */ - let s = lexbuf.lex_start_pos - lexbuf.lex_abs_pos = lexbuf.lex_abs_pos + s - lexbuf.lex_curr_pos = lexbuf.lex_curr_pos - s - lexbuf.lex_start_pos = 0 - lexbuf.lex_last_pos = lexbuf.lex_last_pos - s - lexbuf.lex_buffer_len = lexbuf.lex_buffer_len - s - let t = lexbuf.lex_mem - for i in 0 to Array.length(t) - 1 { - let v = t[i] - if v >= 0 { - t[i] = v - s - } - } - } - /* There is now enough space at the end of the buffer */ - Bytes.blit(aux_buffer, 0, lexbuf.lex_buffer, lexbuf.lex_buffer_len, n) - lexbuf.lex_buffer_len = lexbuf.lex_buffer_len + n -} - -let zero_pos = { - pos_fname: "", - pos_lnum: 1, - pos_bol: 0, - pos_cnum: 0, -} - -let from_function = f => { - refill_buff: lex_refill(f, Bytes.create(512)), - lex_buffer: Bytes.create(1024), - lex_buffer_len: 0, - lex_abs_pos: 0, - lex_start_pos: 0, - lex_curr_pos: 0, - lex_last_pos: 0, - lex_last_action: 0, - lex_mem: [], - lex_eof_reached: false, - lex_start_p: zero_pos, - lex_curr_p: zero_pos, -} - -let from_string = s => { - refill_buff: lexbuf => lexbuf.lex_eof_reached = true, - lex_buffer: Bytes.of_string(s) /* have to make a copy for compatibility - with unsafe-string mode */, - lex_buffer_len: String.length(s), - lex_abs_pos: 0, - lex_start_pos: 0, - lex_curr_pos: 0, - lex_last_pos: 0, - lex_last_action: 0, - lex_mem: [], - lex_eof_reached: true, - lex_start_p: zero_pos, - lex_curr_p: zero_pos, -} - -let lexeme = lexbuf => { - let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos - Bytes.sub_string(lexbuf.lex_buffer, lexbuf.lex_start_pos, len) -} - -let sub_lexeme = (lexbuf, i1, i2) => { - let len = i2 - i1 - Bytes.sub_string(lexbuf.lex_buffer, i1, len) -} - -let sub_lexeme_opt = (lexbuf, i1, i2) => - if i1 >= 0 { - let len = i2 - i1 - Some(Bytes.sub_string(lexbuf.lex_buffer, i1, len)) - } else { - None - } - -let sub_lexeme_char = (lexbuf, i) => Bytes.get(lexbuf.lex_buffer, i) - -let sub_lexeme_char_opt = (lexbuf, i) => - if i >= 0 { - Some(Bytes.get(lexbuf.lex_buffer, i)) - } else { - None - } - -let lexeme_char = (lexbuf, i) => Bytes.get(lexbuf.lex_buffer, lexbuf.lex_start_pos + i) - -let lexeme_start = lexbuf => lexbuf.lex_start_p.pos_cnum -let lexeme_end = lexbuf => lexbuf.lex_curr_p.pos_cnum - -let lexeme_start_p = lexbuf => lexbuf.lex_start_p -let lexeme_end_p = lexbuf => lexbuf.lex_curr_p - -let new_line = lexbuf => { - let lcp = lexbuf.lex_curr_p - lexbuf.lex_curr_p = { - ...lcp, - pos_lnum: lcp.pos_lnum + 1, - pos_bol: lcp.pos_cnum, - } -} - -/* Discard data left in lexer buffer. */ - -let flush_input = lb => { - lb.lex_curr_pos = 0 - lb.lex_abs_pos = 0 - lb.lex_curr_p = {...lb.lex_curr_p, pos_cnum: 0} - lb.lex_buffer_len = 0 -} diff --git a/jscomp/stdlib-406/lexing.resi b/jscomp/stdlib-406/lexing.resi deleted file mode 100644 index 9a84781324..0000000000 --- a/jscomp/stdlib-406/lexing.resi +++ /dev/null @@ -1,164 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** The run-time library for lexers generated by [ocamllex]. */ - -/* {1 Positions} */ - -/** A value of type [position] describes a point in a source file. - [pos_fname] is the file name; [pos_lnum] is the line number; - [pos_bol] is the offset of the beginning of the line (number - of characters between the beginning of the lexbuf and the beginning - of the line); [pos_cnum] is the offset of the position (number of - characters between the beginning of the lexbuf and the position). - The difference between [pos_cnum] and [pos_bol] is the character - offset within the line (i.e. the column number, assuming each - character is one column wide). - - See the documentation of type [lexbuf] for information about - how the lexing engine will manage positions. - */ -type position = { - pos_fname: string, - pos_lnum: int, - pos_bol: int, - pos_cnum: int, -} - -/** A value of type [position], guaranteed to be different from any - valid position. - */ -let dummy_pos: position - -/* {1 Lexer buffers} */ - -/** The type of lexer buffers. A lexer buffer is the argument passed - to the scanning functions defined by the generated scanners. - The lexer buffer holds the current state of the scanner, plus - a function to refill the buffer from the input. - - At each token, the lexing engine will copy [lex_curr_p] to - [lex_start_p], then change the [pos_cnum] field - of [lex_curr_p] by updating it with the number of characters read - since the start of the [lexbuf]. The other fields are left - unchanged by the lexing engine. In order to keep them - accurate, they must be initialised before the first use of the - lexbuf, and updated by the relevant lexer actions (i.e. at each - end of line -- see also [new_line]). - */ -type rec lexbuf = { - refill_buff: lexbuf => unit, - mutable lex_buffer: bytes, - mutable lex_buffer_len: int, - mutable lex_abs_pos: int, - mutable lex_start_pos: int, - mutable lex_curr_pos: int, - mutable lex_last_pos: int, - mutable lex_last_action: int, - mutable lex_eof_reached: bool, - mutable lex_mem: array, - mutable lex_start_p: position, - mutable lex_curr_p: position, -} - -/** Create a lexer buffer which reads from - the given string. Reading starts from the first character in - the string. An end-of-input condition is generated when the - end of the string is reached. */ -let from_string: string => lexbuf - -/** Create a lexer buffer with the given function as its reading method. - When the scanner needs more characters, it will call the given - function, giving it a byte sequence [s] and a byte - count [n]. The function should put [n] bytes or fewer in [s], - starting at index 0, and return the number of bytes - provided. A return value of 0 means end of input. */ -let from_function: ((bytes, int) => int) => lexbuf - -/* {1 Functions for lexer semantic actions} */ - -/* The following functions can be called from the semantic actions - of lexer definitions (the ML code enclosed in braces that - computes the value returned by lexing functions). They give - access to the character string matched by the regular expression - associated with the semantic action. These functions must be - applied to the argument [lexbuf], which, in the code generated by - [ocamllex], is bound to the lexer buffer passed to the parsing - function. */ - -/** [Lexing.lexeme lexbuf] returns the string matched by - the regular expression. */ -let lexeme: lexbuf => string - -/** [Lexing.lexeme_char lexbuf i] returns character number [i] in - the matched string. */ -let lexeme_char: (lexbuf, int) => char - -/** [Lexing.lexeme_start lexbuf] returns the offset in the - input stream of the first character of the matched string. - The first character of the stream has offset 0. */ -let lexeme_start: lexbuf => int - -/** [Lexing.lexeme_end lexbuf] returns the offset in the input stream - of the character following the last character of the matched - string. The first character of the stream has offset 0. */ -let lexeme_end: lexbuf => int - -/** Like [lexeme_start], but return a complete [position] instead - of an offset. */ -let lexeme_start_p: lexbuf => position - -/** Like [lexeme_end], but return a complete [position] instead - of an offset. */ -let lexeme_end_p: lexbuf => position - -/** Update the [lex_curr_p] field of the lexbuf to reflect the start - of a new line. You can call this function in the semantic action - of the rule that matches the end-of-line character. - @since 3.11.0 -*/ -let new_line: lexbuf => unit - -/* {1 Miscellaneous functions} */ - -/** Discard the contents of the buffer and reset the current - position to 0. The next use of the lexbuf will trigger a - refill. */ -let flush_input: lexbuf => unit - -/* The following definitions are used by the generated scanners only. - They are not intended to be used directly by user programs. */ - -let sub_lexeme: (lexbuf, int, int) => string -let sub_lexeme_opt: (lexbuf, int, int) => option -let sub_lexeme_char: (lexbuf, int) => char -let sub_lexeme_char_opt: (lexbuf, int) => option - -type lex_tables = { - lex_base: string, - lex_backtrk: string, - lex_default: string, - lex_trans: string, - lex_check: string, - lex_base_code: string, - lex_backtrk_code: string, - lex_default_code: string, - lex_trans_code: string, - lex_check_code: string, - lex_code: string, -} - -let engine: (lex_tables, int, lexbuf) => int -let new_engine: (lex_tables, int, lexbuf) => int diff --git a/jscomp/stdlib-406/list.res b/jscomp/stdlib-406/list.res index c8ae708a4e..6303c7a6b0 100644 --- a/jscomp/stdlib-406/list.res +++ b/jscomp/stdlib-406/list.res @@ -1,749 +1,851 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ +/* Copyright (C) 2017 Hongbo Zhang, Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/* + perf is not everything, there are better memory represenations + + ``` + type 'a cell = { + mutable head : 'a; + mutable tail : 'a opt_cell + } + + and 'a opt_cell = 'a cell Js.null + + and 'a t = { + length : int ; + data : 'a opt_cell + } + ``` + However, + - people use List not because of its perf, but its + convenience, in that case, pattern match and compatibility seems + more attractive, we could keep a mutable list + - The built in types would indicate that + its construtor is immutable, a better optimizer would break such code + + ``` + type 'a t = { + head : 'a; + mutable tail : 'a t | int + } + ``` + In the future, we could come up with a safer version + ``` + type 'a t = + | Nil + | Cons of { hd : 'a ; mutable tail : 'a t } + ``` +*/ + +@@config({flags: ["-bs-noassertfalse"]}) + +type t<'a> = list<'a> + +// TODO: This module should be inlined eventually, if we end up removing Belt +// from the compiler. +module A = { + let makeUninitializedUnsafe = Belt_Array.makeUninitializedUnsafe + let reduceReverseU = Belt_Array.reduceReverseU + let reduceReverse2U = Belt_Array.reduceReverse2U +} + +external mutableCell: ('a, t<'a>) => t<'a> = "#makemutablelist" + +/* + `mutableCell x []` == `x` + but tell the compiler that is a mutable cell, so it wont + be mis-inlined in the future + dont inline a binding to mutable cell, it is mutable +*/ +/* INVARIANT: relies on Literals.tl (internal representation) */ +@set external unsafeMutateTail: (t<'a>, t<'a>) => unit = "tl" + +/* + - the cell is not empty +*/ -/* List operations */ +let head = x => + switch x { + | list{} => None + | list{x, ..._} => Some(x) + } -let rec length_aux = (len, param) => - switch param { - | list{} => len - | list{_, ...l} => length_aux(len + 1, l) +let headExn = x => + switch x { + | list{} => raise(Not_found) + | list{x, ..._} => x } -let length = l => length_aux(0, l) +let tail = x => + switch x { + | list{} => None + | list{_, ...xs} => Some(xs) + } + +let tailExn = x => + switch x { + | list{} => raise(Not_found) + | list{_, ...t} => t + } -let cons = (a, l) => list{a, ...l} +let add = (xs, x) => list{x, ...xs} -let hd = param => - switch param { - | list{} => failwith("hd") - | list{a, ..._} => a +/* Assume `n >=0` */ +let rec nthAux = (x, n) => + switch x { + | list{h, ...t} => + if n == 0 { + Some(h) + } else { + nthAux(t, n - 1) + } + | _ => None } -let tl = param => - switch param { - | list{} => failwith("tl") - | list{_, ...l} => l +let rec nthAuxAssert = (x, n) => + switch x { + | list{h, ...t} => + if n == 0 { + h + } else { + nthAuxAssert(t, n - 1) + } + | _ => raise(Not_found) } -let nth = (l, n) => +let get = (x, n) => if n < 0 { - invalid_arg("List.nth") + None } else { - let rec nth_aux = (l, n) => - switch l { - | list{} => failwith("nth") - | list{a, ...l} => - if n == 0 { - a - } else { - nth_aux(l, n - 1) - } - } - nth_aux(l, n) + nthAux(x, n) } -let nth_opt = (l, n) => +let getExn = (x, n) => if n < 0 { - invalid_arg("List.nth") + raise(Not_found) } else { - let rec nth_aux = (l, n) => - switch l { - | list{} => None - | list{a, ...l} => - if n == 0 { - Some(a) - } else { - nth_aux(l, n - 1) - } - } - nth_aux(l, n) + nthAuxAssert(x, n) } -let append = \"@" +let rec partitionAux = (p, cell, precX, precY) => + switch cell { + | list{} => () + | list{h, ...t} => + let next = mutableCell(h, list{}) + if p(h) { + unsafeMutateTail(precX, next) + partitionAux(p, t, next, precY) + } else { + unsafeMutateTail(precY, next) + partitionAux(p, t, precX, next) + } + } -let rec rev_append = (l1, l2) => - switch l1 { - | list{} => l2 - | list{a, ...l} => rev_append(l, list{a, ...l2}) +let rec splitAux = (cell, precX, precY) => + switch cell { + | list{} => () + | list{(a, b), ...t} => + let nextA = mutableCell(a, list{}) + let nextB = mutableCell(b, list{}) + unsafeMutateTail(precX, nextA) + unsafeMutateTail(precY, nextB) + splitAux(t, nextA, nextB) } -let rev = l => rev_append(l, list{}) +/* return the tail pointer so it can continue copy other + list +*/ +let rec copyAuxCont = (cellX, prec) => + switch cellX { + | list{} => prec + | list{h, ...t} => + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + copyAuxCont(t, next) + } -let rec init_tailrec_aux = (acc, i, n, f) => - if i >= n { - acc +let rec copyAuxWitFilter = (f, cellX, prec) => + switch cellX { + | list{} => () + | list{h, ...t} => + if f(h) { + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + copyAuxWitFilter(f, t, next) + } else { + copyAuxWitFilter(f, t, prec) + } + } + +let rec copyAuxWithFilterIndex = (f, cellX, prec, i) => + switch cellX { + | list{} => () + | list{h, ...t} => + if f(h, i) { + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + copyAuxWithFilterIndex(f, t, next, i + 1) + } else { + copyAuxWithFilterIndex(f, t, prec, i + 1) + } + } + +let rec copyAuxWitFilterMap = (f, cellX, prec) => + switch cellX { + | list{} => () + | list{h, ...t} => + switch f(h) { + | Some(h) => + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + copyAuxWitFilterMap(f, t, next) + | None => copyAuxWitFilterMap(f, t, prec) + } + } + +let rec removeAssocAuxWithMap = (cellX, x, prec, f) => + switch cellX { + | list{} => false + | list{(a, _) as h, ...t} => + if f(a, x) { + unsafeMutateTail(prec, t) + true + } else { + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + removeAssocAuxWithMap(t, x, next, f) + } + } + +let rec setAssocAuxWithMap = (cellX, x, k, prec, eq) => + switch cellX { + | list{} => false + | list{(a, _) as h, ...t} => + if eq(a, x) { + unsafeMutateTail(prec, list{(x, k), ...t}) + true + } else { + let next = mutableCell(h, list{}) + unsafeMutateTail(prec, next) + setAssocAuxWithMap(t, x, k, next, eq) + } + } + +let rec copyAuxWithMap = (cellX, prec, f) => + switch cellX { + | list{} => () + | list{h, ...t} => + let next = mutableCell(f(h), list{}) + unsafeMutateTail(prec, next) + copyAuxWithMap(t, next, f) + } + +let rec zipAux = (cellX, cellY, prec) => + switch (cellX, cellY) { + | (list{h1, ...t1}, list{h2, ...t2}) => + let next = mutableCell((h1, h2), list{}) + unsafeMutateTail(prec, next) + zipAux(t1, t2, next) + | (list{}, _) | (_, list{}) => () + } + +let rec copyAuxWithMap2 = (f, cellX, cellY, prec) => + switch (cellX, cellY) { + | (list{h1, ...t1}, list{h2, ...t2}) => + let next = mutableCell(f(h1, h2), list{}) + unsafeMutateTail(prec, next) + copyAuxWithMap2(f, t1, t2, next) + | (list{}, _) | (_, list{}) => () + } + +let rec copyAuxWithMapI = (f, i, cellX, prec) => + switch cellX { + | list{h, ...t} => + let next = mutableCell(f(h, i), list{}) + unsafeMutateTail(prec, next) + copyAuxWithMapI(f, i + 1, t, next) + | list{} => () + } + +let rec takeAux = (n, cell, prec) => + if n == 0 { + true } else { - init_tailrec_aux(list{f(i), ...acc}, i + 1, n, f) + switch cell { + | list{} => false + | list{x, ...xs} => + let cell = mutableCell(x, list{}) + unsafeMutateTail(prec, cell) + takeAux(n - 1, xs, cell) + } } -let rec init_aux = (i, n, f) => - if i >= n { - list{} +let rec splitAtAux = (n, cell, prec) => + if n == 0 { + Some(cell) } else { - let r = f(i) - list{r, ...init_aux(i + 1, n, f)} + switch cell { + | list{} => None + | list{x, ...xs} => + let cell = mutableCell(x, list{}) + unsafeMutateTail(prec, cell) + splitAtAux(n - 1, xs, cell) + } + } + +/* invarint `n >= 0` */ +let take = (lst, n) => + if n < 0 { + None + } else if n == 0 { + Some(list{}) + } else { + switch lst { + | list{} => None + | list{x, ...xs} => + let cell = mutableCell(x, list{}) + let has = takeAux(n - 1, xs, cell) + if has { + Some(cell) + } else { + None + } + } + } +/* invariant `n >= 0 ` */ +let rec dropAux = (l, n) => + if n == 0 { + Some(l) + } else { + switch l { + | list{_, ...tl} => dropAux(tl, n - 1) + | list{} => None + } } -let init = (len, f) => - if len < 0 { - invalid_arg("List.init") - } else if len > 10_000 { - rev(init_tailrec_aux(list{}, 0, len, f)) +let drop = (lst, n) => + if n < 0 { + None } else { - init_aux(0, len, f) + dropAux(lst, n) } -let rec flatten = param => - switch param { - | list{} => list{} - | list{l, ...r} => \"@"(l, flatten(r)) +let splitAt = (lst, n) => + if n < 0 { + None + } else if n == 0 { + Some(list{}, lst) + } else { + switch lst { + | list{} => None + | list{x, ...xs} => + let cell = mutableCell(x, list{}) + let rest = splitAtAux(n - 1, xs, cell) + switch rest { + | Some(rest) => Some(cell, rest) + | None => None + } + } } -let concat = flatten +let concat = (xs, ys) => + switch xs { + | list{} => ys + | list{h, ...t} => + let cell = mutableCell(h, list{}) + unsafeMutateTail(copyAuxCont(t, cell), ys) + cell + } -let rec map = (f, param) => - switch param { +let map = (xs, f) => + switch xs { | list{} => list{} - | list{a, ...l} => - let r = f(a) - list{r, ...map(f, l)} + | list{h, ...t} => + let cell = mutableCell(f(h), list{}) + copyAuxWithMap(t, cell, f) + cell } -let rec mapi = (i, f, param) => - switch param { +let zipBy = (l1, l2, f) => + switch (l1, l2) { + | (list{a1, ...l1}, list{a2, ...l2}) => + let cell = mutableCell(f(a1, a2), list{}) + copyAuxWithMap2(f, l1, l2, cell) + cell + | (list{}, _) | (_, list{}) => list{} + } + +let mapWithIndex = (xs, f) => + switch xs { | list{} => list{} - | list{a, ...l} => - let r = f(i, a) - list{r, ...mapi(i + 1, f, l)} + | list{h, ...t} => + let cell = mutableCell(f(h, 0), list{}) + copyAuxWithMapI(f, 1, t, cell) + cell } -let mapi = (f, l) => mapi(0, f, l) +let fromInitializer = (~length as n, f) => + if n <= 0 { + list{} + } else { + let headX = mutableCell(f(0), list{}) + let cur = ref(headX) + let i = ref(1) + while i.contents < n { + let v = mutableCell(f(i.contents), list{}) + unsafeMutateTail(cur.contents, v) + cur.contents = v + i.contents = i.contents + 1 + } + + headX + } -let rev_map = (f, l) => { - let rec rmap_f = (accu, param) => - switch param { - | list{} => accu - | list{a, ...l} => rmap_f(list{f(a), ...accu}, l) +let make = (type a, ~length as n, v: a): list => + if n <= 0 { + list{} + } else { + let headX = mutableCell(v, list{}) + let cur = ref(headX) + let i = ref(1) + while i.contents < n { + let v = mutableCell(v, list{}) + unsafeMutateTail(cur.contents, v) + cur.contents = v + i.contents = i.contents + 1 } - rmap_f(list{}, l) + headX + } + +let rec lengthAux = (x, acc) => + switch x { + | list{} => acc + | list{_, ...t} => lengthAux(t, acc + 1) + } + +let length = xs => lengthAux(xs, 0) +let size = length + +let rec fillAux = (arr, i, x) => + switch x { + | list{} => () + | list{h, ...t} => + Array.setUnsafe(arr, i, h) + fillAux(arr, i + 1, t) + } + +let rec fromArrayAux = (a, i, res) => + if i < 0 { + res + } else { + fromArrayAux(a, i - 1, list{Array.getUnsafe(a, i), ...res}) + } + +let fromArray = a => fromArrayAux(a, Array.length(a) - 1, list{}) + +let toArray = (x: t<_>) => { + let len = length(x) + let arr = A.makeUninitializedUnsafe(len) + fillAux(arr, 0, x) + arr +} + +let toShuffled = xs => { + let v = toArray(xs) + Array.shuffle(v) + fromArray(v) } -let rec iter = (f, param) => - switch param { +/* let rec fillAuxMap arr i x f = + match x with + | [] -> () + | h::t -> + A.setUnsafe arr i (f h [@bs]) ; + fillAuxMap arr (i + 1) t f */ + +/* module J = Js_json */ +/* type json = J.t */ +/* let toJson x f = */ +/* let len = length x in */ +/* let arr = Belt_Array.makeUninitializedUnsafe len in */ +/* fillAuxMap arr 0 x f; */ +/* J.array arr */ + +/* TODO: best practice about raising excpetion + 1. raise OCaml exception, no stacktrace + 2. raise JS exception, how to pattern match +*/ + +let rec reverseConcat = (l1, l2) => + switch l1 { + | list{} => l2 + | list{a, ...l} => reverseConcat(l, list{a, ...l2}) + } + +let reverse = l => reverseConcat(l, list{}) + +let rec flatAux = (prec, xs) => + switch xs { + | list{} => unsafeMutateTail(prec, list{}) + | list{h, ...r} => flatAux(copyAuxCont(h, prec), r) + } + +let rec flat = xs => + switch xs { + | list{} => list{} + | list{list{}, ...xs} => flat(xs) + | list{list{h, ...t}, ...r} => + let cell = mutableCell(h, list{}) + flatAux(copyAuxCont(t, cell), r) + cell + } + +let concatMany = xs => + switch xs { + | [] => list{} + | [x] => x + | _ => + let len = Array.length(xs) + let v = ref(Array.getUnsafe(xs, len - 1)) + for i in len - 2 downto 0 { + v.contents = concat(Array.getUnsafe(xs, i), v.contents) + } + v.contents + } + +let rec mapRevAux = (f, accu, xs) => + switch xs { + | list{} => accu + | list{a, ...l} => mapRevAux(f, list{f(a), ...accu}, l) + } + +let mapReverse = (l, f) => mapRevAux(f, list{}, l) + +let rec forEach = (xs, f) => + switch xs { | list{} => () | list{a, ...l} => f(a) - iter(f, l) + forEach(l, f) } -let rec iteri = (i, f, param) => - switch param { +let rec forEachWithIndexAux = (xs, f, i) => + switch xs { | list{} => () | list{a, ...l} => - f(i, a) - iteri(i + 1, f, l) + f(a, i) + forEachWithIndexAux(l, f, i + 1) } -let iteri = (f, l) => iteri(0, f, l) +let forEachWithIndex = (l, f) => forEachWithIndexAux(l, f, 0) -let rec fold_left = (f, accu, l) => +let rec reduce = (l, accu, f) => switch l { | list{} => accu - | list{a, ...l} => fold_left(f, f(accu, a), l) + | list{a, ...l} => reduce(l, f(accu, a), f) } -let rec fold_right = (f, l, accu) => +let rec reduceReverseUnsafe = (l, accu, f) => switch l { | list{} => accu - | list{a, ...l} => f(a, fold_right(f, l, accu)) + | list{a, ...l} => f(reduceReverseUnsafe(l, accu, f), a) } -let rec map2 = (f, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => list{} - | (list{a1, ...l1}, list{a2, ...l2}) => - let r = f(a1, a2) - list{r, ...map2(f, l1, l2)} - | (_, _) => invalid_arg("List.map2") +let reduceReverse = (type a b, l: list, acc: b, f) => { + let len = length(l) + if len < 1000 { + reduceReverseUnsafe(l, acc, f) + } else { + A.reduceReverseU(toArray(l), acc, f) } +} -let rev_map2 = (f, l1, l2) => { - let rec rmap2_f = (accu, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => rmap2_f(list{f(a1, a2), ...accu}, l1, l2) - | (_, _) => invalid_arg("List.rev_map2") - } +let rec reduceWithIndexAux = (l, acc, f, i) => + switch l { + | list{} => acc + | list{x, ...xs} => reduceWithIndexAux(xs, f(acc, x, i), f, i + 1) + } - rmap2_f(list{}, l1, l2) -} +let reduceWithIndex = (l, acc, f) => reduceWithIndexAux(l, acc, f, 0) + +let rec mapRevAux2 = (l1, l2, accu, f) => + switch (l1, l2) { + | (list{a1, ...l1}, list{a2, ...l2}) => mapRevAux2(l1, l2, list{f(a1, a2), ...accu}, f) + | (_, list{}) | (list{}, _) => accu + } + +let mapReverse2 = (l1, l2, f) => mapRevAux2(l1, l2, list{}, f) -let rec iter2 = (f, l1, l2) => +let rec forEach2 = (l1, l2, f) => switch (l1, l2) { - | (list{}, list{}) => () | (list{a1, ...l1}, list{a2, ...l2}) => - f(a1, a2) - iter2(f, l1, l2) - | (_, _) => invalid_arg("List.iter2") + f(a1, a2)->ignore + forEach2(l1, l2, f) + | (list{}, _) | (_, list{}) => () } -let rec fold_left2 = (f, accu, l1, l2) => +let rec reduce2 = (l1, l2, accu, f) => switch (l1, l2) { - | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => fold_left2(f, f(accu, a1, a2), l1, l2) - | (_, _) => invalid_arg("List.fold_left2") + | (list{a1, ...l1}, list{a2, ...l2}) => reduce2(l1, l2, f(accu, a1, a2), f) + | (list{}, _) | (_, list{}) => accu } -let rec fold_right2 = (f, l1, l2, accu) => +let rec reduceReverse2Unsafe = (l1, l2, accu, f) => switch (l1, l2) { | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => f(a1, a2, fold_right2(f, l1, l2, accu)) - | (_, _) => invalid_arg("List.fold_right2") + | (list{a1, ...l1}, list{a2, ...l2}) => f(reduceReverse2Unsafe(l1, l2, accu, f), a1, a2) + | (_, list{}) | (list{}, _) => accu + } + +let reduceReverse2 = (type a b c, l1: list, l2: list, acc: c, f) => { + let len = length(l1) + if len < 1000 { + reduceReverse2Unsafe(l1, l2, acc, f) + } else { + A.reduceReverse2U(toArray(l1), toArray(l2), acc, f) } +} -let rec for_all = (p, param) => - switch param { +let rec every = (xs, p) => + switch xs { | list{} => true - | list{a, ...l} => p(a) && for_all(p, l) + | list{a, ...l} => p(a) && every(l, p) } -let rec exists = (p, param) => - switch param { +let rec some = (xs, p) => + switch xs { | list{} => false - | list{a, ...l} => p(a) || exists(p, l) + | list{a, ...l} => p(a) || some(l, p) } -let rec for_all2 = (p, l1, l2) => +let rec every2 = (l1, l2, p) => switch (l1, l2) { - | (list{}, list{}) => true - | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) && for_all2(p, l1, l2) - | (_, _) => invalid_arg("List.for_all2") + | (_, list{}) | (list{}, _) => true + | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) && every2(l1, l2, p) } -let rec exists2 = (p, l1, l2) => +let rec compareLength = (l1, l2) => switch (l1, l2) { - | (list{}, list{}) => false - | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) || exists2(p, l1, l2) - | (_, _) => invalid_arg("List.exists2") - } - -let rec mem = (x, param) => - switch param { - | list{} => false - | list{a, ...l} => compare(a, x) == 0 || mem(x, l) + | (list{}, list{}) => Ordering.equal + | (_, list{}) => Ordering.greater + | (list{}, _) => Ordering.less + | (list{_, ...l1s}, list{_, ...l2s}) => compareLength(l1s, l2s) } -let rec memq = (x, param) => - switch param { - | list{} => false - | list{a, ...l} => a === x || memq(x, l) - } - -let rec assoc = (x, param) => - switch param { - | list{} => raise(Not_found) - | list{(a, b), ...l} => - if compare(a, x) == 0 { - b +let rec compare = (l1, l2, p) => + switch (l1, l2) { + | (list{}, list{}) => Ordering.equal + | (_, list{}) => Ordering.greater + | (list{}, _) => Ordering.less + | (list{a1, ...l1}, list{a2, ...l2}) => + let c = p(a1, a2) + if c == Ordering.equal { + compare(l1, l2, p) } else { - assoc(x, l) + c } } -let rec assoc_opt = (x, param) => - switch param { - | list{} => None - | list{(a, b), ...l} => - if compare(a, x) == 0 { - Some(b) +let rec equal = (l1, l2, p) => + switch (l1, l2) { + | (list{}, list{}) => true + | (_, list{}) + | (list{}, _) => false + | (list{a1, ...l1}, list{a2, ...l2}) => + if p(a1, a2) { + equal(l1, l2, p) } else { - assoc_opt(x, l) + false } } -let rec assq = (x, param) => - switch param { - | list{} => raise(Not_found) - | list{(a, b), ...l} => - if a === x { - b - } else { - assq(x, l) - } +let rec some2 = (l1, l2, p) => + switch (l1, l2) { + | (list{}, _) | (_, list{}) => false + | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) || some2(l1, l2, p) } -let rec assq_opt = (x, param) => - switch param { +let rec has = (xs, x, eq) => + switch xs { + | list{} => false + | list{a, ...l} => eq(a, x) || has(l, x, eq) + } + +let rec getAssoc = (xs, x, eq) => + switch xs { | list{} => None | list{(a, b), ...l} => - if a === x { + if eq(a, x) { Some(b) } else { - assq_opt(x, l) + getAssoc(l, x, eq) } } -let rec mem_assoc = (x, param) => - switch param { +let rec hasAssoc = (xs, x, eq) => + switch xs { | list{} => false - | list{(a, _), ...l} => compare(a, x) == 0 || mem_assoc(x, l) + | list{(a, _), ...l} => eq(a, x) || hasAssoc(l, x, eq) } -let rec mem_assq = (x, param) => - switch param { - | list{} => false - | list{(a, _), ...l} => a === x || mem_assq(x, l) - } - -let rec remove_assoc = (x, param) => - switch param { +let removeAssoc = (xs, x, eq) => + switch xs { | list{} => list{} | list{(a, _) as pair, ...l} => - if compare(a, x) == 0 { + if eq(a, x) { l } else { - list{pair, ...remove_assoc(x, l)} + let cell = mutableCell(pair, list{}) + let removed = removeAssocAuxWithMap(l, x, cell, eq) + if removed { + cell + } else { + xs + } } } -let rec remove_assq = (x, param) => - switch param { - | list{} => list{} +let setAssoc = (xs, x, k, eq) => + switch xs { + | list{} => list{(x, k)} | list{(a, _) as pair, ...l} => - if a === x { - l + if eq(a, x) { + list{(x, k), ...l} } else { - list{pair, ...remove_assq(x, l)} + let cell = mutableCell(pair, list{}) + let replaced = setAssocAuxWithMap(l, x, k, cell, eq) + if replaced { + cell + } else { + list{(x, k), ...xs} + } } } -let rec find = (p, param) => - switch param { - | list{} => raise(Not_found) - | list{x, ...l} => - if p(x) { - x - } else { - find(p, l) - } - } +let sort = (xs, cmp) => { + let arr = toArray(xs) + Array.sort(arr, cmp) + fromArray(arr) +} -let rec find_opt = (p, param) => - switch param { +let rec find = (xs, p) => + switch xs { | list{} => None | list{x, ...l} => if p(x) { Some(x) } else { - find_opt(p, l) + find(l, p) } } -let find_all = p => { - let rec find = (accu, param) => - switch param { - | list{} => rev(accu) - | list{x, ...l} => - if p(x) { - find(list{x, ...accu}, l) - } else { - find(accu, l) - } - } - find(list{}) -} - -let filter = find_all - -let partition = (p, l) => { - let rec part = (yes, no, param) => - switch param { - | list{} => (rev(yes), rev(no)) - | list{x, ...l} => - if p(x) { - part(list{x, ...yes}, no, l) - } else { - part(yes, list{x, ...no}, l) - } - } - part(list{}, list{}, l) -} - -let rec split = param => - switch param { - | list{} => (list{}, list{}) - | list{(x, y), ...l} => - let (rx, ry) = split(l) - (list{x, ...rx}, list{y, ...ry}) - } - -let rec combine = (l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => list{} - | (list{a1, ...l1}, list{a2, ...l2}) => list{(a1, a2), ...combine(l1, l2)} - | (_, _) => invalid_arg("List.combine") - } - -/* sorting */ - -let rec merge = (cmp, l1, l2) => - switch (l1, l2) { - | (list{}, l2) => l2 - | (l1, list{}) => l1 - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) <= 0 { - list{h1, ...merge(cmp, t1, l2)} +let rec filter = (xs, p) => + switch xs { + | list{} => list{} + | list{h, ...t} => + if p(h) { + let cell = mutableCell(h, list{}) + copyAuxWitFilter(p, t, cell) + cell } else { - list{h2, ...merge(cmp, l1, t2)} + filter(t, p) } } -let rec chop = (k, l) => - if k == 0 { - l - } else { - switch l { - | list{_, ...t} => chop(k - 1, t) - | _ => assert(false) - } - } - -let stable_sort = (cmp, l) => { - let rec rev_merge = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) <= 0 { - rev_merge(t1, l2, list{h1, ...accu}) - } else { - rev_merge(l1, t2, list{h2, ...accu}) - } - } - - let rec rev_merge_rev = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) > 0 { - rev_merge_rev(t1, l2, list{h1, ...accu}) +let filterWithIndex = (xs, p) => { + let rec auxFilterWithIndex = (xs, p, i) => + switch xs { + | list{} => list{} + | list{h, ...t} => + if p(h, i) { + let cell = mutableCell(h, list{}) + copyAuxWithFilterIndex(p, t, cell, i + 1) + cell } else { - rev_merge_rev(l1, t2, list{h2, ...accu}) + auxFilterWithIndex(t, p, i + 1) } } - - let rec sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - if cmp(x1, x2) <= 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - if cmp(x1, x2) <= 0 { - if cmp(x2, x3) <= 0 { - list{x1, x2, x3} - } else if cmp(x1, x3) <= 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } else if cmp(x1, x3) <= 0 { - list{x2, x1, x3} - } else if cmp(x2, x3) <= 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = rev_sort(n1, l) - let s2 = rev_sort(n2, l2) - rev_merge_rev(s1, s2, list{}) - } - and rev_sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - if cmp(x1, x2) > 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - if cmp(x1, x2) > 0 { - if cmp(x2, x3) > 0 { - list{x1, x2, x3} - } else if cmp(x1, x3) > 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } else if cmp(x1, x3) > 0 { - list{x2, x1, x3} - } else if cmp(x2, x3) > 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = sort(n1, l) - let s2 = sort(n2, l2) - rev_merge(s1, s2, list{}) - } - - let len = length(l) - if len < 2 { - l - } else { - sort(len, l) - } + auxFilterWithIndex(xs, p, 0) } -let sort = stable_sort -let fast_sort = stable_sort - -/* Note: on a list of length between about 100000 (depending on the minor - heap size and the type of the list) and Sys.max_array_size, it is - actually faster to use the following, but it might also use more memory - because the argument list cannot be deallocated incrementally. - - Also, there seems to be a bug in this code or in the - implementation of obj_truncate. - -external obj_truncate : 'a array -> int -> unit = "caml_obj_truncate" - -let array_to_list_in_place a = - let l = Array.length a in - let rec loop accu n p = - if p <= 0 then accu else begin - if p = n then begin - obj_truncate a p; - loop (a.(p-1) :: accu) (n-1000) (p-1) - end else begin - loop (a.(p-1) :: accu) n (p-1) - end - end - in - loop [] (l-1000) l - - -let stable_sort cmp l = - let a = Array.of_list l in - Array.stable_sort cmp a; - array_to_list_in_place a - -*/ - -/* sorting + removing duplicates */ - -let sort_uniq = (cmp, l) => { - let rec rev_merge = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - let c = cmp(h1, h2) - if c == 0 { - rev_merge(t1, t2, list{h1, ...accu}) - } else if c < 0 { - rev_merge(t1, l2, list{h1, ...accu}) - } else { - rev_merge(l1, t2, list{h2, ...accu}) - } - } - - let rec rev_merge_rev = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - let c = cmp(h1, h2) - if c == 0 { - rev_merge_rev(t1, t2, list{h1, ...accu}) - } else if c > 0 { - rev_merge_rev(t1, l2, list{h1, ...accu}) - } else { - rev_merge_rev(l1, t2, list{h2, ...accu}) - } +let rec filterMap = (xs, p) => + switch xs { + | list{} => list{} + | list{h, ...t} => + switch p(h) { + | Some(h) => + let cell = mutableCell(h, list{}) + copyAuxWitFilterMap(p, t, cell) + cell + | None => filterMap(t, p) } + } - let rec sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - list{x1} - } else if c < 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x2} - } else if c < 0 { - list{x2, x3} - } else { - list{x3, x2} - } - } else if c < 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x1, x2} - } else if c < 0 { - list{x1, x2, x3} - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x1, x2} - } else if c < 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x2, x1} - } else if c < 0 { - list{x2, x1, x3} - } else { - let c = cmp(x2, x3) - if c == 0 { - list{x2, x1} - } else if c < 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - } - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = rev_sort(n1, l) - let s2 = rev_sort(n2, l2) - rev_merge_rev(s1, s2, list{}) - } - and rev_sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - list{x1} - } else if c > 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x2} - } else if c > 0 { - list{x2, x3} - } else { - list{x3, x2} - } - } else if c > 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x1, x2} - } else if c > 0 { - list{x1, x2, x3} - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x1, x2} - } else if c > 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x2, x1} - } else if c > 0 { - list{x2, x1, x3} - } else { - let c = cmp(x2, x3) - if c == 0 { - list{x2, x1} - } else if c > 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - } - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = sort(n1, l) - let s2 = sort(n2, l2) - rev_merge(s1, s2, list{}) +let partition = (l, p) => + switch l { + | list{} => (list{}, list{}) + | list{h, ...t} => + let nextX = mutableCell(h, list{}) + let nextY = mutableCell(h, list{}) + let b = p(h) + partitionAux(p, t, nextX, nextY) + if b { + ( + nextX, + switch nextY { + | list{_, ...tail} => tail + | list{} => assert(false) + }, + ) + } else { + ( + switch nextX { + | list{_, ...tail} => tail + | list{} => assert(false) + }, + nextY, + ) } - - let len = length(l) - if len < 2 { - l - } else { - sort(len, l) } -} -let rec compare_lengths = (l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => 0 - | (list{}, _) => -1 - | (_, list{}) => 1 - | (list{_, ...l1}, list{_, ...l2}) => compare_lengths(l1, l2) +let unzip = xs => + switch xs { + | list{} => (list{}, list{}) + | list{(x, y), ...l} => + let cellX = mutableCell(x, list{}) + let cellY = mutableCell(y, list{}) + splitAux(l, cellX, cellY) + (cellX, cellY) } -let rec compare_length_with = (l, n) => - switch l { - | list{} => - if n == 0 { - 0 - } else if n > 0 { - -1 - } else { - 1 - } - | list{_, ...l} => - if n <= 0 { - 1 - } else { - compare_length_with(l, n - 1) - } +let zip = (l1, l2) => + switch (l1, l2) { + | (_, list{}) | (list{}, _) => list{} + | (list{a1, ...l1}, list{a2, ...l2}) => + let cell = mutableCell((a1, a2), list{}) + zipAux(l1, l2, cell) + cell } diff --git a/jscomp/stdlib-406/list.resi b/jscomp/stdlib-406/list.resi index 27e82bbdf8..095a31d693 100644 --- a/jscomp/stdlib-406/list.resi +++ b/jscomp/stdlib-406/list.resi @@ -1,333 +1,876 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ +/* Copyright (C) 2017 Authors of ReScript + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/** +Collection functions for manipulating the `list` data structures, a singly-linked list. + +**Prefer Array** if you need any of the following: + +- Random access of element +- Better interop with JavaScript +- Better memory usage & performance. +*/ +/** `'a t` is compatible with built-in `list` type */ +type t<'a> = list<'a> + +/** +`length(list)` returns the length of `list`. + +## Examples + +```rescript +List.length(list{1, 2, 3}) // 3 +``` +*/ +let length: t<'a> => int + +/** +`size(list)`. See [`length`](#length) + +## Examples + +```rescript +List.size(list{1, 2, 3}) // 3 +``` +*/ +let size: t<'a> => int + +/** +`head(list)` returns `Some(value)` where `value` is the first element in the +list, or `None` if `list` is an empty list. + +## Examples + +```rescript +List.head(list{}) // None +List.head(list{1, 2, 3}) // Some(1) +``` +*/ +let head: t<'a> => option<'a> + +/** +`headExn(list)` same as [`head`](#head). + +## Examples + +```rescript +List.headExn(list{1, 2, 3}) // 1 + +List.headExn(list{}) // Raises an Error +``` + +## Exceptions + +- Raises an Error if list is empty. + +*/ +let headExn: t<'a> => 'a + +/** +`tail(list)` returns `None` if `list` is empty, otherwise it returns `Some(tail)` +where `tail` is everything except the first element of `list`. + +## Examples + +```rescript +List.tail(list{1, 2, 3}) // Some(list{2, 3}) + +List.tail(list{}) // None +``` +*/ +let tail: t<'a> => option> + +/** +`tailExn(list)` same as [`tail`](#tail). + +## Examples + +```rescript +List.tailExn(list{1, 2, 3}) // list{2, 3} + +List.tailExn(list{}) // Raises an Error +``` + +## Exceptions + +- Raises an Error if list is empty. +*/ +let tailExn: t<'a> => t<'a> + +/** +`add(list, value)` adds a `value` to the beginning of list `list`. + +## Examples + +```rescript +List.add(list{2, 3}, 1) // list{1, 2, 3} + +List.add(list{"World", "!"}, "Hello") // list{"Hello", "World", "!"} +``` +*/ +let add: (t<'a>, 'a) => t<'a> + +/** +`get(list, index)` return the `index` element in `list`, or `None` if `index` +is larger than the length of list `list`. + +## Examples + +```rescript +let abc = list{"A", "B", "C"} + +abc->List.get(1) // Some("B") + +abc->List.get(4) // None +``` +*/ +let get: (t<'a>, int) => option<'a> + +/** +`getExn(list, index)` same as [`get`](#get). + +## Examples + +```rescript +let abc = list{"A", "B", "C"} + +abc->List.getExn(1) // "B" + +abc->List.getExn(4) // Raises an Error +``` + +## Exceptions + +- Raises an Error if `index` is larger than the length of list. +*/ +let getExn: (t<'a>, int) => 'a + +/** +`make(length, value)` returns a list of length `length` with each element filled +with `value`. Returns an empty list if `value` is negative. + +## Examples + +```rescript +List.make(~length=3, 1) // list{1, 1, 1} +``` +*/ +let make: (~length: int, 'a) => t<'a> + +/** +`makeBy(length, f)` return a list of length `length` with element initialized +with `f`. Returns an empty list if `length` is negative. + +## Examples + +```rescript +List.fromInitializer(~length=5, i => i) // list{0, 1, 2, 3, 4} + +List.fromInitializer(~length=5, i => i * i) // list{0, 1, 4, 9, 16} +``` +*/ +let fromInitializer: (~length: int, int => 'a) => t<'a> + +/** +`toShuffled(list)` returns a new list in random order. + +## Examples + +```rescript +List.toShuffled(list{1, 2, 3}) // list{2, 1, 3} +``` +*/ +let toShuffled: t<'a> => t<'a> + +/** +`drop(list, value)` return a new list, dropping the first `value` element. +Returns `None` if `list` has fewer than `value` elements. + +## Examples + +```rescript +list{1, 2, 3}->List.drop(2) // Some(list{3}) + +list{1, 2, 3}->List.drop(3) // Some(list{}) -/*** List operations. - - Some functions are flagged as not tail-recursive. A tail-recursive - function uses constant stack space, while a non-tail-recursive function - uses stack space proportional to the length of its list argument, which - can be a problem with very long lists. When the function takes several - list arguments, an approximate formula giving stack usage (in some - unspecified constant unit) is shown in parentheses. - - The above considerations can usually be ignored if your lists are not - longer than about 10000 elements. +list{1, 2, 3}->List.drop(4) // None +``` */ +let drop: (t<'a>, int) => option> -/** Return the length (number of elements) of the given list. */ -let length: list<'a> => int - -/** Compare the lengths of two lists. [compare_lengths l1 l2] is - equivalent to [compare (length l1) (length l2)], except that - the computation stops after itering on the shortest list. - @since 4.05.0 - */ -let compare_lengths: (list<'a>, list<'b>) => int - -/** Compare the length of a list to an integer. [compare_length_with l n] is - equivalent to [compare (length l) n], except that - the computation stops after at most [n] iterations on the list. - @since 4.05.0 +/** +`take(list, value)` returns a list with the first `value` elements from `list`, +or `None` if `list` has fewer than `value` elements. + +## Examples + +```rescript +list{1, 2, 3}->List.take(1) // Some(list{1}) + +list{1, 2, 3}->List.take(2) // Some(list{1, 2}) + +list{1, 2, 3}->List.take(4) // None +``` +*/ +let take: (t<'a>, int) => option> + +/** +`splitAt(list, n)` split the list `list` at `n`. Returns `None` when the length +of `list` is less than `n`. + +## Examples + +```rescript +list{"Hello", "World"}->List.splitAt(1) // Some((list{"Hello"}, list{"World"})) + +list{0, 1, 2, 3, 4}->List.splitAt(2) // Some((list{0, 1}, list{2, 3, 4})) +``` */ -let compare_length_with: (list<'a>, int) => int - -/** [cons x xs] is [x :: xs] - @since 4.03.0 -*/ -let cons: ('a, list<'a>) => list<'a> - -/** Return the first element of the given list. Raise - [Failure "hd"] if the list is empty. */ -let hd: list<'a> => 'a - -/** Return the given list without its first element. Raise - [Failure "tl"] if the list is empty. */ -let tl: list<'a> => list<'a> - -/** Return the [n]-th element of the given list. - The first element (head of the list) is at position 0. - Raise [Failure "nth"] if the list is too short. - Raise [Invalid_argument "List.nth"] if [n] is negative. */ -let nth: (list<'a>, int) => 'a - -/** Return the [n]-th element of the given list. - The first element (head of the list) is at position 0. - Return [None] if the list is too short. - Raise [Invalid_argument "List.nth"] if [n] is negative. - @since 4.05 -*/ -let nth_opt: (list<'a>, int) => option<'a> - -/** List reversal. */ -let rev: list<'a> => list<'a> - -/** [List.init len f] is [f 0; f 1; ...; f (len-1)], evaluated left to right. - - @raise Invalid_argument if len < 0. - @since 4.06.0 -*/ -let init: (int, int => 'a) => list<'a> - -/** Concatenate two lists. Same as the infix operator [@]. - Not tail-recursive (length of the first argument). */ -let append: (list<'a>, list<'a>) => list<'a> - -/** [List.rev_append l1 l2] reverses [l1] and concatenates it to [l2]. - This is equivalent to {!List.rev}[ l1 @ l2], but [rev_append] is - tail-recursive and more efficient. */ -let rev_append: (list<'a>, list<'a>) => list<'a> - -/** Concatenate a list of lists. The elements of the argument are all - concatenated together (in the same order) to give the result. - Not tail-recursive - (length of the argument + length of the longest sub-list). */ -let concat: list> => list<'a> - -/** An alias for [concat]. */ -let flatten: list> => list<'a> - -/* {1 Iterators} */ - -/** [List.iter f [a1; ...; an]] applies function [f] in turn to - [a1; ...; an]. It is equivalent to - [begin f a1; f a2; ...; f an; () end]. */ -let iter: ('a => unit, list<'a>) => unit - -/** Same as {!List.iter}, but the function is applied to the index of - the element as first argument (counting from 0), and the element - itself as second argument. - @since 4.00.0 -*/ -let iteri: ((int, 'a) => unit, list<'a>) => unit +let splitAt: (t<'a>, int) => option<(list<'a>, list<'a>)> + +/** +`concat(list1, list2)` returns the list obtained by adding `list1` after `list2`. + +## Examples + +```rescript +List.concat(list{1, 2, 3}, list{4, 5}) // list{1, 2, 3, 4, 5} +``` +*/ +let concat: (t<'a>, t<'a>) => t<'a> + +/** +`concatMany(arr)` returns the list obtained by concatenating all the lists in +array `arr`, in order. + +## Examples + +```rescript +List.concatMany([list{1, 2, 3}, list{}, list{3}]) // list{1, 2, 3, 3} +``` +*/ +let concatMany: array> => t<'a> + +/** +`reverseConcat(list1, list2)` is equivalent to writing: `concat(reverse(list1, list2)` + +## Examples + +```rescript +List.reverseConcat(list{1, 2}, list{3, 4}) // list{2, 1, 3, 4} +``` +*/ +let reverseConcat: (t<'a>, t<'a>) => t<'a> + +/** +`flat(list)` return the list obtained by concatenating all the lists in +`list`, in order. + +## Examples + +```rescript +List.flat(list{list{1, 2, 3}, list{}, list{3}}) // list{1, 2, 3, 3} +``` +*/ +let flat: t> => t<'a> + +/** +`map(list, f)` returns a new list with `f` applied to each element of `list`. + +## Examples + +```rescript +list{1, 2}->List.map(x => x + 1) // list{3, 4} +``` +*/ +let map: (t<'a>, 'a => 'b) => t<'b> + +/** +`zip(list1, list2)` returns a list of pairs from the two lists with the length +of the shorter list. + +## Examples + +```rescript +List.zip(list{1, 2}, list{3, 4, 5}) // list{(1, 3), (2, 4)} +``` +*/ +let zip: (t<'a>, t<'b>) => t<('a, 'b)> + +/** +`zipBy(list1, list2, f)`. See [`zip`](#zip) + +## Examples + +```rescript +List.zipBy(list{1, 2, 3}, list{4, 5}, (a, b) => 2 * a + b) // list{6, 9} +``` +*/ +let zipBy: (t<'a>, t<'b>, ('a, 'b) => 'c) => t<'c> + +/** +`mapWithIndex(list, f)` applies `f` to each element of `list`. Function `f` +takes two arguments: the index starting from 0 and the element from `list`, in +that order. + +## Examples + +```rescript +list{1, 2, 3}->List.mapWithIndex((x, index) => index + x) // list{1, 3, 5} +``` +*/ +let mapWithIndex: (t<'a>, ('a, int) => 'b) => t<'b> + +/** +`fromArray(arr)` converts the given array `arr` to a list. + +## Examples + +```rescript +List.fromArray([1, 2, 3]) // list{1, 2, 3} +``` +*/ +let fromArray: array<'a> => t<'a> + +/** +`toArray(list)` converts the given list `list` to an array. + +## Examples + +```rescript +List.toArray(list{1, 2, 3}) // [1, 2, 3] +``` +*/ +let toArray: t<'a> => array<'a> + +/* type json = Js_json.t */ + +/* val toJson : 'a t -> ('a -> json [@bs]) -> json */ +/* val fromJson : json -> (json -> 'a [@bs]) -> 'a t */ + +/** +`reverse(list)` returns a new list whose elements are those of `list` in +reversed order. + +## Examples + +```rescript +List.reverse(list{1, 2, 3}) // list{3, 2, 1} +``` +*/ +let reverse: t<'a> => t<'a> + +/** +`mapReverse(list, f)` is equivalent to `map` function. + +## Examples + +```rescript +let f = x => x * x +let l = list{3, 4, 5} + +let withMap = List.map(l, f)->List.reverse +let withMapReverse = l->List.mapReverse(f) + +Console.log(withMap == withMapReverse) // true +``` +*/ +let mapReverse: (t<'a>, 'a => 'b) => t<'b> + +/** +`forEach(list, f)` call `f` on each element of `list` from the beginning to end. +`f` returns `unit`, so no new array is created. Use `forEach` when you are primarily +concerned with repetitively creating side effects. + +## Examples + +```rescript +List.forEach(list{"a", "b", "c"}, x => Console.log("Item: " ++ x)) +/* + prints: + Item: a + Item: b + Item: c +*/ +``` +*/ +let forEach: (t<'a>, 'a => unit) => unit + +/** +`forEachWithIndex(list, f, index)` call `f` on each element of `list` from beginning +to end. Function `f` takes two arguments: the `index` starting from 0 and the +element from `list`. `f` returns `unit`. + +## Examples + +```rescript +List.forEachWithIndex(list{"a", "b", "c"}, (x, index) => { + Console.log("Item " ++ Int.toString(index) ++ " is " ++ x) +}) +/* + prints: + Item 0 is a + Item 1 is b + Item 2 is cc +*/ +``` +*/ +let forEachWithIndex: (t<'a>, ('a, int) => unit) => unit + +/** +`reduce(list, initialValue, f)` applies `f` to each element of `list` from +beginning to end. Function `f` has two parameters: the item from the list and +an "accumulator", which starts with a value of `initialValue`. `reduce` returns +the final value of the accumulator. + +## Examples + +```rescript +list{1, 2, 3, 4}->List.reduce(0, (a, b) => a + b) // 10 + +// same as + +list{1, 2, 3, 4}->List.reduce(0, (acc, item) => acc + item) // 10 +``` +*/ +let reduce: (t<'a>, 'b, ('b, 'a) => 'b) => 'b + +/** +`reduceWithIndex(list, initialValue, f)` applies `f` to each element of `list` +from beginning to end. Function `f` has three parameters: the item from the list +and an "accumulator", which starts with a value of `initialValue` and the index +of each element. `reduceWithIndex` returns the final value of the accumulator. + +## Examples + +```rescript +list{1, 2, 3, 4}->List.reduceWithIndex(0, (acc, item, index) => acc + item + index) // 16 +``` +*/ +let reduceWithIndex: (t<'a>, 'b, ('b, 'a, int) => 'b) => 'b + +/** +`reduceReverse(list, initialValue, f)` works like `reduce`, except that +function `f` is applied to each item of `list` from the last back to the first. + +## Examples + +```rescript +list{1, 2, 3, 4}->List.reduceReverse(0, (a, b) => a + b) // 10 + +list{1, 2, 3, 4}->List.reduceReverse(10, (a, b) => a - b) // 0 + +list{1, 2, 3, 4}->List.reduceReverse(list{}, List.add) // list{1, 2, 3, 4} +``` +*/ +let reduceReverse: (t<'a>, 'b, ('b, 'a) => 'b) => 'b + +/** +`mapReverse2(list1, list2, f)` is equivalent to `List.zipBy(list1, list2, f)->List.reverse`. + +## Examples + +```rescript +List.mapReverse2(list{1, 2, 3}, list{1, 2}, (a, b) => a + b) // list{4, 2} +``` +*/ +let mapReverse2: (t<'a>, t<'b>, ('a, 'b) => 'c) => t<'c> + +/** +`forEach2(list1, list2, f)` is similar to `forEach`, but accepts two lists and +stops at the length of the shorter list. + +## Examples + +```rescript +List.forEach2(list{"Z", "Y"}, list{"A", "B", "C"}, (x, y) => Console.log2(x, y)) + +/* + prints: + "Z" "A" + "Y" "B" +*/ +``` +*/ +let forEach2: (t<'a>, t<'b>, ('a, 'b) => 'c) => unit + +/** +`reduce2(list1, list2, initialValue, f)` applies `f` to each element of `list1` +and `list2` from beginning to end. Stops with the shorter list. Function `f` has +three parameters: an accumulator which starts with a value of `initialValue`, an +item from `l1`, and an item from `l2`. `reduce2` returns the final value of the +accumulator. + +## Examples + +```rescript +List.reduce2(list{1, 2, 3}, list{4, 5}, 0, (acc, x, y) => acc + x * x + y) // 0 + (1 * 1 + 4) + (2 * 2 + 5) +``` +*/ +let reduce2: (t<'b>, t<'c>, 'a, ('a, 'b, 'c) => 'a) => 'a + +/** +`reduceReverse2(list1, list2, initialValue, f)` applies `f` to each element of +`list1` and `list2`from end to beginning. Stops with the shorter list. Function +`f` has three parameters: an accumulator which starts with a value of +`initialValue`, an item from `l1`, and an item from `l2`. `reduce2` returns the +final value of the accumulator. + +## Examples + +```rescript +List.reduceReverse2(list{1, 2, 3}, list{4, 5}, 0, (acc, x, y) => acc + x * x + y) // + (1 * 1 + 4) + (2 * 2 + 5) +``` +*/ +let reduceReverse2: (t<'a>, t<'b>, 'c, ('c, 'a, 'b) => 'c) => 'c + +/** +`every(list, f)` returns `true` if all elements in `list` satisfy `f`, where `f` +is a predicate: a function taking an element and returning a bool. + +## Examples + +```rescript +let isBelow10 = value => value < 10 + +list{1, 9, 8, 2}->List.every(isBelow10) // true + +list{1, 99, 8, 2}->List.every(isBelow10) // false +``` +*/ +let every: (t<'a>, 'a => bool) => bool + +/** +`some(list, f)` returns `true` if at least _one_ of the elements in `list` +satisfies `f`, where `f` is a predicate: a function taking an element and +returning a bool. + +## Examples + +```rescript +let isAbove100 = value => value > 100 + +list{101, 1, 2, 3}->List.some(isAbove100) // true + +list{1, 2, 3, 4}->List.some(isAbove100) // false +``` +*/ +let some: (t<'a>, 'a => bool) => bool + +/** +`every2(list1, list2, f)` returns `true` if predicate `f` is `true` for all +pairs of elements up to the shorter length (i.e. `min(length(list1), length(list2))`) + +## Examples + +```rescript +List.every2(list{1, 2, 3}, list{0, 1}, (a, b) => a > b) // true + +List.every2(list{}, list{1}, (a, b) => a > b) // true + +List.every2(list{2, 3}, list{1}, (a, b) => a > b) // true + +List.every2(list{0, 1}, list{5, 0}, (a, b) => a > b) // false +``` +*/ +let every2: (t<'a>, t<'b>, ('a, 'b) => bool) => bool + +/** +`some2(list1, list2, f)` returns `true` if predicate `f` is `true` for any pair +of elements up to the shorter length (i.e. `min(length(list1), length(list2))`) + +## Examples + +```rescript +List.some2(list{1, 2, 3}, list{0, 1}, (a, b) => a > b) // true + +List.some2(list{}, list{1}, (a, b) => a > b) // false + +List.some2(list{2, 3}, list{1}, (a, b) => a > b) // true + +List.some2(list{0, 1}, list{5, 0}, (a, b) => a > b) // true +``` +*/ +let some2: (t<'a>, t<'b>, ('a, 'b) => bool) => bool + +/** +`compareLength(list1, list2)` compare two lists solely by length. Returns `-1.` if +`length(list1)` is less than `length(list2)`, `0.` if `length(list1)` equals +`length(list2)`, and `1.` if `length(list1)` is greater than `length(list2)`. + +## Examples + +```rescript +List.compareLength(list{1, 2}, list{3, 4, 5, 6}) // -1. + +List.compareLength(list{1, 2, 3}, list{4, 5, 6}) // 0. + +List.compareLength(list{1, 2, 3, 4}, list{5, 6}) // 1. +``` +*/ +let compareLength: (t<'a>, t<'a>) => Ordering.t + +/** +`compare(list1, list2, f)` compare elements one by one `f`. `f` returns a negative +number if `list1` is "less than" `list2`, zero if `list1` is "equal to" `list2`, +a positive number if `list1` is "greater than" `list2`. + +The comparison returns the first non-zero result of `f`, or zero if `f` returns +zero for all `list1` and `list2`. + +- If all items have compared equal, but `list1` is exhausted first, return `-1.`. (`list1` is shorter). +- If all items have compared equal, but `list2` is exhausted first, return `1.` (`list1` is longer). + +## Examples + +```rescript +List.compare(list{3}, list{3, 7}, (a, b) => Int.compare(a, b)) // -1. +List.compare(list{5, 3}, list{5}, (a, b) => Int.compare(a, b)) // 1. +List.compare(list{1, 3, 5}, list{1, 4, 2}, (a, b) => Int.compare(a, b)) // -1. +List.compare(list{1, 3, 5}, list{1, 2, 3}, (a, b) => Int.compare(a, b)) // 1. +List.compare(list{1, 3, 5}, list{1, 3, 5}, (a, b) => Int.compare(a, b)) // 0. +``` + +**Please note:** The total ordering of List is different from Array, +for Array, we compare the length first and, only if the lengths are equal, elements one by one. +For lists, we just compare elements one by one. +*/ +let compare: (t<'a>, t<'a>, ('a, 'a) => Ordering.t) => Ordering.t + +/** +`equal(list1, list2, f)` check equality of `list2` and `list2` using `f` for +equality on elements, where `f` is a function that returns `true` if items `x` and +`y` meet some criterion for equality, `false` otherwise. equal `false` if length +of `list1` and `list2` are not the same. + +## Examples + +```rescript +List.equal(list{1, 2, 3}, list{1, 2}, (a, b) => a == b) // false + +List.equal(list{1, 2}, list{1, 2}, (a, b) => a == b) // true + +List.equal(list{1, 2, 3}, list{(-1), (-2), (-3)}, (a, b) => abs(a) == abs(b)) // true +``` +*/ +let equal: (t<'a>, t<'a>, ('a, 'a) => bool) => bool + +/** +`has(list, element, f)` returns `true` if the list contains at least one +`element` for which `f` returns `true'. + +## Examples + +```rescript +list{1, 2, 3}->List.has(2, (a, b) => a == b) // true + +list{1, 2, 3}->List.has(4, (a, b) => a == b) // false + +list{(-1), (-2), (-3)}->List.has(2, (a, b) => abs(a) == abs(b)) // true +``` +*/ +let has: (t<'a>, 'b, ('a, 'b) => bool) => bool + +/** +`find(list, f)` returns `Some(value)` for the first value in `list` that +satisfies the predicate function `f`. Returns `None` if no element satisfies +the function. + +## Examples + +```rescript +List.find(list{1, 4, 3, 2}, x => x > 3) // Some(4) + +List.find(list{1, 4, 3, 2}, x => x > 4) // None +``` +*/ +let find: (t<'a>, 'a => bool) => option<'a> + +/** +`filter(list, f)` returns a list of all elements in `list` which satisfy the +predicate function `f`. + +## Examples + +```rescript +let isEven = x => mod(x, 2) == 0 + +List.filter(list{1, 2, 3, 4}, isEven) // list{2, 4} + +List.filter(list{None, Some(2), Some(3), None}, Option.isSome) // list{Some(2), Some(3)} +``` +*/ +let filter: (t<'a>, 'a => bool) => t<'a> + +/** +`filterWithIndex(list, f)` returns a list of all elements in `list` which +satisfy the predicate function `f`. + +## Examples + +```rescript +let isEven = x => mod(x, 2) == 0 + +List.filterWithIndex(list{1, 2, 3, 4}, (_x, index) => isEven(index)) // list{1, 3} +``` +*/ +let filterWithIndex: (t<'a>, ('a, int) => bool) => t<'a> + +/** +`filterMap(list, f)` applies `f` to each element of `list`. If `f` returns +`Some(value)`, then `value` is _kept_ in the resulting list. If `f` returns +`None`, the element is _not_ retained in the result. + +## Examples + +```rescript +let isEven = x => mod(x, 2) == 0 + +list{1, 2, 3, 4} +->List.filterMap(x => + if (isEven(x)) { + Some(x) + } else { + None + } + ) // list{2, 4} + +list{Some(1), Some(2), None}->List.filterMap(x => x) // list{1, 2} +``` +*/ +let filterMap: (t<'a>, 'a => option<'b>) => t<'b> + +/** +`partition(list, f)` creates a pair of lists; the first list consists of all +elements of `list` that satisfy the predicate function `f`, the second list +consists of all elements of `list` that _do not_ satisfy `f`. + +## Examples + +```rescript +// (elementsThatSatisfies, elementsThatDoesNotSatisfy) + +List.partition(list{1, 2, 3, 4}, x => x > 2) // (list{3, 4}, list{1, 2}) +``` +*/ +let partition: (t<'a>, 'a => bool) => (t<'a>, t<'a>) + +/** +`unzip(list)` takes a list of pairs and creates a pair of lists. The first list +contains all the first items of the pairs, the second list contains all the +second items. + +## Examples + +```rescript +List.unzip(list{(1, 2), (3, 4)}) // (list{1, 3}, list{2, 4}) + +List.unzip(list{("H", "W"), ("e", "o"), ("l", "r"), ("l", "l"), ("o", "d"), (" ", "!")}) +// (list{"H", "e", "l", "l", "o", " "}, list{"W", "o", "r", "l", "d", "!"}) +``` +*/ +let unzip: t<('a, 'b)> => (t<'a>, t<'b>) + +/** +`getAssoc(list, k, f)` return the second element of a pair in `list` where +the first element equals `k` as per the predicate function `f`, or `None` if +not found. + +## Examples + +```rescript +list{(1, "a"), (2, "b"), (3, "c")}->List.getAssoc(3, (a, b) => a == b) // Some("c") + +list{(9, "morning"), (15, "afternoon"), (22, "night")} +->List.getAssoc(15, (k, item) => k /* 15 */ == item /* 9, 5, 22 */) +// Some("afternoon") +``` +*/ +let getAssoc: (t<('a, 'c)>, 'b, ('a, 'b) => bool) => option<'c> + +/** +`hasAssoc(list, k, f)` returns `true` if there is a pair in `list` where the +first element equals `k` as per the predicate function `f`. + +## Examples + +```rescript +list{(1, "a"), (2, "b"), (3, "c")}->List.hasAssoc(1, (a, b) => a == b) // true + +list{(9, "morning"), (15, "afternoon"), (22, "night")} +->List.hasAssoc(25, (k, item) => k /* 25 */ == item /* 9, 5, 22 */) // false +``` +*/ +let hasAssoc: (t<('a, 'c)>, 'b, ('a, 'b) => bool) => bool + +/** +`removeAssoc(list, k, f)` return a list after removing the first pair whose +first value is `k` per the equality predicate `f`, if not found, return a new +list identical to `list`. + +## Examples + +```rescript +list{(1, "a"), (2, "b"), (3, "c")}->List.removeAssoc(1, (a, b) => a == b) // list{(2, "b"), (3, "c")} + +list{(9, "morning"), (15, "afternoon"), (22, "night")} +->List.removeAssoc(9, (k, item) => k /* 9 */ == item /* 9, 5, 22 */) +// list{(15, "afternoon"), (22, "night")} +``` +*/ +let removeAssoc: (t<('a, 'c)>, 'b, ('a, 'b) => bool) => t<('a, 'c)> + +/** +`setAssoc(list, k, v, f)`. If `k` exists in `list` by satisfying the `f` +predicate, return a new list with the key and value replaced by the new `k` and +`v`, otherwise, return a new list with the pair `k`, `v` added to the head of +`list`. + +## Examples + +```rescript +list{(1, "a"), (2, "b"), (3, "c")}->List.setAssoc(2, "x", (a, b) => a == b) // list{(1, "a"), (2, "x"), (3, "c")} + +list{(1, "a"), (3, "c")}->List.setAssoc(2, "b", (a, b) => a == b) // list{(2, "b"), (1, "a"), (3, "c")} + +list{(9, "morning"), (3, "morning?!"), (22, "night")} +->List.setAssoc(15, "afternoon", (a, b) => mod(a, 12) == mod(b, 12)) +// list{(9, "morning"), (15, "afternoon"), (22, "night")} +``` + +**Please note**: In the last example, since: `15 mod 12` equals `3 mod 12`. Both +the key _and_ the value are replaced in the list. +*/ +let setAssoc: (t<('a, 'c)>, 'a, 'c, ('a, 'a) => bool) => t<('a, 'c)> + +/** +`sort(list, f)` returns a sorted list. + +## Examples -/** [List.map f [a1; ...; an]] applies function [f] to [a1, ..., an], - and builds the list [[f a1; ...; f an]] - with the results returned by [f]. Not tail-recursive. */ -let map: ('a => 'b, list<'a>) => list<'b> - -/** Same as {!List.map}, but the function is applied to the index of - the element as first argument (counting from 0), and the element - itself as second argument. Not tail-recursive. - @since 4.00.0 +```rescript +List.sort(list{5, 4, 9, 3, 7}, Int.compare) // list{3, 4, 5, 7, 9} +``` */ -let mapi: ((int, 'a) => 'b, list<'a>) => list<'b> - -/** [List.rev_map f l] gives the same result as - {!List.rev}[ (]{!List.map}[ f l)], but is tail-recursive and - more efficient. */ -let rev_map: ('a => 'b, list<'a>) => list<'b> - -/** [List.fold_left f a [b1; ...; bn]] is - [f (... (f (f a b1) b2) ...) bn]. */ -let fold_left: (('a, 'b) => 'a, 'a, list<'b>) => 'a - -/** [List.fold_right f [a1; ...; an] b] is - [f a1 (f a2 (... (f an b) ...))]. Not tail-recursive. */ -let fold_right: (('a, 'b) => 'b, list<'a>, 'b) => 'b - -/* {1 Iterators on two lists} */ - -/** [List.iter2 f [a1; ...; an] [b1; ...; bn]] calls in turn - [f a1 b1; ...; f an bn]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let iter2: (('a, 'b) => unit, list<'a>, list<'b>) => unit - -/** [List.map2 f [a1; ...; an] [b1; ...; bn]] is - [[f a1 b1; ...; f an bn]]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. Not tail-recursive. */ -let map2: (('a, 'b) => 'c, list<'a>, list<'b>) => list<'c> - -/** [List.rev_map2 f l1 l2] gives the same result as - {!List.rev}[ (]{!List.map2}[ f l1 l2)], but is tail-recursive and - more efficient. */ -let rev_map2: (('a, 'b) => 'c, list<'a>, list<'b>) => list<'c> - -/** [List.fold_left2 f a [b1; ...; bn] [c1; ...; cn]] is - [f (... (f (f a b1 c1) b2 c2) ...) bn cn]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let fold_left2: (('a, 'b, 'c) => 'a, 'a, list<'b>, list<'c>) => 'a - -/** [List.fold_right2 f [a1; ...; an] [b1; ...; bn] c] is - [f a1 b1 (f a2 b2 (... (f an bn c) ...))]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. Not tail-recursive. */ -let fold_right2: (('a, 'b, 'c) => 'c, list<'a>, list<'b>, 'c) => 'c - -/* {1 List scanning} */ - -/** [for_all p [a1; ...; an]] checks if all elements of the list - satisfy the predicate [p]. That is, it returns - [(p a1) && (p a2) && ... && (p an)]. */ -let for_all: ('a => bool, list<'a>) => bool - -/** [exists p [a1; ...; an]] checks if at least one element of - the list satisfies the predicate [p]. That is, it returns - [(p a1) || (p a2) || ... || (p an)]. */ -let exists: ('a => bool, list<'a>) => bool - -/** Same as {!List.for_all}, but for a two-argument predicate. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let for_all2: (('a, 'b) => bool, list<'a>, list<'b>) => bool - -/** Same as {!List.exists}, but for a two-argument predicate. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let exists2: (('a, 'b) => bool, list<'a>, list<'b>) => bool - -/** [mem a l] is true if and only if [a] is equal - to an element of [l]. */ -let mem: ('a, list<'a>) => bool - -/** Same as {!List.mem}, but uses physical equality instead of structural - equality to compare list elements. */ -let memq: ('a, list<'a>) => bool - -/* {1 List searching} */ - -/** [find p l] returns the first element of the list [l] - that satisfies the predicate [p]. - Raise [Not_found] if there is no value that satisfies [p] in the - list [l]. */ -let find: ('a => bool, list<'a>) => 'a - -/** [find_opt p l] returns the first element of the list [l] that - satisfies the predicate [p], or [None] if there is no value that - satisfies [p] in the list [l]. - @since 4.05 */ -let find_opt: ('a => bool, list<'a>) => option<'a> - -/** [filter p l] returns all the elements of the list [l] - that satisfy the predicate [p]. The order of the elements - in the input list is preserved. */ -let filter: ('a => bool, list<'a>) => list<'a> - -/** [find_all] is another name for {!List.filter}. */ -let find_all: ('a => bool, list<'a>) => list<'a> - -/** [partition p l] returns a pair of lists [(l1, l2)], where - [l1] is the list of all the elements of [l] that - satisfy the predicate [p], and [l2] is the list of all the - elements of [l] that do not satisfy [p]. - The order of the elements in the input list is preserved. */ -let partition: ('a => bool, list<'a>) => (list<'a>, list<'a>) - -/* {1 Association lists} */ - -/** [assoc a l] returns the value associated with key [a] in the list of - pairs [l]. That is, - [assoc a [ ...; (a,b); ...] = b] - if [(a,b)] is the leftmost binding of [a] in list [l]. - Raise [Not_found] if there is no value associated with [a] in the - list [l]. */ -let assoc: ('a, list<('a, 'b)>) => 'b - -/** [assoc_opt a l] returns the value associated with key [a] in the list of - pairs [l]. That is, - [assoc_opt a [ ...; (a,b); ...] = b] - if [(a,b)] is the leftmost binding of [a] in list [l]. - Returns [None] if there is no value associated with [a] in the - list [l]. - @since 4.05 */ -let assoc_opt: ('a, list<('a, 'b)>) => option<'b> - -/** Same as {!List.assoc}, but uses physical equality instead of structural - equality to compare keys. */ -let assq: ('a, list<('a, 'b)>) => 'b - -/** Same as {!List.assoc_opt}, but uses physical equality instead of structural - equality to compare keys. - @since 4.05 */ -let assq_opt: ('a, list<('a, 'b)>) => option<'b> - -/** Same as {!List.assoc}, but simply return true if a binding exists, - and false if no bindings exist for the given key. */ -let mem_assoc: ('a, list<('a, 'b)>) => bool - -/** Same as {!List.mem_assoc}, but uses physical equality instead of - structural equality to compare keys. */ -let mem_assq: ('a, list<('a, 'b)>) => bool - -/** [remove_assoc a l] returns the list of - pairs [l] without the first pair with key [a], if any. - Not tail-recursive. */ -let remove_assoc: ('a, list<('a, 'b)>) => list<('a, 'b)> - -/** Same as {!List.remove_assoc}, but uses physical equality instead - of structural equality to compare keys. Not tail-recursive. */ -let remove_assq: ('a, list<('a, 'b)>) => list<('a, 'b)> - -/* {1 Lists of pairs} */ - -/** Transform a list of pairs into a pair of lists: - [split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])]. - Not tail-recursive. -*/ -let split: list<('a, 'b)> => (list<'a>, list<'b>) - -/** Transform a pair of lists into a list of pairs: - [combine [a1; ...; an] [b1; ...; bn]] is - [[(a1,b1); ...; (an,bn)]]. - Raise [Invalid_argument] if the two lists - have different lengths. Not tail-recursive. */ -let combine: (list<'a>, list<'b>) => list<('a, 'b)> - -/* {1 Sorting} */ - -/** Sort a list in increasing order according to a comparison - function. The comparison function must return 0 if its arguments - compare as equal, a positive integer if the first is greater, - and a negative integer if the first is smaller (see Array.sort for - a complete specification). For example, - {!Pervasives.compare} is a suitable comparison function. - The resulting list is sorted in increasing order. - [List.sort] is guaranteed to run in constant heap space - (in addition to the size of the result list) and logarithmic - stack space. - - The current implementation uses Merge Sort. It runs in constant - heap space and logarithmic stack space. -*/ -let sort: (('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort}, but the sorting algorithm is guaranteed to - be stable (i.e. elements that compare equal are kept in their - original order) . - - The current implementation uses Merge Sort. It runs in constant - heap space and logarithmic stack space. -*/ -let stable_sort: (('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort} or {!List.stable_sort}, whichever is faster - on typical input. */ -let fast_sort: (('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort}, but also remove duplicates. - @since 4.02.0 */ -let sort_uniq: (('a, 'a) => int, list<'a>) => list<'a> - -/** Merge two lists: - Assuming that [l1] and [l2] are sorted according to the - comparison function [cmp], [merge cmp l1 l2] will return a - sorted list containing all the elements of [l1] and [l2]. - If several elements compare equal, the elements of [l1] will be - before the elements of [l2]. - Not tail-recursive (sum of the lengths of the arguments). -*/ -let merge: (('a, 'a) => int, list<'a>, list<'a>) => list<'a> +let sort: (t<'a>, ('a, 'a) => Ordering.t) => t<'a> diff --git a/jscomp/stdlib-406/listLabels.res b/jscomp/stdlib-406/listLabels.res deleted file mode 100644 index 48d46d97fe..0000000000 --- a/jscomp/stdlib-406/listLabels.res +++ /dev/null @@ -1,748 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* List operations */ - -let rec length_aux = (len, param) => - switch param { - | list{} => len - | list{_, ...l} => length_aux(len + 1, l) - } - -let length = l => length_aux(0, l) - -let cons = (a, l) => list{a, ...l} - -let hd = param => - switch param { - | list{} => failwith("hd") - | list{a, ..._} => a - } - -let tl = param => - switch param { - | list{} => failwith("tl") - | list{_, ...l} => l - } - -let nth = (l, n) => - if n < 0 { - invalid_arg("List.nth") - } else { - let rec nth_aux = (l, n) => - switch l { - | list{} => failwith("nth") - | list{a, ...l} => - if n == 0 { - a - } else { - nth_aux(l, n - 1) - } - } - nth_aux(l, n) - } - -let nth_opt = (l, n) => - if n < 0 { - invalid_arg("List.nth") - } else { - let rec nth_aux = (l, n) => - switch l { - | list{} => None - | list{a, ...l} => - if n == 0 { - Some(a) - } else { - nth_aux(l, n - 1) - } - } - nth_aux(l, n) - } - -let append = \"@" - -let rec rev_append = (l1, l2) => - switch l1 { - | list{} => l2 - | list{a, ...l} => rev_append(l, list{a, ...l2}) - } - -let rev = l => rev_append(l, list{}) - -let rec init_tailrec_aux = (acc, i, n, f) => - if i >= n { - acc - } else { - init_tailrec_aux(list{f(i), ...acc}, i + 1, n, f) - } - -let rec init_aux = (i, n, f) => - if i >= n { - list{} - } else { - let r = f(i) - list{r, ...init_aux(i + 1, n, f)} - } - -let init = (~len, ~f) => - if len < 0 { - invalid_arg("List.init") - } else if len > 10_000 { - rev(init_tailrec_aux(list{}, 0, len, f)) - } else { - init_aux(0, len, f) - } - -let rec flatten = param => - switch param { - | list{} => list{} - | list{l, ...r} => \"@"(l, flatten(r)) - } - -let concat = flatten - -let rec map = (~f, param) => - switch param { - | list{} => list{} - | list{a, ...l} => - let r = f(a) - list{r, ...map(~f, l)} - } - -let rec mapi = (i, f, param) => - switch param { - | list{} => list{} - | list{a, ...l} => - let r = f(i, a) - list{r, ...mapi(i + 1, f, l)} - } - -let mapi = (~f, l) => mapi(0, f, l) - -let rev_map = (~f, l) => { - let rec rmap_f = (accu, param) => - switch param { - | list{} => accu - | list{a, ...l} => rmap_f(list{f(a), ...accu}, l) - } - - rmap_f(list{}, l) -} - -let rec iter = (~f, param) => - switch param { - | list{} => () - | list{a, ...l} => - f(a) - iter(~f, l) - } - -let rec iteri = (i, f, param) => - switch param { - | list{} => () - | list{a, ...l} => - f(i, a) - iteri(i + 1, f, l) - } - -let iteri = (~f, l) => iteri(0, f, l) - -let rec fold_left = (~f, ~init as accu, l) => - switch l { - | list{} => accu - | list{a, ...l} => fold_left(~f, ~init=f(accu, a), l) - } - -let rec fold_right = (~f, l, ~init as accu) => - switch l { - | list{} => accu - | list{a, ...l} => f(a, fold_right(~f, l, ~init=accu)) - } - -let rec map2 = (~f, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => list{} - | (list{a1, ...l1}, list{a2, ...l2}) => - let r = f(a1, a2) - list{r, ...map2(~f, l1, l2)} - | (_, _) => invalid_arg("List.map2") - } - -let rev_map2 = (~f, l1, l2) => { - let rec rmap2_f = (accu, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => rmap2_f(list{f(a1, a2), ...accu}, l1, l2) - | (_, _) => invalid_arg("List.rev_map2") - } - - rmap2_f(list{}, l1, l2) -} - -let rec iter2 = (~f, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => () - | (list{a1, ...l1}, list{a2, ...l2}) => - f(a1, a2) - iter2(~f, l1, l2) - | (_, _) => invalid_arg("List.iter2") - } - -let rec fold_left2 = (~f, ~init as accu, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => fold_left2(~f, ~init=f(accu, a1, a2), l1, l2) - | (_, _) => invalid_arg("List.fold_left2") - } - -let rec fold_right2 = (~f, l1, l2, ~init as accu) => - switch (l1, l2) { - | (list{}, list{}) => accu - | (list{a1, ...l1}, list{a2, ...l2}) => f(a1, a2, fold_right2(~f, l1, l2, ~init=accu)) - | (_, _) => invalid_arg("List.fold_right2") - } - -let rec for_all = (~f as p, param) => - switch param { - | list{} => true - | list{a, ...l} => p(a) && for_all(~f=p, l) - } - -let rec exists = (~f as p, param) => - switch param { - | list{} => false - | list{a, ...l} => p(a) || exists(~f=p, l) - } - -let rec for_all2 = (~f as p, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => true - | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) && for_all2(~f=p, l1, l2) - | (_, _) => invalid_arg("List.for_all2") - } - -let rec exists2 = (~f as p, l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => false - | (list{a1, ...l1}, list{a2, ...l2}) => p(a1, a2) || exists2(~f=p, l1, l2) - | (_, _) => invalid_arg("List.exists2") - } - -let rec mem = (x, ~set) => - switch set { - | list{} => false - | list{a, ...l} => compare(a, x) == 0 || mem(x, ~set=l) - } - -let rec memq = (x, ~set) => - switch set { - | list{} => false - | list{a, ...l} => a === x || memq(x, ~set=l) - } - -let rec assoc = (x, param) => - switch param { - | list{} => raise(Not_found) - | list{(a, b), ...l} => - if compare(a, x) == 0 { - b - } else { - assoc(x, l) - } - } - -let rec assoc_opt = (x, param) => - switch param { - | list{} => None - | list{(a, b), ...l} => - if compare(a, x) == 0 { - Some(b) - } else { - assoc_opt(x, l) - } - } - -let rec assq = (x, param) => - switch param { - | list{} => raise(Not_found) - | list{(a, b), ...l} => - if a === x { - b - } else { - assq(x, l) - } - } - -let rec assq_opt = (x, param) => - switch param { - | list{} => None - | list{(a, b), ...l} => - if a === x { - Some(b) - } else { - assq_opt(x, l) - } - } - -let rec mem_assoc = (x, ~map) => - switch map { - | list{} => false - | list{(a, _), ...l} => compare(a, x) == 0 || mem_assoc(x, ~map=l) - } - -let rec mem_assq = (x, ~map) => - switch map { - | list{} => false - | list{(a, _), ...l} => a === x || mem_assq(x, ~map=l) - } - -let rec remove_assoc = (x, param) => - switch param { - | list{} => list{} - | list{(a, _) as pair, ...l} => - if compare(a, x) == 0 { - l - } else { - list{pair, ...remove_assoc(x, l)} - } - } - -let rec remove_assq = (x, param) => - switch param { - | list{} => list{} - | list{(a, _) as pair, ...l} => - if a === x { - l - } else { - list{pair, ...remove_assq(x, l)} - } - } - -let rec find = (~f as p, param) => - switch param { - | list{} => raise(Not_found) - | list{x, ...l} => - if p(x) { - x - } else { - find(~f=p, l) - } - } - -let rec find_opt = (~f as p, param) => - switch param { - | list{} => None - | list{x, ...l} => - if p(x) { - Some(x) - } else { - find_opt(~f=p, l) - } - } - -let find_all = (~f as p) => { - let rec find = (accu, param) => - switch param { - | list{} => rev(accu) - | list{x, ...l} => - if p(x) { - find(list{x, ...accu}, l) - } else { - find(accu, l) - } - } - find(list{}) -} - -let filter = find_all - -let partition = (~f as p, l) => { - let rec part = (yes, no, param) => - switch param { - | list{} => (rev(yes), rev(no)) - | list{x, ...l} => - if p(x) { - part(list{x, ...yes}, no, l) - } else { - part(yes, list{x, ...no}, l) - } - } - part(list{}, list{}, l) -} - -let rec split = param => - switch param { - | list{} => (list{}, list{}) - | list{(x, y), ...l} => - let (rx, ry) = split(l) - (list{x, ...rx}, list{y, ...ry}) - } - -let rec combine = (l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => list{} - | (list{a1, ...l1}, list{a2, ...l2}) => list{(a1, a2), ...combine(l1, l2)} - | (_, _) => invalid_arg("List.combine") - } - -/* sorting */ - -let rec merge = (~cmp, l1, l2) => - switch (l1, l2) { - | (list{}, l2) => l2 - | (l1, list{}) => l1 - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) <= 0 { - list{h1, ...merge(~cmp, t1, l2)} - } else { - list{h2, ...merge(~cmp, l1, t2)} - } - } - -let rec chop = (k, l) => - if k == 0 { - l - } else { - switch l { - | list{_, ...t} => chop(k - 1, t) - | _ => assert(false) - } - } - -let stable_sort = (~cmp, l) => { - let rec rev_merge = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) <= 0 { - rev_merge(t1, l2, list{h1, ...accu}) - } else { - rev_merge(l1, t2, list{h2, ...accu}) - } - } - - let rec rev_merge_rev = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - if cmp(h1, h2) > 0 { - rev_merge_rev(t1, l2, list{h1, ...accu}) - } else { - rev_merge_rev(l1, t2, list{h2, ...accu}) - } - } - - let rec sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - if cmp(x1, x2) <= 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - if cmp(x1, x2) <= 0 { - if cmp(x2, x3) <= 0 { - list{x1, x2, x3} - } else if cmp(x1, x3) <= 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } else if cmp(x1, x3) <= 0 { - list{x2, x1, x3} - } else if cmp(x2, x3) <= 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = rev_sort(n1, l) - let s2 = rev_sort(n2, l2) - rev_merge_rev(s1, s2, list{}) - } - and rev_sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - if cmp(x1, x2) > 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - if cmp(x1, x2) > 0 { - if cmp(x2, x3) > 0 { - list{x1, x2, x3} - } else if cmp(x1, x3) > 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } else if cmp(x1, x3) > 0 { - list{x2, x1, x3} - } else if cmp(x2, x3) > 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = sort(n1, l) - let s2 = sort(n2, l2) - rev_merge(s1, s2, list{}) - } - - let len = length(l) - if len < 2 { - l - } else { - sort(len, l) - } -} - -let sort = stable_sort -let fast_sort = stable_sort - -/* Note: on a list of length between about 100000 (depending on the minor - heap size and the type of the list) and Sys.max_array_size, it is - actually faster to use the following, but it might also use more memory - because the argument list cannot be deallocated incrementally. - - Also, there seems to be a bug in this code or in the - implementation of obj_truncate. - -external obj_truncate : 'a array -> int -> unit = "caml_obj_truncate" - -let array_to_list_in_place a = - let l = Array.length a in - let rec loop accu n p = - if p <= 0 then accu else begin - if p = n then begin - obj_truncate a p; - loop (a.(p-1) :: accu) (n-1000) (p-1) - end else begin - loop (a.(p-1) :: accu) n (p-1) - end - end - in - loop [] (l-1000) l - - -let stable_sort cmp l = - let a = Array.of_list l in - Array.stable_sort cmp a; - array_to_list_in_place a -*/ - -/* sorting + removing duplicates */ - -let sort_uniq = (~cmp, l) => { - let rec rev_merge = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - let c = cmp(h1, h2) - if c == 0 { - rev_merge(t1, t2, list{h1, ...accu}) - } else if c < 0 { - rev_merge(t1, l2, list{h1, ...accu}) - } else { - rev_merge(l1, t2, list{h2, ...accu}) - } - } - - let rec rev_merge_rev = (l1, l2, accu) => - switch (l1, l2) { - | (list{}, l2) => rev_append(l2, accu) - | (l1, list{}) => rev_append(l1, accu) - | (list{h1, ...t1}, list{h2, ...t2}) => - let c = cmp(h1, h2) - if c == 0 { - rev_merge_rev(t1, t2, list{h1, ...accu}) - } else if c > 0 { - rev_merge_rev(t1, l2, list{h1, ...accu}) - } else { - rev_merge_rev(l1, t2, list{h2, ...accu}) - } - } - - let rec sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - list{x1} - } else if c < 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x2} - } else if c < 0 { - list{x2, x3} - } else { - list{x3, x2} - } - } else if c < 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x1, x2} - } else if c < 0 { - list{x1, x2, x3} - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x1, x2} - } else if c < 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x2, x1} - } else if c < 0 { - list{x2, x1, x3} - } else { - let c = cmp(x2, x3) - if c == 0 { - list{x2, x1} - } else if c < 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - } - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = rev_sort(n1, l) - let s2 = rev_sort(n2, l2) - rev_merge_rev(s1, s2, list{}) - } - and rev_sort = (n, l) => - switch (n, l) { - | (2, list{x1, x2, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - list{x1} - } else if c > 0 { - list{x1, x2} - } else { - list{x2, x1} - } - | (3, list{x1, x2, x3, ..._}) => - let c = cmp(x1, x2) - if c == 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x2} - } else if c > 0 { - list{x2, x3} - } else { - list{x3, x2} - } - } else if c > 0 { - let c = cmp(x2, x3) - if c == 0 { - list{x1, x2} - } else if c > 0 { - list{x1, x2, x3} - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x1, x2} - } else if c > 0 { - list{x1, x3, x2} - } else { - list{x3, x1, x2} - } - } - } else { - let c = cmp(x1, x3) - if c == 0 { - list{x2, x1} - } else if c > 0 { - list{x2, x1, x3} - } else { - let c = cmp(x2, x3) - if c == 0 { - list{x2, x1} - } else if c > 0 { - list{x2, x3, x1} - } else { - list{x3, x2, x1} - } - } - } - | (n, l) => - let n1 = asr(n, 1) - let n2 = n - n1 - let l2 = chop(n1, l) - let s1 = sort(n1, l) - let s2 = sort(n2, l2) - rev_merge(s1, s2, list{}) - } - - let len = length(l) - if len < 2 { - l - } else { - sort(len, l) - } -} - -let rec compare_lengths = (l1, l2) => - switch (l1, l2) { - | (list{}, list{}) => 0 - | (list{}, _) => -1 - | (_, list{}) => 1 - | (list{_, ...l1}, list{_, ...l2}) => compare_lengths(l1, l2) - } - -let rec compare_length_with = (l, ~len as n) => - switch l { - | list{} => - if n == 0 { - 0 - } else if n > 0 { - -1 - } else { - 1 - } - | list{_, ...l} => - if n <= 0 { - 1 - } else { - compare_length_with(l, ~len=n - 1) - } - } diff --git a/jscomp/stdlib-406/listLabels.resi b/jscomp/stdlib-406/listLabels.resi deleted file mode 100644 index c48e830a47..0000000000 --- a/jscomp/stdlib-406/listLabels.resi +++ /dev/null @@ -1,337 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** List operations. - - Some functions are flagged as not tail-recursive. A tail-recursive - function uses constant stack space, while a non-tail-recursive function - uses stack space proportional to the length of its list argument, which - can be a problem with very long lists. When the function takes several - list arguments, an approximate formula giving stack usage (in some - unspecified constant unit) is shown in parentheses. - - The above considerations can usually be ignored if your lists are not - longer than about 10000 elements. -*/ - -/** Return the length (number of elements) of the given list. */ -let length: list<'a> => int - -/** Return the first element of the given list. Raise - [Failure "hd"] if the list is empty. */ -let hd: list<'a> => 'a - -/** Compare the lengths of two lists. [compare_lengths l1 l2] is - equivalent to [compare (length l1) (length l2)], except that - the computation stops after itering on the shortest list. - @since 4.05.0 - */ -let compare_lengths: (list<'a>, list<'b>) => int - -/** Compare the length of a list to an integer. [compare_length_with l n] is - equivalent to [compare (length l) n], except that - the computation stops after at most [n] iterations on the list. - @since 4.05.0 -*/ -let compare_length_with: (list<'a>, ~len: int) => int - -/** [cons x xs] is [x :: xs] - @since 4.05.0 -*/ -let cons: ('a, list<'a>) => list<'a> - -/** Return the given list without its first element. Raise - [Failure "tl"] if the list is empty. */ -let tl: list<'a> => list<'a> - -/** Return the [n]-th element of the given list. - The first element (head of the list) is at position 0. - Raise [Failure "nth"] if the list is too short. - Raise [Invalid_argument "List.nth"] if [n] is negative. */ -let nth: (list<'a>, int) => 'a - -/** Return the [n]-th element of the given list. - The first element (head of the list) is at position 0. - Return [None] if the list is too short. - Raise [Invalid_argument "List.nth"] if [n] is negative. - @since 4.05 -*/ -let nth_opt: (list<'a>, int) => option<'a> - -/** List reversal. */ -let rev: list<'a> => list<'a> - -/** [List.init len f] is [f 0; f 1; ...; f (len-1)], evaluated left to right. - - @raise Invalid_argument if [len < 0]. - @since 4.06.0 -*/ -let init: (~len: int, ~f: int => 'a) => list<'a> - -/** Catenate two lists. Same function as the infix operator [@]. - Not tail-recursive (length of the first argument). The [@] - operator is not tail-recursive either. */ -let append: (list<'a>, list<'a>) => list<'a> - -/** [List.rev_append l1 l2] reverses [l1] and concatenates it with [l2]. - This is equivalent to [(]{!List.rev}[ l1) @ l2], but [rev_append] is - tail-recursive and more efficient. */ -let rev_append: (list<'a>, list<'a>) => list<'a> - -/** Concatenate a list of lists. The elements of the argument are all - concatenated together (in the same order) to give the result. - Not tail-recursive - (length of the argument + length of the longest sub-list). */ -let concat: list> => list<'a> - -/** Same as [concat]. Not tail-recursive - (length of the argument + length of the longest sub-list). */ -let flatten: list> => list<'a> - -/* {1 Iterators} */ - -/** [List.iter f [a1; ...; an]] applies function [f] in turn to - [a1; ...; an]. It is equivalent to - [begin f a1; f a2; ...; f an; () end]. */ -let iter: (~f: 'a => unit, list<'a>) => unit - -/** Same as {!List.iter}, but the function is applied to the index of - the element as first argument (counting from 0), and the element - itself as second argument. - @since 4.00.0 -*/ -let iteri: (~f: (int, 'a) => unit, list<'a>) => unit - -/** [List.map f [a1; ...; an]] applies function [f] to [a1, ..., an], - and builds the list [[f a1; ...; f an]] - with the results returned by [f]. Not tail-recursive. */ -let map: (~f: 'a => 'b, list<'a>) => list<'b> - -/** Same as {!List.map}, but the function is applied to the index of - the element as first argument (counting from 0), and the element - itself as second argument. - @since 4.00.0 -*/ -let mapi: (~f: (int, 'a) => 'b, list<'a>) => list<'b> - -/** [List.rev_map f l] gives the same result as - {!List.rev}[ (]{!List.map}[ f l)], but is tail-recursive and - more efficient. */ -let rev_map: (~f: 'a => 'b, list<'a>) => list<'b> - -/** [List.fold_left f a [b1; ...; bn]] is - [f (... (f (f a b1) b2) ...) bn]. */ -let fold_left: (~f: ('a, 'b) => 'a, ~init: 'a, list<'b>) => 'a - -/** [List.fold_right f [a1; ...; an] b] is - [f a1 (f a2 (... (f an b) ...))]. Not tail-recursive. */ -let fold_right: (~f: ('a, 'b) => 'b, list<'a>, ~init: 'b) => 'b - -/* {1 Iterators on two lists} */ - -/** [List.iter2 f [a1; ...; an] [b1; ...; bn]] calls in turn - [f a1 b1; ...; f an bn]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let iter2: (~f: ('a, 'b) => unit, list<'a>, list<'b>) => unit - -/** [List.map2 f [a1; ...; an] [b1; ...; bn]] is - [[f a1 b1; ...; f an bn]]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. Not tail-recursive. */ -let map2: (~f: ('a, 'b) => 'c, list<'a>, list<'b>) => list<'c> - -/** [List.rev_map2 f l1 l2] gives the same result as - {!List.rev}[ (]{!List.map2}[ f l1 l2)], but is tail-recursive and - more efficient. */ -let rev_map2: (~f: ('a, 'b) => 'c, list<'a>, list<'b>) => list<'c> - -/** [List.fold_left2 f a [b1; ...; bn] [c1; ...; cn]] is - [f (... (f (f a b1 c1) b2 c2) ...) bn cn]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let fold_left2: (~f: ('a, 'b, 'c) => 'a, ~init: 'a, list<'b>, list<'c>) => 'a - -/** [List.fold_right2 f [a1; ...; an] [b1; ...; bn] c] is - [f a1 b1 (f a2 b2 (... (f an bn c) ...))]. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. Not tail-recursive. */ -let fold_right2: (~f: ('a, 'b, 'c) => 'c, list<'a>, list<'b>, ~init: 'c) => 'c - -/* {1 List scanning} */ - -/** [for_all p [a1; ...; an]] checks if all elements of the list - satisfy the predicate [p]. That is, it returns - [(p a1) && (p a2) && ... && (p an)]. */ -let for_all: (~f: 'a => bool, list<'a>) => bool - -/** [exists p [a1; ...; an]] checks if at least one element of - the list satisfies the predicate [p]. That is, it returns - [(p a1) || (p a2) || ... || (p an)]. */ -let exists: (~f: 'a => bool, list<'a>) => bool - -/** Same as {!List.for_all}, but for a two-argument predicate. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let for_all2: (~f: ('a, 'b) => bool, list<'a>, list<'b>) => bool - -/** Same as {!List.exists}, but for a two-argument predicate. - Raise [Invalid_argument] if the two lists are determined - to have different lengths. */ -let exists2: (~f: ('a, 'b) => bool, list<'a>, list<'b>) => bool - -/** [mem a l] is true if and only if [a] is equal - to an element of [l]. */ -let mem: ('a, ~set: list<'a>) => bool - -/** Same as {!List.mem}, but uses physical equality instead of structural - equality to compare list elements. */ -let memq: ('a, ~set: list<'a>) => bool - -/* {1 List searching} */ - -/** [find p l] returns the first element of the list [l] - that satisfies the predicate [p]. - Raise [Not_found] if there is no value that satisfies [p] in the - list [l]. */ -let find: (~f: 'a => bool, list<'a>) => 'a - -/** [find p l] returns the first element of the list [l] - that satisfies the predicate [p]. - Returns [None] if there is no value that satisfies [p] in the - list [l]. - @since 4.05 */ -let find_opt: (~f: 'a => bool, list<'a>) => option<'a> - -/** [filter p l] returns all the elements of the list [l] - that satisfy the predicate [p]. The order of the elements - in the input list is preserved. */ -let filter: (~f: 'a => bool, list<'a>) => list<'a> - -/** [find_all] is another name for {!List.filter}. */ -let find_all: (~f: 'a => bool, list<'a>) => list<'a> - -/** [partition p l] returns a pair of lists [(l1, l2)], where - [l1] is the list of all the elements of [l] that - satisfy the predicate [p], and [l2] is the list of all the - elements of [l] that do not satisfy [p]. - The order of the elements in the input list is preserved. */ -let partition: (~f: 'a => bool, list<'a>) => (list<'a>, list<'a>) - -/* {1 Association lists} */ - -/** [assoc a l] returns the value associated with key [a] in the list of - pairs [l]. That is, - [assoc a [ ...; (a,b); ...] = b] - if [(a,b)] is the leftmost binding of [a] in list [l]. - Raise [Not_found] if there is no value associated with [a] in the - list [l]. */ -let assoc: ('a, list<('a, 'b)>) => 'b - -/** [assoc_opt a l] returns the value associated with key [a] in the list of - pairs [l]. That is, - [assoc a [ ...; (a,b); ...] = b] - if [(a,b)] is the leftmost binding of [a] in list [l]. - Returns [None] if there is no value associated with [a] in the - list [l]. - @since 4.05 -*/ -let assoc_opt: ('a, list<('a, 'b)>) => option<'b> - -/** Same as {!List.assoc}, but uses physical equality instead of - structural equality to compare keys. */ -let assq: ('a, list<('a, 'b)>) => 'b - -/** Same as {!List.assoc_opt}, but uses physical equality instead of - structural equality to compare keys. - @since 4.05.0 */ -let assq_opt: ('a, list<('a, 'b)>) => option<'b> - -/** Same as {!List.assoc}, but simply return true if a binding exists, - and false if no bindings exist for the given key. */ -let mem_assoc: ('a, ~map: list<('a, 'b)>) => bool - -/** Same as {!List.mem_assoc}, but uses physical equality instead of - structural equality to compare keys. */ -let mem_assq: ('a, ~map: list<('a, 'b)>) => bool - -/** [remove_assoc a l] returns the list of - pairs [l] without the first pair with key [a], if any. - Not tail-recursive. */ -let remove_assoc: ('a, list<('a, 'b)>) => list<('a, 'b)> - -/** Same as {!List.remove_assoc}, but uses physical equality instead - of structural equality to compare keys. Not tail-recursive. */ -let remove_assq: ('a, list<('a, 'b)>) => list<('a, 'b)> - -/* {1 Lists of pairs} */ - -/** Transform a list of pairs into a pair of lists: - [split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])]. - Not tail-recursive. -*/ -let split: list<('a, 'b)> => (list<'a>, list<'b>) - -/** Transform a pair of lists into a list of pairs: - [combine [a1; ...; an] [b1; ...; bn]] is - [[(a1,b1); ...; (an,bn)]]. - Raise [Invalid_argument] if the two lists - have different lengths. Not tail-recursive. */ -let combine: (list<'a>, list<'b>) => list<('a, 'b)> - -/* {1 Sorting} */ - -/** Sort a list in increasing order according to a comparison - function. The comparison function must return 0 if its arguments - compare as equal, a positive integer if the first is greater, - and a negative integer if the first is smaller (see Array.sort for - a complete specification). For example, - {!Pervasives.compare} is a suitable comparison function. - The resulting list is sorted in increasing order. - [List.sort] is guaranteed to run in constant heap space - (in addition to the size of the result list) and logarithmic - stack space. - - The current implementation uses Merge Sort. It runs in constant - heap space and logarithmic stack space. -*/ -let sort: (~cmp: ('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort}, but the sorting algorithm is guaranteed to - be stable (i.e. elements that compare equal are kept in their - original order) . - - The current implementation uses Merge Sort. It runs in constant - heap space and logarithmic stack space. -*/ -let stable_sort: (~cmp: ('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort} or {!List.stable_sort}, whichever is - faster on typical input. */ -let fast_sort: (~cmp: ('a, 'a) => int, list<'a>) => list<'a> - -/** Same as {!List.sort}, but also remove duplicates. - @since 4.03.0 */ -let sort_uniq: (~cmp: ('a, 'a) => int, list<'a>) => list<'a> - -/** Merge two lists: - Assuming that [l1] and [l2] are sorted according to the - comparison function [cmp], [merge cmp l1 l2] will return a - sorted list containing all the elements of [l1] and [l2]. - If several elements compare equal, the elements of [l1] will be - before the elements of [l2]. - Not tail-recursive (sum of the lengths of the arguments). -*/ -let merge: (~cmp: ('a, 'a) => int, list<'a>, list<'a>) => list<'a> diff --git a/jscomp/stdlib-406/map.res b/jscomp/stdlib-406/map.res index f485f302e2..a6fa75344c 100644 --- a/jscomp/stdlib-406/map.res +++ b/jscomp/stdlib-406/map.res @@ -1,669 +1,21 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ +type t<'k, 'v> = Js.Map.t<'k, 'v> -module type OrderedType = { - type t - let compare: (t, t) => int -} +@new external make: unit => t<'k, 'v> = "Map" +@new external fromArray: array<('k, 'v)> => t<'k, 'v> = "Map" +@new external fromIterator: Iterator.t<('k, 'v)> => t<'k, 'v> = "Map" -module type S = { - type key - type t<+'a> - let empty: t<'a> - let is_empty: t<'a> => bool - let mem: (key, t<'a>) => bool - let add: (key, 'a, t<'a>) => t<'a> - let update: (key, option<'a> => option<'a>, t<'a>) => t<'a> - let singleton: (key, 'a) => t<'a> - let remove: (key, t<'a>) => t<'a> - let merge: ((key, option<'a>, option<'b>) => option<'c>, t<'a>, t<'b>) => t<'c> - let union: ((key, 'a, 'a) => option<'a>, t<'a>, t<'a>) => t<'a> - let compare: (('a, 'a) => int, t<'a>, t<'a>) => int - let equal: (('a, 'a) => bool, t<'a>, t<'a>) => bool - let iter: ((key, 'a) => unit, t<'a>) => unit - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - let for_all: ((key, 'a) => bool, t<'a>) => bool - let exists: ((key, 'a) => bool, t<'a>) => bool - let filter: ((key, 'a) => bool, t<'a>) => t<'a> - let partition: ((key, 'a) => bool, t<'a>) => (t<'a>, t<'a>) - let cardinal: t<'a> => int - let bindings: t<'a> => list<(key, 'a)> - let min_binding: t<'a> => (key, 'a) - let min_binding_opt: t<'a> => option<(key, 'a)> - let max_binding: t<'a> => (key, 'a) - let max_binding_opt: t<'a> => option<(key, 'a)> - let choose: t<'a> => (key, 'a) - let choose_opt: t<'a> => option<(key, 'a)> - let split: (key, t<'a>) => (t<'a>, option<'a>, t<'a>) - let find: (key, t<'a>) => 'a - let find_opt: (key, t<'a>) => option<'a> - let find_first: (key => bool, t<'a>) => (key, 'a) - let find_first_opt: (key => bool, t<'a>) => option<(key, 'a)> - let find_last: (key => bool, t<'a>) => (key, 'a) - let find_last_opt: (key => bool, t<'a>) => option<(key, 'a)> - let map: ('a => 'b, t<'a>) => t<'b> - let mapi: ((key, 'a) => 'b, t<'a>) => t<'b> -} +@get external size: t<'k, 'v> => int = "size" -module Make = (Ord: OrderedType) => { - type key = Ord.t +@send external clear: t<'k, 'v> => unit = "clear" - type rec t<'a> = - | Empty - | Node({l: t<'a>, v: key, d: 'a, r: t<'a>, h: int}) +@send external forEach: (t<'k, 'v>, 'v => unit) => unit = "forEach" +@send external forEachWithKey: (t<'k, 'v>, ('v, 'k) => unit) => unit = "forEach" - let height = param => - switch param { - | Empty => 0 - | Node({h}) => h - } +@send external get: (t<'k, 'v>, 'k) => option<'v> = "get" +@send external has: (t<'k, 'v>, 'k) => bool = "has" +@send external set: (t<'k, 'v>, 'k, 'v) => unit = "set" +@send external delete: (t<'k, 'v>, 'k) => bool = "delete" - let create = (l, x, d, r) => { - let hl = height(l) and hr = height(r) - Node({ - l, - v: x, - d, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - - let singleton = (x, d) => Node({l: Empty, v: x, d, r: Empty, h: 1}) - - let bal = (l, x, d, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - if hl > hr + 2 { - switch l { - | Empty => invalid_arg("Map.bal") - | Node({l: ll, v: lv, d: ld, r: lr}) => - if height(ll) >= height(lr) { - create(ll, lv, ld, create(lr, x, d, r)) - } else { - switch lr { - | Empty => invalid_arg("Map.bal") - | Node({l: lrl, v: lrv, d: lrd, r: lrr}) => - create(create(ll, lv, ld, lrl), lrv, lrd, create(lrr, x, d, r)) - } - } - } - } else if hr > hl + 2 { - switch r { - | Empty => invalid_arg("Map.bal") - | Node({l: rl, v: rv, d: rd, r: rr}) => - if height(rr) >= height(rl) { - create(create(l, x, d, rl), rv, rd, rr) - } else { - switch rl { - | Empty => invalid_arg("Map.bal") - | Node({l: rll, v: rlv, d: rld, r: rlr}) => - create(create(l, x, d, rll), rlv, rld, create(rlr, rv, rd, rr)) - } - } - } - } else { - Node({ - l, - v: x, - d, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - } - - let empty = Empty - - let is_empty = param => - switch param { - | Empty => true - | _ => false - } - - let rec add = (x, data, param) => - switch param { - | Empty => Node({l: Empty, v: x, d: data, r: Empty, h: 1}) - | Node({l, v, d, r, h}) as m => - let c = Ord.compare(x, v) - if c == 0 { - if d === data { - m - } else { - Node({l, v: x, d: data, r, h}) - } - } else if c < 0 { - let ll = add(x, data, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = add(x, data, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec find = (x, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - d - } else { - find( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec find_first_aux = (v0, d0, f, param) => - switch param { - | Empty => (v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_first_aux(v, d, f, l) - } else { - find_first_aux(v0, d0, f, r) - } - } - - let rec find_first = (f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - if f(v) { - find_first_aux(v, d, f, l) - } else { - find_first(f, r) - } - } - - let rec find_first_opt_aux = (v0, d0, f, param) => - switch param { - | Empty => Some(v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_first_opt_aux(v, d, f, l) - } else { - find_first_opt_aux(v0, d0, f, r) - } - } - - let rec find_first_opt = (f, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - if f(v) { - find_first_opt_aux(v, d, f, l) - } else { - find_first_opt(f, r) - } - } - - let rec find_last_aux = (v0, d0, f, param) => - switch param { - | Empty => (v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_last_aux(v, d, f, r) - } else { - find_last_aux(v0, d0, f, l) - } - } - - let rec find_last = (f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - if f(v) { - find_last_aux(v, d, f, r) - } else { - find_last(f, l) - } - } - - let rec find_last_opt_aux = (v0, d0, f, param) => - switch param { - | Empty => Some(v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_last_opt_aux(v, d, f, r) - } else { - find_last_opt_aux(v0, d0, f, l) - } - } - - let rec find_last_opt = (f, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - if f(v) { - find_last_opt_aux(v, d, f, r) - } else { - find_last_opt(f, l) - } - } - - let rec find_opt = (x, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - Some(d) - } else { - find_opt( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec mem = (x, param) => - switch param { - | Empty => false - | Node({l, v, r}) => - let c = Ord.compare(x, v) - c == 0 || - mem( - x, - if c < 0 { - l - } else { - r - }, - ) - } - - let rec min_binding = param => - switch param { - | Empty => raise(Not_found) - | Node({l: Empty, v, d}) => (v, d) - | Node({l}) => min_binding(l) - } - - let rec min_binding_opt = param => - switch param { - | Empty => None - | Node({l: Empty, v, d}) => Some(v, d) - | Node({l}) => min_binding_opt(l) - } - - let rec max_binding = param => - switch param { - | Empty => raise(Not_found) - | Node({v, d, r: Empty}) => (v, d) - | Node({r}) => max_binding(r) - } - - let rec max_binding_opt = param => - switch param { - | Empty => None - | Node({v, d, r: Empty}) => Some(v, d) - | Node({r}) => max_binding_opt(r) - } - - let rec remove_min_binding = param => - switch param { - | Empty => invalid_arg("Map.remove_min_elt") - | Node({l: Empty, r}) => r - | Node({l, v, d, r}) => bal(remove_min_binding(l), v, d, r) - } - - let merge = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => - let (x, d) = min_binding(t2) - bal(t1, x, d, remove_min_binding(t2)) - } - - let rec remove = (x, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r}) as m => - let c = Ord.compare(x, v) - if c == 0 { - merge(l, r) - } else if c < 0 { - let ll = remove(x, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = remove(x, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec update = (x, f, param) => - switch param { - | Empty => - switch f(None) { - | None => Empty - | Some(data) => Node({l: Empty, v: x, d: data, r: Empty, h: 1}) - } - | Node({l, v, d, r, h}) as m => - let c = Ord.compare(x, v) - if c == 0 { - switch f(Some(d)) { - | None => merge(l, r) - | Some(data) => - if d === data { - m - } else { - Node({l, v: x, d: data, r, h}) - } - } - } else if c < 0 { - let ll = update(x, f, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = update(x, f, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec iter = (f, param) => - switch param { - | Empty => () - | Node({l, v, d, r}) => - iter(f, l) - f(v, d) - iter(f, r) - } - - let rec map = (f, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r, h}) => - let l' = map(f, l) - let d' = f(d) - let r' = map(f, r) - Node({l: l', v, d: d', r: r', h}) - } - - let rec mapi = (f, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r, h}) => - let l' = mapi(f, l) - let d' = f(v, d) - let r' = mapi(f, r) - Node({l: l', v, d: d', r: r', h}) - } - - let rec fold = (f, m, accu) => - switch m { - | Empty => accu - | Node({l, v, d, r}) => fold(f, r, f(v, d, fold(f, l, accu))) - } - - let rec for_all = (p, param) => - switch param { - | Empty => true - | Node({l, v, d, r}) => p(v, d) && (for_all(p, l) && for_all(p, r)) - } - - let rec exists = (p, param) => - switch param { - | Empty => false - | Node({l, v, d, r}) => p(v, d) || (exists(p, l) || exists(p, r)) - } - - /* Beware: those two functions assume that the added k is *strictly* - smaller (or bigger) than all the present keys in the tree; it - does not test for equality with the current min (or max) key. - - Indeed, they are only used during the "join" operation which - respects this precondition. - */ - - let rec add_min_binding = (k, x, param) => - switch param { - | Empty => singleton(k, x) - | Node({l, v, d, r}) => bal(add_min_binding(k, x, l), v, d, r) - } - - let rec add_max_binding = (k, x, param) => - switch param { - | Empty => singleton(k, x) - | Node({l, v, d, r}) => bal(l, v, d, add_max_binding(k, x, r)) - } - - /* Same as create and bal, but no assumptions are made on the - relative heights of l and r. */ - - let rec join = (l, v, d, r) => - switch (l, r) { - | (Empty, _) => add_min_binding(v, d, r) - | (_, Empty) => add_max_binding(v, d, l) - | (Node({l: ll, v: lv, d: ld, r: lr, h: lh}), Node({l: rl, v: rv, d: rd, r: rr, h: rh})) => - if lh > rh + 2 { - bal(ll, lv, ld, join(lr, v, d, r)) - } else if rh > lh + 2 { - bal(join(l, v, d, rl), rv, rd, rr) - } else { - create(l, v, d, r) - } - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - No assumption on the heights of l and r. */ - - let concat = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => - let (x, d) = min_binding(t2) - join(t1, x, d, remove_min_binding(t2)) - } - - let concat_or_join = (t1, v, d, t2) => - switch d { - | Some(d) => join(t1, v, d, t2) - | None => concat(t1, t2) - } - - let rec split = (x, param) => - switch param { - | Empty => (Empty, None, Empty) - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - (l, Some(d), r) - } else if c < 0 { - let (ll, pres, rl) = split(x, l) - (ll, pres, join(rl, v, d, r)) - } else { - let (lr, pres, rr) = split(x, r) - (join(l, v, d, lr), pres, rr) - } - } - - let rec merge = (f, s1, s2) => - switch (s1, s2) { - | (Empty, Empty) => Empty - | (Node({l: l1, v: v1, d: d1, r: r1, h: h1}), _) if h1 >= height(s2) => - let (l2, d2, r2) = split(v1, s2) - concat_or_join(merge(f, l1, l2), v1, f(v1, Some(d1), d2), merge(f, r1, r2)) - | (_, Node({l: l2, v: v2, d: d2, r: r2})) => - let (l1, d1, r1) = split(v2, s1) - concat_or_join(merge(f, l1, l2), v2, f(v2, d1, Some(d2)), merge(f, r1, r2)) - | _ => assert(false) - } - - let rec union = (f, s1, s2) => - switch (s1, s2) { - | (Empty, s) | (s, Empty) => s - | (Node({l: l1, v: v1, d: d1, r: r1, h: h1}), Node({l: l2, v: v2, d: d2, r: r2, h: h2})) => - if h1 >= h2 { - let (l2, d2, r2) = split(v1, s2) - let l = union(f, l1, l2) and r = union(f, r1, r2) - switch d2 { - | None => join(l, v1, d1, r) - | Some(d2) => concat_or_join(l, v1, f(v1, d1, d2), r) - } - } else { - let (l1, d1, r1) = split(v2, s1) - let l = union(f, l1, l2) and r = union(f, r1, r2) - switch d1 { - | None => join(l, v2, d2, r) - | Some(d1) => concat_or_join(l, v2, f(v2, d1, d2), r) - } - } - } - - let rec filter = (p, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r}) as m => - /* call [p] in the expected left-to-right order */ - let l' = filter(p, l) - let pvd = p(v, d) - let r' = filter(p, r) - if pvd { - if l === l' && r === r' { - m - } else { - join(l', v, d, r') - } - } else { - concat(l', r') - } - } - - let rec partition = (p, param) => - switch param { - | Empty => (Empty, Empty) - | Node({l, v, d, r}) => - /* call [p] in the expected left-to-right order */ - let (lt, lf) = partition(p, l) - let pvd = p(v, d) - let (rt, rf) = partition(p, r) - if pvd { - (join(lt, v, d, rt), concat(lf, rf)) - } else { - (concat(lt, rt), join(lf, v, d, rf)) - } - } - - type rec enumeration<'a> = End | More(key, 'a, t<'a>, enumeration<'a>) - - let rec cons_enum = (m, e) => - switch m { - | Empty => e - | Node({l, v, d, r}) => cons_enum(l, More(v, d, r, e)) - } - - let compare = (cmp, m1, m2) => { - let rec compare_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => 0 - | (End, _) => -1 - | (_, End) => 1 - | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) => - let c = Ord.compare(v1, v2) - if c != 0 { - c - } else { - let c = cmp(d1, d2) - if c != 0 { - c - } else { - compare_aux(cons_enum(r1, e1), cons_enum(r2, e2)) - } - } - } - compare_aux(cons_enum(m1, End), cons_enum(m2, End)) - } - - let equal = (cmp, m1, m2) => { - let rec equal_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => true - | (End, _) => false - | (_, End) => false - | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) => - Ord.compare(v1, v2) == 0 && (cmp(d1, d2) && equal_aux(cons_enum(r1, e1), cons_enum(r2, e2))) - } - equal_aux(cons_enum(m1, End), cons_enum(m2, End)) - } - - let rec cardinal = param => - switch param { - | Empty => 0 - | Node({l, r}) => cardinal(l) + 1 + cardinal(r) - } - - let rec bindings_aux = (accu, param) => - switch param { - | Empty => accu - | Node({l, v, d, r}) => bindings_aux(list{(v, d), ...bindings_aux(accu, r)}, l) - } - - let bindings = s => bindings_aux(list{}, s) - - let choose = min_binding - - let choose_opt = min_binding_opt -} +@send external keys: t<'k, 'v> => Iterator.t<'k> = "keys" +@send external values: t<'k, 'v> => Iterator.t<'v> = "values" +@send external entries: t<'k, 'v> => Iterator.t<('k, 'v)> = "entries" diff --git a/jscomp/stdlib-406/map.resi b/jscomp/stdlib-406/map.resi index 11458cb69a..f1067a8abb 100644 --- a/jscomp/stdlib-406/map.resi +++ b/jscomp/stdlib-406/map.resi @@ -1,310 +1,265 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Association tables over ordered types. - - This module implements applicative association tables, also known as - finite maps or dictionaries, given a total ordering function - over the keys. - All operations over maps are purely applicative (no side-effects). - The implementation uses balanced binary trees, and therefore searching - and insertion take time logarithmic in the size of the map. - - For instance: - {[ - module IntPairs = - struct - type t = int * int - let compare (x0,y0) (x1,y1) = - match Pervasives.compare x0 x1 with - 0 -> Pervasives.compare y0 y1 - | c -> c - end - - module PairsMap = Map.Make(IntPairs) - - let m = PairsMap.(empty |> add (0,1) \"hello\" |> add (1,0) \"world\") - ]} - - This creates a new module [PairsMap], with a new type ['a PairsMap.t] - of maps from [int * int] to ['a]. In this example, [m] contains [string] - values so its type is [string PairsMap.t]. +/*** +Bindings to the mutable JavaScript `Map`. + +See [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) on MDN. +*/ + +/** +Type representing an instance of `Map`. +*/ +type t<'k, 'v> = Js.Map.t<'k, 'v> + +/** +Creates a new, mutable JavaScript `Map`. A `Map` can have any values as both keys and values. + +See [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) on MDN. + + + +## Examples +```rescript +`make()` +// You can annotate the type of your map if you want to +let myMap: Map.t = Map.make() + +// Or you can let ReScript infer what's in your map +let map = Map.make() +map->Map.set("lang", "ReScript") // Inferred as Map.t +``` + +## Alternatives +A JavaScript `Map` is mutable. If you're looking for an immutable alternative, check out`Belt.Map`. +*/ +@new +external make: unit => t<'k, 'v> = "Map" + +/** +Turns an array of key/value pairs into a Map. + +## Examples +```rescript +type languages = ReScript | JavaScript | TypeScript +let languageRank = [(ReScript, 1), (JavaScript, 2), (TypeScript, 3)] + +let map = Map.fromArray(languageRank) // Map.t + +switch map->Map.get(ReScript) { +| Some(1) => Console.log("Yay, ReScript is #1!") +| _ => Console.log("Uh-oh, something is _terribly_ wrong with this program... abort.") +} +``` +*/ +@new +external fromArray: array<('k, 'v)> => t<'k, 'v> = "Map" + +/** +Turns an iterator in the shape of `('key, 'value)` into a `Map`. + +## Examples +```rescript +// Let's pretend we have an interator in the correct shape +@val external someIterator: Iterator.t<(string, int)> = "someIterator" + +let map = Map.fromIterator(someIterator) // Map.t +``` +*/ +@new +external fromIterator: Iterator.t<('k, 'v)> => t<'k, 'v> = "Map" + +/** +Returns the size, the number of key/value pairs, of the map. + +## Examples +```rescript +let map = Map.make() + +map->Map.set("someKey", "someValue") + +let size = map->Map.size // 1 +``` +*/ +@get +external size: t<'k, 'v> => int = "size" + +/** +Clears all entries in the map. + +## Examples +```rescript +let map = Map.make() + +map->Map.set("someKey", "someValue") +map->Map.size // 1 + +map->Map.clear +map->Map.size // 0 +``` +*/ +@send +external clear: t<'k, 'v> => unit = "clear" + +/** +Iterates through all values of the map. + +> Please note that this is *without the keys*, just the values. If you need the key as well, use `Map.forEachWithKey`. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("someKey2", "someValue2") + +map->Map.forEach(value => { + Console.log(value) +}) +``` */ +@send +external forEach: (t<'k, 'v>, 'v => unit) => unit = "forEach" + +/** +Iterates through all values of the map, including the key for each value. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("someKey2", "someValue2") + +map->Map.forEachWithKey((value, key) => { + Console.log2(value, key) +}) +``` +*/ +@send +external forEachWithKey: (t<'k, 'v>, ('v, 'k) => unit) => unit = "forEach" + +/** +Returns the value for a key, if a value exists at that key. -/** Input signature of the functor {!Map.Make}. */ -module type OrderedType = { - /** The type of the map keys. */ - type t - - /** A total ordering function over the keys. - This is a two-argument function [f] such that - [f e1 e2] is zero if the keys [e1] and [e2] are equal, - [f e1 e2] is strictly negative if [e1] is smaller than [e2], - and [f e1 e2] is strictly positive if [e1] is greater than [e2]. - Example: a suitable ordering function is the generic structural - comparison function {!Pervasives.compare}. */ - let compare: (t, t) => int +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") + +switch map->Map.get("someKey") { +| None => Console.log("Nope, didn't have it.") +| Some(value) => Console.log2("Yay, had the value, and it's:", value) } +``` +*/ +@send +external get: (t<'k, 'v>, 'k) => option<'v> = "get" -/** Output signature of the functor {!Map.Make}. */ -module type S = { - /** The type of the map keys. */ - type key - - /** The type of maps from type [key] to type ['a]. */ - type t<+'a> - - /** The empty map. */ - let empty: t<'a> - - /** Test whether a map is empty or not. */ - let is_empty: t<'a> => bool - - /** [mem x m] returns [true] if [m] contains a binding for [x], - and [false] otherwise. */ - let mem: (key, t<'a>) => bool - - /** [add x y m] returns a map containing the same bindings as - [m], plus a binding of [x] to [y]. If [x] was already bound - in [m] to a value that is physically equal to [y], - [m] is returned unchanged (the result of the function is - then physically equal to [m]). Otherwise, the previous binding - of [x] in [m] disappears. - @before 4.03 Physical equality was not ensured. */ - let add: (key, 'a, t<'a>) => t<'a> - - /** [update x f m] returns a map containing the same bindings as - [m], except for the binding of [x]. Depending on the value of - [y] where [y] is [f (find_opt x m)], the binding of [x] is - added, removed or updated. If [y] is [None], the binding is - removed if it exists; otherwise, if [y] is [Some z] then [x] - is associated to [z] in the resulting map. If [x] was already - bound in [m] to a value that is physically equal to [z], [m] - is returned unchanged (the result of the function is then - physically equal to [m]). - @since 4.06.0 - */ - let update: (key, option<'a> => option<'a>, t<'a>) => t<'a> - - /** [singleton x y] returns the one-element map that contains a binding [y] - for [x]. - @since 3.12.0 - */ - let singleton: (key, 'a) => t<'a> - - /** [remove x m] returns a map containing the same bindings as - [m], except for [x] which is unbound in the returned map. - If [x] was not in [m], [m] is returned unchanged - (the result of the function is then physically equal to [m]). - @before 4.03 Physical equality was not ensured. */ - let remove: (key, t<'a>) => t<'a> - - /** [merge f m1 m2] computes a map whose keys is a subset of keys of [m1] - and of [m2]. The presence of each such binding, and the corresponding - value, is determined with the function [f]. - In terms of the [find_opt] operation, we have - [find_opt x (merge f m1 m2) = f (find_opt x m1) (find_opt x m2)] - for any key [x], provided that [f None None = None]. - @since 3.12.0 - */ - let merge: ((key, option<'a>, option<'b>) => option<'c>, t<'a>, t<'b>) => t<'c> - - /** [union f m1 m2] computes a map whose keys is the union of keys - of [m1] and of [m2]. When the same binding is defined in both - arguments, the function [f] is used to combine them. - This is a special case of [merge]: [union f m1 m2] is equivalent - to [merge f' m1 m2], where - - [f' None None = None] - - [f' (Some v) None = Some v] - - [f' None (Some v) = Some v] - - [f' (Some v1) (Some v2) = f v1 v2] - - @since 4.03.0 - */ - let union: ((key, 'a, 'a) => option<'a>, t<'a>, t<'a>) => t<'a> - - /** Total ordering between maps. The first argument is a total ordering - used to compare data associated with equal keys in the two maps. */ - let compare: (('a, 'a) => int, t<'a>, t<'a>) => int - - /** [equal cmp m1 m2] tests whether the maps [m1] and [m2] are - equal, that is, contain equal keys and associate them with - equal data. [cmp] is the equality predicate used to compare - the data associated with the keys. */ - let equal: (('a, 'a) => bool, t<'a>, t<'a>) => bool - - /** [iter f m] applies [f] to all bindings in map [m]. - [f] receives the key as first argument, and the associated value - as second argument. The bindings are passed to [f] in increasing - order with respect to the ordering over the type of the keys. */ - let iter: ((key, 'a) => unit, t<'a>) => unit - - /** [fold f m a] computes [(f kN dN ... (f k1 d1 a)...)], - where [k1 ... kN] are the keys of all bindings in [m] - (in increasing order), and [d1 ... dN] are the associated data. */ - let fold: ((key, 'a, 'b) => 'b, t<'a>, 'b) => 'b - - /** [for_all p m] checks if all the bindings of the map - satisfy the predicate [p]. - @since 3.12.0 - */ - let for_all: ((key, 'a) => bool, t<'a>) => bool - - /** [exists p m] checks if at least one binding of the map - satisfies the predicate [p]. - @since 3.12.0 - */ - let exists: ((key, 'a) => bool, t<'a>) => bool - - /** [filter p m] returns the map with all the bindings in [m] - that satisfy predicate [p]. If [p] satisfies every binding in [m], - [m] is returned unchanged (the result of the function is then - physically equal to [m]) - @since 3.12.0 - @before 4.03 Physical equality was not ensured. - */ - let filter: ((key, 'a) => bool, t<'a>) => t<'a> - - /** [partition p m] returns a pair of maps [(m1, m2)], where - [m1] contains all the bindings of [s] that satisfy the - predicate [p], and [m2] is the map with all the bindings of - [s] that do not satisfy [p]. - @since 3.12.0 - */ - let partition: ((key, 'a) => bool, t<'a>) => (t<'a>, t<'a>) - - /** Return the number of bindings of a map. - @since 3.12.0 - */ - let cardinal: t<'a> => int - - /** Return the list of all bindings of the given map. - The returned list is sorted in increasing order with respect - to the ordering [Ord.compare], where [Ord] is the argument - given to {!Map.Make}. - @since 3.12.0 - */ - let bindings: t<'a> => list<(key, 'a)> - - /** Return the smallest binding of the given map - (with respect to the [Ord.compare] ordering), or raise - [Not_found] if the map is empty. - @since 3.12.0 - */ - let min_binding: t<'a> => (key, 'a) - - /** Return the smallest binding of the given map - (with respect to the [Ord.compare] ordering), or [None] - if the map is empty. - @since 4.05 - */ - let min_binding_opt: t<'a> => option<(key, 'a)> - - /** Same as {!Map.S.min_binding}, but returns the largest binding - of the given map. - @since 3.12.0 - */ - let max_binding: t<'a> => (key, 'a) - - /** Same as {!Map.S.min_binding_opt}, but returns the largest binding - of the given map. - @since 4.05 - */ - let max_binding_opt: t<'a> => option<(key, 'a)> - - /** Return one binding of the given map, or raise [Not_found] if - the map is empty. Which binding is chosen is unspecified, - but equal bindings will be chosen for equal maps. - @since 3.12.0 - */ - let choose: t<'a> => (key, 'a) - - /** Return one binding of the given map, or [None] if - the map is empty. Which binding is chosen is unspecified, - but equal bindings will be chosen for equal maps. - @since 4.05 - */ - let choose_opt: t<'a> => option<(key, 'a)> - - /** [split x m] returns a triple [(l, data, r)], where - [l] is the map with all the bindings of [m] whose key - is strictly less than [x]; - [r] is the map with all the bindings of [m] whose key - is strictly greater than [x]; - [data] is [None] if [m] contains no binding for [x], - or [Some v] if [m] binds [v] to [x]. - @since 3.12.0 - */ - let split: (key, t<'a>) => (t<'a>, option<'a>, t<'a>) - - /** [find x m] returns the current binding of [x] in [m], - or raises [Not_found] if no such binding exists. */ - let find: (key, t<'a>) => 'a - - /** [find_opt x m] returns [Some v] if the current binding of [x] - in [m] is [v], or [None] if no such binding exists. - @since 4.05 - */ - let find_opt: (key, t<'a>) => option<'a> - - /** [find_first f m], where [f] is a monotonically increasing function, - returns the binding of [m] with the lowest key [k] such that [f k], - or raises [Not_found] if no such key exists. - - For example, [find_first (fun k -> Ord.compare k x >= 0) m] will return - the first binding [k, v] of [m] where [Ord.compare k x >= 0] - (intuitively: [k >= x]), or raise [Not_found] if [x] is greater than any - element of [m]. - - @since 4.05 - */ - let find_first: (key => bool, t<'a>) => (key, 'a) - - /** [find_first_opt f m], where [f] is a monotonically increasing function, - returns an option containing the binding of [m] with the lowest key [k] - such that [f k], or [None] if no such key exists. - @since 4.05 - */ - let find_first_opt: (key => bool, t<'a>) => option<(key, 'a)> - - /** [find_last f m], where [f] is a monotonically decreasing function, - returns the binding of [m] with the highest key [k] such that [f k], - or raises [Not_found] if no such key exists. - @since 4.05 - */ - let find_last: (key => bool, t<'a>) => (key, 'a) - - /** [find_last_opt f m], where [f] is a monotonically decreasing function, - returns an option containing the binding of [m] with the highest key [k] - such that [f k], or [None] if no such key exists. - @since 4.05 - */ - let find_last_opt: (key => bool, t<'a>) => option<(key, 'a)> - - /** [map f m] returns a map with same domain as [m], where the - associated value [a] of all bindings of [m] has been - replaced by the result of the application of [f] to [a]. - The bindings are passed to [f] in increasing order - with respect to the ordering over the type of the keys. */ - let map: ('a => 'b, t<'a>) => t<'b> - - /** Same as {!Map.S.map}, but the function receives as arguments both the - key and the associated value for each binding of the map. */ - let mapi: ((key, 'a) => 'b, t<'a>) => t<'b> +/** +Checks whether the map has a specific key. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") + +switch map->Map.has("someKey") { +| false => Console.log("Nope, didn't have it.") +| true => Console.log("Yay, we have the value!") } +``` +*/ +@send +external has: (t<'k, 'v>, 'k) => bool = "has" + +/** +Sets the provided `value` to the provided `key`. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +``` +*/ +@send +external set: (t<'k, 'v>, 'k, 'v) => unit = "set" + +/** +Deletes the provided `key` and its value from the map. Returns a `bool` for whether the key existed, and was deleted. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +let didDeleteKey = map->Map.delete("someKey") +Console.log(didDeleteKey) // Logs `true` to the console, becuase the map had the key, so it was successfully deleted + +let didDeleteKey = map->Map.delete("someNonExistantKey") +Console.log(didDeleteKey) // Logs `false` to the console, becuase the key did not exist +``` +*/ +@send +external delete: (t<'k, 'v>, 'k) => bool = "delete" + +/** +Returns an iterator that holds all keys of the map. -/** Functor building an implementation of the map structure - given a totally ordered type. */ -module Make: (Ord: OrderedType) => (S with type key = Ord.t) +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("anotherKey", "anotherValue") + +let keys = map->Map.keys + +// Logs the first key +Console.log(Iterator.next(keys).value) + +// You can also turn the iterator into an array. +// Remember that an iterator consumes values. We'll need a fresh keys iterator to get an array of all keys, since we consumed a value via `next` above already. +Console.log(map->Map.keys->Iterator.toArray) +``` +*/ +@send +external keys: t<'k, 'v> => Iterator.t<'k> = "keys" + +/** +Returns an iterator that holds all values of the map. + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("anotherKey", "anotherValue") + +let values = map->Map.values + +// Logs the first value +Console.log(Iterator.next(values).value) + +// You can also turn the iterator into an array. +// Remember that an iterator consumes values. We'll need a fresh values iterator to get an array of all values, since we consumed a value via `next` above already. +Console.log(map->Map.values->Iterator.toArray) +``` +*/ +@send +external values: t<'k, 'v> => Iterator.t<'v> = "values" + +/** +Returns an iterator that holds all entries of the map. +An entry is represented as a tuple of `('key, 'value)`, + +## Examples +```rescript +let map = Map.make() +map->Map.set("someKey", "someValue") +map->Map.set("anotherKey", "anotherValue") + +let entries = map->Map.entries + +// Logs the first value +Console.log(Iterator.next(entries).value) + +// You can also turn the iterator into an array. +// Remember that an iterator consumes entries. We'll need a fresh entries iterator to get an array of all entries, since we consumed a value via `next` above already. +Console.log(map->Map.entries->Iterator.toArray) +``` +*/ +@send +external entries: t<'k, 'v> => Iterator.t<('k, 'v)> = "entries" diff --git a/jscomp/stdlib-406/mapLabels.res b/jscomp/stdlib-406/mapLabels.res deleted file mode 100644 index 7a1a395075..0000000000 --- a/jscomp/stdlib-406/mapLabels.res +++ /dev/null @@ -1,669 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -module type OrderedType = { - type t - let compare: (t, t) => int -} - -module type S = { - type key - type t<+'a> - let empty: t<'a> - let is_empty: t<'a> => bool - let mem: (key, t<'a>) => bool - let add: (~key: key, ~data: 'a, t<'a>) => t<'a> - let update: (~key: key, ~f: option<'a> => option<'a>, t<'a>) => t<'a> - let singleton: (key, 'a) => t<'a> - let remove: (key, t<'a>) => t<'a> - let merge: (~f: (key, option<'a>, option<'b>) => option<'c>, t<'a>, t<'b>) => t<'c> - let union: (~f: (key, 'a, 'a) => option<'a>, t<'a>, t<'a>) => t<'a> - let compare: (~cmp: ('a, 'a) => int, t<'a>, t<'a>) => int - let equal: (~cmp: ('a, 'a) => bool, t<'a>, t<'a>) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let for_all: (~f: (key, 'a) => bool, t<'a>) => bool - let exists: (~f: (key, 'a) => bool, t<'a>) => bool - let filter: (~f: (key, 'a) => bool, t<'a>) => t<'a> - let partition: (~f: (key, 'a) => bool, t<'a>) => (t<'a>, t<'a>) - let cardinal: t<'a> => int - let bindings: t<'a> => list<(key, 'a)> - let min_binding: t<'a> => (key, 'a) - let min_binding_opt: t<'a> => option<(key, 'a)> - let max_binding: t<'a> => (key, 'a) - let max_binding_opt: t<'a> => option<(key, 'a)> - let choose: t<'a> => (key, 'a) - let choose_opt: t<'a> => option<(key, 'a)> - let split: (key, t<'a>) => (t<'a>, option<'a>, t<'a>) - let find: (key, t<'a>) => 'a - let find_opt: (key, t<'a>) => option<'a> - let find_first: (~f: key => bool, t<'a>) => (key, 'a) - let find_first_opt: (~f: key => bool, t<'a>) => option<(key, 'a)> - let find_last: (~f: key => bool, t<'a>) => (key, 'a) - let find_last_opt: (~f: key => bool, t<'a>) => option<(key, 'a)> - let map: (~f: 'a => 'b, t<'a>) => t<'b> - let mapi: (~f: (key, 'a) => 'b, t<'a>) => t<'b> -} - -module Make = (Ord: OrderedType) => { - type key = Ord.t - - type rec t<'a> = - | Empty - | Node({l: t<'a>, v: key, d: 'a, r: t<'a>, h: int}) - - let height = param => - switch param { - | Empty => 0 - | Node({h}) => h - } - - let create = (l, x, d, r) => { - let hl = height(l) and hr = height(r) - Node({ - l, - v: x, - d, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - - let singleton = (x, d) => Node({l: Empty, v: x, d, r: Empty, h: 1}) - - let bal = (l, x, d, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - if hl > hr + 2 { - switch l { - | Empty => invalid_arg("Map.bal") - | Node({l: ll, v: lv, d: ld, r: lr}) => - if height(ll) >= height(lr) { - create(ll, lv, ld, create(lr, x, d, r)) - } else { - switch lr { - | Empty => invalid_arg("Map.bal") - | Node({l: lrl, v: lrv, d: lrd, r: lrr}) => - create(create(ll, lv, ld, lrl), lrv, lrd, create(lrr, x, d, r)) - } - } - } - } else if hr > hl + 2 { - switch r { - | Empty => invalid_arg("Map.bal") - | Node({l: rl, v: rv, d: rd, r: rr}) => - if height(rr) >= height(rl) { - create(create(l, x, d, rl), rv, rd, rr) - } else { - switch rl { - | Empty => invalid_arg("Map.bal") - | Node({l: rll, v: rlv, d: rld, r: rlr}) => - create(create(l, x, d, rll), rlv, rld, create(rlr, rv, rd, rr)) - } - } - } - } else { - Node({ - l, - v: x, - d, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - } - - let empty = Empty - - let is_empty = param => - switch param { - | Empty => true - | _ => false - } - - let rec add = (~key as x, ~data, param) => - switch param { - | Empty => Node({l: Empty, v: x, d: data, r: Empty, h: 1}) - | Node({l, v, d, r, h}) as m => - let c = Ord.compare(x, v) - if c == 0 { - if d === data { - m - } else { - Node({l, v: x, d: data, r, h}) - } - } else if c < 0 { - let ll = add(~key=x, ~data, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = add(~key=x, ~data, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec find = (x, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - d - } else { - find( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec find_first_aux = (v0, d0, f, param) => - switch param { - | Empty => (v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_first_aux(v, d, f, l) - } else { - find_first_aux(v0, d0, f, r) - } - } - - let rec find_first = (~f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - if f(v) { - find_first_aux(v, d, f, l) - } else { - find_first(~f, r) - } - } - - let rec find_first_opt_aux = (v0, d0, f, param) => - switch param { - | Empty => Some(v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_first_opt_aux(v, d, f, l) - } else { - find_first_opt_aux(v0, d0, f, r) - } - } - - let rec find_first_opt = (~f, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - if f(v) { - find_first_opt_aux(v, d, f, l) - } else { - find_first_opt(~f, r) - } - } - - let rec find_last_aux = (v0, d0, f, param) => - switch param { - | Empty => (v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_last_aux(v, d, f, r) - } else { - find_last_aux(v0, d0, f, l) - } - } - - let rec find_last = (~f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, d, r}) => - if f(v) { - find_last_aux(v, d, f, r) - } else { - find_last(~f, l) - } - } - - let rec find_last_opt_aux = (v0, d0, f, param) => - switch param { - | Empty => Some(v0, d0) - | Node({l, v, d, r}) => - if f(v) { - find_last_opt_aux(v, d, f, r) - } else { - find_last_opt_aux(v0, d0, f, l) - } - } - - let rec find_last_opt = (~f, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - if f(v) { - find_last_opt_aux(v, d, f, r) - } else { - find_last_opt(~f, l) - } - } - - let rec find_opt = (x, param) => - switch param { - | Empty => None - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - Some(d) - } else { - find_opt( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec mem = (x, param) => - switch param { - | Empty => false - | Node({l, v, r}) => - let c = Ord.compare(x, v) - c == 0 || - mem( - x, - if c < 0 { - l - } else { - r - }, - ) - } - - let rec min_binding = param => - switch param { - | Empty => raise(Not_found) - | Node({l: Empty, v, d}) => (v, d) - | Node({l}) => min_binding(l) - } - - let rec min_binding_opt = param => - switch param { - | Empty => None - | Node({l: Empty, v, d}) => Some(v, d) - | Node({l}) => min_binding_opt(l) - } - - let rec max_binding = param => - switch param { - | Empty => raise(Not_found) - | Node({v, d, r: Empty}) => (v, d) - | Node({r}) => max_binding(r) - } - - let rec max_binding_opt = param => - switch param { - | Empty => None - | Node({v, d, r: Empty}) => Some(v, d) - | Node({r}) => max_binding_opt(r) - } - - let rec remove_min_binding = param => - switch param { - | Empty => invalid_arg("Map.remove_min_elt") - | Node({l: Empty, r}) => r - | Node({l, v, d, r}) => bal(remove_min_binding(l), v, d, r) - } - - let merge = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => - let (x, d) = min_binding(t2) - bal(t1, x, d, remove_min_binding(t2)) - } - - let rec remove = (x, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r}) as m => - let c = Ord.compare(x, v) - if c == 0 { - merge(l, r) - } else if c < 0 { - let ll = remove(x, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = remove(x, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec update = (~key as x, ~f, param) => - switch param { - | Empty => - switch f(None) { - | None => Empty - | Some(data) => Node({l: Empty, v: x, d: data, r: Empty, h: 1}) - } - | Node({l, v, d, r, h}) as m => - let c = Ord.compare(x, v) - if c == 0 { - switch f(Some(d)) { - | None => merge(l, r) - | Some(data) => - if d === data { - m - } else { - Node({l, v: x, d: data, r, h}) - } - } - } else if c < 0 { - let ll = update(~key=x, ~f, l) - if l === ll { - m - } else { - bal(ll, v, d, r) - } - } else { - let rr = update(~key=x, ~f, r) - if r === rr { - m - } else { - bal(l, v, d, rr) - } - } - } - - let rec iter = (~f, param) => - switch param { - | Empty => () - | Node({l, v, d, r}) => - iter(~f, l) - f(~key=v, ~data=d) - iter(~f, r) - } - - let rec map = (~f, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r, h}) => - let l' = map(~f, l) - let d' = f(d) - let r' = map(~f, r) - Node({l: l', v, d: d', r: r', h}) - } - - let rec mapi = (~f, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r, h}) => - let l' = mapi(~f, l) - let d' = f(v, d) - let r' = mapi(~f, r) - Node({l: l', v, d: d', r: r', h}) - } - - let rec fold = (~f, m, ~init as accu) => - switch m { - | Empty => accu - | Node({l, v, d, r}) => fold(~f, r, ~init=f(~key=v, ~data=d, fold(~f, l, ~init=accu))) - } - - let rec for_all = (~f as p, param) => - switch param { - | Empty => true - | Node({l, v, d, r}) => p(v, d) && (for_all(~f=p, l) && for_all(~f=p, r)) - } - - let rec exists = (~f as p, param) => - switch param { - | Empty => false - | Node({l, v, d, r}) => p(v, d) || (exists(~f=p, l) || exists(~f=p, r)) - } - - /* Beware: those two functions assume that the added k is *strictly* - smaller (or bigger) than all the present keys in the tree; it - does not test for equality with the current min (or max) key. - - Indeed, they are only used during the "join" operation which - respects this precondition. - */ - - let rec add_min_binding = (k, x, param) => - switch param { - | Empty => singleton(k, x) - | Node({l, v, d, r}) => bal(add_min_binding(k, x, l), v, d, r) - } - - let rec add_max_binding = (k, x, param) => - switch param { - | Empty => singleton(k, x) - | Node({l, v, d, r}) => bal(l, v, d, add_max_binding(k, x, r)) - } - - /* Same as create and bal, but no assumptions are made on the - relative heights of l and r. */ - - let rec join = (l, v, d, r) => - switch (l, r) { - | (Empty, _) => add_min_binding(v, d, r) - | (_, Empty) => add_max_binding(v, d, l) - | (Node({l: ll, v: lv, d: ld, r: lr, h: lh}), Node({l: rl, v: rv, d: rd, r: rr, h: rh})) => - if lh > rh + 2 { - bal(ll, lv, ld, join(lr, v, d, r)) - } else if rh > lh + 2 { - bal(join(l, v, d, rl), rv, rd, rr) - } else { - create(l, v, d, r) - } - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - No assumption on the heights of l and r. */ - - let concat = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => - let (x, d) = min_binding(t2) - join(t1, x, d, remove_min_binding(t2)) - } - - let concat_or_join = (t1, v, d, t2) => - switch d { - | Some(d) => join(t1, v, d, t2) - | None => concat(t1, t2) - } - - let rec split = (x, param) => - switch param { - | Empty => (Empty, None, Empty) - | Node({l, v, d, r}) => - let c = Ord.compare(x, v) - if c == 0 { - (l, Some(d), r) - } else if c < 0 { - let (ll, pres, rl) = split(x, l) - (ll, pres, join(rl, v, d, r)) - } else { - let (lr, pres, rr) = split(x, r) - (join(l, v, d, lr), pres, rr) - } - } - - let rec merge = (~f, s1, s2) => - switch (s1, s2) { - | (Empty, Empty) => Empty - | (Node({l: l1, v: v1, d: d1, r: r1, h: h1}), _) if h1 >= height(s2) => - let (l2, d2, r2) = split(v1, s2) - concat_or_join(merge(~f, l1, l2), v1, f(v1, Some(d1), d2), merge(~f, r1, r2)) - | (_, Node({l: l2, v: v2, d: d2, r: r2})) => - let (l1, d1, r1) = split(v2, s1) - concat_or_join(merge(~f, l1, l2), v2, f(v2, d1, Some(d2)), merge(~f, r1, r2)) - | _ => assert(false) - } - - let rec union = (~f, s1, s2) => - switch (s1, s2) { - | (Empty, s) | (s, Empty) => s - | (Node({l: l1, v: v1, d: d1, r: r1, h: h1}), Node({l: l2, v: v2, d: d2, r: r2, h: h2})) => - if h1 >= h2 { - let (l2, d2, r2) = split(v1, s2) - let l = union(~f, l1, l2) and r = union(~f, r1, r2) - switch d2 { - | None => join(l, v1, d1, r) - | Some(d2) => concat_or_join(l, v1, f(v1, d1, d2), r) - } - } else { - let (l1, d1, r1) = split(v2, s1) - let l = union(~f, l1, l2) and r = union(~f, r1, r2) - switch d1 { - | None => join(l, v2, d2, r) - | Some(d1) => concat_or_join(l, v2, f(v2, d1, d2), r) - } - } - } - - let rec filter = (~f as p, param) => - switch param { - | Empty => Empty - | Node({l, v, d, r}) as m => - /* call [p] in the expected left-to-right order */ - let l' = filter(~f=p, l) - let pvd = p(v, d) - let r' = filter(~f=p, r) - if pvd { - if l === l' && r === r' { - m - } else { - join(l', v, d, r') - } - } else { - concat(l', r') - } - } - - let rec partition = (~f as p, param) => - switch param { - | Empty => (Empty, Empty) - | Node({l, v, d, r}) => - /* call [p] in the expected left-to-right order */ - let (lt, lf) = partition(~f=p, l) - let pvd = p(v, d) - let (rt, rf) = partition(~f=p, r) - if pvd { - (join(lt, v, d, rt), concat(lf, rf)) - } else { - (concat(lt, rt), join(lf, v, d, rf)) - } - } - - type rec enumeration<'a> = End | More(key, 'a, t<'a>, enumeration<'a>) - - let rec cons_enum = (m, e) => - switch m { - | Empty => e - | Node({l, v, d, r}) => cons_enum(l, More(v, d, r, e)) - } - - let compare = (~cmp, m1, m2) => { - let rec compare_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => 0 - | (End, _) => -1 - | (_, End) => 1 - | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) => - let c = Ord.compare(v1, v2) - if c != 0 { - c - } else { - let c = cmp(d1, d2) - if c != 0 { - c - } else { - compare_aux(cons_enum(r1, e1), cons_enum(r2, e2)) - } - } - } - compare_aux(cons_enum(m1, End), cons_enum(m2, End)) - } - - let equal = (~cmp, m1, m2) => { - let rec equal_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => true - | (End, _) => false - | (_, End) => false - | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) => - Ord.compare(v1, v2) == 0 && (cmp(d1, d2) && equal_aux(cons_enum(r1, e1), cons_enum(r2, e2))) - } - equal_aux(cons_enum(m1, End), cons_enum(m2, End)) - } - - let rec cardinal = param => - switch param { - | Empty => 0 - | Node({l, r}) => cardinal(l) + 1 + cardinal(r) - } - - let rec bindings_aux = (accu, param) => - switch param { - | Empty => accu - | Node({l, v, d, r}) => bindings_aux(list{(v, d), ...bindings_aux(accu, r)}, l) - } - - let bindings = s => bindings_aux(list{}, s) - - let choose = min_binding - - let choose_opt = min_binding_opt -} diff --git a/jscomp/stdlib-406/moreLabels.res b/jscomp/stdlib-406/moreLabels.res deleted file mode 100644 index 2fb9e46e70..0000000000 --- a/jscomp/stdlib-406/moreLabels.res +++ /dev/null @@ -1,22 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Jacques Garrigue, Kyoto University RIMS */ -/* */ -/* Copyright 2001 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Module [MoreLabels]: meta-module for compatibility labelled libraries */ - -module Hashtbl = HashtblLabels - -module Map = MapLabels - -module Set = SetLabels diff --git a/jscomp/stdlib-406/moreLabels.resi b/jscomp/stdlib-406/moreLabels.resi deleted file mode 100644 index 397641d669..0000000000 --- a/jscomp/stdlib-406/moreLabels.resi +++ /dev/null @@ -1,182 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Jacques Garrigue, Kyoto University RIMS */ -/* */ -/* Copyright 2001 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Extra labeled libraries. - - This meta-module provides labelized version of the {!Hashtbl}, - {!Map} and {!Set} modules. - - They only differ by their labels. They are provided to help - porting from previous versions of OCaml. - The contents of this module are subject to change. -*/ - -module Hashtbl: { - type t<'a, 'b> = Hashtbl.t<'a, 'b> - let create: (~random: bool=?, int) => t<'a, 'b> - let clear: t<'a, 'b> => unit - let reset: t<'a, 'b> => unit - let copy: t<'a, 'b> => t<'a, 'b> - let add: (t<'a, 'b>, ~key: 'a, ~data: 'b) => unit - let find: (t<'a, 'b>, 'a) => 'b - let find_opt: (t<'a, 'b>, 'a) => option<'b> - let find_all: (t<'a, 'b>, 'a) => list<'b> - let mem: (t<'a, 'b>, 'a) => bool - let remove: (t<'a, 'b>, 'a) => unit - let replace: (t<'a, 'b>, ~key: 'a, ~data: 'b) => unit - let iter: (~f: (~key: 'a, ~data: 'b) => unit, t<'a, 'b>) => unit - let filter_map_inplace: (~f: (~key: 'a, ~data: 'b) => option<'b>, t<'a, 'b>) => unit - let fold: (~f: (~key: 'a, ~data: 'b, 'c) => 'c, t<'a, 'b>, ~init: 'c) => 'c - let length: t<'a, 'b> => int - let randomize: unit => unit - let is_randomized: unit => bool - type statistics = Hashtbl.statistics - let stats: t<'a, 'b> => statistics - module type HashedType = Hashtbl.HashedType - module type SeededHashedType = Hashtbl.SeededHashedType - module type S = { - type rec key - and t<'a> - let create: int => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, ~key: key, ~data: 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, ~key: key, ~data: 'a) => unit - let mem: (t<'a>, key) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let filter_map_inplace: (~f: (~key: key, ~data: 'a) => option<'a>, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics - } - module type SeededS = { - type rec key - and t<'a> - let create: (~random: bool=?, int) => t<'a> - let clear: t<'a> => unit - let reset: t<'a> => unit - let copy: t<'a> => t<'a> - let add: (t<'a>, ~key: key, ~data: 'a) => unit - let remove: (t<'a>, key) => unit - let find: (t<'a>, key) => 'a - let find_opt: (t<'a>, key) => option<'a> - let find_all: (t<'a>, key) => list<'a> - let replace: (t<'a>, ~key: key, ~data: 'a) => unit - let mem: (t<'a>, key) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let filter_map_inplace: (~f: (~key: key, ~data: 'a) => option<'a>, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let length: t<'a> => int - let stats: t<'a> => statistics - } - module Make: (H: HashedType) => (S with type key = H.t) - module MakeSeeded: (H: SeededHashedType) => (SeededS with type key = H.t) - let hash: 'a => int - let seeded_hash: (int, 'a) => int - let hash_param: (int, int, 'a) => int - let seeded_hash_param: (int, int, int, 'a) => int -} - -module Map: { - module type OrderedType = Map.OrderedType - module type S = { - type rec key - and t<+'a> - let empty: t<'a> - let is_empty: t<'a> => bool - let mem: (key, t<'a>) => bool - let add: (~key: key, ~data: 'a, t<'a>) => t<'a> - let update: (~key: key, ~f: option<'a> => option<'a>, t<'a>) => t<'a> - let singleton: (key, 'a) => t<'a> - let remove: (key, t<'a>) => t<'a> - let merge: (~f: (key, option<'a>, option<'b>) => option<'c>, t<'a>, t<'b>) => t<'c> - let union: (~f: (key, 'a, 'a) => option<'a>, t<'a>, t<'a>) => t<'a> - let compare: (~cmp: ('a, 'a) => int, t<'a>, t<'a>) => int - let equal: (~cmp: ('a, 'a) => bool, t<'a>, t<'a>) => bool - let iter: (~f: (~key: key, ~data: 'a) => unit, t<'a>) => unit - let fold: (~f: (~key: key, ~data: 'a, 'b) => 'b, t<'a>, ~init: 'b) => 'b - let for_all: (~f: (key, 'a) => bool, t<'a>) => bool - let exists: (~f: (key, 'a) => bool, t<'a>) => bool - let filter: (~f: (key, 'a) => bool, t<'a>) => t<'a> - let partition: (~f: (key, 'a) => bool, t<'a>) => (t<'a>, t<'a>) - let cardinal: t<'a> => int - let bindings: t<'a> => list<(key, 'a)> - let min_binding: t<'a> => (key, 'a) - let min_binding_opt: t<'a> => option<(key, 'a)> - let max_binding: t<'a> => (key, 'a) - let max_binding_opt: t<'a> => option<(key, 'a)> - let choose: t<'a> => (key, 'a) - let choose_opt: t<'a> => option<(key, 'a)> - let split: (key, t<'a>) => (t<'a>, option<'a>, t<'a>) - let find: (key, t<'a>) => 'a - let find_opt: (key, t<'a>) => option<'a> - let find_first: (~f: key => bool, t<'a>) => (key, 'a) - let find_first_opt: (~f: key => bool, t<'a>) => option<(key, 'a)> - let find_last: (~f: key => bool, t<'a>) => (key, 'a) - let find_last_opt: (~f: key => bool, t<'a>) => option<(key, 'a)> - let map: (~f: 'a => 'b, t<'a>) => t<'b> - let mapi: (~f: (key, 'a) => 'b, t<'a>) => t<'b> - } - module Make: (Ord: OrderedType) => (S with type key = Ord.t) -} - -module Set: { - module type OrderedType = Set.OrderedType - module type S = { - type rec elt - and t - let empty: t - let is_empty: t => bool - let mem: (elt, t) => bool - let add: (elt, t) => t - let singleton: elt => t - let remove: (elt, t) => t - let union: (t, t) => t - let inter: (t, t) => t - let diff: (t, t) => t - let compare: (t, t) => int - let equal: (t, t) => bool - let subset: (t, t) => bool - let iter: (~f: elt => unit, t) => unit - let map: (~f: elt => elt, t) => t - let fold: (~f: (elt, 'a) => 'a, t, ~init: 'a) => 'a - let for_all: (~f: elt => bool, t) => bool - let exists: (~f: elt => bool, t) => bool - let filter: (~f: elt => bool, t) => t - let partition: (~f: elt => bool, t) => (t, t) - let cardinal: t => int - let elements: t => list - let min_elt: t => elt - let min_elt_opt: t => option - let max_elt: t => elt - let max_elt_opt: t => option - let choose: t => elt - let choose_opt: t => option - let split: (elt, t) => (t, bool, t) - let find: (elt, t) => elt - let find_opt: (elt, t) => option - let find_first: (~f: elt => bool, t) => elt - let find_first_opt: (~f: elt => bool, t) => option - let find_last: (~f: elt => bool, t) => elt - let find_last_opt: (~f: elt => bool, t) => option - let of_list: list => t - } - module Make: (Ord: OrderedType) => (S with type elt = Ord.t) -} diff --git a/jscomp/stdlib-406/parsing.res b/jscomp/stdlib-406/parsing.res deleted file mode 100644 index 6614e94357..0000000000 --- a/jscomp/stdlib-406/parsing.res +++ /dev/null @@ -1,232 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* The parsing engine */ - -open Lexing - -/* Internal interface to the parsing engine */ - -type parser_env = { - mutable s_stack: array /* States */, - mutable v_stack: array /* Semantic attributes */, - mutable symb_start_stack: array /* Start positions */, - mutable symb_end_stack: array /* End positions */, - mutable stacksize: int /* Size of the stacks */, - mutable stackbase: int /* Base sp for current parse */, - mutable curr_char: int /* Last token read */, - mutable lval: Obj.t /* Its semantic attribute */, - mutable symb_start: position /* Start pos. of the current symbol */, - mutable symb_end: position /* End pos. of the current symbol */, - mutable asp: int /* The stack pointer for attributes */, - mutable rule_len: int /* Number of rhs items in the rule */, - mutable rule_number: int /* Rule number to reduce by */, - mutable sp: int /* Saved sp for parse_engine */, - mutable state: int /* Saved state for parse_engine */, - mutable errflag: int, -} /* Saved error flag for parse_engine */ - -type parse_tables = { - actions: array Obj.t>, - transl_const: array, - transl_block: array, - lhs: string, - len: string, - defred: string, - dgoto: string, - sindex: string, - rindex: string, - gindex: string, - tablesize: int, - table: string, - check: string, - error_function: string => unit, - names_const: string, - names_block: string, -} - -exception YYexit(Obj.t) -exception Parse_error - -type parser_input = - | Start - | Token_read - | Stacks_grown_1 - | Stacks_grown_2 - | Semantic_action_computed - | Error_detected - -type parser_output = - | Read_token - | Raise_parse_error - | Grow_stacks_1 - | Grow_stacks_2 - | Compute_semantic_action - | Call_error_function - -/* to avoid warnings */ -let _ = list{ - Read_token, - Raise_parse_error, - Grow_stacks_1, - Grow_stacks_2, - Compute_semantic_action, - Call_error_function, -} - -external parse_engine: (parse_tables, parser_env, parser_input, Obj.t) => parser_output = - "?parse_engine" - -external set_trace: bool => bool = "?set_parser_trace" - -let env = { - s_stack: Array.make(100, 0), - v_stack: Array.make(100, Obj.repr()), - symb_start_stack: Array.make(100, dummy_pos), - symb_end_stack: Array.make(100, dummy_pos), - stacksize: 100, - stackbase: 0, - curr_char: 0, - lval: Obj.repr(), - symb_start: dummy_pos, - symb_end: dummy_pos, - asp: 0, - rule_len: 0, - rule_number: 0, - sp: 0, - state: 0, - errflag: 0, -} - -let grow_stacks = () => { - let oldsize = env.stacksize - let newsize = oldsize * 2 - let new_s = Array.make(newsize, 0) - and new_v = Array.make(newsize, Obj.repr()) - and new_start = Array.make(newsize, dummy_pos) - and new_end = Array.make(newsize, dummy_pos) - Array.blit(env.s_stack, 0, new_s, 0, oldsize) - env.s_stack = new_s - Array.blit(env.v_stack, 0, new_v, 0, oldsize) - env.v_stack = new_v - Array.blit(env.symb_start_stack, 0, new_start, 0, oldsize) - env.symb_start_stack = new_start - Array.blit(env.symb_end_stack, 0, new_end, 0, oldsize) - env.symb_end_stack = new_end - env.stacksize = newsize -} - -let clear_parser = () => { - Array.fill(env.v_stack, 0, env.stacksize, Obj.repr()) - env.lval = Obj.repr() -} - -let current_lookahead_fun = ref((_: Obj.t) => false) - -let yyparse = (tables, start, lexer, lexbuf) => { - let rec loop = (cmd, arg) => - switch parse_engine(tables, env, cmd, arg) { - | Read_token => - let t = Obj.repr(lexer(lexbuf)) - env.symb_start = lexbuf.lex_start_p - env.symb_end = lexbuf.lex_curr_p - loop(Token_read, t) - | Raise_parse_error => raise(Parse_error) - | Compute_semantic_action => - let (action, value) = try ( - Semantic_action_computed, - tables.actions[env.rule_number](env), - ) catch { - | Parse_error => (Error_detected, Obj.repr()) - } - loop(action, value) - | Grow_stacks_1 => - grow_stacks() - loop(Stacks_grown_1, Obj.repr()) - | Grow_stacks_2 => - grow_stacks() - loop(Stacks_grown_2, Obj.repr()) - | Call_error_function => - tables.error_function("syntax error") - loop(Error_detected, Obj.repr()) - } - let init_asp = env.asp - and init_sp = env.sp - and init_stackbase = env.stackbase - and init_state = env.state - and init_curr_char = env.curr_char - and init_lval = env.lval - and init_errflag = env.errflag - env.stackbase = env.sp + 1 - env.curr_char = start - env.symb_end = lexbuf.lex_curr_p - try loop(Start, Obj.repr()) catch { - | exn => - let curr_char = env.curr_char - env.asp = init_asp - env.sp = init_sp - env.stackbase = init_stackbase - env.state = init_state - env.curr_char = init_curr_char - env.lval = init_lval - env.errflag = init_errflag - switch exn { - | YYexit(v) => Obj.magic(v) - | _ => - current_lookahead_fun := - ( - tok => - if Js.typeof(tok) != "number" { - tables.transl_block[Obj.tag(tok)] == curr_char - } else { - tables.transl_const[Obj.magic(tok)] == curr_char - } - ) - raise(exn) - } - } -} - -let peek_val = (env, n) => Obj.magic(env.v_stack[env.asp - n]) - -let symbol_start_pos = () => { - let rec loop = i => - if i <= 0 { - env.symb_end_stack[env.asp] - } else { - let st = env.symb_start_stack[env.asp - i + 1] - let en = env.symb_end_stack[env.asp - i + 1] - if st != en { - st - } else { - loop(i - 1) - } - } - - loop(env.rule_len) -} - -let symbol_end_pos = () => env.symb_end_stack[env.asp] -let rhs_start_pos = n => env.symb_start_stack[env.asp - (env.rule_len - n)] -let rhs_end_pos = n => env.symb_end_stack[env.asp - (env.rule_len - n)] - -let symbol_start = () => symbol_start_pos().pos_cnum -let symbol_end = () => symbol_end_pos().pos_cnum -let rhs_start = n => rhs_start_pos(n).pos_cnum -let rhs_end = n => rhs_end_pos(n).pos_cnum - -let is_current_lookahead = tok => current_lookahead_fun.contents(Obj.repr(tok)) - -let parse_error = (_: string) => () diff --git a/jscomp/stdlib-406/parsing.resi b/jscomp/stdlib-406/parsing.resi deleted file mode 100644 index f93fd0fcd1..0000000000 --- a/jscomp/stdlib-406/parsing.resi +++ /dev/null @@ -1,101 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* The run-time library for parsers generated by [ocamlyacc]. */ - -/** [symbol_start] and {!Parsing.symbol_end} are to be called in the - action part of a grammar rule only. They return the offset of the - string that matches the left-hand side of the rule: [symbol_start()] - returns the offset of the first character; [symbol_end()] returns the - offset after the last character. The first character in a file is at - offset 0. */ -let symbol_start: unit => int - -/** See {!Parsing.symbol_start}. */ -let symbol_end: unit => int - -/** Same as {!Parsing.symbol_start} and {!Parsing.symbol_end}, but - return the offset of the string matching the [n]th item on the - right-hand side of the rule, where [n] is the integer parameter - to [rhs_start] and [rhs_end]. [n] is 1 for the leftmost item. */ -let rhs_start: int => int - -/** See {!Parsing.rhs_start}. */ -let rhs_end: int => int - -/** Same as [symbol_start], but return a [position] instead of an offset. */ -let symbol_start_pos: unit => Lexing.position - -/** Same as [symbol_end], but return a [position] instead of an offset. */ -let symbol_end_pos: unit => Lexing.position - -/** Same as [rhs_start], but return a [position] instead of an offset. */ -let rhs_start_pos: int => Lexing.position - -/** Same as [rhs_end], but return a [position] instead of an offset. */ -let rhs_end_pos: int => Lexing.position - -/** Empty the parser stack. Call it just after a parsing function - has returned, to remove all pointers from the parser stack - to structures that were built by semantic actions during parsing. - This is optional, but lowers the memory requirements of the - programs. */ -let clear_parser: unit => unit - -/** Raised when a parser encounters a syntax error. - Can also be raised from the action part of a grammar rule, - to initiate error recovery. */ -exception Parse_error - -/** Control debugging support for [ocamlyacc]-generated parsers. - After [Parsing.set_trace true], the pushdown automaton that - executes the parsers prints a trace of its actions (reading a token, - shifting a state, reducing by a rule) on standard output. - [Parsing.set_trace false] turns this debugging trace off. - The boolean returned is the previous state of the trace flag. - @since 3.11.0 -*/ -let set_trace: bool => bool - -/* The following definitions are used by the generated parsers only. - They are not intended to be used directly by user programs. */ - -type parser_env - -type parse_tables = { - actions: array Obj.t>, - transl_const: array, - transl_block: array, - lhs: string, - len: string, - defred: string, - dgoto: string, - sindex: string, - rindex: string, - gindex: string, - tablesize: int, - table: string, - check: string, - error_function: string => unit, - names_const: string, - names_block: string, -} - -exception YYexit(Obj.t) - -let yyparse: (parse_tables, int, Lexing.lexbuf => 'a, Lexing.lexbuf) => 'b -let peek_val: (parser_env, int) => 'a -let is_current_lookahead: 'a => bool -let parse_error: string => unit diff --git a/jscomp/stdlib-406/queue.res b/jscomp/stdlib-406/queue.res deleted file mode 100644 index 89d9297229..0000000000 --- a/jscomp/stdlib-406/queue.res +++ /dev/null @@ -1,142 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Francois Pottier, projet Cristal, INRIA Rocquencourt */ -/* Jeremie Dimino, Jane Street Europe */ -/* */ -/* Copyright 2002 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -exception Empty - -type rec cell<'a> = - | Nil - | Cons({content: 'a, mutable next: cell<'a>}) - -type t<'a> = { - mutable length: int, - mutable first: cell<'a>, - mutable last: cell<'a>, -} - -let create = () => { - length: 0, - first: Nil, - last: Nil, -} - -let clear = q => { - q.length = 0 - q.first = Nil - q.last = Nil -} - -let add = (x, q) => { - let cell = Cons({ - content: x, - next: Nil, - }) - switch q.last { - | Nil => - q.length = 1 - q.first = cell - q.last = cell - | Cons(last) => - q.length = q.length + 1 - last.next = cell - q.last = cell - } -} - -let push = add - -let peek = q => - switch q.first { - | Nil => raise(Empty) - | Cons({content}) => content - } - -let top = peek - -let take = q => - switch q.first { - | Nil => raise(Empty) - | Cons({content, next: Nil}) => - clear(q) - content - | Cons({content, next}) => - q.length = q.length - 1 - q.first = next - content - } - -let pop = take - -let copy = { - let rec copy = (q_res, prev, cell) => - switch cell { - | Nil => - q_res.last = prev - q_res - | Cons({content, next}) => - let res = Cons({content, next: Nil}) - switch prev { - | Nil => q_res.first = res - | Cons(p) => p.next = res - } - copy(q_res, res, next) - } - - q => copy({length: q.length, first: Nil, last: Nil}, Nil, q.first) -} - -let is_empty = q => q.length == 0 - -let length = q => q.length - -let iter = { - let rec iter = (f, cell) => - switch cell { - | Nil => () - | Cons({content, next}) => - f(content) - iter(f, next) - } - - (f, q) => iter(f, q.first) -} - -let fold = { - let rec fold = (f, accu, cell) => - switch cell { - | Nil => accu - | Cons({content, next}) => - let accu = f(accu, content) - fold(f, accu, next) - } - - (f, accu, q) => fold(f, accu, q.first) -} - -let transfer = (q1, q2) => - if q1.length > 0 { - switch q2.last { - | Nil => - q2.length = q1.length - q2.first = q1.first - q2.last = q1.last - clear(q1) - | Cons(last) => - q2.length = q2.length + q1.length - last.next = q1.first - q2.last = q1.last - clear(q1) - } - } diff --git a/jscomp/stdlib-406/queue.resi b/jscomp/stdlib-406/queue.resi deleted file mode 100644 index c5ed5ae64b..0000000000 --- a/jscomp/stdlib-406/queue.resi +++ /dev/null @@ -1,79 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** First-in first-out queues. - - This module implements queues (FIFOs), with in-place modification. - - {b Warning} This module is not thread-safe: each {!Queue.t} value - must be protected from concurrent access (e.g. with a [Mutex.t]). - Failure to do so can lead to a crash. -*/ - -/** The type of queues containing elements of type ['a]. */ -type t<'a> - -/** Raised when {!Queue.take} or {!Queue.peek} is applied to an empty queue. */ exception Empty - -/** Return a new queue, initially empty. */ -let create: unit => t<'a> - -/** [add x q] adds the element [x] at the end of the queue [q]. */ -let add: ('a, t<'a>) => unit - -/** [push] is a synonym for [add]. */ -let push: ('a, t<'a>) => unit - -/** [take q] removes and returns the first element in queue [q], - or raises {!Empty} if the queue is empty. */ -let take: t<'a> => 'a - -/** [pop] is a synonym for [take]. */ -let pop: t<'a> => 'a - -/** [peek q] returns the first element in queue [q], without removing - it from the queue, or raises {!Empty} if the queue is empty. */ -let peek: t<'a> => 'a - -/** [top] is a synonym for [peek]. */ -let top: t<'a> => 'a - -/** Discard all elements from a queue. */ -let clear: t<'a> => unit - -/** Return a copy of the given queue. */ -let copy: t<'a> => t<'a> - -/** Return [true] if the given queue is empty, [false] otherwise. */ -let is_empty: t<'a> => bool - -/** Return the number of elements in a queue. */ -let length: t<'a> => int - -/** [iter f q] applies [f] in turn to all elements of [q], - from the least recently entered to the most recently entered. - The queue itself is unchanged. */ -let iter: ('a => unit, t<'a>) => unit - -/** [fold f accu q] is equivalent to [List.fold_left f accu l], - where [l] is the list of [q]'s elements. The queue remains - unchanged. */ -let fold: (('b, 'a) => 'b, 'b, t<'a>) => 'b - -/** [transfer q1 q2] adds all of [q1]'s elements at the end of - the queue [q2], then clears [q1]. It is equivalent to the - sequence [iter (fun x -> add x q2) q1; clear q1], but runs - in constant time. */ -let transfer: (t<'a>, t<'a>) => unit diff --git a/jscomp/stdlib-406/random.res b/jscomp/stdlib-406/random.res deleted file mode 100644 index 11b4e42f4d..0000000000 --- a/jscomp/stdlib-406/random.res +++ /dev/null @@ -1,336 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Damien Doligez, projet Para, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Pseudo-random number generator - This is a lagged-Fibonacci F(55, 24, +) with a modified addition - function to enhance the mixing of bits. - If we use normal addition, the low-order bit fails tests 1 and 7 - of the Diehard test suite, and bits 1 and 2 also fail test 7. - If we use multiplication as suggested by Marsaglia, it doesn't fare - much better. - By mixing the bits of one of the numbers before addition (XOR the - 5 high-order bits into the low-order bits), we get a generator that - passes all the Diehard tests. -*/ - -let random_seed: unit => array = _ => { - let seed: int = %raw("Math.floor(Math.random()*0x7fffffff)") - [seed] -} - -module State = { - type t = {st: array, mutable idx: int} - - let new_state = () => {st: Array.make(55, 0), idx: 0} - let assign = (st1, st2) => { - Array.blit(st2.st, 0, st1.st, 0, 55) - st1.idx = st2.idx - } - - let full_init = (s, seed) => { - let combine = (accu, x) => Digest.string(accu ++ string_of_int(x)) - let extract = d => - Char.code(String.get(d, 0)) + - lsl(Char.code(String.get(d, 1)), 8) + - lsl(Char.code(String.get(d, 2)), 16) + - lsl(Char.code(String.get(d, 3)), 24) - - let seed = if Array.length(seed) == 0 { - [0] - } else { - seed - } - let l = Array.length(seed) - for i in 0 to 54 { - s.st[i] = i - } - let accu = ref("x") - for i in 0 to 54 + max(55, l) { - let j = mod(i, 55) - let k = mod(i, l) - accu := combine(accu.contents, seed[k]) - s.st[j] = land(lxor(s.st[j], extract(accu.contents)), 0x3FFFFFFF) /* PR#5575 */ - } - s.idx = 0 - } - - let make = seed => { - let result = new_state() - full_init(result, seed) - result - } - - let make_self_init = () => make(random_seed()) - - let copy = s => { - let result = new_state() - assign(result, s) - result - } - - /* Returns 30 random bits as an integer 0 <= x < 1073741824 */ - let bits = s => { - s.idx = mod(s.idx + 1, 55) - let curval = s.st[s.idx] - let newval = s.st[mod(s.idx + 24, 55)] + lxor(curval, land(lsr(curval, 25), 0x1F)) - let newval30 = land(newval, 0x3FFFFFFF) /* PR#5575 */ - s.st[s.idx] = newval30 - newval30 - } - - let rec intaux = (s, n) => { - let r = bits(s) - let v = mod(r, n) - if r - v > 0x3FFFFFFF - n + 1 { - intaux(s, n) - } else { - v - } - } - - let int = (s, bound) => - if bound > 0x3FFFFFFF || bound <= 0 { - invalid_arg("Random.int") - } else { - intaux(s, bound) - } - - let rec int32aux = (s, n) => { - let b1 = Int32.of_int(bits(s)) - let b2 = Int32.shift_left(Int32.of_int(land(bits(s), 1)), 30) - let r = Int32.logor(b1, b2) - let v = Int32.rem(r, n) - if Int32.sub(r, v) > Int32.add(Int32.sub(Int32.max_int, n), 1l) { - int32aux(s, n) - } else { - v - } - } - - let int32 = (s, bound) => - if bound <= 0l { - invalid_arg("Random.int32") - } else { - int32aux(s, bound) - } - - let rec int64aux = (s, n) => { - let b1 = Int64.of_int(bits(s)) - let b2 = Int64.shift_left(Int64.of_int(bits(s)), 30) - let b3 = Int64.shift_left(Int64.of_int(land(bits(s), 7)), 60) - let r = Int64.logor(b1, Int64.logor(b2, b3)) - let v = Int64.rem(r, n) - if Int64.sub(r, v) > Int64.add(Int64.sub(Int64.max_int, n), 1L) { - int64aux(s, n) - } else { - v - } - } - - let int64 = (s, bound) => - if bound <= 0L { - invalid_arg("Random.int64") - } else { - int64aux(s, bound) - } - - /* Returns a float 0 <= x <= 1 with at most 60 bits of precision. */ - let rawfloat = s => { - let scale = 1073741824.0 /* 2^30 */ - and r1 = Pervasives.float(bits(s)) - and r2 = Pervasives.float(bits(s)) - (r1 /. scale +. r2) /. scale - } - - let float = (s, bound) => rawfloat(s) *. bound - - let bool = s => land(bits(s), 1) == 0 -} - -/* This is the state you get with [init 27182818] and then applying - the "land 0x3FFFFFFF" filter to them. See #5575, #5793, #5977. */ -let default = { - State.st: [ - 0x3ae2522b, - 0x1d8d4634, - 0x15b4fad0, - 0x18b14ace, - 0x12f8a3c4, - 0x3b086c47, - 0x16d467d6, - 0x101d91c7, - 0x321df177, - 0x0176c193, - 0x1ff72bf1, - 0x1e889109, - 0x0b464b18, - 0x2b86b97c, - 0x0891da48, - 0x03137463, - 0x085ac5a1, - 0x15d61f2f, - 0x3bced359, - 0x29c1c132, - 0x3a86766e, - 0x366d8c86, - 0x1f5b6222, - 0x3ce1b59f, - 0x2ebf78e1, - 0x27cd1b86, - 0x258f3dc3, - 0x389a8194, - 0x02e4c44c, - 0x18c43f7d, - 0x0f6e534f, - 0x1e7df359, - 0x055d0b7e, - 0x10e84e7e, - 0x126198e4, - 0x0e7722cb, - 0x1cbede28, - 0x3391b964, - 0x3d40e92a, - 0x0c59933d, - 0x0b8cd0b7, - 0x24efff1c, - 0x2803fdaa, - 0x08ebc72e, - 0x0f522e32, - 0x05398edc, - 0x2144a04c, - 0x0aef3cbd, - 0x01ad4719, - 0x35b93cd6, - 0x2a559d4f, - 0x1e6fd768, - 0x26e27f36, - 0x186f18c3, - 0x2fbf967a, - ], - State.idx: 0, -} - -let bits = () => State.bits(default) -let int = bound => State.int(default, bound) -let int32 = bound => State.int32(default, bound) - -let int64 = bound => State.int64(default, bound) -let float = scale => State.float(default, scale) -let bool = () => State.bool(default) - -let full_init = seed => State.full_init(default, seed) -let init = seed => State.full_init(default, [seed]) -let self_init = () => full_init(random_seed()) - -/* Manipulating the current state. */ - -let get_state = () => State.copy(default) -let set_state = s => State.assign(default, s) - -/* ******************* - -(* Test functions. Not included in the library. - The [chisquare] function should be called with n > 10r. - It returns a triple (low, actual, high). - If low <= actual <= high, the [g] function passed the test, - otherwise it failed. - - Some results: - -init 27182818; chisquare int 100000 1000 -init 27182818; chisquare int 100000 100 -init 27182818; chisquare int 100000 5000 -init 27182818; chisquare int 1000000 1000 -init 27182818; chisquare int 100000 1024 -init 299792643; chisquare int 100000 1024 -init 14142136; chisquare int 100000 1024 -init 27182818; init_diff 1024; chisquare diff 100000 1024 -init 27182818; init_diff 100; chisquare diff 100000 100 -init 27182818; init_diff2 1024; chisquare diff2 100000 1024 -init 27182818; init_diff2 100; chisquare diff2 100000 100 -init 14142136; init_diff2 100; chisquare diff2 100000 100 -init 299792643; init_diff2 100; chisquare diff2 100000 100 -- : float * float * float = (936.754446796632465, 997.5, 1063.24555320336754) -# - : float * float * float = (80., 89.7400000000052387, 120.) -# - : float * float * float = (4858.57864376269, 5045.5, 5141.42135623731) -# - : float * float * float = -(936.754446796632465, 944.805999999982305, 1063.24555320336754) -# - : float * float * float = (960., 1019.19744000000355, 1088.) -# - : float * float * float = (960., 1059.31776000000536, 1088.) -# - : float * float * float = (960., 1039.98463999999512, 1088.) -# - : float * float * float = (960., 1054.38207999999577, 1088.) -# - : float * float * float = (80., 90.096000000005, 120.) -# - : float * float * float = (960., 1076.78720000000612, 1088.) -# - : float * float * float = (80., 85.1760000000067521, 120.) -# - : float * float * float = (80., 85.2160000000003492, 120.) -# - : float * float * float = (80., 80.6220000000030268, 120.) - -*) - -(* Return the sum of the squares of v[i0,i1[ *) -let rec sumsq v i0 i1 = - if i0 >= i1 then 0.0 - else if i1 = i0 + 1 then Pervasives.float v.(i0) *. Pervasives.float v.(i0) - else sumsq v i0 ((i0+i1)/2) +. sumsq v ((i0+i1)/2) i1 - - -let chisquare g n r = - if n <= 10 * r then invalid_arg "chisquare"; - let f = Array.make r 0 in - for i = 1 to n do - let t = g r in - f.(t) <- f.(t) + 1 - done; - let t = sumsq f 0 r - and r = Pervasives.float r - and n = Pervasives.float n in - let sr = 2.0 *. sqrt r in - (r -. sr, (r *. t /. n) -. n, r +. sr) - - -(* This is to test for linear dependencies between successive random numbers. -*) -let st = ref 0 -let init_diff r = st := int r -let diff r = - let x1 = !st - and x2 = int r - in - st := x2; - if x1 >= x2 then - x1 - x2 - else - r + x1 - x2 - - -let st1 = ref 0 -and st2 = ref 0 - - -(* This is to test for quadratic dependencies between successive random - numbers. -*) -let init_diff2 r = st1 := int r; st2 := int r -let diff2 r = - let x1 = !st1 - and x2 = !st2 - and x3 = int r - in - st1 := x2; - st2 := x3; - (x3 - x2 - x2 + x1 + 2*r) mod r - - -********************/ diff --git a/jscomp/stdlib-406/random.resi b/jscomp/stdlib-406/random.resi deleted file mode 100644 index 05624c98eb..0000000000 --- a/jscomp/stdlib-406/random.resi +++ /dev/null @@ -1,100 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Damien Doligez, projet Para, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Pseudo-random number generators (PRNG). */ - -/* {1 Basic functions} */ - -/** Initialize the generator, using the argument as a seed. - The same seed will always yield the same sequence of numbers. */ -let init: int => unit - -/** Same as {!Random.init} but takes more data as seed. */ -let full_init: array => unit - -/** Initialize the generator with a random seed chosen - in a system-dependent way. If [/dev/urandom] is available on - the host machine, it is used to provide a highly random initial - seed. Otherwise, a less random seed is computed from system - parameters (current time, process IDs). */ -let self_init: unit => unit - -/** Return 30 random bits in a nonnegative integer. - @before 3.12.0 used a different algorithm (affects all the following - functions) -*/ -let bits: unit => int - -/** [Random.int bound] returns a random integer between 0 (inclusive) - and [bound] (exclusive). [bound] must be greater than 0 and less - than 2{^30}. */ -let int: int => int - -/** [Random.int32 bound] returns a random integer between 0 (inclusive) - and [bound] (exclusive). [bound] must be greater than 0. */ -let int32: Int32.t => Int32.t - -/** [Random.int64 bound] returns a random integer between 0 (inclusive) - and [bound] (exclusive). [bound] must be greater than 0. */ -let int64: Int64.t => Int64.t - -/** [Random.float bound] returns a random floating-point number - between 0 and [bound] (inclusive). If [bound] is - negative, the result is negative or zero. If [bound] is 0, - the result is 0. */ -let float: float => float - -/** [Random.bool ()] returns [true] or [false] with probability 0.5 each. */ -let bool: unit => bool - -/* {1 Advanced functions} */ - -module State: { - /*** The functions from module {!State} manipulate the current state - of the random generator explicitly. - This allows using one or several deterministic PRNGs, - even in a multi-threaded program, without interference from - other parts of the program. - */ - - /** The type of PRNG states. */ - type t - - /** Create a new state and initialize it with the given seed. */ - let make: array => t - - /** Create a new state and initialize it with a system-dependent - low-entropy seed. */ - let make_self_init: unit => t - - /** Return a copy of the given state. */ - let copy: t => t - - let bits: t => int - let int: (t, int) => int - let int32: (t, Int32.t) => Int32.t - let int64: (t, Int64.t) => Int64.t - let float: (t, float) => float - /** These functions are the same as the basic functions, except that they - use (and update) the given PRNG state instead of the default one. - */ - let bool: t => bool -} - -/** Return the current state of the generator used by the basic functions. */ -let get_state: unit => State.t - -/** Set the state of the generator used by the basic functions. */ -let set_state: State.t => unit diff --git a/jscomp/stdlib-406/release.ninja b/jscomp/stdlib-406/release.ninja index 992f90f652..1e4ab16ba1 100644 --- a/jscomp/stdlib-406/release.ninja +++ b/jscomp/stdlib-406/release.ninja @@ -12,81 +12,71 @@ o stdlib-406/pervasives.cmj : cc_cmi stdlib-406/pervasives.res | stdlib-406/perv bsc_flags = $bsc_flags -nopervasives o stdlib-406/pervasives.cmi : cc stdlib-406/pervasives.resi | $bsc others bsc_flags = $bsc_flags -nopervasives -o stdlib-406/arg.cmj : cc_cmi stdlib-406/arg.res | stdlib-406/arg.cmi stdlib-406/array.cmj stdlib-406/buffer.cmj stdlib-406/list.cmj stdlib-406/string.cmj stdlib-406/sys.cmj $bsc others -o stdlib-406/arg.cmi : cc stdlib-406/arg.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/array.cmj : cc_cmi stdlib-406/array.res | stdlib-406/array.cmi $bsc others -o stdlib-406/array.cmi : cc stdlib-406/array.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/arrayLabels.cmj : cc_cmi stdlib-406/arrayLabels.res | stdlib-406/arrayLabels.cmi $bsc others -o stdlib-406/arrayLabels.cmi : cc stdlib-406/arrayLabels.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/buffer.cmj : cc_cmi stdlib-406/buffer.res | stdlib-406/buffer.cmi stdlib-406/bytes.cmj stdlib-406/char.cmj stdlib-406/string.cmj stdlib-406/uchar.cmj $bsc others -o stdlib-406/buffer.cmi : cc stdlib-406/buffer.resi | stdlib-406/pervasives.cmj stdlib-406/uchar.cmi $bsc others -o stdlib-406/bytes.cmj : cc_cmi stdlib-406/bytes.res | stdlib-406/bytes.cmi stdlib-406/char.cmj $bsc others -o stdlib-406/bytes.cmi : cc stdlib-406/bytes.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/bytesLabels.cmj : cc_cmi stdlib-406/bytesLabels.res | stdlib-406/bytesLabels.cmi stdlib-406/char.cmj $bsc others -o stdlib-406/bytesLabels.cmi : cc stdlib-406/bytesLabels.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/callback.cmj : cc_cmi stdlib-406/callback.res | stdlib-406/callback.cmi $bsc others -o stdlib-406/callback.cmi : cc stdlib-406/callback.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/ArrayBuffer.cmi stdlib-406/ArrayBuffer.cmj : cc stdlib-406/ArrayBuffer.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/AsyncIterator.cmj : cc_cmi stdlib-406/AsyncIterator.res | stdlib-406/AsyncIterator.cmi $bsc others +o stdlib-406/AsyncIterator.cmi : cc stdlib-406/AsyncIterator.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/BigInt.cmi stdlib-406/BigInt.cmj : cc stdlib-406/BigInt.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Console.cmj : cc_cmi stdlib-406/Console.res | stdlib-406/Console.cmi $bsc others +o stdlib-406/Console.cmi : cc stdlib-406/Console.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/DataView.cmi stdlib-406/DataView.cmj : cc stdlib-406/DataView.res | stdlib-406/ArrayBuffer.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Date.cmj : cc_cmi stdlib-406/Date.res | stdlib-406/Date.cmi stdlib-406/Float.cmj $bsc others +o stdlib-406/Date.cmi : cc stdlib-406/Date.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Dict.cmj : cc_cmi stdlib-406/Dict.res | stdlib-406/Dict.cmi stdlib-406/Iterator.cmj stdlib-406/array.cmj $bsc others +o stdlib-406/Dict.cmi : cc stdlib-406/Dict.resi | stdlib-406/Iterator.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Error.cmj : cc_cmi stdlib-406/Error.res | stdlib-406/Error.cmi $bsc others +o stdlib-406/Error.cmi : cc stdlib-406/Error.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Float.cmj : cc_cmi stdlib-406/Float.res | stdlib-406/Float.cmi stdlib-406/Ordering.cmj $bsc others +o stdlib-406/Float.cmi : cc stdlib-406/Float.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Global.cmj : cc_cmi stdlib-406/Global.res | stdlib-406/Global.cmi $bsc others +o stdlib-406/Global.cmi : cc stdlib-406/Global.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Int.cmj : cc_cmi stdlib-406/Int.res | stdlib-406/Error.cmj stdlib-406/Float.cmj stdlib-406/Int.cmi stdlib-406/Ordering.cmj stdlib-406/array.cmj $bsc others +o stdlib-406/Int.cmi : cc stdlib-406/Int.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Intl.cmi stdlib-406/Intl.cmj : cc stdlib-406/Intl.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Iterator.cmj : cc_cmi stdlib-406/Iterator.res | stdlib-406/Iterator.cmi $bsc others +o stdlib-406/Iterator.cmi : cc stdlib-406/Iterator.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/JSON.cmj : cc_cmi stdlib-406/JSON.res | stdlib-406/Dict.cmj stdlib-406/JSON.cmi stdlib-406/Object.cmj stdlib-406/String.cmj stdlib-406/Type.cmj stdlib-406/array.cmj stdlib-406/obj.cmj $bsc others +o stdlib-406/JSON.cmi : cc stdlib-406/JSON.resi | stdlib-406/Dict.cmi stdlib-406/Object.cmj stdlib-406/String.cmi stdlib-406/array.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/List.cmj : cc_cmi stdlib-406/List.res | stdlib-406/List.cmi stdlib-406/Ordering.cmj stdlib-406/array.cmj $bsc others +o stdlib-406/List.cmi : cc stdlib-406/List.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Map.cmj : cc_cmi stdlib-406/Map.res | stdlib-406/Iterator.cmj stdlib-406/Map.cmi $bsc others +o stdlib-406/Map.cmi : cc stdlib-406/Map.resi | stdlib-406/Iterator.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Math.cmj : cc_cmi stdlib-406/Math.res | stdlib-406/Float.cmj stdlib-406/Int.cmj stdlib-406/Math.cmi $bsc others +o stdlib-406/Math.cmi : cc stdlib-406/Math.resi | stdlib-406/Int.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Object.cmi stdlib-406/Object.cmj : cc stdlib-406/Object.res | stdlib-406/Symbol.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Option.cmj : cc_cmi stdlib-406/Option.res | stdlib-406/Error.cmj stdlib-406/Option.cmi stdlib-406/Ordering.cmj $bsc others +o stdlib-406/Option.cmi : cc stdlib-406/Option.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Ordering.cmi stdlib-406/Ordering.cmj : cc stdlib-406/Ordering.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Promise.cmj : cc_cmi stdlib-406/Promise.res | stdlib-406/Promise.cmi $bsc others +o stdlib-406/Promise.cmi : cc stdlib-406/Promise.resi | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/RegExp.cmj : cc_cmi stdlib-406/RegExp.res | stdlib-406/RegExp.cmi stdlib-406/Result.cmj $bsc others +o stdlib-406/RegExp.cmi : cc stdlib-406/RegExp.resi | stdlib-406/Result.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Result.cmj : cc_cmi stdlib-406/Result.res | stdlib-406/Ordering.cmj stdlib-406/Result.cmi $bsc others +o stdlib-406/Result.cmi : cc stdlib-406/Result.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Set.cmj : cc_cmi stdlib-406/Set.res | stdlib-406/Iterator.cmj stdlib-406/Set.cmi $bsc others +o stdlib-406/Set.cmi : cc stdlib-406/Set.resi | stdlib-406/Iterator.cmi stdlib-406/pervasives.cmj $bsc others +o stdlib-406/String.cmj : cc_cmi stdlib-406/String.res | stdlib-406/Ordering.cmj stdlib-406/RegExp.cmj stdlib-406/String.cmi stdlib-406/Symbol.cmj $bsc others +o stdlib-406/String.cmi : cc stdlib-406/String.resi | stdlib-406/Ordering.cmj stdlib-406/RegExp.cmi stdlib-406/Symbol.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Symbol.cmi stdlib-406/Symbol.cmj : cc stdlib-406/Symbol.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/Type.cmj : cc_cmi stdlib-406/Type.res | stdlib-406/BigInt.cmj stdlib-406/Object.cmj stdlib-406/String.cmj stdlib-406/Symbol.cmj stdlib-406/Type.cmi $bsc others +o stdlib-406/Type.cmi : cc stdlib-406/Type.resi | stdlib-406/BigInt.cmj stdlib-406/Object.cmj stdlib-406/String.cmi stdlib-406/Symbol.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/WeakMap.cmi stdlib-406/WeakMap.cmj : cc stdlib-406/WeakMap.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/WeakSet.cmi stdlib-406/WeakSet.cmj : cc stdlib-406/WeakSet.res | stdlib-406/pervasives.cmj $bsc others +o stdlib-406/array.cmj : cc_cmi stdlib-406/array.res | stdlib-406/Iterator.cmj stdlib-406/Ordering.cmj stdlib-406/Symbol.cmj stdlib-406/array.cmi $bsc others +o stdlib-406/array.cmi : cc stdlib-406/array.resi | stdlib-406/Iterator.cmi stdlib-406/Ordering.cmj stdlib-406/Symbol.cmj stdlib-406/pervasives.cmj $bsc others o stdlib-406/camlinternalLazy.cmj : cc_cmi stdlib-406/camlinternalLazy.res | stdlib-406/camlinternalLazy.cmi $bsc others o stdlib-406/camlinternalLazy.cmi : cc stdlib-406/camlinternalLazy.resi | stdlib-406/pervasives.cmj $bsc others o stdlib-406/camlinternalMod.cmj : cc_cmi stdlib-406/camlinternalMod.res | stdlib-406/camlinternalMod.cmi stdlib-406/obj.cmj $bsc others o stdlib-406/camlinternalMod.cmi : cc stdlib-406/camlinternalMod.resi | stdlib-406/obj.cmi stdlib-406/pervasives.cmj $bsc others o stdlib-406/char.cmj : cc_cmi stdlib-406/char.res | stdlib-406/char.cmi $bsc others o stdlib-406/char.cmi : cc stdlib-406/char.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/complex.cmj : cc_cmi stdlib-406/complex.res | stdlib-406/complex.cmi $bsc others -o stdlib-406/complex.cmi : cc stdlib-406/complex.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/digest.cmj : cc_cmi stdlib-406/digest.res | stdlib-406/bytes.cmj stdlib-406/char.cmj stdlib-406/digest.cmi stdlib-406/string.cmj $bsc others -o stdlib-406/digest.cmi : cc stdlib-406/digest.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/filename.cmj : cc_cmi stdlib-406/filename.res | stdlib-406/buffer.cmj stdlib-406/filename.cmi stdlib-406/string.cmj stdlib-406/sys.cmj $bsc others -o stdlib-406/filename.cmi : cc stdlib-406/filename.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/genlex.cmj : cc_cmi stdlib-406/genlex.res | stdlib-406/bytes.cmj stdlib-406/char.cmj stdlib-406/genlex.cmi stdlib-406/hashtbl.cmj stdlib-406/list.cmj stdlib-406/stream.cmj stdlib-406/string.cmj $bsc others -o stdlib-406/genlex.cmi : cc stdlib-406/genlex.resi | stdlib-406/pervasives.cmj stdlib-406/stream.cmi $bsc others -o stdlib-406/hashtbl.cmj : cc_cmi stdlib-406/hashtbl.res | stdlib-406/array.cmj stdlib-406/hashtbl.cmi stdlib-406/lazy.cmj stdlib-406/random.cmj $bsc others -o stdlib-406/hashtbl.cmi : cc stdlib-406/hashtbl.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/hashtblLabels.cmi stdlib-406/hashtblLabels.cmj : cc stdlib-406/hashtblLabels.res | stdlib-406/hashtbl.cmj stdlib-406/pervasives.cmj $bsc others -o stdlib-406/int32.cmj : cc_cmi stdlib-406/int32.res | stdlib-406/int32.cmi $bsc others -o stdlib-406/int32.cmi : cc stdlib-406/int32.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/int64.cmj : cc_cmi stdlib-406/int64.res | stdlib-406/int64.cmi $bsc others -o stdlib-406/int64.cmi : cc stdlib-406/int64.resi | stdlib-406/pervasives.cmj $bsc others o stdlib-406/lazy.cmj : cc_cmi stdlib-406/lazy.res | stdlib-406/camlinternalLazy.cmj stdlib-406/lazy.cmi $bsc others o stdlib-406/lazy.cmi : cc stdlib-406/lazy.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/lexing.cmj : cc_cmi stdlib-406/lexing.res | stdlib-406/array.cmj stdlib-406/bytes.cmj stdlib-406/lexing.cmi stdlib-406/string.cmj $bsc others -o stdlib-406/lexing.cmi : cc stdlib-406/lexing.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/list.cmj : cc_cmi stdlib-406/list.res | stdlib-406/list.cmi $bsc others -o stdlib-406/list.cmi : cc stdlib-406/list.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/listLabels.cmj : cc_cmi stdlib-406/listLabels.res | stdlib-406/listLabels.cmi $bsc others -o stdlib-406/listLabels.cmi : cc stdlib-406/listLabels.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/map.cmj : cc_cmi stdlib-406/map.res | stdlib-406/map.cmi $bsc others -o stdlib-406/map.cmi : cc stdlib-406/map.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/mapLabels.cmi stdlib-406/mapLabels.cmj : cc stdlib-406/mapLabels.res | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/moreLabels.cmj : cc_cmi stdlib-406/moreLabels.res | stdlib-406/hashtblLabels.cmj stdlib-406/mapLabels.cmj stdlib-406/moreLabels.cmi stdlib-406/setLabels.cmj $bsc others -o stdlib-406/moreLabels.cmi : cc stdlib-406/moreLabels.resi | stdlib-406/hashtbl.cmi stdlib-406/map.cmi stdlib-406/pervasives.cmj stdlib-406/set.cmi $bsc others +o stdlib-406/nullable.cmj : cc_cmi stdlib-406/nullable.res | stdlib-406/Option.cmj stdlib-406/nullable.cmi stdlib-406/obj.cmj $bsc others +o stdlib-406/nullable.cmi : cc stdlib-406/nullable.resi | stdlib-406/Ordering.cmj stdlib-406/pervasives.cmj $bsc others +o stdlib-406/nulll.cmj : cc_cmi stdlib-406/nulll.res | stdlib-406/Option.cmj stdlib-406/nullable.cmj stdlib-406/nulll.cmi $bsc others +o stdlib-406/nulll.cmi : cc stdlib-406/nulll.resi | stdlib-406/Ordering.cmj stdlib-406/nullable.cmi stdlib-406/pervasives.cmj $bsc others o stdlib-406/obj.cmj : cc_cmi stdlib-406/obj.res | stdlib-406/obj.cmi $bsc others o stdlib-406/obj.cmi : cc stdlib-406/obj.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/parsing.cmj : cc_cmi stdlib-406/parsing.res | stdlib-406/array.cmj stdlib-406/lexing.cmj stdlib-406/obj.cmj stdlib-406/parsing.cmi $bsc others -o stdlib-406/parsing.cmi : cc stdlib-406/parsing.resi | stdlib-406/lexing.cmi stdlib-406/obj.cmi stdlib-406/pervasives.cmj $bsc others o stdlib-406/pervasivesU.cmj : cc_cmi stdlib-406/pervasivesU.res | stdlib-406/pervasivesU.cmi $bsc others o stdlib-406/pervasivesU.cmi : cc stdlib-406/pervasivesU.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/queue.cmj : cc_cmi stdlib-406/queue.res | stdlib-406/queue.cmi $bsc others -o stdlib-406/queue.cmi : cc stdlib-406/queue.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/random.cmj : cc_cmi stdlib-406/random.res | stdlib-406/array.cmj stdlib-406/char.cmj stdlib-406/digest.cmj stdlib-406/int32.cmj stdlib-406/int64.cmj stdlib-406/random.cmi stdlib-406/string.cmj $bsc others -o stdlib-406/random.cmi : cc stdlib-406/random.resi | stdlib-406/int32.cmi stdlib-406/int64.cmi stdlib-406/pervasives.cmj $bsc others -o stdlib-406/set.cmj : cc_cmi stdlib-406/set.res | stdlib-406/list.cmj stdlib-406/set.cmi $bsc others -o stdlib-406/set.cmi : cc stdlib-406/set.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/setLabels.cmi stdlib-406/setLabels.cmj : cc stdlib-406/setLabels.res | stdlib-406/list.cmj stdlib-406/pervasives.cmj $bsc others -o stdlib-406/sort.cmj : cc_cmi stdlib-406/sort.res | stdlib-406/array.cmj stdlib-406/sort.cmi $bsc others -o stdlib-406/sort.cmi : cc stdlib-406/sort.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/stack.cmj : cc_cmi stdlib-406/stack.res | stdlib-406/list.cmj stdlib-406/stack.cmi $bsc others -o stdlib-406/stack.cmi : cc stdlib-406/stack.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/stdLabels.cmj : cc_cmi stdlib-406/stdLabels.res | stdlib-406/arrayLabels.cmj stdlib-406/bytesLabels.cmj stdlib-406/listLabels.cmj stdlib-406/stdLabels.cmi stdlib-406/stringLabels.cmj $bsc others -o stdlib-406/stdLabels.cmi : cc stdlib-406/stdLabels.resi | stdlib-406/arrayLabels.cmi stdlib-406/bytesLabels.cmi stdlib-406/listLabels.cmi stdlib-406/pervasives.cmj stdlib-406/stringLabels.cmi $bsc others -o stdlib-406/stream.cmj : cc_cmi stdlib-406/stream.res | stdlib-406/bytes.cmj stdlib-406/lazy.cmj stdlib-406/list.cmj stdlib-406/stream.cmi stdlib-406/string.cmj $bsc others -o stdlib-406/stream.cmi : cc stdlib-406/stream.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/string.cmj : cc_cmi stdlib-406/string.res | stdlib-406/array.cmj stdlib-406/bytes.cmj stdlib-406/string.cmi $bsc others -o stdlib-406/string.cmi : cc stdlib-406/string.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/stringLabels.cmj : cc_cmi stdlib-406/stringLabels.res | stdlib-406/array.cmj stdlib-406/bytes.cmj stdlib-406/stringLabels.cmi $bsc others -o stdlib-406/stringLabels.cmi : cc stdlib-406/stringLabels.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/sys.cmj : cc_cmi stdlib-406/sys.res | stdlib-406/sys.cmi $bsc others -o stdlib-406/sys.cmi : cc stdlib-406/sys.resi | stdlib-406/pervasives.cmj $bsc others -o stdlib-406/uchar.cmj : cc_cmi stdlib-406/uchar.res | stdlib-406/char.cmj stdlib-406/uchar.cmi $bsc others -o stdlib-406/uchar.cmi : cc stdlib-406/uchar.resi | stdlib-406/pervasives.cmj $bsc others -o $stdlib : phony stdlib-406/pervasives.cmi stdlib-406/pervasives.cmj stdlib-406/arg.cmi stdlib-406/arg.cmj stdlib-406/array.cmi stdlib-406/array.cmj stdlib-406/arrayLabels.cmi stdlib-406/arrayLabels.cmj stdlib-406/buffer.cmi stdlib-406/buffer.cmj stdlib-406/bytes.cmi stdlib-406/bytes.cmj stdlib-406/bytesLabels.cmi stdlib-406/bytesLabels.cmj stdlib-406/callback.cmi stdlib-406/callback.cmj stdlib-406/camlinternalLazy.cmi stdlib-406/camlinternalLazy.cmj stdlib-406/camlinternalMod.cmi stdlib-406/camlinternalMod.cmj stdlib-406/char.cmi stdlib-406/char.cmj stdlib-406/complex.cmi stdlib-406/complex.cmj stdlib-406/digest.cmi stdlib-406/digest.cmj stdlib-406/filename.cmi stdlib-406/filename.cmj stdlib-406/genlex.cmi stdlib-406/genlex.cmj stdlib-406/hashtbl.cmi stdlib-406/hashtbl.cmj stdlib-406/hashtblLabels.cmi stdlib-406/hashtblLabels.cmj stdlib-406/int32.cmi stdlib-406/int32.cmj stdlib-406/int64.cmi stdlib-406/int64.cmj stdlib-406/lazy.cmi stdlib-406/lazy.cmj stdlib-406/lexing.cmi stdlib-406/lexing.cmj stdlib-406/list.cmi stdlib-406/list.cmj stdlib-406/listLabels.cmi stdlib-406/listLabels.cmj stdlib-406/map.cmi stdlib-406/map.cmj stdlib-406/mapLabels.cmi stdlib-406/mapLabels.cmj stdlib-406/moreLabels.cmi stdlib-406/moreLabels.cmj stdlib-406/obj.cmi stdlib-406/obj.cmj stdlib-406/parsing.cmi stdlib-406/parsing.cmj stdlib-406/pervasivesU.cmi stdlib-406/pervasivesU.cmj stdlib-406/queue.cmi stdlib-406/queue.cmj stdlib-406/random.cmi stdlib-406/random.cmj stdlib-406/set.cmi stdlib-406/set.cmj stdlib-406/setLabels.cmi stdlib-406/setLabels.cmj stdlib-406/sort.cmi stdlib-406/sort.cmj stdlib-406/stack.cmi stdlib-406/stack.cmj stdlib-406/stdLabels.cmi stdlib-406/stdLabels.cmj stdlib-406/stream.cmi stdlib-406/stream.cmj stdlib-406/string.cmi stdlib-406/string.cmj stdlib-406/stringLabels.cmi stdlib-406/stringLabels.cmj stdlib-406/sys.cmi stdlib-406/sys.cmj stdlib-406/uchar.cmi stdlib-406/uchar.cmj +o $stdlib : phony stdlib-406/pervasives.cmi stdlib-406/pervasives.cmj stdlib-406/ArrayBuffer.cmi stdlib-406/ArrayBuffer.cmj stdlib-406/AsyncIterator.cmi stdlib-406/AsyncIterator.cmj stdlib-406/BigInt.cmi stdlib-406/BigInt.cmj stdlib-406/Console.cmi stdlib-406/Console.cmj stdlib-406/DataView.cmi stdlib-406/DataView.cmj stdlib-406/Date.cmi stdlib-406/Date.cmj stdlib-406/Dict.cmi stdlib-406/Dict.cmj stdlib-406/Error.cmi stdlib-406/Error.cmj stdlib-406/Float.cmi stdlib-406/Float.cmj stdlib-406/Global.cmi stdlib-406/Global.cmj stdlib-406/Int.cmi stdlib-406/Int.cmj stdlib-406/Intl.cmi stdlib-406/Intl.cmj stdlib-406/Iterator.cmi stdlib-406/Iterator.cmj stdlib-406/JSON.cmi stdlib-406/JSON.cmj stdlib-406/List.cmi stdlib-406/List.cmj stdlib-406/Map.cmi stdlib-406/Map.cmj stdlib-406/Math.cmi stdlib-406/Math.cmj stdlib-406/Object.cmi stdlib-406/Object.cmj stdlib-406/Option.cmi stdlib-406/Option.cmj stdlib-406/Ordering.cmi stdlib-406/Ordering.cmj stdlib-406/Promise.cmi stdlib-406/Promise.cmj stdlib-406/RegExp.cmi stdlib-406/RegExp.cmj stdlib-406/Result.cmi stdlib-406/Result.cmj stdlib-406/Set.cmi stdlib-406/Set.cmj stdlib-406/String.cmi stdlib-406/String.cmj stdlib-406/Symbol.cmi stdlib-406/Symbol.cmj stdlib-406/Type.cmi stdlib-406/Type.cmj stdlib-406/WeakMap.cmi stdlib-406/WeakMap.cmj stdlib-406/WeakSet.cmi stdlib-406/WeakSet.cmj stdlib-406/array.cmi stdlib-406/array.cmj stdlib-406/camlinternalLazy.cmi stdlib-406/camlinternalLazy.cmj stdlib-406/camlinternalMod.cmi stdlib-406/camlinternalMod.cmj stdlib-406/char.cmi stdlib-406/char.cmj stdlib-406/lazy.cmi stdlib-406/lazy.cmj stdlib-406/nullable.cmi stdlib-406/nullable.cmj stdlib-406/nulll.cmi stdlib-406/nulll.cmj stdlib-406/obj.cmi stdlib-406/obj.cmj stdlib-406/pervasivesU.cmi stdlib-406/pervasivesU.cmj diff --git a/jscomp/stdlib-406/set.res b/jscomp/stdlib-406/set.res index 49d30edd63..c7782a972b 100644 --- a/jscomp/stdlib-406/set.res +++ b/jscomp/stdlib-406/set.res @@ -1,711 +1,17 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ +type t<'a> = Js.Set.t<'a> -/* Sets over ordered types */ +@new external make: unit => t<'a> = "Set" +@new external fromArray: array<'a> => t<'a> = "Set" +@new external fromIterator: Iterator.t<'a> => t<'a> = "Set" -module type OrderedType = { - type t - let compare: (t, t) => int -} +@get external size: t<'a> => int = "size" -module type S = { - type elt - type t - let empty: t - let is_empty: t => bool - let mem: (elt, t) => bool - let add: (elt, t) => t - let singleton: elt => t - let remove: (elt, t) => t - let union: (t, t) => t - let inter: (t, t) => t - let diff: (t, t) => t - let compare: (t, t) => int - let equal: (t, t) => bool - let subset: (t, t) => bool - let iter: (elt => unit, t) => unit - let map: (elt => elt, t) => t - let fold: ((elt, 'a) => 'a, t, 'a) => 'a - let for_all: (elt => bool, t) => bool - let exists: (elt => bool, t) => bool - let filter: (elt => bool, t) => t - let partition: (elt => bool, t) => (t, t) - let cardinal: t => int - let elements: t => list - let min_elt: t => elt - let min_elt_opt: t => option - let max_elt: t => elt - let max_elt_opt: t => option - let choose: t => elt - let choose_opt: t => option - let split: (elt, t) => (t, bool, t) - let find: (elt, t) => elt - let find_opt: (elt, t) => option - let find_first: (elt => bool, t) => elt - let find_first_opt: (elt => bool, t) => option - let find_last: (elt => bool, t) => elt - let find_last_opt: (elt => bool, t) => option - let of_list: list => t -} +@send external clear: t<'a> => unit = "clear" -module Make = (Ord: OrderedType) => { - type elt = Ord.t - type rec t = Empty | Node({l: t, v: elt, r: t, h: int}) +@send external add: (t<'a>, 'a) => unit = "add" +@send external delete: (t<'a>, 'a) => bool = "delete" +@send external has: (t<'a>, 'a) => bool = "has" - /* Sets are represented by balanced binary trees (the heights of the - children differ by at most 2 */ +@send external forEach: (t<'a>, 'a => unit) => unit = "forEach" - let height = param => - switch param { - | Empty => 0 - | Node({h}) => h - } - - /* Creates a new node with left son l, value v and right son r. - We must have all elements of l < v < all elements of r. - l and r must be balanced and | height l - height r | <= 2. - Inline expansion of height for better speed. */ - - let create = (l, v, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - Node({ - l, - v, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - - /* Same as create, but performs one step of rebalancing if necessary. - Assumes l and r balanced and | height l - height r | <= 3. - Inline expansion of create for better speed in the most frequent case - where no rebalancing is required. */ - - let bal = (l, v, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - if hl > hr + 2 { - switch l { - | Empty => invalid_arg("Set.bal") - | Node({l: ll, v: lv, r: lr}) => - if height(ll) >= height(lr) { - create(ll, lv, create(lr, v, r)) - } else { - switch lr { - | Empty => invalid_arg("Set.bal") - | Node({l: lrl, v: lrv, r: lrr}) => create(create(ll, lv, lrl), lrv, create(lrr, v, r)) - } - } - } - } else if hr > hl + 2 { - switch r { - | Empty => invalid_arg("Set.bal") - | Node({l: rl, v: rv, r: rr}) => - if height(rr) >= height(rl) { - create(create(l, v, rl), rv, rr) - } else { - switch rl { - | Empty => invalid_arg("Set.bal") - | Node({l: rll, v: rlv, r: rlr}) => create(create(l, v, rll), rlv, create(rlr, rv, rr)) - } - } - } - } else { - Node({ - l, - v, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - } - - /* Insertion of one element */ - - let rec add = (x, param) => - switch param { - | Empty => Node({l: Empty, v: x, r: Empty, h: 1}) - | Node({l, v, r}) as t => - let c = Ord.compare(x, v) - if c == 0 { - t - } else if c < 0 { - let ll = add(x, l) - if l === ll { - t - } else { - bal(ll, v, r) - } - } else { - let rr = add(x, r) - if r === rr { - t - } else { - bal(l, v, rr) - } - } - } - - let singleton = x => Node({l: Empty, v: x, r: Empty, h: 1}) - - /* Beware: those two functions assume that the added v is *strictly* - smaller (or bigger) than all the present elements in the tree; it - does not test for equality with the current min (or max) element. - Indeed, they are only used during the "join" operation which - respects this precondition. - */ - - let rec add_min_element = (x, param) => - switch param { - | Empty => singleton(x) - | Node({l, v, r}) => bal(add_min_element(x, l), v, r) - } - - let rec add_max_element = (x, param) => - switch param { - | Empty => singleton(x) - | Node({l, v, r}) => bal(l, v, add_max_element(x, r)) - } - - /* Same as create and bal, but no assumptions are made on the - relative heights of l and r. */ - - let rec join = (l, v, r) => - switch (l, r) { - | (Empty, _) => add_min_element(v, r) - | (_, Empty) => add_max_element(v, l) - | (Node({l: ll, v: lv, r: lr, h: lh}), Node({l: rl, v: rv, r: rr, h: rh})) => - if lh > rh + 2 { - bal(ll, lv, join(lr, v, r)) - } else if rh > lh + 2 { - bal(join(l, v, rl), rv, rr) - } else { - create(l, v, r) - } - } - - /* Smallest and greatest element of a set */ - - let rec min_elt = param => - switch param { - | Empty => raise(Not_found) - | Node({l: Empty, v}) => v - | Node({l}) => min_elt(l) - } - - let rec min_elt_opt = param => - switch param { - | Empty => None - | Node({l: Empty, v}) => Some(v) - | Node({l}) => min_elt_opt(l) - } - - let rec max_elt = param => - switch param { - | Empty => raise(Not_found) - | Node({v, r: Empty}) => v - | Node({r}) => max_elt(r) - } - - let rec max_elt_opt = param => - switch param { - | Empty => None - | Node({v, r: Empty}) => Some(v) - | Node({r}) => max_elt_opt(r) - } - - /* Remove the smallest element of the given set */ - - let rec remove_min_elt = param => - switch param { - | Empty => invalid_arg("Set.remove_min_elt") - | Node({l: Empty, r}) => r - | Node({l, v, r}) => bal(remove_min_elt(l), v, r) - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - Assume | height l - height r | <= 2. */ - - let merge = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => bal(t1, min_elt(t2), remove_min_elt(t2)) - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - No assumption on the heights of l and r. */ - - let concat = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => join(t1, min_elt(t2), remove_min_elt(t2)) - } - - /* Splitting. split x s returns a triple (l, present, r) where - - l is the set of elements of s that are < x - - r is the set of elements of s that are > x - - present is false if s contains no element equal to x, - or true if s contains an element equal to x. */ - - let rec split = (x, param) => - switch param { - | Empty => (Empty, false, Empty) - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - (l, true, r) - } else if c < 0 { - let (ll, pres, rl) = split(x, l) - (ll, pres, join(rl, v, r)) - } else { - let (lr, pres, rr) = split(x, r) - (join(l, v, lr), pres, rr) - } - } - - /* Implementation of the set operations */ - - let empty = Empty - - let is_empty = param => - switch param { - | Empty => true - | _ => false - } - - let rec mem = (x, param) => - switch param { - | Empty => false - | Node({l, v, r}) => - let c = Ord.compare(x, v) - c == 0 || - mem( - x, - if c < 0 { - l - } else { - r - }, - ) - } - - let rec remove = (x, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - let c = Ord.compare(x, v) - if c == 0 { - merge(l, r) - } else if c < 0 { - let ll = remove(x, l) - if l === ll { - t - } else { - bal(ll, v, r) - } - } else { - let rr = remove(x, r) - if r === rr { - t - } else { - bal(l, v, rr) - } - } - } - - let rec union = (s1, s2) => - switch (s1, s2) { - | (Empty, t2) => t2 - | (t1, Empty) => t1 - | (Node({l: l1, v: v1, r: r1, h: h1}), Node({l: l2, v: v2, r: r2, h: h2})) => - if h1 >= h2 { - if h2 == 1 { - add(v2, s1) - } else { - let (l2, _, r2) = split(v1, s2) - join(union(l1, l2), v1, union(r1, r2)) - } - } else if h1 == 1 { - add(v1, s2) - } else { - let (l1, _, r1) = split(v2, s1) - join(union(l1, l2), v2, union(r1, r2)) - } - } - - let rec inter = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => Empty - | (_, Empty) => Empty - | (Node({l: l1, v: v1, r: r1}), t2) => - switch split(v1, t2) { - | (l2, false, r2) => concat(inter(l1, l2), inter(r1, r2)) - | (l2, true, r2) => join(inter(l1, l2), v1, inter(r1, r2)) - } - } - - let rec diff = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => Empty - | (t1, Empty) => t1 - | (Node({l: l1, v: v1, r: r1}), t2) => - switch split(v1, t2) { - | (l2, false, r2) => join(diff(l1, l2), v1, diff(r1, r2)) - | (l2, true, r2) => concat(diff(l1, l2), diff(r1, r2)) - } - } - - type rec enumeration = End | More(elt, t, enumeration) - - let rec cons_enum = (s, e) => - switch s { - | Empty => e - | Node({l, v, r}) => cons_enum(l, More(v, r, e)) - } - - let rec compare_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => 0 - | (End, _) => -1 - | (_, End) => 1 - | (More(v1, r1, e1), More(v2, r2, e2)) => - let c = Ord.compare(v1, v2) - if c != 0 { - c - } else { - compare_aux(cons_enum(r1, e1), cons_enum(r2, e2)) - } - } - - let compare = (s1, s2) => compare_aux(cons_enum(s1, End), cons_enum(s2, End)) - - let equal = (s1, s2) => compare(s1, s2) == 0 - - let rec subset = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => true - | (_, Empty) => false - | (Node({l: l1, v: v1, r: r1}), Node({l: l2, v: v2, r: r2}) as t2) => - let c = Ord.compare(v1, v2) - if c == 0 { - subset(l1, l2) && subset(r1, r2) - } else if c < 0 { - subset(Node({l: l1, v: v1, r: Empty, h: 0}), l2) && subset(r1, t2) - } else { - subset(Node({l: Empty, v: v1, r: r1, h: 0}), r2) && subset(l1, t2) - } - } - - let rec iter = (f, param) => - switch param { - | Empty => () - | Node({l, v, r}) => - iter(f, l) - f(v) - iter(f, r) - } - - let rec fold = (f, s, accu) => - switch s { - | Empty => accu - | Node({l, v, r}) => fold(f, r, f(v, fold(f, l, accu))) - } - - let rec for_all = (p, param) => - switch param { - | Empty => true - | Node({l, v, r}) => p(v) && (for_all(p, l) && for_all(p, r)) - } - - let rec exists = (p, param) => - switch param { - | Empty => false - | Node({l, v, r}) => p(v) || (exists(p, l) || exists(p, r)) - } - - let rec filter = (p, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - /* call [p] in the expected left-to-right order */ - let l' = filter(p, l) - let pv = p(v) - let r' = filter(p, r) - if pv { - if l === l' && r === r' { - t - } else { - join(l', v, r') - } - } else { - concat(l', r') - } - } - - let rec partition = (p, param) => - switch param { - | Empty => (Empty, Empty) - | Node({l, v, r}) => - /* call [p] in the expected left-to-right order */ - let (lt, lf) = partition(p, l) - let pv = p(v) - let (rt, rf) = partition(p, r) - if pv { - (join(lt, v, rt), concat(lf, rf)) - } else { - (concat(lt, rt), join(lf, v, rf)) - } - } - - let rec cardinal = param => - switch param { - | Empty => 0 - | Node({l, r}) => cardinal(l) + 1 + cardinal(r) - } - - let rec elements_aux = (accu, param) => - switch param { - | Empty => accu - | Node({l, v, r}) => elements_aux(list{v, ...elements_aux(accu, r)}, l) - } - - let elements = s => elements_aux(list{}, s) - - let choose = min_elt - - let choose_opt = min_elt_opt - - let rec find = (x, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - v - } else { - find( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec find_first_aux = (v0, f, param) => - switch param { - | Empty => v0 - | Node({l, v, r}) => - if f(v) { - find_first_aux(v, f, l) - } else { - find_first_aux(v0, f, r) - } - } - - let rec find_first = (f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - if f(v) { - find_first_aux(v, f, l) - } else { - find_first(f, r) - } - } - - let rec find_first_opt_aux = (v0, f, param) => - switch param { - | Empty => Some(v0) - | Node({l, v, r}) => - if f(v) { - find_first_opt_aux(v, f, l) - } else { - find_first_opt_aux(v0, f, r) - } - } - - let rec find_first_opt = (f, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - if f(v) { - find_first_opt_aux(v, f, l) - } else { - find_first_opt(f, r) - } - } - - let rec find_last_aux = (v0, f, param) => - switch param { - | Empty => v0 - | Node({l, v, r}) => - if f(v) { - find_last_aux(v, f, r) - } else { - find_last_aux(v0, f, l) - } - } - - let rec find_last = (f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - if f(v) { - find_last_aux(v, f, r) - } else { - find_last(f, l) - } - } - - let rec find_last_opt_aux = (v0, f, param) => - switch param { - | Empty => Some(v0) - | Node({l, v, r}) => - if f(v) { - find_last_opt_aux(v, f, r) - } else { - find_last_opt_aux(v0, f, l) - } - } - - let rec find_last_opt = (f, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - if f(v) { - find_last_opt_aux(v, f, r) - } else { - find_last_opt(f, l) - } - } - - let rec find_opt = (x, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - Some(v) - } else { - find_opt( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let try_join = (l, v, r) => - /* [join l v r] can only be called when (elements of l < v < - elements of r); use [try_join l v r] when this property may - not hold, but you hope it does hold in the common case */ - if ( - (l == Empty || Ord.compare(max_elt(l), v) < 0) && - (r == Empty || Ord.compare(v, min_elt(r)) < 0) - ) { - join(l, v, r) - } else { - union(l, add(v, r)) - } - - let rec map = (f, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - /* enforce left-to-right evaluation order */ - let l' = map(f, l) - let v' = f(v) - let r' = map(f, r) - if l === l' && (v === v' && r === r') { - t - } else { - try_join(l', v', r') - } - } - - let of_sorted_list = l => { - let rec sub = (n, l) => - switch (n, l) { - | (0, l) => (Empty, l) - | (1, list{x0, ...l}) => (Node({l: Empty, v: x0, r: Empty, h: 1}), l) - | (2, list{x0, x1, ...l}) => ( - Node({l: Node({l: Empty, v: x0, r: Empty, h: 1}), v: x1, r: Empty, h: 2}), - l, - ) - | (3, list{x0, x1, x2, ...l}) => ( - Node({ - l: Node({l: Empty, v: x0, r: Empty, h: 1}), - v: x1, - r: Node({l: Empty, v: x2, r: Empty, h: 1}), - h: 2, - }), - l, - ) - | (n, l) => - let nl = n / 2 - let (left, l) = sub(nl, l) - switch l { - | list{} => assert(false) - | list{mid, ...l} => - let (right, l) = sub(n - nl - 1, l) - (create(left, mid, right), l) - } - } - - fst(sub(List.length(l), l)) - } - - let of_list = l => - switch l { - | list{} => empty - | list{x0} => singleton(x0) - | list{x0, x1} => add(x1, singleton(x0)) - | list{x0, x1, x2} => add(x2, add(x1, singleton(x0))) - | list{x0, x1, x2, x3} => add(x3, add(x2, add(x1, singleton(x0)))) - | list{x0, x1, x2, x3, x4} => add(x4, add(x3, add(x2, add(x1, singleton(x0))))) - | _ => of_sorted_list(List.sort_uniq(Ord.compare, l)) - } -} +@send external values: t<'a> => Iterator.t<'a> = "values" diff --git a/jscomp/stdlib-406/set.resi b/jscomp/stdlib-406/set.resi index 7d68f7b7c6..ea99881efa 100644 --- a/jscomp/stdlib-406/set.resi +++ b/jscomp/stdlib-406/set.resi @@ -1,264 +1,185 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Sets over ordered types. - - This module implements the set data structure, given a total ordering - function over the set elements. All operations over sets - are purely applicative (no side-effects). - The implementation uses balanced binary trees, and is therefore - reasonably efficient: insertion and membership take time - logarithmic in the size of the set, for instance. - - The {!Make} functor constructs implementations for any type, given a - [compare] function. - For instance: - {[ - module IntPairs = - struct - type t = int * int - let compare (x0,y0) (x1,y1) = - match Pervasives.compare x0 x1 with - 0 -> Pervasives.compare y0 y1 - | c -> c - end - - module PairsSet = Set.Make(IntPairs) - - let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) - ]} - - This creates a new module [PairsSet], with a new type [PairsSet.t] - of sets of [int * int]. +/*** +Bindings to the mutable JavaScript `Set`. + +See [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) on MDN. +*/ + +/** +Type representing an instance of `Set`. +*/ +type t<'a> = Js.Set.t<'a> + +/** +Creates a new, mutable JavaScript `Set`. A `Set` is a collection of unique values. + +See [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) on MDN. + + + +## Examples +```rescript +// You can annotate the type of your set if you want to +let mySet: Set.t = Set.make() + +// Or you can let ReScript infer what's in your Set +let set = Set.make() +set->Set.add("Fine name") // Inferred as Set.t +``` + +## Alternatives +A JavaScript `Set` is mutable. If you're looking for an immutable alternative, check out `Belt.Set`. */ +@new +external make: unit => t<'a> = "Set" -/** Input signature of the functor {!Set.Make}. */ -module type OrderedType = { - /** The type of the set elements. */ - type t - - /** A total ordering function over the set elements. - This is a two-argument function [f] such that - [f e1 e2] is zero if the elements [e1] and [e2] are equal, - [f e1 e2] is strictly negative if [e1] is smaller than [e2], - and [f e1 e2] is strictly positive if [e1] is greater than [e2]. - Example: a suitable ordering function is the generic structural - comparison function {!Pervasives.compare}. */ - let compare: (t, t) => int +/** +Turns an array of values into a Set. Meaning only unique values are preserved. + +## Examples +```rescript +type languages = ReScript | JavaScript | TypeScript +let languageRank = [ReScript, JavaScript, TypeScript] + +let set = Set.fromArray(languageRank) // Set.t + +switch set->Set.has(ReScript) { +| true => Console.log("Yay, ReScript is in there!") +| false => Console.log("Uh-oh, something is _terribly_ wrong with this program... abort.") } +``` +*/ +@new +external fromArray: array<'a> => t<'a> = "Set" + +/** +Turns an iterator into a `Set`. + +## Examples +```rescript +// Let's pretend we have an interator +@val external someIterator: Iterator.t = "someIterator" + +let set = Set.fromIterator(someIterator) // Set.t +``` +*/ +@new +external fromIterator: Iterator.t<'a> => t<'a> = "Set" + +/** +Returns the size, the number of unique values, of the set. + +## Examples +```rescript +let set = Set.make() -/** Output signature of the functor {!Set.Make}. */ -module type S = { - /** The type of the set elements. */ - type elt +set->Set.add("someValue") +set->Set.add("someValue") +set->Set.add("someValue2") - /** The type of sets. */ - type t - - /** The empty set. */ - let empty: t - - /** Test whether a set is empty or not. */ - let is_empty: t => bool - - /** [mem x s] tests whether [x] belongs to the set [s]. */ - let mem: (elt, t) => bool - - /** [add x s] returns a set containing all elements of [s], - plus [x]. If [x] was already in [s], [s] is returned unchanged - (the result of the function is then physically equal to [s]). - @before 4.03 Physical equality was not ensured. */ - let add: (elt, t) => t - - /** [singleton x] returns the one-element set containing only [x]. */ - let singleton: elt => t - - /** [remove x s] returns a set containing all elements of [s], - except [x]. If [x] was not in [s], [s] is returned unchanged - (the result of the function is then physically equal to [s]). - @before 4.03 Physical equality was not ensured. */ - let remove: (elt, t) => t - - /** Set union. */ - let union: (t, t) => t - - /** Set intersection. */ - let inter: (t, t) => t - - /** Set difference. */ - let diff: (t, t) => t - - /** Total ordering between sets. Can be used as the ordering function - for doing sets of sets. */ - let compare: (t, t) => int - - /** [equal s1 s2] tests whether the sets [s1] and [s2] are - equal, that is, contain equal elements. */ - let equal: (t, t) => bool - - /** [subset s1 s2] tests whether the set [s1] is a subset of - the set [s2]. */ - let subset: (t, t) => bool - - /** [iter f s] applies [f] in turn to all elements of [s]. - The elements of [s] are presented to [f] in increasing order - with respect to the ordering over the type of the elements. */ - let iter: (elt => unit, t) => unit - - /** [map f s] is the set whose elements are [f a0],[f a1]... [f - aN], where [a0],[a1]...[aN] are the elements of [s]. - - The elements are passed to [f] in increasing order - with respect to the ordering over the type of the elements. - - If no element of [s] is changed by [f], [s] is returned - unchanged. (If each output of [f] is physically equal to its - input, the returned set is physically equal to [s].) - @since 4.04.0 */ - let map: (elt => elt, t) => t - - /** [fold f s a] computes [(f xN ... (f x2 (f x1 a))...)], - where [x1 ... xN] are the elements of [s], in increasing order. */ - let fold: ((elt, 'a) => 'a, t, 'a) => 'a - - /** [for_all p s] checks if all elements of the set - satisfy the predicate [p]. */ - let for_all: (elt => bool, t) => bool - - /** [exists p s] checks if at least one element of - the set satisfies the predicate [p]. */ - let exists: (elt => bool, t) => bool - - /** [filter p s] returns the set of all elements in [s] - that satisfy predicate [p]. If [p] satisfies every element in [s], - [s] is returned unchanged (the result of the function is then - physically equal to [s]). - @before 4.03 Physical equality was not ensured.*/ - let filter: (elt => bool, t) => t - - /** [partition p s] returns a pair of sets [(s1, s2)], where - [s1] is the set of all the elements of [s] that satisfy the - predicate [p], and [s2] is the set of all the elements of - [s] that do not satisfy [p]. */ - let partition: (elt => bool, t) => (t, t) - - /** Return the number of elements of a set. */ - let cardinal: t => int - - /** Return the list of all elements of the given set. - The returned list is sorted in increasing order with respect - to the ordering [Ord.compare], where [Ord] is the argument - given to {!Set.Make}. */ - let elements: t => list - - /** Return the smallest element of the given set - (with respect to the [Ord.compare] ordering), or raise - [Not_found] if the set is empty. */ - let min_elt: t => elt - - /** Return the smallest element of the given set - (with respect to the [Ord.compare] ordering), or [None] - if the set is empty. - @since 4.05 - */ - let min_elt_opt: t => option - - /** Same as {!Set.S.min_elt}, but returns the largest element of the - given set. */ - let max_elt: t => elt - - /** Same as {!Set.S.min_elt_opt}, but returns the largest element of the - given set. - @since 4.05 - */ - let max_elt_opt: t => option - - /** Return one element of the given set, or raise [Not_found] if - the set is empty. Which element is chosen is unspecified, - but equal elements will be chosen for equal sets. */ - let choose: t => elt - - /** Return one element of the given set, or [None] if - the set is empty. Which element is chosen is unspecified, - but equal elements will be chosen for equal sets. - @since 4.05 - */ - let choose_opt: t => option - - /** [split x s] returns a triple [(l, present, r)], where - [l] is the set of elements of [s] that are - strictly less than [x]; - [r] is the set of elements of [s] that are - strictly greater than [x]; - [present] is [false] if [s] contains no element equal to [x], - or [true] if [s] contains an element equal to [x]. */ - let split: (elt, t) => (t, bool, t) - - /** [find x s] returns the element of [s] equal to [x] (according - to [Ord.compare]), or raise [Not_found] if no such element - exists. - @since 4.01.0 */ - let find: (elt, t) => elt - - /** [find_opt x s] returns the element of [s] equal to [x] (according - to [Ord.compare]), or [None] if no such element - exists. - @since 4.05 */ - let find_opt: (elt, t) => option - - /** [find_first f s], where [f] is a monotonically increasing function, - returns the lowest element [e] of [s] such that [f e], - or raises [Not_found] if no such element exists. - - For example, [find_first (fun e -> Ord.compare e x >= 0) s] will return - the first element [e] of [s] where [Ord.compare e x >= 0] (intuitively: - [e >= x]), or raise [Not_found] if [x] is greater than any element of - [s]. - - @since 4.05 - */ - let find_first: (elt => bool, t) => elt - - /** [find_first_opt f s], where [f] is a monotonically increasing function, - returns an option containing the lowest element [e] of [s] such that - [f e], or [None] if no such element exists. - @since 4.05 - */ - let find_first_opt: (elt => bool, t) => option - - /** [find_last f s], where [f] is a monotonically decreasing function, - returns the highest element [e] of [s] such that [f e], - or raises [Not_found] if no such element exists. - @since 4.05 - */ - let find_last: (elt => bool, t) => elt - - /** [find_last_opt f s], where [f] is a monotonically decreasing function, - returns an option containing the highest element [e] of [s] such that - [f e], or [None] if no such element exists. - @since 4.05 - */ - let find_last_opt: (elt => bool, t) => option - - /** [of_list l] creates a set from a list of elements. - This is usually more efficient than folding [add] over the list, - except perhaps for lists with many duplicated elements. - @since 4.02.0 */ - let of_list: list => t +let size = set->Set.size // 2 +``` +*/ +@get +external size: t<'a> => int = "size" + +/** +Clears all entries in the set. + +## Examples +```rescript +let set = Set.make() + +set->Set.add("someKey") +set->Set.size // 1 + +set->Set.clear +set->Set.size // 0 +``` +*/ +@send +external clear: t<'a> => unit = "clear" + +/** +Adds a new value to the set. + +## Examples +```rescript +let set = Set.make() +set->Set.add("someValue") +``` +*/ +@send +external add: (t<'a>, 'a) => unit = "add" + +/** +Deletes the provided `value` from the set. Returns a `bool` for whether the value existed, and was deleted. + +## Examples +```rescript +let set = Set.make() +set->Set.add("someValue") +let didDeleteValue = set->Set.delete("someValue") +Console.log(didDeleteValue) // Logs `true` to the console, becuase the set had the value, so it was successfully deleted + +let didDeleteValue = set->Set.delete("someNonExistantKey") +Console.log(didDeleteValue) // Logs `false` to the console, becuase the value did not exist in the set +``` +*/ +@send +external delete: (t<'a>, 'a) => bool = "delete" + +/** +Checks whether the set has a specific value. + +## Examples +```rescript +let set = Set.make() +set->Set.add("someValue") + +switch set->Set.has("someValue") { +| false => Console.log("Nope, didn't have it.") +| true => Console.log("Yay, we have the value!") } +``` +*/ +@send +external has: (t<'a>, 'a) => bool = "has" + +/** +Iterates through all values of the set. + +## Examples +```rescript +let set = Set.make() +set->Set.add("someValue") +set->Set.add("someValue2") + +set->Set.forEach(value => { + Console.log(value) +}) +``` +*/ +@send +external forEach: (t<'a>, 'a => unit) => unit = "forEach" -/** Functor building an implementation of the set structure - given a totally ordered type. */ -module Make: (Ord: OrderedType) => (S with type elt = Ord.t) +/** +Returns an iterator that holds all values of the set. + +## Examples +```rescript +let set = Set.make() +set->Set.add("someValue") +set->Set.add("anotherValue") + +let values = set->Set.values + +// Logs the first value +Console.log(Iterator.next(values).value) + +// You can also turn the iterator into an array. +// Remember that an iterator consumes values. We'll need a fresh values iterator to get an array of all values, since we consumed a value via `next` above already. +Console.log(set->Set.values->Iterator.toArray) +``` +*/ +@send +external values: t<'a> => Iterator.t<'a> = "values" diff --git a/jscomp/stdlib-406/setLabels.res b/jscomp/stdlib-406/setLabels.res deleted file mode 100644 index 4e0ed5e2c8..0000000000 --- a/jscomp/stdlib-406/setLabels.res +++ /dev/null @@ -1,711 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Sets over ordered types */ - -module type OrderedType = { - type t - let compare: (t, t) => int -} - -module type S = { - type elt - type t - let empty: t - let is_empty: t => bool - let mem: (elt, t) => bool - let add: (elt, t) => t - let singleton: elt => t - let remove: (elt, t) => t - let union: (t, t) => t - let inter: (t, t) => t - let diff: (t, t) => t - let compare: (t, t) => int - let equal: (t, t) => bool - let subset: (t, t) => bool - let iter: (~f: elt => unit, t) => unit - let map: (~f: elt => elt, t) => t - let fold: (~f: (elt, 'a) => 'a, t, ~init: 'a) => 'a - let for_all: (~f: elt => bool, t) => bool - let exists: (~f: elt => bool, t) => bool - let filter: (~f: elt => bool, t) => t - let partition: (~f: elt => bool, t) => (t, t) - let cardinal: t => int - let elements: t => list - let min_elt: t => elt - let min_elt_opt: t => option - let max_elt: t => elt - let max_elt_opt: t => option - let choose: t => elt - let choose_opt: t => option - let split: (elt, t) => (t, bool, t) - let find: (elt, t) => elt - let find_opt: (elt, t) => option - let find_first: (~f: elt => bool, t) => elt - let find_first_opt: (~f: elt => bool, t) => option - let find_last: (~f: elt => bool, t) => elt - let find_last_opt: (~f: elt => bool, t) => option - let of_list: list => t -} - -module Make = (Ord: OrderedType) => { - type elt = Ord.t - type rec t = Empty | Node({l: t, v: elt, r: t, h: int}) - - /* Sets are represented by balanced binary trees (the heights of the - children differ by at most 2 */ - - let height = param => - switch param { - | Empty => 0 - | Node({h}) => h - } - - /* Creates a new node with left son l, value v and right son r. - We must have all elements of l < v < all elements of r. - l and r must be balanced and | height l - height r | <= 2. - Inline expansion of height for better speed. */ - - let create = (l, v, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - Node({ - l, - v, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - - /* Same as create, but performs one step of rebalancing if necessary. - Assumes l and r balanced and | height l - height r | <= 3. - Inline expansion of create for better speed in the most frequent case - where no rebalancing is required. */ - - let bal = (l, v, r) => { - let hl = switch l { - | Empty => 0 - | Node({h}) => h - } - let hr = switch r { - | Empty => 0 - | Node({h}) => h - } - if hl > hr + 2 { - switch l { - | Empty => invalid_arg("Set.bal") - | Node({l: ll, v: lv, r: lr}) => - if height(ll) >= height(lr) { - create(ll, lv, create(lr, v, r)) - } else { - switch lr { - | Empty => invalid_arg("Set.bal") - | Node({l: lrl, v: lrv, r: lrr}) => create(create(ll, lv, lrl), lrv, create(lrr, v, r)) - } - } - } - } else if hr > hl + 2 { - switch r { - | Empty => invalid_arg("Set.bal") - | Node({l: rl, v: rv, r: rr}) => - if height(rr) >= height(rl) { - create(create(l, v, rl), rv, rr) - } else { - switch rl { - | Empty => invalid_arg("Set.bal") - | Node({l: rll, v: rlv, r: rlr}) => create(create(l, v, rll), rlv, create(rlr, rv, rr)) - } - } - } - } else { - Node({ - l, - v, - r, - h: if hl >= hr { - hl + 1 - } else { - hr + 1 - }, - }) - } - } - - /* Insertion of one element */ - - let rec add = (x, param) => - switch param { - | Empty => Node({l: Empty, v: x, r: Empty, h: 1}) - | Node({l, v, r}) as t => - let c = Ord.compare(x, v) - if c == 0 { - t - } else if c < 0 { - let ll = add(x, l) - if l === ll { - t - } else { - bal(ll, v, r) - } - } else { - let rr = add(x, r) - if r === rr { - t - } else { - bal(l, v, rr) - } - } - } - - let singleton = x => Node({l: Empty, v: x, r: Empty, h: 1}) - - /* Beware: those two functions assume that the added v is *strictly* - smaller (or bigger) than all the present elements in the tree; it - does not test for equality with the current min (or max) element. - Indeed, they are only used during the "join" operation which - respects this precondition. - */ - - let rec add_min_element = (x, param) => - switch param { - | Empty => singleton(x) - | Node({l, v, r}) => bal(add_min_element(x, l), v, r) - } - - let rec add_max_element = (x, param) => - switch param { - | Empty => singleton(x) - | Node({l, v, r}) => bal(l, v, add_max_element(x, r)) - } - - /* Same as create and bal, but no assumptions are made on the - relative heights of l and r. */ - - let rec join = (l, v, r) => - switch (l, r) { - | (Empty, _) => add_min_element(v, r) - | (_, Empty) => add_max_element(v, l) - | (Node({l: ll, v: lv, r: lr, h: lh}), Node({l: rl, v: rv, r: rr, h: rh})) => - if lh > rh + 2 { - bal(ll, lv, join(lr, v, r)) - } else if rh > lh + 2 { - bal(join(l, v, rl), rv, rr) - } else { - create(l, v, r) - } - } - - /* Smallest and greatest element of a set */ - - let rec min_elt = param => - switch param { - | Empty => raise(Not_found) - | Node({l: Empty, v}) => v - | Node({l}) => min_elt(l) - } - - let rec min_elt_opt = param => - switch param { - | Empty => None - | Node({l: Empty, v}) => Some(v) - | Node({l}) => min_elt_opt(l) - } - - let rec max_elt = param => - switch param { - | Empty => raise(Not_found) - | Node({v, r: Empty}) => v - | Node({r}) => max_elt(r) - } - - let rec max_elt_opt = param => - switch param { - | Empty => None - | Node({v, r: Empty}) => Some(v) - | Node({r}) => max_elt_opt(r) - } - - /* Remove the smallest element of the given set */ - - let rec remove_min_elt = param => - switch param { - | Empty => invalid_arg("Set.remove_min_elt") - | Node({l: Empty, r}) => r - | Node({l, v, r}) => bal(remove_min_elt(l), v, r) - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - Assume | height l - height r | <= 2. */ - - let merge = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => bal(t1, min_elt(t2), remove_min_elt(t2)) - } - - /* Merge two trees l and r into one. - All elements of l must precede the elements of r. - No assumption on the heights of l and r. */ - - let concat = (t1, t2) => - switch (t1, t2) { - | (Empty, t) => t - | (t, Empty) => t - | (_, _) => join(t1, min_elt(t2), remove_min_elt(t2)) - } - - /* Splitting. split x s returns a triple (l, present, r) where - - l is the set of elements of s that are < x - - r is the set of elements of s that are > x - - present is false if s contains no element equal to x, - or true if s contains an element equal to x. */ - - let rec split = (x, param) => - switch param { - | Empty => (Empty, false, Empty) - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - (l, true, r) - } else if c < 0 { - let (ll, pres, rl) = split(x, l) - (ll, pres, join(rl, v, r)) - } else { - let (lr, pres, rr) = split(x, r) - (join(l, v, lr), pres, rr) - } - } - - /* Implementation of the set operations */ - - let empty = Empty - - let is_empty = param => - switch param { - | Empty => true - | _ => false - } - - let rec mem = (x, param) => - switch param { - | Empty => false - | Node({l, v, r}) => - let c = Ord.compare(x, v) - c == 0 || - mem( - x, - if c < 0 { - l - } else { - r - }, - ) - } - - let rec remove = (x, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - let c = Ord.compare(x, v) - if c == 0 { - merge(l, r) - } else if c < 0 { - let ll = remove(x, l) - if l === ll { - t - } else { - bal(ll, v, r) - } - } else { - let rr = remove(x, r) - if r === rr { - t - } else { - bal(l, v, rr) - } - } - } - - let rec union = (s1, s2) => - switch (s1, s2) { - | (Empty, t2) => t2 - | (t1, Empty) => t1 - | (Node({l: l1, v: v1, r: r1, h: h1}), Node({l: l2, v: v2, r: r2, h: h2})) => - if h1 >= h2 { - if h2 == 1 { - add(v2, s1) - } else { - let (l2, _, r2) = split(v1, s2) - join(union(l1, l2), v1, union(r1, r2)) - } - } else if h1 == 1 { - add(v1, s2) - } else { - let (l1, _, r1) = split(v2, s1) - join(union(l1, l2), v2, union(r1, r2)) - } - } - - let rec inter = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => Empty - | (_, Empty) => Empty - | (Node({l: l1, v: v1, r: r1}), t2) => - switch split(v1, t2) { - | (l2, false, r2) => concat(inter(l1, l2), inter(r1, r2)) - | (l2, true, r2) => join(inter(l1, l2), v1, inter(r1, r2)) - } - } - - let rec diff = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => Empty - | (t1, Empty) => t1 - | (Node({l: l1, v: v1, r: r1}), t2) => - switch split(v1, t2) { - | (l2, false, r2) => join(diff(l1, l2), v1, diff(r1, r2)) - | (l2, true, r2) => concat(diff(l1, l2), diff(r1, r2)) - } - } - - type rec enumeration = End | More(elt, t, enumeration) - - let rec cons_enum = (s, e) => - switch s { - | Empty => e - | Node({l, v, r}) => cons_enum(l, More(v, r, e)) - } - - let rec compare_aux = (e1, e2) => - switch (e1, e2) { - | (End, End) => 0 - | (End, _) => -1 - | (_, End) => 1 - | (More(v1, r1, e1), More(v2, r2, e2)) => - let c = Ord.compare(v1, v2) - if c != 0 { - c - } else { - compare_aux(cons_enum(r1, e1), cons_enum(r2, e2)) - } - } - - let compare = (s1, s2) => compare_aux(cons_enum(s1, End), cons_enum(s2, End)) - - let equal = (s1, s2) => compare(s1, s2) == 0 - - let rec subset = (s1, s2) => - switch (s1, s2) { - | (Empty, _) => true - | (_, Empty) => false - | (Node({l: l1, v: v1, r: r1}), Node({l: l2, v: v2, r: r2}) as t2) => - let c = Ord.compare(v1, v2) - if c == 0 { - subset(l1, l2) && subset(r1, r2) - } else if c < 0 { - subset(Node({l: l1, v: v1, r: Empty, h: 0}), l2) && subset(r1, t2) - } else { - subset(Node({l: Empty, v: v1, r: r1, h: 0}), r2) && subset(l1, t2) - } - } - - let rec iter = (~f, param) => - switch param { - | Empty => () - | Node({l, v, r}) => - iter(~f, l) - f(v) - iter(~f, r) - } - - let rec fold = (~f, s, ~init as accu) => - switch s { - | Empty => accu - | Node({l, v, r}) => fold(~f, r, ~init=f(v, fold(~f, l, ~init=accu))) - } - - let rec for_all = (~f as p, param) => - switch param { - | Empty => true - | Node({l, v, r}) => p(v) && (for_all(~f=p, l) && for_all(~f=p, r)) - } - - let rec exists = (~f as p, param) => - switch param { - | Empty => false - | Node({l, v, r}) => p(v) || (exists(~f=p, l) || exists(~f=p, r)) - } - - let rec filter = (~f as p, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - /* call [p] in the expected left-to-right order */ - let l' = filter(~f=p, l) - let pv = p(v) - let r' = filter(~f=p, r) - if pv { - if l === l' && r === r' { - t - } else { - join(l', v, r') - } - } else { - concat(l', r') - } - } - - let rec partition = (~f as p, param) => - switch param { - | Empty => (Empty, Empty) - | Node({l, v, r}) => - /* call [p] in the expected left-to-right order */ - let (lt, lf) = partition(~f=p, l) - let pv = p(v) - let (rt, rf) = partition(~f=p, r) - if pv { - (join(lt, v, rt), concat(lf, rf)) - } else { - (concat(lt, rt), join(lf, v, rf)) - } - } - - let rec cardinal = param => - switch param { - | Empty => 0 - | Node({l, r}) => cardinal(l) + 1 + cardinal(r) - } - - let rec elements_aux = (accu, param) => - switch param { - | Empty => accu - | Node({l, v, r}) => elements_aux(list{v, ...elements_aux(accu, r)}, l) - } - - let elements = s => elements_aux(list{}, s) - - let choose = min_elt - - let choose_opt = min_elt_opt - - let rec find = (x, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - v - } else { - find( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let rec find_first_aux = (v0, f, param) => - switch param { - | Empty => v0 - | Node({l, v, r}) => - if f(v) { - find_first_aux(v, f, l) - } else { - find_first_aux(v0, f, r) - } - } - - let rec find_first = (~f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - if f(v) { - find_first_aux(v, f, l) - } else { - find_first(~f, r) - } - } - - let rec find_first_opt_aux = (v0, f, param) => - switch param { - | Empty => Some(v0) - | Node({l, v, r}) => - if f(v) { - find_first_opt_aux(v, f, l) - } else { - find_first_opt_aux(v0, f, r) - } - } - - let rec find_first_opt = (~f, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - if f(v) { - find_first_opt_aux(v, f, l) - } else { - find_first_opt(~f, r) - } - } - - let rec find_last_aux = (v0, f, param) => - switch param { - | Empty => v0 - | Node({l, v, r}) => - if f(v) { - find_last_aux(v, f, r) - } else { - find_last_aux(v0, f, l) - } - } - - let rec find_last = (~f, param) => - switch param { - | Empty => raise(Not_found) - | Node({l, v, r}) => - if f(v) { - find_last_aux(v, f, r) - } else { - find_last(~f, l) - } - } - - let rec find_last_opt_aux = (v0, f, param) => - switch param { - | Empty => Some(v0) - | Node({l, v, r}) => - if f(v) { - find_last_opt_aux(v, f, r) - } else { - find_last_opt_aux(v0, f, l) - } - } - - let rec find_last_opt = (~f, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - if f(v) { - find_last_opt_aux(v, f, r) - } else { - find_last_opt(~f, l) - } - } - - let rec find_opt = (x, param) => - switch param { - | Empty => None - | Node({l, v, r}) => - let c = Ord.compare(x, v) - if c == 0 { - Some(v) - } else { - find_opt( - x, - if c < 0 { - l - } else { - r - }, - ) - } - } - - let try_join = (l, v, r) => - /* [join l v r] can only be called when (elements of l < v < - elements of r); use [try_join l v r] when this property may - not hold, but you hope it does hold in the common case */ - if ( - (l == Empty || Ord.compare(max_elt(l), v) < 0) && - (r == Empty || Ord.compare(v, min_elt(r)) < 0) - ) { - join(l, v, r) - } else { - union(l, add(v, r)) - } - - let rec map = (~f, param) => - switch param { - | Empty => Empty - | Node({l, v, r}) as t => - /* enforce left-to-right evaluation order */ - let l' = map(~f, l) - let v' = f(v) - let r' = map(~f, r) - if l === l' && (v === v' && r === r') { - t - } else { - try_join(l', v', r') - } - } - - let of_sorted_list = l => { - let rec sub = (n, l) => - switch (n, l) { - | (0, l) => (Empty, l) - | (1, list{x0, ...l}) => (Node({l: Empty, v: x0, r: Empty, h: 1}), l) - | (2, list{x0, x1, ...l}) => ( - Node({l: Node({l: Empty, v: x0, r: Empty, h: 1}), v: x1, r: Empty, h: 2}), - l, - ) - | (3, list{x0, x1, x2, ...l}) => ( - Node({ - l: Node({l: Empty, v: x0, r: Empty, h: 1}), - v: x1, - r: Node({l: Empty, v: x2, r: Empty, h: 1}), - h: 2, - }), - l, - ) - | (n, l) => - let nl = n / 2 - let (left, l) = sub(nl, l) - switch l { - | list{} => assert(false) - | list{mid, ...l} => - let (right, l) = sub(n - nl - 1, l) - (create(left, mid, right), l) - } - } - - fst(sub(List.length(l), l)) - } - - let of_list = l => - switch l { - | list{} => empty - | list{x0} => singleton(x0) - | list{x0, x1} => add(x1, singleton(x0)) - | list{x0, x1, x2} => add(x2, add(x1, singleton(x0))) - | list{x0, x1, x2, x3} => add(x3, add(x2, add(x1, singleton(x0)))) - | list{x0, x1, x2, x3, x4} => add(x4, add(x3, add(x2, add(x1, singleton(x0))))) - | _ => of_sorted_list(List.sort_uniq(Ord.compare, l)) - } -} diff --git a/jscomp/stdlib-406/sort.res b/jscomp/stdlib-406/sort.res deleted file mode 100644 index ab1713a6ee..0000000000 --- a/jscomp/stdlib-406/sort.res +++ /dev/null @@ -1,134 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Merging and sorting */ - -open Array - -let rec merge = (order, l1, l2) => - switch l1 { - | list{} => l2 - | list{h1, ...t1} => - switch l2 { - | list{} => l1 - | list{h2, ...t2} => - if order(h1, h2) { - list{h1, ...merge(order, t1, l2)} - } else { - list{h2, ...merge(order, l1, t2)} - } - } - } - -let list = (order, l) => { - let rec initlist = param => - switch param { - | list{} => list{} - | list{e} => list{list{e}} - | list{e1, e2, ...rest} => - list{ - if order(e1, e2) { - list{e1, e2} - } else { - list{e2, e1} - }, - ...initlist(rest), - } - } - let rec merge2 = param => - switch param { - | list{l1, l2, ...rest} => list{merge(order, l1, l2), ...merge2(rest)} - | x => x - } - let rec mergeall = param => - switch param { - | list{} => list{} - | list{l} => l - | llist => mergeall(merge2(llist)) - } - mergeall(initlist(l)) -} - -let swap = (arr, i, j) => { - let tmp = unsafe_get(arr, i) - unsafe_set(arr, i, unsafe_get(arr, j)) - unsafe_set(arr, j, tmp) -} - -/* There is a known performance bug in the code below. If you find - it, don't bother reporting it. You're not supposed to use this - module anyway. */ -let array = (cmp, arr) => { - let rec qsort = (lo, hi) => - if hi - lo >= 6 { - let mid = lsr(lo + hi, 1) - - /* Select median value from among LO, MID, and HI. Rearrange - LO and HI so the three values are sorted. This lowers the - probability of picking a pathological pivot. It also - avoids extra comparisons on i and j in the two tight "while" - loops below. */ - if cmp(unsafe_get(arr, mid), unsafe_get(arr, lo)) { - swap(arr, mid, lo) - } - if cmp(unsafe_get(arr, hi), unsafe_get(arr, mid)) { - swap(arr, mid, hi) - if cmp(unsafe_get(arr, mid), unsafe_get(arr, lo)) { - swap(arr, mid, lo) - } - } - let pivot = unsafe_get(arr, mid) - let i = ref(lo + 1) and j = ref(hi - 1) - if !cmp(pivot, unsafe_get(arr, hi)) || !cmp(unsafe_get(arr, lo), pivot) { - raise(Invalid_argument("Sort.array")) - } - while i.contents < j.contents { - while !cmp(pivot, unsafe_get(arr, i.contents)) { - incr(i) - } - while !cmp(unsafe_get(arr, j.contents), pivot) { - decr(j) - } - if i.contents < j.contents { - swap(arr, i.contents, j.contents) - } - incr(i) - decr(j) - } - - /* Recursion on smaller half, tail-call on larger half */ - if j.contents - lo <= hi - i.contents { - qsort(lo, j.contents) - qsort(i.contents, hi) - } else { - qsort(i.contents, hi) - qsort(lo, j.contents) - } - } - qsort(0, Array.length(arr) - 1) - /* Finish sorting by insertion sort */ - for i in 1 to Array.length(arr) - 1 { - let val_i = unsafe_get(arr, i) - if !cmp(unsafe_get(arr, i - 1), val_i) { - unsafe_set(arr, i, unsafe_get(arr, i - 1)) - let j = ref(i - 1) - while j.contents >= 1 && !cmp(unsafe_get(arr, j.contents - 1), val_i) { - unsafe_set(arr, j.contents, unsafe_get(arr, j.contents - 1)) - decr(j) - } - unsafe_set(arr, j.contents, val_i) - } - } -} diff --git a/jscomp/stdlib-406/sort.resi b/jscomp/stdlib-406/sort.resi deleted file mode 100644 index b4de4f98f0..0000000000 --- a/jscomp/stdlib-406/sort.resi +++ /dev/null @@ -1,44 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Sorting and merging lists. - - @deprecated This module is obsolete and exists only for backward - compatibility. - The sorting functions in {!Array} and {!List} should be used instead. - The new functions are faster and use less memory. -*/ - -@deprecated("Use List.sort instead.") -/** Sort a list in increasing order according to an ordering predicate. - The predicate should return [true] if its first argument is - less than or equal to its second argument. */ -let list: (('a, 'a) => bool, list<'a>) => list<'a> - -@deprecated("Use Array.sort instead.") -/** Sort an array in increasing order according to an - ordering predicate. - The predicate should return [true] if its first argument is - less than or equal to its second argument. - The array is sorted in place. */ -let array: (('a, 'a) => bool, array<'a>) => unit - -@deprecated("Use List.merge instead.") -/** Merge two lists according to the given predicate. - Assuming the two argument lists are sorted according to the - predicate, [merge] returns a sorted list containing the elements - from the two lists. The behavior is undefined if the two - argument lists were not sorted. */ -let merge: (('a, 'a) => bool, list<'a>, list<'a>) => list<'a> diff --git a/jscomp/stdlib-406/stack.res b/jscomp/stdlib-406/stack.res deleted file mode 100644 index ee13834b0f..0000000000 --- a/jscomp/stdlib-406/stack.res +++ /dev/null @@ -1,55 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -type t<'a> = {mutable c: list<'a>, mutable len: int} - -exception Empty - -let create = () => {c: list{}, len: 0} - -let clear = s => { - s.c = list{} - s.len = 0 -} - -let copy = s => {c: s.c, len: s.len} - -let push = (x, s) => { - s.c = list{x, ...s.c} - s.len = s.len + 1 -} - -let pop = s => - switch s.c { - | list{hd, ...tl} => - s.c = tl - s.len = s.len - 1 - hd - | list{} => raise(Empty) - } - -let top = s => - switch s.c { - | list{hd, ..._} => hd - | list{} => raise(Empty) - } - -let is_empty = s => s.c == list{} - -let length = s => s.len - -let iter = (f, s) => List.iter(f, s.c) - -let fold = (f, acc, s) => List.fold_left(f, acc, s.c) diff --git a/jscomp/stdlib-406/stack.resi b/jscomp/stdlib-406/stack.resi deleted file mode 100644 index 6acaaa7a03..0000000000 --- a/jscomp/stdlib-406/stack.resi +++ /dev/null @@ -1,61 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Last-in first-out stacks. - - This module implements stacks (LIFOs), with in-place modification. -*/ - -/** The type of stacks containing elements of type ['a]. */ -type t<'a> - -/** Raised when {!Stack.pop} or {!Stack.top} is applied to an empty stack. */ exception Empty - -/** Return a new stack, initially empty. */ -let create: unit => t<'a> - -/** [push x s] adds the element [x] at the top of stack [s]. */ -let push: ('a, t<'a>) => unit - -/** [pop s] removes and returns the topmost element in stack [s], - or raises {!Empty} if the stack is empty. */ -let pop: t<'a> => 'a - -/** [top s] returns the topmost element in stack [s], - or raises {!Empty} if the stack is empty. */ -let top: t<'a> => 'a - -/** Discard all elements from a stack. */ -let clear: t<'a> => unit - -/** Return a copy of the given stack. */ -let copy: t<'a> => t<'a> - -/** Return [true] if the given stack is empty, [false] otherwise. */ -let is_empty: t<'a> => bool - -/** Return the number of elements in a stack. Time complexity O(1) */ -let length: t<'a> => int - -/** [iter f s] applies [f] in turn to all elements of [s], - from the element at the top of the stack to the element at the - bottom of the stack. The stack itself is unchanged. */ -let iter: ('a => unit, t<'a>) => unit - -/** [fold f accu s] is [(f (... (f (f accu x1) x2) ...) xn)] - where [x1] is the top of the stack, [x2] the second element, - and [xn] the bottom element. The stack is unchanged. - @since 4.03 */ -let fold: (('b, 'a) => 'b, 'b, t<'a>) => 'b diff --git a/jscomp/stdlib-406/stdLabels.res b/jscomp/stdlib-406/stdLabels.res deleted file mode 100644 index 8e35db9f80..0000000000 --- a/jscomp/stdlib-406/stdLabels.res +++ /dev/null @@ -1,24 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Jacques Garrigue, Kyoto University RIMS */ -/* */ -/* Copyright 2001 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* Module [StdLabels]: meta-module for labelled libraries */ - -module Array = ArrayLabels - -module List = ListLabels - -module String = StringLabels - -module Bytes = BytesLabels diff --git a/jscomp/stdlib-406/stdLabels.resi b/jscomp/stdlib-406/stdLabels.resi deleted file mode 100644 index a36e9d33a3..0000000000 --- a/jscomp/stdlib-406/stdLabels.resi +++ /dev/null @@ -1,29 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Jacques Garrigue, Kyoto University RIMS */ -/* */ -/* Copyright 2001 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Standard labeled libraries. - - This meta-module provides labelized version of the {!Array}, - {!Bytes}, {!List} and {!String} modules. - - They only differ by their labels. Detailed interfaces can be found - in [arrayLabels.mli], [bytesLabels.mli], [listLabels.mli] - and [stringLabels.mli]. -*/ - -module Array = ArrayLabels -module Bytes = BytesLabels -module List = ListLabels -module String = StringLabels diff --git a/jscomp/stdlib-406/stream.res b/jscomp/stdlib-406/stream.res deleted file mode 100644 index 03bbd7240c..0000000000 --- a/jscomp/stdlib-406/stream.res +++ /dev/null @@ -1,260 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1997 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -type rec t<'a> = option> -and cell<'a> = {mutable count: int, mutable data: data<'a>} -and data<'a> = - | Sempty - | Scons('a, data<'a>) - | Sapp(data<'a>, data<'a>) - | Slazy(Lazy.t>) - | Sgen(gen<'a>) -and gen<'a> = {mutable curr: option>, func: int => option<'a>} - -exception Failure -exception Error(string) - -let count = param => - switch param { - | None => 0 - | Some({count}) => count - } -let data = param => - switch param { - | None => Sempty - | Some({data}) => data - } - -let rec get_data: - type v. (int, data) => data = - (count, d) => - switch d { - /* Returns either Sempty or Scons(a, _) even when d is a generator - or a buffer. In those cases, the item a is seen as extracted from - the generator/buffer. - The count parameter is used for calling `Sgen-functions'. */ - | Sempty | Scons(_, _) => d - | Sapp(d1, d2) => - switch get_data(count, d1) { - | Scons(a, d11) => Scons(a, Sapp(d11, d2)) - | Sempty => get_data(count, d2) - | _ => assert(false) - } - | Sgen({curr: Some(None)}) => Sempty - | Sgen({curr: Some(Some(a))} as g) => - g.curr = None - Scons(a, d) - | Sgen(g) => - switch g.func(count) { - | None => - g.curr = Some(None) - Sempty - | Some(a) => Scons(a, d) - /* Warning: anyone using g thinks that an item has been read */ - } - | Slazy(f) => get_data(count, Lazy.force(f)) - } - -let rec peek_data: - type v. cell => option = - s => - /* consult the first item of s */ - switch s.data { - | Sempty => None - | Scons(a, _) => Some(a) - | Sapp(_, _) => - switch get_data(s.count, s.data) { - | Scons(a, _) as d => - s.data = d - Some(a) - | Sempty => None - | _ => assert(false) - } - | Slazy(f) => - s.data = Lazy.force(f) - peek_data(s) - | Sgen({curr: Some(a)}) => a - | Sgen(g) => - let x = g.func(s.count) - g.curr = Some(x) - x - } - -let peek = param => - switch param { - | None => None - | Some(s) => peek_data(s) - } - -let rec junk_data: - type v. cell => unit = - s => - switch s.data { - | Scons(_, d) => - s.count = succ(s.count) - s.data = d - | Sgen({curr: Some(_)} as g) => - s.count = succ(s.count) - g.curr = None - | _ => - switch peek_data(s) { - | None => () - | Some(_) => junk_data(s) - } - } - -let junk = param => - switch param { - | None => () - | Some(data) => junk_data(data) - } - -let rec nget_data = (n, s) => - if n <= 0 { - (list{}, s.data, 0) - } else { - switch peek_data(s) { - | Some(a) => - junk_data(s) - let (al, d, k) = nget_data(pred(n), s) - (list{a, ...al}, Scons(a, d), succ(k)) - | None => (list{}, s.data, 0) - } - } - -let npeek_data = (n, s) => { - let (al, d, len) = nget_data(n, s) - s.count = s.count - len - s.data = d - al -} - -let npeek = (n, param) => - switch param { - | None => list{} - | Some(d) => npeek_data(n, d) - } - -let next = s => - switch peek(s) { - | Some(a) => - junk(s) - a - | None => raise(Failure) - } - -let empty = s => - switch peek(s) { - | Some(_) => raise(Failure) - | None => () - } - -let iter = (f, strm) => { - let rec do_rec = () => - switch peek(strm) { - | Some(a) => - junk(strm) - ignore(f(a)) - do_rec() - | None => () - } - - do_rec() -} - -/* Stream building functions */ - -let from = f => Some({count: 0, data: Sgen({curr: None, func: f})}) - -let of_list = l => Some({count: 0, data: List.fold_right((x, l) => Scons(x, l), l, Sempty)}) - -let of_string = s => { - let count = ref(0) - from(_ => { - /* We cannot use the index passed by the [from] function directly - because it returns the current stream count, with absolutely no - guarantee that it will start from 0. For example, in the case - of [Stream.icons 'c' (Stream.from_string "ab")], the first - access to the string will be made with count [1] already. - */ - let c = count.contents - if c < String.length(s) { - incr(count) - Some(String.get(s, c)) - } else { - None - } - }) -} - -let of_bytes = s => { - let count = ref(0) - from(_ => { - let c = count.contents - if c < Bytes.length(s) { - incr(count) - Some(Bytes.get(s, c)) - } else { - None - } - }) -} - -/* Stream expressions builders */ - -let iapp = (i, s) => Some({count: 0, data: Sapp(data(i), data(s))}) -let icons = (i, s) => Some({count: 0, data: Scons(i, data(s))}) -let ising = i => Some({count: 0, data: Scons(i, Sempty)}) - -let lapp = (f, s) => Some({count: 0, data: Slazy(Lazy.from_fun(() => Sapp(data(f()), data(s))))}) - -let lcons = (f, s) => Some({count: 0, data: Slazy(Lazy.from_fun(() => Scons(f(), data(s))))}) -let lsing = f => Some({count: 0, data: Slazy(Lazy.from_fun(() => Scons(f(), Sempty)))}) - -let sempty = None -let slazy = f => Some({count: 0, data: Slazy(Lazy.from_fun(() => data(f())))}) - -/* For debugging use */ - -let rec dump: - type v. (v => unit, t) => unit = - (f, s) => { - print_string("{count = ") - print_int(count(s)) - print_string("; data = ") - dump_data(f, data(s)) - print_string("}") - print_newline() - } -and dump_data: - type v. (v => unit, data) => unit = - (f, param) => - switch param { - | Sempty => print_string("Sempty") - | Scons(a, d) => - print_string("Scons (") - f(a) - print_string(", ") - dump_data(f, d) - print_string(")") - | Sapp(d1, d2) => - print_string("Sapp (") - dump_data(f, d1) - print_string(", ") - dump_data(f, d2) - print_string(")") - | Slazy(_) => print_string("Slazy") - | Sgen(_) => print_string("Sgen") - } diff --git a/jscomp/stdlib-406/stream.resi b/jscomp/stdlib-406/stream.resi deleted file mode 100644 index 952e6b9d4e..0000000000 --- a/jscomp/stdlib-406/stream.resi +++ /dev/null @@ -1,101 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1997 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Streams and parsers. */ - -/** The type of streams holding values of type ['a]. */ -type t<'a> - -/** Raised by parsers when none of the first components of the stream - patterns is accepted. */ -exception Failure - -/** Raised by parsers when the first component of a stream pattern is - accepted, but one of the following components is rejected. */ -exception Error(string) - -/*** {1 Stream builders} */ - -/** [Stream.from f] returns a stream built from the function [f]. - To create a new stream element, the function [f] is called with - the current stream count. The user function [f] must return either - [Some ] for a value or [None] to specify the end of the - stream. - - Do note that the indices passed to [f] may not start at [0] in the - general case. For example, [[< '0; '1; Stream.from f >]] would call - [f] the first time with count [2]. -*/ -let from: (int => option<'a>) => t<'a> - -/** Return the stream holding the elements of the list in the same - order. */ -let of_list: list<'a> => t<'a> - -/** Return the stream of the characters of the string parameter. */ -let of_string: string => t - -/** Return the stream of the characters of the bytes parameter. - @since 4.02.0 */ -let of_bytes: bytes => t - -/* {1 Stream iterator} */ - -/** [Stream.iter f s] scans the whole stream s, applying function [f] - in turn to each stream element encountered. */ -let iter: ('a => unit, t<'a>) => unit - -/* {1 Predefined parsers} */ - -/** Return the first element of the stream and remove it from the - stream. Raise {!Stream.Failure} if the stream is empty. */ -let next: t<'a> => 'a - -/** Return [()] if the stream is empty, else raise {!Stream.Failure}. */ -let empty: t<'a> => unit - -/* {1 Useful functions} */ - -/** Return [Some] of "the first element" of the stream, or [None] if - the stream is empty. */ -let peek: t<'a> => option<'a> - -/** Remove the first element of the stream, possibly unfreezing - it before. */ -let junk: t<'a> => unit - -/** Return the current count of the stream elements, i.e. the number - of the stream elements discarded. */ -let count: t<'a> => int - -/** [npeek n] returns the list of the [n] first elements of - the stream, or all its remaining elements if less than [n] - elements are available. */ -let npeek: (int, t<'a>) => list<'a> - -/* The following is for system use only. Do not call directly. */ - -let iapp: (t<'a>, t<'a>) => t<'a> -let icons: ('a, t<'a>) => t<'a> -let ising: 'a => t<'a> - -let lapp: (unit => t<'a>, t<'a>) => t<'a> -let lcons: (unit => 'a, t<'a>) => t<'a> -let lsing: (unit => 'a) => t<'a> - -let sempty: t<'a> -let slazy: (unit => t<'a>) => t<'a> - -let dump: ('a => unit, t<'a>) => unit diff --git a/jscomp/stdlib-406/string.res b/jscomp/stdlib-406/string.res index a038bfdaf8..86647f0139 100644 --- a/jscomp/stdlib-406/string.res +++ b/jscomp/stdlib-406/string.res @@ -1,235 +1,133 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Damien Doligez, projet Gallium, INRIA Rocquencourt */ -/* */ -/* Copyright 2014 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* String operations, based on byte sequence operations */ - -/* WARNING: Some functions in this file are duplicated in bytes.ml for - efficiency reasons. When you modify the one in this file you need to - modify its duplicate in bytes.ml. - These functions have a "duplicated" comment above their definition. -*/ - -external length: string => int = "%string_length" -external get: (string, int) => char = "%string_safe_get" -external unsafe_get: (string, int) => char = "%string_unsafe_get" - -module B = Bytes - -let bts = B.unsafe_to_string -let bos = B.unsafe_of_string - -external make: (int, char) => string = "?string_repeat" - -let init = (n, f) => bts(B.init(n, f)) -let sub = (s, ofs, len) => bts(B.sub(bos(s), ofs, len)) -let blit = B.blit_string - -%%private(@send external join: (array, string) => string = "join") - -let concat = (sep: string, xs: list) => xs->Array.of_list->join(sep) - -/* duplicated in bytes.ml */ -let iter = (f, s) => - for i in 0 to length(s) - 1 { - f(unsafe_get(s, i)) - } - -/* duplicated in bytes.ml */ -let iteri = (f, s) => - for i in 0 to length(s) - 1 { - f(i, unsafe_get(s, i)) - } - -let map = (f, s) => bts(B.map(f, bos(s))) -let mapi = (f, s) => bts(B.mapi(f, bos(s))) - -/* Beware: we cannot use B.trim or B.escape because they always make a - copy, but String.mli spells out some cases where we are not allowed - to make a copy. */ - -let is_space = param => - switch param { - | ' ' | ' ' | '\n' | '\r' | '\t' => true - | _ => false - } - -let trim = s => - if s == "" { - s - } else if is_space(unsafe_get(s, 0)) || is_space(unsafe_get(s, length(s) - 1)) { - bts(B.trim(bos(s))) - } else { - s - } - -let escaped = s => { - let rec needs_escape = i => - if i >= length(s) { - false - } else { - switch unsafe_get(s, i) { - | '"' | '\\' | '\n' | '\t' | '\r' | '\b' => true - | ' ' .. '~' => needs_escape(i + 1) - | _ => true - } - } - - if needs_escape(0) { - bts(B.escaped(bos(s))) - } else { - s - } -} - -/* duplicated in bytes.ml */ -let rec index_rec = (s, lim, i, c) => - if i >= lim { - raise(Not_found) - } else if unsafe_get(s, i) == c { - i - } else { - index_rec(s, lim, i + 1, c) - } - -/* duplicated in bytes.ml */ -let index = (s, c) => index_rec(s, length(s), 0, c) - -/* duplicated in bytes.ml */ -let rec index_rec_opt = (s, lim, i, c) => - if i >= lim { - None - } else if unsafe_get(s, i) == c { - Some(i) - } else { - index_rec_opt(s, lim, i + 1, c) - } - -/* duplicated in bytes.ml */ -let index_opt = (s, c) => index_rec_opt(s, length(s), 0, c) - -/* duplicated in bytes.ml */ -let index_from = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.index_from / Bytes.index_from") - } else { - index_rec(s, l, i, c) - } -} - -/* duplicated in bytes.ml */ -let index_from_opt = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.index_from_opt / Bytes.index_from_opt") - } else { - index_rec_opt(s, l, i, c) - } -} - -/* duplicated in bytes.ml */ -let rec rindex_rec = (s, i, c) => - if i < 0 { - raise(Not_found) - } else if unsafe_get(s, i) == c { - i - } else { - rindex_rec(s, i - 1, c) - } - -/* duplicated in bytes.ml */ -let rindex = (s, c) => rindex_rec(s, length(s) - 1, c) - -/* duplicated in bytes.ml */ -let rindex_from = (s, i, c) => - if i < -1 || i >= length(s) { - invalid_arg("String.rindex_from / Bytes.rindex_from") - } else { - rindex_rec(s, i, c) - } - -/* duplicated in bytes.ml */ -let rec rindex_rec_opt = (s, i, c) => - if i < 0 { - None - } else if unsafe_get(s, i) == c { - Some(i) - } else { - rindex_rec_opt(s, i - 1, c) - } - -/* duplicated in bytes.ml */ -let rindex_opt = (s, c) => rindex_rec_opt(s, length(s) - 1, c) - -/* duplicated in bytes.ml */ -let rindex_from_opt = (s, i, c) => - if i < -1 || i >= length(s) { - invalid_arg("String.rindex_from_opt / Bytes.rindex_from_opt") - } else { - rindex_rec_opt(s, i, c) - } - -/* duplicated in bytes.ml */ -let contains_from = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.contains_from / Bytes.contains_from") - } else { - try { - ignore(index_rec(s, l, i, c)) - true - } catch { - | Not_found => false - } - } -} - -/* duplicated in bytes.ml */ -let contains = (s, c) => contains_from(s, 0, c) - -/* duplicated in bytes.ml */ -let rcontains_from = (s, i, c) => - if i < 0 || i >= length(s) { - invalid_arg("String.rcontains_from / Bytes.rcontains_from") - } else { - try { - ignore(rindex_rec(s, i, c)) - true - } catch { - | Not_found => false - } - } - -let uppercase_ascii = s => bts(B.uppercase_ascii(bos(s))) -let lowercase_ascii = s => bts(B.lowercase_ascii(bos(s))) -let capitalize_ascii = s => bts(B.capitalize_ascii(bos(s))) -let uncapitalize_ascii = s => bts(B.uncapitalize_ascii(bos(s))) - -type t = string - -let compare = (x: t, y: t) => Pervasives.compare(x, y) -let equal: (string, string) => bool = (a, b) => a == b - -let split_on_char = (sep, s) => { - let r = ref(list{}) - let j = ref(length(s)) - for i in length(s) - 1 downto 0 { - if unsafe_get(s, i) == sep { - r := list{sub(s, i + 1, j.contents - i - 1), ...r.contents} - j := i - } - } - list{sub(s, 0, j.contents), ...r.contents} -} +@val external make: 'a => string = "String" + +@val external fromCharCode: int => string = "String.fromCharCode" +@variadic @val external fromCharCodeMany: array => string = "String.fromCharCode" + +@val external fromCodePoint: int => string = "String.fromCodePoint" +@variadic @val external fromCodePointMany: array => string = "String.fromCodePoint" + +let equal = (a: string, b: string) => a === b + +let compare = (a: string, b: string) => + a < b ? Ordering.less : a > b ? Ordering.greater : Ordering.equal + +@get external length: string => int = "length" +@get_index external get: (string, int) => option = "" +@send external charAt: (string, int) => string = "charAt" + +@send external charCodeAt: (string, int) => float = "charCodeAt" +@send external codePointAt: (string, int) => option = "codePointAt" + +@send external concat: (string, string) => string = "concat" +@variadic @send external concatMany: (string, array) => string = "concat" + +@send external endsWith: (string, string) => bool = "endsWith" +@send external endsWithFrom: (string, string, int) => bool = "endsWith" + +@send external includes: (string, string) => bool = "includes" +@send external includesFrom: (string, string, int) => bool = "includes" + +@send external indexOf: (string, string) => int = "indexOf" +let indexOfOpt = (s, search) => + switch indexOf(s, search) { + | -1 => None + | index => Some(index) + } +@send external indexOfFrom: (string, string, int) => int = "indexOf" + +@send external lastIndexOf: (string, string) => int = "lastIndexOf" +let lastIndexOfOpt = (s, search) => + switch lastIndexOf(s, search) { + | -1 => None + | index => Some(index) + } +@send external lastIndexOfFrom: (string, string, int) => int = "lastIndexOf" + +@return(nullable) @send +external match: (string, RegExp.t) => option = "match" + +type normalizeForm = [#NFC | #NFD | #NFKC | #NFKD] +@send external normalize: string => string = "normalize" +@send external normalizeByForm: (string, normalizeForm) => string = "normalize" + +@send external repeat: (string, int) => string = "repeat" + +@send external replace: (string, string, string) => string = "replace" +@send external replaceRegExp: (string, RegExp.t, string) => string = "replace" +@send external replaceAll: (string, string, string) => string = "replaceAll" +@send external replaceAllRegExp: (string, RegExp.t, string) => string = "replaceAll" + +@send +external unsafeReplaceRegExpBy0: ( + string, + RegExp.t, + (~match: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +@send +external unsafeReplaceRegExpBy1: ( + string, + RegExp.t, + (~match: string, ~group1: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +@send +external unsafeReplaceRegExpBy2: ( + string, + RegExp.t, + (~match: string, ~group1: string, ~group2: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +@send +external unsafeReplaceRegExpBy3: ( + string, + RegExp.t, + ( + ~match: string, + ~group1: string, + ~group2: string, + ~group3: string, + ~offset: int, + ~input: string, + ) => string, +) => string = "replace" + +@send external search: (string, RegExp.t) => int = "search" +let searchOpt = (s, re) => + switch search(s, re) { + | -1 => None + | index => Some(index) + } + +@send external slice: (string, ~start: int, ~end: int) => string = "slice" +@send external sliceToEnd: (string, ~start: int) => string = "slice" + +@send external split: (string, string) => array = "split" +@send external splitAtMost: (string, string, ~limit: int) => array = "split" +@send external splitByRegExp: (string, RegExp.t) => array> = "split" +@send +external splitByRegExpAtMost: (string, RegExp.t, ~limit: int) => array> = "split" + +@send external startsWith: (string, string) => bool = "startsWith" +@send external startsWithFrom: (string, string, int) => bool = "startsWith" + +@send external substring: (string, ~start: int, ~end: int) => string = "substring" +@send external substringToEnd: (string, ~start: int) => string = "substring" + +@send external toLowerCase: string => string = "toLowerCase" +@send external toLocaleLowerCase: string => string = "toLocaleLowerCase" +@send external toUpperCase: string => string = "toUpperCase" +@send external toLocaleUpperCase: string => string = "toLocaleUpperCase" + +@send external trim: string => string = "trim" +@send external trimStart: string => string = "trimStart" +@send external trimEnd: string => string = "trimEnd" + +@send external padStart: (string, int, string) => string = "padStart" +@send external padEnd: (string, int, string) => string = "padEnd" + +@get_index external getSymbol: (string, Symbol.t) => option<'a> = "" +@get_index external getSymbolUnsafe: (string, Symbol.t) => 'a = "" +@set_index external setSymbol: (string, Symbol.t, 'a) => unit = "" + +@send external localeCompare: (string, string) => float = "localeCompare" diff --git a/jscomp/stdlib-406/string.resi b/jscomp/stdlib-406/string.resi index 319e089ae4..677f88374a 100644 --- a/jscomp/stdlib-406/string.resi +++ b/jscomp/stdlib-406/string.resi @@ -1,275 +1,1008 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** String operations. - - A string is an immutable data structure that contains a - fixed-length sequence of (single-byte) characters. Each character - can be accessed in constant time through its index. - - Given a string [s] of length [l], we can access each of the [l] - characters of [s] via its index in the sequence. Indexes start at - [0], and we will call an index valid in [s] if it falls within the - range [[0...l-1]] (inclusive). A position is the point between two - characters or at the beginning or end of the string. We call a - position valid in [s] if it falls within the range [[0...l]] - (inclusive). Note that the character at index [n] is between - positions [n] and [n+1]. - - Two parameters [start] and [len] are said to designate a valid - substring of [s] if [len >= 0] and [start] and [start+len] are - valid positions in [s]. - - OCaml strings used to be modifiable in place, for instance via the - {!String.set} and {!String.blit} functions described below. This - usage is deprecated and only possible when the compiler is put in - "unsafe-string" mode by giving the [-unsafe-string] command-line - option (which is currently the default for reasons of backward - compatibility). This is done by making the types [string] and - [bytes] (see module {!Bytes}) interchangeable so that functions - expecting byte sequences can also accept strings as arguments and - modify them. - - All new code should avoid this feature and be compiled with the - [-safe-string] command-line option to enforce the separation between - the types [string] and [bytes]. -*/ - -/** Return the length (number of characters) of the given string. */ -external length: string => int = "%string_length" - -/** [String.get s n] returns the character at index [n] in string [s]. - You can also write [s.[n]] instead of [String.get s n]. - - Raise [Invalid_argument] if [n] not a valid index in [s]. */ -external get: (string, int) => char = "%string_safe_get" - -/** [String.make n c] returns a fresh string of length [n], - filled with the character [c]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let make: (int, char) => string - -/** [String.init n f] returns a string of length [n], with character - [i] initialized to the result of [f i] (called in increasing - index order). - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. - - @since 4.02.0 -*/ -let init: (int, int => char) => string - -/** [String.sub s start len] returns a fresh string of length [len], - containing the substring of [s] that starts at position [start] and - has length [len]. - - Raise [Invalid_argument] if [start] and [len] do not - designate a valid substring of [s]. */ -let sub: (string, int, int) => string - -/** Same as {!Bytes.blit_string}. */ -let blit: (string, int, bytes, int, int) => unit - -/** [String.concat sep sl] concatenates the list of strings [sl], - inserting the separator string [sep] between each. - - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. */ -let concat: (string, list) => string - -/** [String.iter f s] applies function [f] in turn to all - the characters of [s]. It is equivalent to - [f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. */ -let iter: (char => unit, string) => unit - -/** Same as {!String.iter}, but the - function is applied to the index of the element as first argument - (counting from 0), and the character itself as second argument. - @since 4.00.0 */ -let iteri: ((int, char) => unit, string) => unit - -/** [String.map f s] applies function [f] in turn to all the - characters of [s] (in increasing index order) and stores the - results in a new string that is returned. - @since 4.00.0 */ -let map: (char => char, string) => string +/* Copyright (C) 2015-2016 Bloomberg Finance L.P. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * In addition to the permissions granted to you by the LGPL, you may combine + * or link a "work that uses the Library" with a publicly distributed version + * of this file to produce a combined library or application, then distribute + * that combined work under the terms of your choosing, with no requirement + * to comply with the obligations normally placed on you by section 4 of the + * LGPL version 3 (or the corresponding section of a later version of the LGPL + * should you choose to use a later version). + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ + +/*** +Functions for interacting with JavaScript strings. +See: [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). +*/ + +/** +`make(value)` converts the given value to a `string`. + +## Examples + +```rescript +String.make(3.5) == "3.5" +String.make([1, 2, 3]) == "1,2,3" +``` +*/ +@val +external make: 'a => string = "String" + +/** +`fromCharCode(n)` creates a `string` containing the character corresponding to +that number, `n` ranges from 0 to 65535. If out of range, the lower 16 bits of +the value are used. Thus, `fromCharCode(0x1F63A)` gives the same result as +`fromCharCode(0xF63A)`. +See [`String.fromCharCode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode) on MDN. + +## Examples + +```rescript +String.fromCharCode(65) == "A" +String.fromCharCode(0x3c8) == `ψ` +String.fromCharCode(0xd55c) == `한` +String.fromCharCode(-64568) == `ψ` +``` +*/ +@val +external fromCharCode: int => string = "String.fromCharCode" + +/** +`fromCharCodeMany([n1, n2, n3])` creates a `string` from the characters +corresponding to the given numbers, using the same rules as `fromCharCode`. +See [`String.fromCharCode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode) on MDN. + +## Examples + +```rescript +String.fromCharCodeMany([189, 43, 190, 61]) == "½+¾=" +String.fromCharCodeMany([65, 66, 67]) == "ABC" +``` +*/ +@variadic +@val +external fromCharCodeMany: array => string = "String.fromCharCode" + +/** +`fromCodePoint(n)` creates a `string` containing the character corresponding to +that numeric code point. +See [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) on MDN. + +## Examples + +```rescript +String.fromCodePoint(65) == "A" +String.fromCodePoint(0x3c8) == `ψ` +String.fromCodePoint(0xd55c) == `한` +String.fromCodePoint(0x1f63a) == `😺` +``` + +## Exceptions + +- `RangeError`: If the number is not a valid code point, like `fromCharCode(-5)`. +*/ +@val +external fromCodePoint: int => string = "String.fromCodePoint" + +/** +`fromCodePointMany([n1, n2, n3])` creates a `string` from the characters +corresponding to the given code point numbers, using the same rules as +`fromCodePoint`. +See [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) on MDN. + +## Examples + +```rescript +String.fromCodePointMany([0xd55c, 0xae00, 0x1f63a]) == `한글😺` +``` + +## Exceptions + +- `RangeError`: If one of the number is not a valid code point, like +`fromCharCode([1, -5])`. + +*/ +@variadic +@val +external fromCodePointMany: array => string = "String.fromCodePoint" + +let equal: (string, string) => bool + +let compare: (string, string) => Ordering.t + +/** +`length(str)` returns the length of the given `string`. +See [`String.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) on MDN. + +## Examples + +```rescript +String.length("abcd") == 4 +``` +*/ +@get +external length: string => int = "length" + +/** +`get(str, index)` returns an `option` at the given `index` number. If +`index` is out of range, this function returns `None`. + +## Examples + +```rescript +String.get("ReScript", 0) == Some("R") +String.get("Hello", 4) == Some("o") +String.get(`JS`, 4) == None +``` +*/ +@get_index +external get: (string, int) => option = "" + +/** +`charAt(str, index)` gets the character at `index` within string `str`. If +`index` is negative or greater than the length of `str`, it returns the empty +string. If the string contains characters outside the range \u0000-\uffff, it +will return the first 16-bit value at that position in the string. +See [`String.charAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) on MDN. + +## Examples + +```rescript +String.charAt("ReScript", 0) == "R" +String.charAt("Hello", 12) == "" +String.charAt(`JS`, 5) == "" +``` +*/ +@send +external charAt: (string, int) => string = "charAt" + +/** +`charCodeAt(str, index)` returns the character code at position `index` in +string `str` the result is in the range 0-65535, unlike `codePointAt`, so it +will not work correctly for characters with code points greater than or equal +to 0x10000. The return type is `float` because this function returns NaN if +`index` is less than zero or greater than the length of the string. +See [`String.charCodeAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt) on MDN. + +## Examples + +```rescript +String.charCodeAt(`😺`, 0) == 0xd83d->Int.toFloat +String.codePointAt(`😺`, 0) == Some(0x1f63a) +``` +*/ +@send +external charCodeAt: (string, int) => float = "charCodeAt" + +/** +`codePointAt(str, index)` returns the code point at position `index` within +string `str` as a `Some(value)`. The return value handles code points greater +than or equal to 0x10000. If there is no code point at the given position, the +function returns `None`. +See [`String.codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) on MDN. + +## Examples + +```rescript +String.codePointAt(`¿😺?`, 1) == Some(0x1f63a) +String.codePointAt("abc", 5) == None +``` +*/ +@send +external codePointAt: (string, int) => option = "codePointAt" + +/** +`concat(original, append)` returns a new `string` with `append` added after +`original`. +See [`String.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat) on MDN. + +## Examples + +```rescript +String.concat("cow", "bell") == "cowbell" +String.concat("Re", "Script") == "ReScript" +``` +*/ +@send +external concat: (string, string) => string = "concat" + +/** +`concatMany(original, arr)` returns a new `string` consisting of each item of an +array of strings added to the `original` string. +See [`String.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat) on MDN. + +## Examples + +```rescript +String.concatMany("1st", ["2nd", "3rd", "4th"]) == "1st2nd3rd4th" +``` +*/ +@variadic +@send +external concatMany: (string, array) => string = "concat" + +/** +`endsWith(str, substr)` returns `true` if the `str` ends with `substr`, `false` +otherwise. +See [`String.endsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith) on MDN. -/** [String.mapi f s] calls [f] with each character of [s] and its - index (in increasing index order) and stores the results in a new - string that is returned. - @since 4.02.0 */ -let mapi: ((int, char) => char, string) => string +## Examples -/** Return a copy of the argument, without leading and trailing - whitespace. The characters regarded as whitespace are: [' '], - ['\x0c'], ['\n'], ['\r'], and ['\t']. If there is neither leading nor - trailing whitespace character in the argument, return the original - string itself, not a copy. - @since 4.00.0 */ -let trim: string => string +```rescript +String.endsWith("BuckleScript", "Script") == true +String.endsWith("BuckleShoes", "Script") == false +``` +*/ +@send +external endsWith: (string, string) => bool = "endsWith" + +// NOTE: Honestly, this should have been named endsWithAt, but oh well +/** +`endsWithFrom(str, ending, len)` returns `true` if the first len characters of +`str` end with `ending`, `false` otherwise. If `len` is greater than or equal +to the length of `str`, then it works like `endsWith`. +See [`String.endsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith) on MDN. + +## Examples + +```rescript +String.endsWithFrom("abcd", "cd", 4) == true +String.endsWithFrom("abcde", "cd", 3) == false +String.endsWithFrom("abcde", "cde", 99) == true +String.endsWithFrom("example.dat", "ple", 7) == true +``` +*/ +@send +external endsWithFrom: (string, string, int) => bool = "endsWith" + +/** +`includes(str, searchValue)` returns `true` if `searchValue` is found anywhere +within `str`, `false` otherwise. +See [`String.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) on MDN. + +## Examples + +```rescript +String.includes("programmer", "gram") == true +String.includes("programmer", "er") == true +String.includes("programmer", "pro") == true +String.includes("programmer.dat", "xyz") == false +``` +*/ +@send +external includes: (string, string) => bool = "includes" + +/** +`includesFrom(str, searchValue, start)` returns `true` if `searchValue` is found +anywhere within `str` starting at character number `start` (where 0 is the +first character), `false` otherwise. +See [`String.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) on MDN. + +## Examples + +```rescript +String.includesFrom("programmer", "gram", 1) == true +String.includesFrom("programmer", "gram", 4) == false +String.includesFrom(`대한민국`, `한`, 1) == true +``` +*/ +@send +external includesFrom: (string, string, int) => bool = "includes" + +/** +`indexOf(str, searchValue)` returns the position at which `searchValue` was +first found within `str`, or `-1` if `searchValue` is not in `str`. +See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN. + +## Examples + +```rescript +String.indexOf("bookseller", "ok") == 2 +String.indexOf("bookseller", "sell") == 4 +String.indexOf("beekeeper", "ee") == 1 +String.indexOf("bookseller", "xyz") == -1 +``` +*/ +@send +external indexOf: (string, string) => int = "indexOf" -/** Return a copy of the argument, with special characters - represented by escape sequences, following the lexical - conventions of OCaml. - All characters outside the ASCII printable range (32..126) are - escaped, as well as backslash and double-quote. +/** +`indexOfOpt(str, searchValue)`. Like `indexOf`, but return an `option`. - If there is no special character in the argument that needs - escaping, return the original string itself, not a copy. +## Examples - Raise [Invalid_argument] if the result is longer than - {!Sys.max_string_length} bytes. +```rescript +String.indexOfOpt("bookseller", "ok") == Some(2) +String.indexOfOpt("bookseller", "xyz") == None +``` +*/ +let indexOfOpt: (string, string) => option + +/** +`indexOfFrom(str, searchValue, start)` returns the position at which +`searchValue` was found within `str` starting at character position `start`, or +`-1` if `searchValue` is not found in that portion of `str`. The return value is +relative to the beginning of the string, no matter where the search started +from. +See [`String.indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) on MDN. + +## Examples + +```rescript +String.indexOfFrom("bookseller", "ok", 1) == 2 +String.indexOfFrom("bookseller", "sell", 2) == 4 +String.indexOfFrom("bookseller", "sell", 5) == -1 +``` +*/ +@send +external indexOfFrom: (string, string, int) => int = "indexOf" + +/** +`lastIndexOf(str, searchValue)` returns the position of the last occurrence of +`searchValue` within `str`, searching backwards from the end of the string. +Returns `-1` if `searchValue` is not in `str`. The return value is always +relative to the beginning of the string. +See [`String.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) on MDN. + +## Examples + +```rescript +String.lastIndexOf("bookseller", "ok") == 2 +String.lastIndexOf("beekeeper", "ee") == 4 +String.lastIndexOf("abcdefg", "xyz") == -1 +``` +*/ +@send +external lastIndexOf: (string, string) => int = "lastIndexOf" - The function {!Scanf.unescaped} is a left inverse of [escaped], - i.e. [Scanf.unescaped (escaped s) = s] for any string [s] (unless - [escape s] fails). */ -let escaped: string => string +/** +`lastIndexOfOpt(str, searchValue)`. Like `lastIndexOfOpt`, but return an +`option`. -/** [String.index s c] returns the index of the first - occurrence of character [c] in string [s]. +## Examples - Raise [Not_found] if [c] does not occur in [s]. */ -let index: (string, char) => int +```rescript +String.lastIndexOfOpt("bookseller", "ok") == Some(2) +String.lastIndexOfOpt("beekeeper", "ee") == Some(4) +String.lastIndexOfOpt("abcdefg", "xyz") == None +``` +*/ +let lastIndexOfOpt: (string, string) => option + +/** +`lastIndexOfFrom(str, searchValue, start)` returns the position of the last +occurrence of `searchValue` within `str`, searching backwards from the given +start position. Returns `-1` if `searchValue` is not in `str`. The return value +is always relative to the beginning of the string. +See [`String.lastIndexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) on MDN. + +## Examples + +```rescript +String.lastIndexOfFrom("bookseller", "ok", 6) == 2 +String.lastIndexOfFrom("beekeeper", "ee", 8) == 4 +String.lastIndexOfFrom("beekeeper", "ee", 3) == 1 +String.lastIndexOfFrom("abcdefg", "xyz", 4) == -1 +``` +*/ +@send +external lastIndexOfFrom: (string, string, int) => int = "lastIndexOf" + +/** +`match(str, regexp)` matches a `string` against the given `regexp`. If there is +no match, it returns `None`. For regular expressions without the g modifier, if +there is a match, the return value is `Some(array)` where the array contains: +- The entire matched string +- Any capture groups if the regexp had parentheses +For regular expressions with the g modifier, a matched expression returns +`Some(array)` with all the matched substrings and no capture groups. +See [`String.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) on MDN. + +## Examples + +```rescript +String.match("The better bats", %re("/b[aeiou]t/")) == Some(["bet"]) +String.match("The better bats", %re("/b[aeiou]t/g")) == Some(["bet", "bat"]) +String.match("Today is 2018-04-05.", %re("/(\d+)-(\d+)-(\d+)/")) == + Some(["2018-04-05", "2018", "04", "05"]) +String.match("The large container.", %re("/b[aeiou]g/")) == None +``` +*/ +@return(nullable) +@send +external match: (string, RegExp.t) => option = "match" + +/** +`normalize(str)` returns the normalized Unicode string using Normalization Form +Canonical (NFC) Composition. Consider the character ã, which can be represented +as the single codepoint \u00e3 or the combination of a lower case letter A +\u0061 and a combining tilde \u0303. Normalization ensures that both can be +stored in an equivalent binary representation. +See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. +See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for details. + +## Examples + +```rescript +let string1 = "\uFB00" +let string2 = "\u0066\u0066" +Console.log(string1 === string2) // false + +let normalizeString1 = String.normalize(string1) +let normalizeString2 = String.normalize(string2) +assert(normalizeString1 === normalizeString2) +``` +*/ +@send +external normalize: string => string = "normalize" + +/** +`normalizeByForm(str, form)` returns the normalized Unicode string using the +specified form of normalization, which may be one of: +- "NFC" — Normalization Form Canonical Composition. +- "NFD" — Normalization Form Canonical Decomposition. +- "NFKC" — Normalization Form Compatibility Composition. +- "NFKD" — Normalization Form Compatibility Decomposition. +See [`String.normalize`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize) on MDN. +See also [Unicode technical report #15](https://unicode.org/reports/tr15/) for +details. + +## Examples + +```rescript +let string1 = "\uFB00" +let string2 = "\u0066\u0066" +Console.log(string1 == string2) // false + +let normalizeString1 = String.normalizeByForm(string1, #NFKD) +let normalizeString2 = String.normalizeByForm(string2, #NFKD) +Console.log(normalizeString1 == normalizeString2) // true +``` +*/ +type normalizeForm = [#NFC | #NFD | #NFKC | #NFKD] +@send +external normalizeByForm: (string, normalizeForm) => string = "normalize" + +/** +`repeat(str, n)` returns a `string` that consists of `n` repetitions of `str`. +See [`String.repeat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) on MDN. -/** [String.index_opt s c] returns the index of the first - occurrence of character [c] in string [s], or - [None] if [c] does not occur in [s]. - @since 4.05 */ -let index_opt: (string, char) => option +## Examples -/** [String.rindex s c] returns the index of the last - occurrence of character [c] in string [s]. +```rescript +String.repeat("ha", 3) == "hahaha" +String.repeat("empty", 0) == "" +``` - Raise [Not_found] if [c] does not occur in [s]. */ -let rindex: (string, char) => int +## Exceptions -/** [String.rindex_opt s c] returns the index of the last occurrence - of character [c] in string [s], or [None] if [c] does not occur in - [s]. - @since 4.05 */ -let rindex_opt: (string, char) => option +- `RangeError`: if `n` is negative. +*/ +@send +external repeat: (string, int) => string = "repeat" + +/** +`replace(str, substr, newSubstr)` returns a new `string` which is +identical to `str` except with the first matching instance of `substr` replaced +by `newSubstr`. `substr` is treated as a verbatim string to match, not a +regular expression. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. + +## Examples + +```rescript +String.replace("old string", "old", "new") == "new string" +String.replace("the cat and the dog", "the", "this") == "this cat and the dog" +``` +*/ +@send +external replace: (string, string, string) => string = "replace" -/** [String.index_from s i c] returns the index of the - first occurrence of character [c] in string [s] after position [i]. - [String.index s c] is equivalent to [String.index_from s 0 c]. +/** +`replaceRegExp(str, regex, replacement)` returns a new `string` where +occurrences matching regex have been replaced by `replacement`. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. - Raise [Invalid_argument] if [i] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] after position [i]. */ -let index_from: (string, int, char) => int +## Examples -/** [String.index_from_opt s i c] returns the index of the - first occurrence of character [c] in string [s] after position [i] - or [None] if [c] does not occur in [s] after position [i]. +```rescript +String.replaceRegExp("vowels be gone", %re("/[aeiou]/g"), "x") == "vxwxls bx gxnx" +String.replaceRegExp("Juan Fulano", %re("/(\w+) (\w+)/"), "$2, $1") == "Fulano, Juan" +``` +*/ +@send +external replaceRegExp: (string, RegExp.t, string) => string = "replace" + +/** +`replaceAll(str, substr, newSubstr)` returns a new `string` which is +identical to `str` except with all matching instances of `substr` replaced +by `newSubstr`. `substr` is treated as a verbatim string to match, not a +regular expression. +See [`String.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) on MDN. + +## Examples + +```rescript +String.replaceAll("old old string", "old", "new") == "new new string" +String.replaceAll("the cat and the dog", "the", "this") == "this cat and this dog" +``` +*/ +@send +external replaceAll: (string, string, string) => string = "replaceAll" - [String.index_opt s c] is equivalent to [String.index_from_opt s 0 c]. - Raise [Invalid_argument] if [i] is not a valid position in [s]. +/** +`replaceAllRegExp(str, regex, replacement)` returns a new `string` where +all occurrences matching regex have been replaced by `replacement`. +The pattern must include the global (`g`) flag or a runtime TypeError will be thrown. +See [`String.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) on MDN. - @since 4.05 +## Examples + +```rescript +String.replaceAllRegExp("vowels be gone", %re("/[aeiou]/g"), "x") == "vxwxls bx gxnx" +String.replaceAllRegExp("aabbcc", %re("/b/g"), ".") == "aa..cc" +``` +*/ +@send +external replaceAllRegExp: (string, RegExp.t, string) => string = "replaceAll" + +/** +`unsafeReplaceRegExpBy0(str, regex, f)` returns a new `string` with some or all +matches of a pattern with no capturing parentheses replaced by the value +returned from the given function. The function receives as its parameters the +matched string, the offset at which the match begins, and the whole string being +matched. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. + +## Examples + +```rescript +let str = "beautiful vowels" +let re = %re("/[aeiou]/g") +let matchFn = (~match, ~offset as _, ~input as _) => String.toUpperCase(match) +String.unsafeReplaceRegExpBy0(str, re, matchFn) == "bEAUtIfUl vOwEls" +``` +*/ +@send +external unsafeReplaceRegExpBy0: ( + string, + RegExp.t, + (~match: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +/** +`unsafeReplaceRegExpBy1(str, regexp, f)`. Like `unsafeReplaceRegExpBy0`, but `f` +has `group1` parameter. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. + +## Examples + +```rescript +let str = "Jony is 40" +let re = %re("/(Jony is )\d+/g") +let matchFn = (~match as _, ~group1, ~offset as _, ~input as _) => { + group1 ++ "41" +} +String.unsafeReplaceRegExpBy1(str, re, matchFn) == "Jony is 41" +``` +*/ +@send +external unsafeReplaceRegExpBy1: ( + string, + RegExp.t, + (~match: string, ~group1: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +/** +`unsafeReplaceRegExpBy2(str, regexp, f)`. Like `unsafeReplaceRegExpBy1`, but `f` +has two group parameters. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. + +## Examples + +```rescript +let str = "7 times 6" +let re = %re("/(\d+) times (\d+)/") +let matchFn = (~match as _, ~group1, ~group2, ~offset as _, ~input as _) => { + switch (Int.fromString(group1), Int.fromString(group2)) { + | (Some(x), Some(y)) => Int.toString(x * y) + | _ => "???" + } +} +String.unsafeReplaceRegExpBy2(str, re, matchFn) == "42" +``` +*/ +@send +external unsafeReplaceRegExpBy2: ( + string, + RegExp.t, + (~match: string, ~group1: string, ~group2: string, ~offset: int, ~input: string) => string, +) => string = "replace" + +/** +`unsafeReplaceRegExpBy3(str, regexp, f)`. Like `unsafeReplaceRegExpBy1`, but `f` +has three group parameters. +See [`String.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) on MDN. */ -let index_from_opt: (string, int, char) => option +@send +external unsafeReplaceRegExpBy3: ( + string, + RegExp.t, + ( + ~match: string, + ~group1: string, + ~group2: string, + ~group3: string, + ~offset: int, + ~input: string, + ) => string, +) => string = "replace" + +/** +`search(str, regexp)` returns the starting position of the first match of +`regexp` in the given `str`, or -1 if there is no match. +See [`String.search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) on MDN. + +## Examples + +```rescript +String.search("testing 1 2 3", %re("/\d+/")) == 8 +String.search("no numbers", %re("/\d+/")) == -1 +``` +*/ +@send +external search: (string, RegExp.t) => int = "search" -/** [String.rindex_from s i c] returns the index of the - last occurrence of character [c] in string [s] before position [i+1]. - [String.rindex s c] is equivalent to - [String.rindex_from s (String.length s - 1) c]. +/** +`searchOpt(str, regexp)`. Like `search`, but return an `option`. - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] before position [i+1]. */ -let rindex_from: (string, int, char) => int +## Examples -/** [String.rindex_from_opt s i c] returns the index of the - last occurrence of character [c] in string [s] before position [i+1] - or [None] if [c] does not occur in [s] before position [i+1]. +```rescript +String.searchOpt("testing 1 2 3", %re("/\d+/")) == Some(8) +String.searchOpt("no numbers", %re("/\d+/")) == None +``` +*/ +let searchOpt: (string, RegExp.t) => option + +/** +`slice(str, ~start, ~end)` returns the substring of `str` starting at +character `start` up to but not including `end`. +- If either `start` or `end` is negative, then it is evaluated as +`length(str - start)` or `length(str - end)`. +- If `end` is greater than the length of `str`, then it is treated as +`length(str)`. +- If `start` is greater than `end`, slice returns the empty string. +See [`String.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) on MDN. + +## Examples + +```rescript +String.slice("abcdefg", ~start=2, ~end=5) == "cde" +String.slice("abcdefg", ~start=2, ~end=9) == "cdefg" +String.slice("abcdefg", ~start=-4, ~end=-2) == "de" +String.slice("abcdefg", ~start=5, ~end=1) == "" +``` +*/ +@send +external slice: (string, ~start: int, ~end: int) => string = "slice" + +/** +`sliceToEnd(str, ~start)` returns the substring of `str` starting at character +`start` to the end of the string. +- If `start` is negative, then it is evaluated as `length(str - start)`. +- If `start` is greater than the length of `str`, then sliceToEnd returns the empty string. +See [`String.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) on MDN. + +## Examples + +```rescript +String.sliceToEnd("abcdefg", ~start=4) == "efg" +String.sliceToEnd("abcdefg", ~start=-2) == "fg" +String.sliceToEnd("abcdefg", ~start=7) == "" +``` +*/ +@send +external sliceToEnd: (string, ~start: int) => string = "slice" + +/** +`split(str, delimiter)` splits the given `str` at every occurrence of +`delimiter` and returns an array of the resulting substrings. +See [`String.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) on MDN. + +## Examples + +```rescript +String.split("2018-01-02", "-") == ["2018", "01", "02"] +String.split("a,b,,c", ",") == ["a", "b", "", "c"] +String.split("good::bad as great::awful", "::") == ["good", "bad as great", "awful"] +String.split("has-no-delimiter", ";") == ["has-no-delimiter"] +``` +*/ +@send +external split: (string, string) => array = "split" + +/** +`splitAtMost(str, delimiter, ~limit)` splits the given `str` at every +occurrence of `delimiter` and returns an array of the first `limit` resulting +substrings. If `limit` is negative or greater than the number of substrings, +the array will contain all the substrings. + +## Examples + +```rescript +String.splitAtMost("ant/bee/cat/dog/elk", "/", ~limit=3) == ["ant", "bee", "cat"] +String.splitAtMost("ant/bee/cat/dog/elk", "/", ~limit=0) == [] +String.splitAtMost("ant/bee/cat/dog/elk", "/", ~limit=9) == ["ant", "bee", "cat", "dog", "elk"] +``` +*/ +@send +external splitAtMost: (string, string, ~limit: int) => array = "split" - [String.rindex_opt s c] is equivalent to - [String.rindex_from_opt s (String.length s - 1) c]. +/** +`splitByRegExp(str, regexp)` splits the given `str` at every occurrence of +`regexp` and returns an array of the resulting substrings. +See [`String.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) on MDN. - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. +## Examples - @since 4.05 +```rescript +String.splitByRegExp("Jan,Feb,Mar", %re("/,/")) == [Some("Jan"), Some("Feb"), Some("Mar")] +``` */ -let rindex_from_opt: (string, int, char) => option +@send +external splitByRegExp: (string, RegExp.t) => array> = "split" + +/** +`splitByRegExpAtMost(str, regexp, ~limit)` splits the given `str` at every +occurrence of `regexp` and returns an array of the first `limit` resulting +substrings. If `limit` is negative or greater than the number of substrings, the +array will contain all the substrings. +See [`String.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) on MDN. + +## Examples + +```rescript +String.splitByRegExpAtMost("Hello World. How are you doing?", %re("/ /"), ~limit=3) == [ + Some("Hello"), + Some("World."), + Some("How"), +] +``` +*/ +@send +external splitByRegExpAtMost: (string, RegExp.t, ~limit: int) => array> = "split" + +/** +`startsWith(str, substr)` returns `true` if the `str` starts with `substr`, +`false` otherwise. +See [`String.startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) on MDN. -/** [String.contains s c] tests if character [c] - appears in the string [s]. */ -let contains: (string, char) => bool +## Examples -/** [String.contains_from s start c] tests if character [c] - appears in [s] after position [start]. - [String.contains s c] is equivalent to - [String.contains_from s 0 c]. +```rescript +String.startsWith("BuckleScript", "Buckle") == true +String.startsWith("BuckleScript", "") == true +String.startsWith("JavaScript", "Buckle") == false +``` +*/ +@send +external startsWith: (string, string) => bool = "startsWith" + +/** +`startsWithFrom(str, substr, n)` returns `true` if the `str` starts +with `substr` starting at position `n`, `false` otherwise. If `n` is negative, +the search starts at the beginning of `str`. +See [`String.startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) on MDN. + +## Examples + +```rescript +String.startsWithFrom("BuckleScript", "kle", 3) == true +String.startsWithFrom("BuckleScript", "", 3) == true +String.startsWithFrom("JavaScript", "Buckle", 2) == false +``` +*/ +@send +external startsWithFrom: (string, string, int) => bool = "startsWith" + +/** +`substring(str, ~start, ~end)` returns characters `start` up to but not +including end from `str`. +- If `start` is less than zero, it is treated as zero. +- If `end` is zero or negative, the empty string is returned. +- If `start` is greater than `end`, the `start` and `end` points are swapped. +See [`String.substring`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) on MDN. + +## Examples + +```rescript +String.substring("playground", ~start=3, ~end=6) == "ygr" +String.substring("playground", ~start=6, ~end=3) == "ygr" +String.substring("playground", ~start=4, ~end=12) == "ground" +``` +*/ +@send +external substring: (string, ~start: int, ~end: int) => string = "substring" + +/** +`substringToEnd(str, ~start)` returns the substring of `str` from position +`start` to the end. +- If `start` is less than or equal to zero, the entire string is returned. +- If `start` is greater than or equal to the length of `str`, the empty string +is returned. +See [`String.substring`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) on MDN. + +## Examples + +```rescript +String.substringToEnd("playground", ~start=4) == "ground" +String.substringToEnd("playground", ~start=-3) == "playground" +String.substringToEnd("playground", ~start=12) == "" +``` +*/ +@send +external substringToEnd: (string, ~start: int) => string = "substring" + +/** +`toLowerCase(str)` converts `str` to lower case using the locale-insensitive +case mappings in the Unicode Character Database. Notice that the conversion can +give different results depending upon context, for example with the Greek +letter sigma, which has two different lower case forms, one when it is the last +character in a string and another when it is not. +See [`String.toLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) on MDN. + +## Examples + +```rescript +String.toLowerCase("ABC") == "abc" +String.toLowerCase(`ΣΠ`) == `σπ` +String.toLowerCase(`ΠΣ`) == `πς` +``` +*/ +@send +external toLowerCase: string => string = "toLowerCase" - Raise [Invalid_argument] if [start] is not a valid position in [s]. */ -let contains_from: (string, int, char) => bool +/** +`toLocaleLowerCase(str)` converts `str` to lower case using the current locale. +See [`String.toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase) on MDN. +*/ +@send +external toLocaleLowerCase: string => string = "toLocaleLowerCase" + +/** +`toUpperCase(str)` converts `str` to upper case using the locale-insensitive +case mappings in the Unicode Character Database. Notice that the conversion can +expand the number of letters in the result, for example the German ß +capitalizes to two Ses in a row. +See [`String.toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) on MDN. + +## Examples + +```rescript +String.toUpperCase("abc") == "ABC" +String.toUpperCase(`Straße`) == `STRASSE` +String.toUpperCase(`πς`) == `ΠΣ` +``` +*/ +@send +external toUpperCase: string => string = "toUpperCase" -/** [String.rcontains_from s stop c] tests if character [c] - appears in [s] before position [stop+1]. +/** +`toLocaleUpperCase(str)` converts `str` to upper case using the current locale. +See [`String.toLocaleUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase) on MDN. +*/ +@send +external toLocaleUpperCase: string => string = "toLocaleUpperCase" - Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid - position in [s]. */ -let rcontains_from: (string, int, char) => bool +/** +`trim(str)` returns a string that is `str` with whitespace stripped from both +ends. Internal whitespace is not removed. +See [`String.trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim) on MDN. -/** Return a copy of the argument, with all lowercase letters - translated to uppercase, using the US-ASCII character set. - @since 4.03.0 */ -let uppercase_ascii: string => string +## Examples -/** Return a copy of the argument, with all uppercase letters - translated to lowercase, using the US-ASCII character set. - @since 4.03.0 */ -let lowercase_ascii: string => string +```rescript +String.trim(" abc def ") == "abc def" +String.trim("\n\r\t abc def \n\n\t\r ") == "abc def" +``` +*/ +@send +external trim: string => string = "trim" -/** Return a copy of the argument, with the first character set to uppercase, - using the US-ASCII character set. - @since 4.03.0 */ -let capitalize_ascii: string => string +/** +`trimStart(str)` returns a string that is `str` with whitespace stripped from +the beginning of a string. Internal whitespace is not removed. +See [`String.trimStart`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart) on MDN. -/** Return a copy of the argument, with the first character set to lowercase, - using the US-ASCII character set. - @since 4.03.0 */ -let uncapitalize_ascii: string => string +## Examples -/** An alias for the type of strings. */ -type t = string +```rescript +String.trimStart(" Hello world! ") == "Hello world! " +String.trimStart(" Hello world! ") == "Hello world! " +``` +*/ +@send +external trimStart: string => string = "trimStart" -/** The comparison function for strings, with the same specification as - {!Pervasives.compare}. Along with the type [t], this function [compare] - allows the module [String] to be passed as argument to the functors - {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int +/** +`trinEnd(str)` returns a string that is `str` with whitespace stripped from the +end of a string. Internal whitespace is not removed. +See [`String.trimEnd`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd) on MDN. -/** The equal function for strings. - @since 4.03.0 */ -let equal: (t, t) => bool +## Examples -/** [String.split_on_char sep s] returns the list of all (possibly empty) - substrings of [s] that are delimited by the [sep] character. +```rescript +String.trimEnd(" Hello world! ") == " Hello world!" +String.trimEnd(" Hello world! ") == " Hello world!" +``` +*/ +@send +external trimEnd: string => string = "trimEnd" - The function's output is specified by the following invariants: +/** +`padStart(str, n, padStr)` returns a string that has been padded with `padStr` +(multiple times, if needed) until the resulting string reaches the given `n` +length. The padding is applied from the start of the current string. +See [`String.padStart`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) on MDN. - - The list is not empty. - - Concatenating its elements using [sep] as a separator returns a - string equal to the input ([String.concat (String.make 1 sep) - (String.split_on_char sep s) = s]). - - No string in the result contains the [sep] character. +## Examples - @since 4.04.0 +```rescript +String.padStart("abc", 5, " ") == " abc" +String.padStart("abc", 6, "123465") == "123abc" +``` */ -let split_on_char: (char, string) => list +@send +external padStart: (string, int, string) => string = "padStart" + +/** +`padEnd(str, n, padStr)` returns a string that has been padded with `padStr` +(multiple times, if needed) until the resulting string reaches the given `n` +length. The padding is applied from the end of the current string. +See [`String.padEnd`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd) on MDN. -/* The following is for system use only. Do not call directly. */ +## Examples -external unsafe_get: (string, int) => char = "%string_unsafe_get" +```rescript +String.padEnd("Hello", 10, ".") == "Hello....." +String.padEnd("abc", 1, "") == "abc" +``` +*/ +@send +external padEnd: (string, int, string) => string = "padEnd" + +// TODO: add docs +@get_index external getSymbol: (string, Symbol.t) => option<'a> = "" +@get_index external getSymbolUnsafe: (string, Symbol.t) => 'a = "" +@set_index external setSymbol: (string, Symbol.t, 'a) => unit = "" + +/** +`localeCompare(referenceStr, compareStr)` returns a float than indicatings +whether a reference string comes before or after, or is the same as the given +string in sort order. If `referenceStr` occurs before `compareStr` positive if +the `referenceStr` occurs after `compareStr`, `0` if they are equivalent. +Do not rely on exact return values of `-1` or `1` +See [`String.localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) on MDN. + +## Examples + +```rescript +String.localeCompare("a", "c") < 0.0 == true +String.localeCompare("a", "a") == 0.0 +``` +*/ +@send +external localeCompare: (string, string) => float = "localeCompare" diff --git a/jscomp/stdlib-406/stringLabels.res b/jscomp/stdlib-406/stringLabels.res deleted file mode 100644 index a9ea486d14..0000000000 --- a/jscomp/stdlib-406/stringLabels.res +++ /dev/null @@ -1,235 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Damien Doligez, projet Gallium, INRIA Rocquencourt */ -/* */ -/* Copyright 2014 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* String operations, based on byte sequence operations */ - -/* WARNING: Some functions in this file are duplicated in bytes.ml for - efficiency reasons. When you modify the one in this file you need to - modify its duplicate in bytes.ml. - These functions have a "duplicated" comment above their definition. -*/ - -external length: string => int = "%string_length" -external get: (string, int) => char = "%string_safe_get" -external unsafe_get: (string, int) => char = "%string_unsafe_get" - -module B = Bytes - -let bts = B.unsafe_to_string -let bos = B.unsafe_of_string - -external make: (int, char) => string = "?string_repeat" - -let init = (n, ~f) => bts(B.init(n, f)) -let sub = (s, ~pos as ofs, ~len) => bts(B.sub(bos(s), ofs, len)) -let blit = (~src, ~src_pos, ~dst, ~dst_pos, ~len) => B.blit_string(src, src_pos, dst, dst_pos, len) - -%%private(@send external join: (array, string) => string = "join") - -let concat = (~sep: string, xs: list) => xs->Array.of_list->join(sep) - -/* duplicated in bytes.ml */ -let iter = (~f, s) => - for i in 0 to length(s) - 1 { - f(unsafe_get(s, i)) - } - -/* duplicated in bytes.ml */ -let iteri = (~f, s) => - for i in 0 to length(s) - 1 { - f(i, unsafe_get(s, i)) - } - -let map = (~f, s) => bts(B.map(f, bos(s))) -let mapi = (~f, s) => bts(B.mapi(f, bos(s))) - -/* Beware: we cannot use B.trim or B.escape because they always make a - copy, but String.mli spells out some cases where we are not allowed - to make a copy. */ - -let is_space = param => - switch param { - | ' ' | ' ' | '\n' | '\r' | '\t' => true - | _ => false - } - -let trim = s => - if s == "" { - s - } else if is_space(unsafe_get(s, 0)) || is_space(unsafe_get(s, length(s) - 1)) { - bts(B.trim(bos(s))) - } else { - s - } - -let escaped = s => { - let rec needs_escape = i => - if i >= length(s) { - false - } else { - switch unsafe_get(s, i) { - | '"' | '\\' | '\n' | '\t' | '\r' | '\b' => true - | ' ' .. '~' => needs_escape(i + 1) - | _ => true - } - } - - if needs_escape(0) { - bts(B.escaped(bos(s))) - } else { - s - } -} - -/* duplicated in bytes.ml */ -let rec index_rec = (s, lim, i, c) => - if i >= lim { - raise(Not_found) - } else if unsafe_get(s, i) == c { - i - } else { - index_rec(s, lim, i + 1, c) - } - -/* duplicated in bytes.ml */ -let index = (s, c) => index_rec(s, length(s), 0, c) - -/* duplicated in bytes.ml */ -let rec index_rec_opt = (s, lim, i, c) => - if i >= lim { - None - } else if unsafe_get(s, i) == c { - Some(i) - } else { - index_rec_opt(s, lim, i + 1, c) - } - -/* duplicated in bytes.ml */ -let index_opt = (s, c) => index_rec_opt(s, length(s), 0, c) - -/* duplicated in bytes.ml */ -let index_from = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.index_from / Bytes.index_from") - } else { - index_rec(s, l, i, c) - } -} - -/* duplicated in bytes.ml */ -let index_from_opt = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.index_from_opt / Bytes.index_from_opt") - } else { - index_rec_opt(s, l, i, c) - } -} - -/* duplicated in bytes.ml */ -let rec rindex_rec = (s, i, c) => - if i < 0 { - raise(Not_found) - } else if unsafe_get(s, i) == c { - i - } else { - rindex_rec(s, i - 1, c) - } - -/* duplicated in bytes.ml */ -let rindex = (s, c) => rindex_rec(s, length(s) - 1, c) - -/* duplicated in bytes.ml */ -let rindex_from = (s, i, c) => - if i < -1 || i >= length(s) { - invalid_arg("String.rindex_from / Bytes.rindex_from") - } else { - rindex_rec(s, i, c) - } - -/* duplicated in bytes.ml */ -let rec rindex_rec_opt = (s, i, c) => - if i < 0 { - None - } else if unsafe_get(s, i) == c { - Some(i) - } else { - rindex_rec_opt(s, i - 1, c) - } - -/* duplicated in bytes.ml */ -let rindex_opt = (s, c) => rindex_rec_opt(s, length(s) - 1, c) - -/* duplicated in bytes.ml */ -let rindex_from_opt = (s, i, c) => - if i < -1 || i >= length(s) { - invalid_arg("String.rindex_from_opt / Bytes.rindex_from_opt") - } else { - rindex_rec_opt(s, i, c) - } - -/* duplicated in bytes.ml */ -let contains_from = (s, i, c) => { - let l = length(s) - if i < 0 || i > l { - invalid_arg("String.contains_from / Bytes.contains_from") - } else { - try { - ignore(index_rec(s, l, i, c)) - true - } catch { - | Not_found => false - } - } -} - -/* duplicated in bytes.ml */ -let contains = (s, c) => contains_from(s, 0, c) - -/* duplicated in bytes.ml */ -let rcontains_from = (s, i, c) => - if i < 0 || i >= length(s) { - invalid_arg("String.rcontains_from / Bytes.rcontains_from") - } else { - try { - ignore(rindex_rec(s, i, c)) - true - } catch { - | Not_found => false - } - } - -let uppercase_ascii = s => bts(B.uppercase_ascii(bos(s))) -let lowercase_ascii = s => bts(B.lowercase_ascii(bos(s))) -let capitalize_ascii = s => bts(B.capitalize_ascii(bos(s))) -let uncapitalize_ascii = s => bts(B.uncapitalize_ascii(bos(s))) - -type t = string - -let compare = (x: t, y: t) => Pervasives.compare(x, y) -let equal: (string, string) => bool = (a, b) => a == b - -let split_on_char = (~sep, s) => { - let r = ref(list{}) - let j = ref(length(s)) - for i in length(s) - 1 downto 0 { - if unsafe_get(s, i) == sep { - r := list{sub(s, ~pos=i + 1, ~len=j.contents - i - 1), ...r.contents} - j := i - } - } - list{sub(s, ~pos=0, ~len=j.contents), ...r.contents} -} diff --git a/jscomp/stdlib-406/stringLabels.resi b/jscomp/stdlib-406/stringLabels.resi deleted file mode 100644 index 2886ac2a44..0000000000 --- a/jscomp/stdlib-406/stringLabels.resi +++ /dev/null @@ -1,233 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** String operations. */ - -/** Return the length (number of characters) of the given string. */ -external length: string => int = "%string_length" - -/** [String.get s n] returns the character at index [n] in string [s]. - You can also write [s.[n]] instead of [String.get s n]. - - Raise [Invalid_argument] if [n] not a valid index in [s]. */ -external get: (string, int) => char = "%string_safe_get" - -/** [String.make n c] returns a fresh string of length [n], - filled with the character [c]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. */ -let make: (int, char) => string - -/** [init n f] returns a string of length [n], - with character [i] initialized to the result of [f i]. - - Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. - @since 4.02.0 */ -let init: (int, ~f: int => char) => string - -/** [String.sub s start len] returns a fresh string of length [len], - containing the substring of [s] that starts at position [start] and - has length [len]. - - Raise [Invalid_argument] if [start] and [len] do not - designate a valid substring of [s]. */ -let sub: (string, ~pos: int, ~len: int) => string - -/** [String.blit src srcoff dst dstoff len] copies [len] bytes - from the string [src], starting at index [srcoff], - to byte sequence [dst], starting at character number [dstoff]. - - Raise [Invalid_argument] if [srcoff] and [len] do not - designate a valid range of [src], or if [dstoff] and [len] - do not designate a valid range of [dst]. */ -let blit: (~src: string, ~src_pos: int, ~dst: bytes, ~dst_pos: int, ~len: int) => unit - -/** [String.concat sep sl] concatenates the list of strings [sl], - inserting the separator string [sep] between each. */ -let concat: (~sep: string, list) => string - -/** [String.iter f s] applies function [f] in turn to all - the characters of [s]. It is equivalent to - [f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. */ -let iter: (~f: char => unit, string) => unit - -/** Same as {!String.iter}, but the - function is applied to the index of the element as first argument - (counting from 0), and the character itself as second argument. - @since 4.00.0 */ -let iteri: (~f: (int, char) => unit, string) => unit - -/** [String.map f s] applies function [f] in turn to all - the characters of [s] and stores the results in a new string that - is returned. - @since 4.00.0 */ -let map: (~f: char => char, string) => string - -/** [String.mapi f s] calls [f] with each character of [s] and its - index (in increasing index order) and stores the results in a new - string that is returned. - @since 4.02.0 */ -let mapi: (~f: (int, char) => char, string) => string - -/** Return a copy of the argument, without leading and trailing - whitespace. The characters regarded as whitespace are: [' '], - ['\x0c'], ['\n'], ['\r'], and ['\t']. If there is no leading nor - trailing whitespace character in the argument, return the original - string itself, not a copy. - @since 4.00.0 */ -let trim: string => string - -/** Return a copy of the argument, with special characters - represented by escape sequences, following the lexical - conventions of OCaml. If there is no special - character in the argument, return the original string itself, - not a copy. Its inverse function is Scanf.unescaped. */ -let escaped: string => string - -/** [String.index s c] returns the index of the first - occurrence of character [c] in string [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let index: (string, char) => int - -/** [String.index_opt s c] returns the index of the first - occurrence of character [c] in string [s], or - [None] if [c] does not occur in [s]. - @since 4.05 */ -let index_opt: (string, char) => option - -/** [String.rindex s c] returns the index of the last - occurrence of character [c] in string [s]. - - Raise [Not_found] if [c] does not occur in [s]. */ -let rindex: (string, char) => int - -/** [String.rindex_opt s c] returns the index of the last occurrence - of character [c] in string [s], or [None] if [c] does not occur in - [s]. - @since 4.05 */ -let rindex_opt: (string, char) => option - -/** [String.index_from s i c] returns the index of the - first occurrence of character [c] in string [s] after position [i]. - [String.index s c] is equivalent to [String.index_from s 0 c]. - - Raise [Invalid_argument] if [i] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] after position [i]. */ -let index_from: (string, int, char) => int - -/** [String.index_from_opt s i c] returns the index of the - first occurrence of character [c] in string [s] after position [i] - or [None] if [c] does not occur in [s] after position [i]. - - [String.index_opt s c] is equivalent to [String.index_from_opt s 0 c]. - Raise [Invalid_argument] if [i] is not a valid position in [s]. - - @since 4.05 -*/ -let index_from_opt: (string, int, char) => option - -/** [String.rindex_from s i c] returns the index of the - last occurrence of character [c] in string [s] before position [i+1]. - [String.rindex s c] is equivalent to - [String.rindex_from s (String.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - Raise [Not_found] if [c] does not occur in [s] before position [i+1]. */ -let rindex_from: (string, int, char) => int - -/** [String.rindex_from_opt s i c] returns the index of the - last occurrence of character [c] in string [s] before position [i+1] - or [None] if [c] does not occur in [s] before position [i+1]. - - [String.rindex_opt s c] is equivalent to - [String.rindex_from_opt s (String.length s - 1) c]. - - Raise [Invalid_argument] if [i+1] is not a valid position in [s]. - - @since 4.05 -*/ -let rindex_from_opt: (string, int, char) => option - -/** [String.contains s c] tests if character [c] - appears in the string [s]. */ -let contains: (string, char) => bool - -/** [String.contains_from s start c] tests if character [c] - appears in [s] after position [start]. - [String.contains s c] is equivalent to - [String.contains_from s 0 c]. - - Raise [Invalid_argument] if [start] is not a valid position in [s]. */ -let contains_from: (string, int, char) => bool - -/** [String.rcontains_from s stop c] tests if character [c] - appears in [s] before position [stop+1]. - - Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid - position in [s]. */ -let rcontains_from: (string, int, char) => bool - -/** Return a copy of the argument, with all lowercase letters - translated to uppercase, using the US-ASCII character set. - @since 4.05.0 */ -let uppercase_ascii: string => string - -/** Return a copy of the argument, with all uppercase letters - translated to lowercase, using the US-ASCII character set. - @since 4.05.0 */ -let lowercase_ascii: string => string - -/** Return a copy of the argument, with the first character set to uppercase, - using the US-ASCII character set. - @since 4.05.0 */ -let capitalize_ascii: string => string - -/** Return a copy of the argument, with the first character set to lowercase, - using the US-ASCII character set. - @since 4.05.0 */ -let uncapitalize_ascii: string => string - -/** An alias for the type of strings. */ -type t = string - -/** The comparison function for strings, with the same specification as - {!Pervasives.compare}. Along with the type [t], this function [compare] - allows the module [String] to be passed as argument to the functors - {!Set.Make} and {!Map.Make}. */ -let compare: (t, t) => int - -/** The equal function for strings. - @since 4.05.0 */ -let equal: (t, t) => bool - -/** [String.split_on_char sep s] returns the list of all (possibly empty) - substrings of [s] that are delimited by the [sep] character. - - The function's output is specified by the following invariants: - - - The list is not empty. - - Concatenating its elements using [sep] as a separator returns a - string equal to the input ([String.concat (String.make 1 sep) - (String.split_on_char sep s) = s]). - - No string in the result contains the [sep] character. - - @since 4.05.0 -*/ -let split_on_char: (~sep: char, string) => list - -/* The following is for system use only. Do not call directly. */ - -external unsafe_get: (string, int) => char = "%string_unsafe_get" diff --git a/jscomp/stdlib-406/symbol.res b/jscomp/stdlib-406/symbol.res new file mode 100644 index 0000000000..8b4c1b218d --- /dev/null +++ b/jscomp/stdlib-406/symbol.res @@ -0,0 +1,19 @@ +type t = Js.Types.symbol + +@val external make: string => t = "Symbol" +@val external getFor: string => t = "Symbol.for" +@val external keyFor: t => option = "Symbol.keyFor" + +@val external asyncIterator: t = "Symbol.asyncIterator" +@val external hasInstance: t = "Symbol.hasInstance" +@val external isConcatSpreadable: t = "Symbol.isConcatSpreadable" +@val external iterator: t = "Symbol.iterator" +@val external match: t = "Symbol.match" +@val external matchAll: t = "Symbol.matchAll" +@val external replace: t = "Symbol.replace" +@val external search: t = "Symbol.search" +@val external species: t = "Symbol.species" +@val external split: t = "Symbol.split" +@val external toPrimitive: t = "Symbol.toPrimitive" +@val external toStringTag: t = "Symbol.toStringTag" +@val external unscopables: t = "Symbol.unscopables" diff --git a/jscomp/stdlib-406/sys.res b/jscomp/stdlib-406/sys.res deleted file mode 100644 index 947c892f61..0000000000 --- a/jscomp/stdlib-406/sys.res +++ /dev/null @@ -1,131 +0,0 @@ -@@config({flags: ["-bs-no-cross-module-opt"]}) -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/* WARNING: sys.ml is generated from sys.mlp. DO NOT EDIT sys.ml or - your changes will be lost. -*/ - -type backend_type = - | Native - | Bytecode - | Other(string) -/* System interface */ - -external get_argv: unit => (string, array) = "?sys_get_argv" -external big_endian: unit => bool = "%big_endian" -external word_size: unit => int = "%word_size" -external int_size: unit => int = "%int_size" -/* external max_wosize : unit -> int = "%max_wosize" */ -external unix: unit => bool = "%ostype_unix" -external win32: unit => bool = "%ostype_win32" -external cygwin: unit => bool = "%ostype_cygwin" -external get_backend_type: unit => backend_type = "%backend_type" - -let (executable_name, argv) = get_argv() - -external get_os_type: unit => string = "#os_type" -let os_type = get_os_type() -let backend_type = get_backend_type() -let big_endian = big_endian() -let word_size = word_size() -let int_size = int_size() -let unix = unix() -let win32 = win32() -let cygwin = cygwin() - -let max_array_length = 2147483647 /* 2^ 31 - 1 */ -let max_string_length = 2147483647 - -external runtime_variant: unit => string = "?runtime_variant" -external runtime_parameters: unit => string = "?runtime_parameters" - -external file_exists: string => bool = "?sys_file_exists" -external is_directory: string => bool = "?sys_is_directory" -external remove: string => unit = "?sys_remove" -external rename: (string, string) => unit = "?sys_rename" -external getenv: string => string = "?sys_getenv" - -@get_index external getEnv: ('a, string) => option = "" -let getenv_opt = s => - switch %external(process) { - | None => None - | Some(x) => getEnv(x["env"], s) - } - -let command: string => int = _ => 127 -external time: unit => float = "?sys_time" -external chdir: string => unit = "?sys_chdir" -external getcwd: unit => string = "?sys_getcwd" -external readdir: string => array = "?sys_read_directory" - -let interactive = ref(false) - -type signal_behavior = - | Signal_default - | Signal_ignore - | Signal_handle(int => unit) - -let signal: (int, signal_behavior) => signal_behavior = (_, _) => Signal_default - -let set_signal = (sig_num, sig_beh) => ignore(signal(sig_num, sig_beh)) - -let sigabrt = -1 -let sigalrm = -2 -let sigfpe = -3 -let sighup = -4 -let sigill = -5 -let sigint = -6 -let sigkill = -7 -let sigpipe = -8 -let sigquit = -9 -let sigsegv = -10 -let sigterm = -11 -let sigusr1 = -12 -let sigusr2 = -13 -let sigchld = -14 -let sigcont = -15 -let sigstop = -16 -let sigtstp = -17 -let sigttin = -18 -let sigttou = -19 -let sigvtalrm = -20 -let sigprof = -21 -let sigbus = -22 -let sigpoll = -23 -let sigsys = -24 -let sigtrap = -25 -let sigurg = -26 -let sigxcpu = -27 -let sigxfsz = -28 - -exception Break - -let catch_break = on => - if on { - set_signal(sigint, Signal_handle(_ => raise(Break))) - } else { - set_signal(sigint, Signal_default) - } - -let enable_runtime_warnings: bool => unit = _ => () -let runtime_warnings_enabled: unit => bool = _ => false -/* The version string is found in file ../VERSION */ - -let ocaml_version = "4.06.2+BS" - -/* Optimization */ - -external opaque_identity: 'a => 'a = "%opaque" diff --git a/jscomp/stdlib-406/sys.resi b/jscomp/stdlib-406/sys.resi deleted file mode 100644 index 544b6434ad..0000000000 --- a/jscomp/stdlib-406/sys.resi +++ /dev/null @@ -1,323 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ -/* */ -/* Copyright 1996 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** System interface. - - Every function in this module raises [Sys_error] with an - informative message when the underlying system call signal - an error. -*/ - -/** The command line arguments given to the process. - The first element is the command name used to invoke the program. - The following elements are the command-line arguments - given to the program. */ -let argv: array - -/** The name of the file containing the executable currently running. */ -let executable_name: string - -/** Test if a file with the given name exists. */ -external file_exists: string => bool = "?sys_file_exists" - -/** Returns [true] if the given name refers to a directory, - [false] if it refers to another kind of file. - Raise [Sys_error] if no file exists with the given name. - @since 3.10.0 -*/ -external is_directory: string => bool = "?sys_is_directory" - -/** Remove the given file name from the file system. */ -external remove: string => unit = "?sys_remove" - -/** Rename a file. [rename oldpath newpath] renames the file - called [oldpath], giving it [newpath] as its new name, - moving it between directories if needed. If [newpath] already - exists, its contents will be replaced with those of [oldpath]. - Depending on the operating system, the metadata (permissions, - owner, etc) of [newpath] can either be preserved or be replaced by - those of [oldpath]. - @since 4.06 concerning the "replace existing file" behavior */ -external rename: (string, string) => unit = "?sys_rename" - -/** Return the value associated to a variable in the process - environment. Raise [Not_found] if the variable is unbound. */ -external getenv: string => string = "?sys_getenv" - -/** Return the value associated to a variable in the process - environment or [None] if the variable is unbound. - @since 4.05 -*/ -let getenv_opt: string => option - -/** Execute the given shell command and return its exit code. */ -let command: string => int - -/** Return the processor time, in seconds, used by the program - since the beginning of execution. */ -external time: unit => float = "?sys_time" - -/** Change the current working directory of the process. */ -external chdir: string => unit = "?sys_chdir" - -/** Return the current working directory of the process. */ -external getcwd: unit => string = "?sys_getcwd" - -/** Return the names of all files present in the given directory. - Names denoting the current directory and the parent directory - (["."] and [".."] in Unix) are not returned. Each string in the - result is a file name rather than a complete path. There is no - guarantee that the name strings in the resulting array will appear - in any specific order; they are not, in particular, guaranteed to - appear in alphabetical order. */ -external readdir: string => array = "?sys_read_directory" - -/** This reference is initially set to [false] in standalone - programs and to [true] if the code is being executed under - the interactive toplevel system [ocaml]. */ -let interactive: ref - -/** Operating system currently executing the OCaml program. One of -- ["Unix"] (for all Unix versions, including Linux and Mac OS X), -- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw), -- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). */ -let os_type: string - -/** Currently, the official distribution only supports [Native] and - [Bytecode], but it can be other backends with alternative - compilers, for example, javascript. - - @since 4.04.0 -*/ -type backend_type = - | Native - | Bytecode - | Other(string) - -/** Backend type currently executing the OCaml program. - @since 4.04.0 - */ -let backend_type: backend_type - -/** True if [Sys.os_type = "Unix"]. - @since 4.01.0 */ -let unix: bool - -/** True if [Sys.os_type = "Win32"]. - @since 4.01.0 */ -let win32: bool - -/** True if [Sys.os_type = "Cygwin"]. - @since 4.01.0 */ -let cygwin: bool - -/** Size of one word on the machine currently executing the OCaml - program, in bits: 32 or 64. */ -let word_size: int - -/** Size of an int. It is 31 bits (resp. 63 bits) when using the - OCaml compiler on a 32 bits (resp. 64 bits) platform. It may - differ for other compilers, e.g. it is 32 bits when compiling to - JavaScript. - @since 4.03.0 */ -let int_size: int - -/** Whether the machine currently executing the Caml program is big-endian. - @since 4.00.0 */ -let big_endian: bool - -/** Maximum length of strings and byte sequences. */ -let max_string_length: int - -/** Maximum length of a normal array. The maximum length of a float - array is [max_array_length/2] on 32-bit machines and - [max_array_length] on 64-bit machines. */ -let max_array_length: int - -/** Return the name of the runtime variant the program is running on. - This is normally the argument given to [-runtime-variant] at compile - time, but for byte-code it can be changed after compilation. - @since 4.03.0 */ -external runtime_variant: unit => string = "?runtime_variant" - -/** Return the value of the runtime parameters, in the same format - as the contents of the [OCAMLRUNPARAM] environment variable. - @since 4.03.0 */ -external runtime_parameters: unit => string = "?runtime_parameters" - -/* {1 Signal handling} */ - -/** What to do when receiving a signal: - - [Signal_default]: take the default behavior - (usually: abort the program) - - [Signal_ignore]: ignore the signal - - [Signal_handle f]: call function [f], giving it the signal - number as argument. */ -type signal_behavior = - | Signal_default - | Signal_ignore - | /** */ Signal_handle(int => unit) - -/** Set the behavior of the system on receipt of a given signal. The - first argument is the signal number. Return the behavior - previously associated with the signal. If the signal number is - invalid (or not available on your system), an [Invalid_argument] - exception is raised. */ -let signal: (int, signal_behavior) => signal_behavior - -/** Same as {!Sys.signal} but return value is ignored. */ -let set_signal: (int, signal_behavior) => unit - -/* {2 Signal numbers for the standard POSIX signals.} */ - -/** Abnormal termination */ -let sigabrt: int - -/** Timeout */ -let sigalrm: int - -/** Arithmetic exception */ -let sigfpe: int - -/** Hangup on controlling terminal */ -let sighup: int - -/** Invalid hardware instruction */ -let sigill: int - -/** Interactive interrupt (ctrl-C) */ -let sigint: int - -/** Termination (cannot be ignored) */ -let sigkill: int - -/** Broken pipe */ -let sigpipe: int - -/** Interactive termination */ -let sigquit: int - -/** Invalid memory reference */ -let sigsegv: int - -/** Termination */ -let sigterm: int - -/** Application-defined signal 1 */ -let sigusr1: int - -/** Application-defined signal 2 */ -let sigusr2: int - -/** Child process terminated */ -let sigchld: int - -/** Continue */ -let sigcont: int - -/** Stop */ -let sigstop: int - -/** Interactive stop */ -let sigtstp: int - -/** Terminal read from background process */ -let sigttin: int - -/** Terminal write from background process */ -let sigttou: int - -/** Timeout in virtual time */ -let sigvtalrm: int - -/** Profiling interrupt */ -let sigprof: int - -/** Bus error - @since 4.03 */ -let sigbus: int - -/** Pollable event - @since 4.03 */ -let sigpoll: int - -/** Bad argument to routine - @since 4.03 */ -let sigsys: int - -/** Trace/breakpoint trap - @since 4.03 */ -let sigtrap: int - -/** Urgent condition on socket - @since 4.03 */ -let sigurg: int - -/** Timeout in cpu time - @since 4.03 */ -let sigxcpu: int - -/** File size limit exceeded - @since 4.03 */ -let sigxfsz: int - -/** Exception raised on interactive interrupt if {!Sys.catch_break} - is on. */ exception Break - -/** [catch_break] governs whether interactive interrupt (ctrl-C) - terminates the program or raises the [Break] exception. - Call [catch_break true] to enable raising [Break], - and [catch_break false] to let the system - terminate the program on user interrupt. */ -let catch_break: bool => unit - -/** [ocaml_version] is the version of OCaml. - It is a string of the form ["major.minor[.patchlevel][+additional-info]"], - where [major], [minor], and [patchlevel] are integers, and - [additional-info] is an arbitrary string. The [[.patchlevel]] and - [[+additional-info]] parts may be absent. */ -let ocaml_version: string - -/** Control whether the OCaml runtime system can emit warnings - on stderr. Currently, the only supported warning is triggered - when a channel created by [open_*] functions is finalized without - being closed. Runtime warnings are enabled by default. - - @since 4.03.0 */ -let enable_runtime_warnings: bool => unit - -/** Return whether runtime warnings are currently enabled. - - @since 4.03.0 */ -let runtime_warnings_enabled: unit => bool - -/* {1 Optimization} */ - -/** For the purposes of optimization, [opaque_identity] behaves like an - unknown (and thus possibly side-effecting) function. - - At runtime, [opaque_identity] disappears altogether. - - A typical use of this function is to prevent pure computations from being - optimized away in benchmarking loops. For example: - {[ - for _round = 1 to 100_000 do - ignore (Sys.opaque_identity (my_pure_computation ())) - done - ]} - - @since 4.03.0 -*/ -external opaque_identity: 'a => 'a = "%opaque" diff --git a/jscomp/stdlib-406/typed-arrays/BigInt64Array.res b/jscomp/stdlib-406/typed-arrays/BigInt64Array.res new file mode 100644 index 0000000000..4435a72108 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/BigInt64Array.res @@ -0,0 +1,53 @@ +/** The `BigInt64Array` typed array represents an array of 64-bit signed integers in platform byte order. See [BigInt64Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "BigInt64Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `BigInt64Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array) +*/ +@new +external fromArray: array => t = "BigInt64Array" + +/** `fromBuffer` creates a `BigInt64Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "BigInt64Array" + +/** `fromBufferToEnd` creates a `BigInt64Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "BigInt64Array" + +/** `fromBufferWithRange` creates a `BigInt64Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "BigInt64Array" + +/** `fromLength` creates a zero-initialized `BigInt64Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array/BigInt64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "BigInt64Array" + +/** `fromArrayLikeOrIterable` creates a `BigInt64Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "BigInt64Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `BigInt64Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => bigint) => t = "BigInt64Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/BigUint64Array.res b/jscomp/stdlib-406/typed-arrays/BigUint64Array.res new file mode 100644 index 0000000000..d9f527d59a --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/BigUint64Array.res @@ -0,0 +1,54 @@ +/** The `BigUint64Array` typed array represents an array of 64-bit unsigned integers in platform byte order. See [BigUint64Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "BigUint64Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `BigUint64Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array) +*/ +@new +external fromArray: array => t = "BigUint64Array" + +/** `fromBuffer` creates a `BigUint64Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "BigUint64Array" + +/** `fromBufferToEnd` creates a `BigUint64Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "BigUint64Array" + +/** `fromBufferWithRange` creates a `BigUint64Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = + "BigUint64Array" + +/** `fromLength` creates a zero-initialized `BigUint64Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array/BigUint64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "BigUint64Array" + +/** `fromArrayLikeOrIterable` creates a `BigUint64Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "BigUint64Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `BigUint64Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => bigint) => t = "BigUint64Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Float32Array.res b/jscomp/stdlib-406/typed-arrays/Float32Array.res new file mode 100644 index 0000000000..6c04d070a8 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Float32Array.res @@ -0,0 +1,53 @@ +/** The `Float32Array` typed array represents an array of 32-bit floating point numbers in platform byte order. See [Float32Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Float32Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Float32Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array) +*/ +@new +external fromArray: array => t = "Float32Array" + +/** `fromBuffer` creates a `Float32Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Float32Array" + +/** `fromBufferToEnd` creates a `Float32Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Float32Array" + +/** `fromBufferWithRange` creates a `Float32Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Float32Array" + +/** `fromLength` creates a zero-initialized `Float32Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Float32Array" + +/** `fromArrayLikeOrIterable` creates a `Float32Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Float32Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Float32Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => float) => t = "Float32Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Float64Array.res b/jscomp/stdlib-406/typed-arrays/Float64Array.res new file mode 100644 index 0000000000..03203eb189 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Float64Array.res @@ -0,0 +1,53 @@ +/** The `Float64Array` typed array represents an array of 64-bit floating point numbers in platform byte order. See [Float64Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Float64Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Float64Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array) +*/ +@new +external fromArray: array => t = "Float64Array" + +/** `fromBuffer` creates a `Float64Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Float64Array" + +/** `fromBufferToEnd` creates a `Float64Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Float64Array" + +/** `fromBufferWithRange` creates a `Float64Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Float64Array" + +/** `fromLength` creates a zero-initialized `Float64Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array/Float64Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Float64Array" + +/** `fromArrayLikeOrIterable` creates a `Float64Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Float64Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Float64Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => float) => t = "Float64Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Int16Array.res b/jscomp/stdlib-406/typed-arrays/Int16Array.res new file mode 100644 index 0000000000..8fe25cf2ae --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Int16Array.res @@ -0,0 +1,53 @@ +/** The `Int16Array` typed array represents an array of twos-complement 16-bit signed integers in platform byte order. See [Int16Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Int16Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Int16Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array) +*/ +@new +external fromArray: array => t = "Int16Array" + +/** `fromBuffer` creates a `Int16Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Int16Array" + +/** `fromBufferToEnd` creates a `Int16Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Int16Array" + +/** `fromBufferWithRange` creates a `Int16Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Int16Array" + +/** `fromLength` creates a zero-initialized `Int16Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array/Int16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Int16Array" + +/** `fromArrayLikeOrIterable` creates a `Int16Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Int16Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Int16Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Int16Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Int32Array.res b/jscomp/stdlib-406/typed-arrays/Int32Array.res new file mode 100644 index 0000000000..febba5a2c7 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Int32Array.res @@ -0,0 +1,53 @@ +/** The `Int32Array` typed array represents an array of twos-complemenet 32-bit signed integers in platform byte order. See [Int32Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Int32Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Int32Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array) +*/ +@new +external fromArray: array => t = "Int32Array" + +/** `fromBuffer` creates a `Int32Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Int32Array" + +/** `fromBufferToEnd` creates a `Int32Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Int32Array" + +/** `fromBufferWithRange` creates a `Int32Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Int32Array" + +/** `fromLength` creates a zero-initialized `Int32Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Int32Array" + +/** `fromArrayLikeOrIterable` creates a `Int32Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Int32Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Int32Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Int32Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Int8Array.res b/jscomp/stdlib-406/typed-arrays/Int8Array.res new file mode 100644 index 0000000000..3c8e14ba8b --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Int8Array.res @@ -0,0 +1,53 @@ +/** The `Int8Array` typed array represents an array of twos-complement 8-bit signed integers. See [Int8Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Int8Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Int8Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array) +*/ +@new +external fromArray: array => t = "Int8Array" + +/** `fromBuffer` creates a `Int8Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Int8Array" + +/** `fromBufferToEnd` creates a `Int8Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Int8Array" + +/** `fromBufferWithRange` creates a `Int8Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Int8Array" + +/** `fromLength` creates a zero-initialized `Int8Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array/Int8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Int8Array" + +/** `fromArrayLikeOrIterable` creates a `Int8Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Int8Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Int8Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Int8Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/TypedArray.res b/jscomp/stdlib-406/typed-arrays/TypedArray.res new file mode 100644 index 0000000000..0ce5ab7ac7 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/TypedArray.res @@ -0,0 +1,77 @@ +type t<'a> + +@get_index external get: (t<'a>, int) => option<'a> = "" +@set_index external set: (t<'a>, int, 'a) => unit = "" + +@get external buffer: t<'a> => Core__ArrayBuffer.t = "buffer" +@get external byteLength: t<'a> => int = "byteLength" +@get external byteOffset: t<'a> => int = "byteOffset" + +@send external setArray: (t<'a>, array<'a>) => unit = "set" +@send external setArrayFrom: (t<'a>, array<'a>, int) => unit = "set" + +@get external length: t<'a> => int = "length" + +@send external copyAllWithin: (t<'a>, ~target: int) => array<'a> = "copyWithin" +@send external copyWithinToEnd: (t<'a>, ~target: int, ~start: int) => array<'a> = "copyWithin" +@send +external copyWithin: (t<'a>, ~target: int, ~start: int, ~end: int) => array<'a> = "copyWithin" + +@send external fillAll: (t<'a>, 'a) => t<'a> = "fill" +@send external fillToEnd: (t<'a>, 'a, ~start: int) => t<'a> = "fill" +@send external fill: (t<'a>, 'a, ~start: int, ~end: int) => t<'a> = "fill" + +@send external reverse: t<'a> => unit = "reverse" +@send external toReversed: t<'a> => t<'a> = "toReversed" + +@send external sort: (t<'a>, ('a, 'a) => Core__Ordering.t) => unit = "sort" +@send external toSorted: (t<'a>, ('a, 'a) => Core__Ordering.t) => t<'a> = "toSorted" + +@send external with: (t<'a>, int, 'a) => t<'a> = "with" + +@send external includes: (t<'a>, 'a) => bool = "includes" + +@send external indexOf: (t<'a>, 'a) => int = "indexOf" +@send external indexOfFrom: (t<'a>, 'a, int) => int = "indexOf" + +@send external joinWith: (t<'a>, string) => string = "join" + +@send external lastIndexOf: (t<'a>, 'a) => int = "lastIndexOf" +@send external lastIndexOfFrom: (t<'a>, 'a, int) => int = "lastIndexOf" + +@send external slice: (t<'a>, ~start: int, ~end: int) => t<'a> = "slice" +@send external sliceToEnd: (t<'a>, ~start: int) => t<'a> = "slice" +@send external copy: t<'a> => t<'a> = "slice" + +@send external subarray: (t<'a>, ~start: int, ~end: int) => t<'a> = "subarray" +@send external subarrayToEnd: (t<'a>, ~start: int) => t<'a> = "subarray" + +@send external toString: t<'a> => string = "toString" +@send external toLocaleString: t<'a> => string = "toLocaleString" + +@send external every: (t<'a>, 'a => bool) => bool = "every" +@send external everyWithIndex: (t<'a>, ('a, int) => bool) => bool = "every" + +@send external filter: (t<'a>, 'a => bool) => t<'a> = "filter" +@send external filterWithIndex: (t<'a>, ('a, int) => bool) => t<'a> = "filter" + +@send external find: (t<'a>, 'a => bool) => option<'a> = "find" +@send external findWithIndex: (t<'a>, ('a, int) => bool) => option<'a> = "find" + +@send external findIndex: (t<'a>, 'a => bool) => int = "findIndex" +@send external findIndexWithIndex: (t<'a>, ('a, int) => bool) => int = "findIndex" + +@send external forEach: (t<'a>, 'a => unit) => unit = "forEach" +@send external forEachWithIndex: (t<'a>, ('a, int) => unit) => unit = "forEach" + +@send external map: (t<'a>, 'a => 'b) => t<'b> = "map" +@send external mapWithIndex: (t<'a>, ('a, int) => 'b) => t<'b> = "map" + +@send external reduce: (t<'a>, ('b, 'a) => 'b, 'b) => 'b = "reduce" +@send external reduceWithIndex: (t<'a>, ('b, 'a, int) => 'b, 'b) => 'b = "reduce" + +@send external reduceRight: (t<'a>, ('b, 'a) => 'b, 'b) => 'b = "reduceRight" +@send external reduceRightWithIndex: (t<'a>, ('b, 'a, int) => 'b, 'b) => 'b = "reduceRight" + +@send external some: (t<'a>, 'a => bool) => bool = "some" +@send external someWithIndex: (t<'a>, ('a, int) => bool) => bool = "some" diff --git a/jscomp/stdlib-406/typed-arrays/Uint16Array.res b/jscomp/stdlib-406/typed-arrays/Uint16Array.res new file mode 100644 index 0000000000..115caf8a2f --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Uint16Array.res @@ -0,0 +1,53 @@ +/** The `Uint16Array` typed array represents an array of 16-bit unsigned integers in platform byte order. See [Uint16Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Uint16Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Uint16Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array) +*/ +@new +external fromArray: array => t = "Uint16Array" + +/** `fromBuffer` creates a `Uint16Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Uint16Array" + +/** `fromBufferToEnd` creates a `Uint16Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Uint16Array" + +/** `fromBufferWithRange` creates a `Uint16Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Uint16Array" + +/** `fromLength` creates a zero-initialized `Uint16Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Uint16Array" + +/** `fromArrayLikeOrIterable` creates a `Uint16Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Uint16Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Uint16Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Uint16Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Uint32Array.res b/jscomp/stdlib-406/typed-arrays/Uint32Array.res new file mode 100644 index 0000000000..ba6693054a --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Uint32Array.res @@ -0,0 +1,53 @@ +/** The `Uint32Array` typed array represents an array of 32-bit unsigned integers in platform byte order. See [Uint32Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Uint32Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Uint32Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array) +*/ +@new +external fromArray: array => t = "Uint32Array" + +/** `fromBuffer` creates a `Uint32Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Uint32Array" + +/** `fromBufferToEnd` creates a `Uint32Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Uint32Array" + +/** `fromBufferWithRange` creates a `Uint32Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Uint32Array" + +/** `fromLength` creates a zero-initialized `Uint32Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array/Uint32Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Uint32Array" + +/** `fromArrayLikeOrIterable` creates a `Uint32Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Uint32Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Uint32Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Uint32Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Uint8Array.res b/jscomp/stdlib-406/typed-arrays/Uint8Array.res new file mode 100644 index 0000000000..2233a039b3 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Uint8Array.res @@ -0,0 +1,53 @@ +/** The `Uint8Array` typed array represents an array of 8-bit unsigned integers. See [Uint8Array on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Uint8Array.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Uint8Array` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array) +*/ +@new +external fromArray: array => t = "Uint8Array" + +/** `fromBuffer` creates a `Uint8Array` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Uint8Array" + +/** `fromBufferToEnd` creates a `Uint8Array` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Uint8Array" + +/** `fromBufferWithRange` creates a `Uint8Array` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = "Uint8Array" + +/** `fromLength` creates a zero-initialized `Uint8Array` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Uint8Array" + +/** `fromArrayLikeOrIterable` creates a `Uint8Array` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Uint8Array.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Uint8Array` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Uint8Array.from" diff --git a/jscomp/stdlib-406/typed-arrays/Uint8ClampedArray.res b/jscomp/stdlib-406/typed-arrays/Uint8ClampedArray.res new file mode 100644 index 0000000000..633dd4ca18 --- /dev/null +++ b/jscomp/stdlib-406/typed-arrays/Uint8ClampedArray.res @@ -0,0 +1,54 @@ +/** The `Uint8ClampedArray` typed array represents an array of 8-bit unsigned integers clamped to 0-255. See [Uint8ClampedArray on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) +*/ +type t = TypedArray.t + +module Constants = { + /**`bytesPerElement` returns the element size. See [BYTES_PER_ELEMENT on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) + */ + @val + external bytesPerElement: int = "Uint8ClampedArray.BYTES_PER_ELEMENT" +} + +/** `fromArray` creates a `Uint8ClampedArray` from an array of values. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray) +*/ +@new +external fromArray: array => t = "Uint8ClampedArray" + +/** `fromBuffer` creates a `Uint8ClampedArray` from an `ArrayBuffer.t`. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBuffer: ArrayBuffer.t => t = "Uint8ClampedArray" + +/** `fromBufferToEnd` creates a `Uint8ClampedArray` from an `ArrayBuffer.t`, starting at a particular offset and continuing through to the end. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferToEnd: (ArrayBuffer.t, ~byteOffset: int) => t = "Uint8ClampedArray" + +/** `fromBufferWithRange` creates a `Uint8ClampedArray` from an `ArrayBuffer.t`, starting at a particular offset and consuming `length` **bytes**. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromBufferWithRange: (ArrayBuffer.t, ~byteOffset: int, ~length: int) => t = + "Uint8ClampedArray" + +/** `fromLength` creates a zero-initialized `Uint8ClampedArray` to hold the specified count of numbers; this is **not** a byte length. See [TypedArray constructor on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray) + +**Note:** This is a potentially unsafe operation. Ensure the buffer is large enough and only accessed within its bounds. +*/ +@new +external fromLength: int => t = "Uint8ClampedArray" + +/** `fromArrayLikeOrIterable` creates a `Uint8ClampedArray` from an array-like or iterable object. See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterable: 'a => t = "Uint8ClampedArray.from" + +/** `fromArrayLikeOrIterableWithMap` creates a `Uint8ClampedArray` from an array-like or iterable object and applies the mapping function to each item. The mapping function expects (value, index). See [TypedArray.from on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) +*/ +@val +external fromArrayLikeOrIterableWithMap: ('a, ('b, int) => int) => t = "Uint8ClampedArray.from" diff --git a/jscomp/stdlib-406/uchar.res b/jscomp/stdlib-406/uchar.res deleted file mode 100644 index de27d35e75..0000000000 --- a/jscomp/stdlib-406/uchar.res +++ /dev/null @@ -1,74 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Daniel C. Buenzli */ -/* */ -/* Copyright 2014 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -external format_int: (string, int) => string = "?format_int" - -let err_no_pred = "U+0000 has no predecessor" -let err_no_succ = "U+10FFFF has no successor" -let err_not_sv = i => format_int("%X", i) ++ " is not an Unicode scalar value" -let err_not_latin1 = u => "U+" ++ (format_int("%04X", u) ++ " is not a latin1 character") - -type t = int - -let min = 0x0000 -let max = 0x10FFFF -let lo_bound = 0xD7FF -let hi_bound = 0xE000 - -let bom = 0xFEFF -let rep = 0xFFFD - -let succ = u => - if u == lo_bound { - hi_bound - } else if u == max { - invalid_arg(err_no_succ) - } else { - u + 1 - } - -let pred = u => - if u == hi_bound { - lo_bound - } else if u == min { - invalid_arg(err_no_pred) - } else { - u - 1 - } - -let is_valid = i => (min <= i && i <= lo_bound) || (hi_bound <= i && i <= max) -let of_int = i => - if is_valid(i) { - i - } else { - invalid_arg(err_not_sv(i)) - } -external unsafe_of_int: int => t = "%identity" -external to_int: t => int = "%identity" - -let is_char = u => u < 256 -let of_char = c => Char.code(c) -let to_char = u => - if u > 255 { - invalid_arg(err_not_latin1(u)) - } else { - Char.unsafe_chr(u) - } - -let unsafe_to_char = Char.unsafe_chr - -let equal: (int, int) => bool = \"=" -let compare: (int, int) => int = Pervasives.compare -let hash = to_int diff --git a/jscomp/stdlib-406/uchar.resi b/jscomp/stdlib-406/uchar.resi deleted file mode 100644 index d837b86a19..0000000000 --- a/jscomp/stdlib-406/uchar.resi +++ /dev/null @@ -1,94 +0,0 @@ -/* ************************************************************************ */ -/* */ -/* OCaml */ -/* */ -/* Daniel C. Buenzli */ -/* */ -/* Copyright 2014 Institut National de Recherche en Informatique et */ -/* en Automatique. */ -/* */ -/* All rights reserved. This file is distributed under the terms of */ -/* the GNU Lesser General Public License version 2.1, with the */ -/* special exception on linking described in the file LICENSE. */ -/* */ -/* ************************************************************************ */ - -/*** Unicode characters. - - @since 4.03 */ - -/** The type for Unicode characters. - - A value of this type represents an Unicode - {{:http://unicode.org/glossary/#unicode_scalar_value}scalar - value} which is an integer in the ranges [0x0000]...[0xD7FF] or - [0xE000]...[0x10FFFF]. */ -type t - -/** [min] is U+0000. */ -let min: t - -/** [max] is U+10FFFF. */ -let max: t - -/** [bom] is U+FEFF, the - {{:http://unicode.org/glossary/#byte_order_mark}byte order mark} (BOM) - character. - - @since 4.06.0 */ -let bom: t - -/** [rep] is U+FFFD, the - {{:http://unicode.org/glossary/#replacement_character}replacement} - character. - - @since 4.06.0 */ -let rep: t - -/** [succ u] is the scalar value after [u] in the set of Unicode scalar - values. - - @raise Invalid_argument if [u] is {!max}. */ -let succ: t => t - -/** [pred u] is the scalar value before [u] in the set of Unicode scalar - values. - - @raise Invalid_argument if [u] is {!min}. */ -let pred: t => t - -/** [is_valid n] is [true] iff [n] is an Unicode scalar value - (i.e. in the ranges [0x0000]...[0xD7FF] or [0xE000]...[0x10FFFF]).*/ -let is_valid: int => bool - -/** [of_int i] is [i] as an Unicode character. - - @raise Invalid_argument if [i] does not satisfy {!is_valid}. */ -let of_int: int => t - -let unsafe_of_int: int => t - -/** [to_int u] is [u] as an integer. */ -let to_int: t => int - -/** [is_char u] is [true] iff [u] is a latin1 OCaml character. */ -let is_char: t => bool - -/** [of_char c] is [c] as an Unicode character. */ -let of_char: char => t - -/** [to_char u] is [u] as an OCaml latin1 character. - - @raise Invalid_argument if [u] does not satisfy {!is_char}. */ -let to_char: t => char - -let unsafe_to_char: t => char - -/** [equal u u'] is [u = u']. */ -let equal: (t, t) => bool - -/** [compare u u'] is [Pervasives.compare u u']. */ -let compare: (t, t) => int - -/** [hash u] associates a non-negative integer to [u]. */ -let hash: t => int diff --git a/lib/es6/belt_Array.js b/lib/es6/belt_Array.js index 8e0ca501cb..c9ebd57ecd 100644 --- a/lib/es6/belt_Array.js +++ b/lib/es6/belt_Array.js @@ -1,7 +1,6 @@ import * as Caml from "./caml.js"; -import * as Curry from "./curry.js"; import * as Js_math from "./js_math.js"; import * as Caml_option from "./caml_option.js"; @@ -110,7 +109,9 @@ function makeByU(l, f) { } function makeBy(l, f) { - return makeByU(l, Curry.__1(f)); + return makeByU(l, (function (a) { + return f(a); + })); } function makeByAndShuffleU(l, f) { @@ -120,7 +121,9 @@ function makeByAndShuffleU(l, f) { } function makeByAndShuffle(l, f) { - return makeByAndShuffleU(l, Curry.__1(f)); + return makeByAndShuffleU(l, (function (a) { + return f(a); + })); } function range(start, finish) { @@ -176,7 +179,9 @@ function zipByU(xs, ys, f) { } function zipBy(xs, ys, f) { - return zipByU(xs, ys, Curry.__2(f)); + return zipByU(xs, ys, (function (a, b) { + return f(a, b); + })); } function concat(a1, a2) { @@ -291,7 +296,9 @@ function forEachU(a, f) { } function forEach(a, f) { - forEachU(a, Curry.__1(f)); + forEachU(a, (function (a) { + f(a); + })); } function mapU(a, f) { @@ -304,7 +311,9 @@ function mapU(a, f) { } function map(a, f) { - return mapU(a, Curry.__1(f)); + return mapU(a, (function (a) { + return f(a); + })); } function flatMapU(a, f) { @@ -312,7 +321,9 @@ function flatMapU(a, f) { } function flatMap(a, f) { - return concatMany(mapU(a, Curry.__1(f))); + return flatMapU(a, (function (a) { + return f(a); + })); } function getByU(a, p) { @@ -330,7 +341,9 @@ function getByU(a, p) { } function getBy(a, p) { - return getByU(a, Curry.__1(p)); + return getByU(a, (function (a) { + return p(a); + })); } function getIndexByU(a, p) { @@ -348,7 +361,9 @@ function getIndexByU(a, p) { } function getIndexBy(a, p) { - return getIndexByU(a, Curry.__1(p)); + return getIndexByU(a, (function (a) { + return p(a); + })); } function keepU(a, f) { @@ -368,7 +383,9 @@ function keepU(a, f) { } function keep(a, f) { - return keepU(a, Curry.__1(f)); + return keepU(a, (function (a) { + return f(a); + })); } function keepWithIndexU(a, f) { @@ -388,7 +405,9 @@ function keepWithIndexU(a, f) { } function keepWithIndex(a, f) { - return keepWithIndexU(a, Curry.__2(f)); + return keepWithIndexU(a, (function (a, i) { + return f(a, i); + })); } function keepMapU(a, f) { @@ -409,7 +428,9 @@ function keepMapU(a, f) { } function keepMap(a, f) { - return keepMapU(a, Curry.__1(f)); + return keepMapU(a, (function (a) { + return f(a); + })); } function forEachWithIndexU(a, f) { @@ -419,7 +440,9 @@ function forEachWithIndexU(a, f) { } function forEachWithIndex(a, f) { - forEachWithIndexU(a, Curry.__2(f)); + forEachWithIndexU(a, (function (a, b) { + f(a, b); + })); } function mapWithIndexU(a, f) { @@ -432,7 +455,9 @@ function mapWithIndexU(a, f) { } function mapWithIndex(a, f) { - return mapWithIndexU(a, Curry.__2(f)); + return mapWithIndexU(a, (function (a, b) { + return f(a, b); + })); } function reduceU(a, x, f) { @@ -444,7 +469,9 @@ function reduceU(a, x, f) { } function reduce(a, x, f) { - return reduceU(a, x, Curry.__2(f)); + return reduceU(a, x, (function (a, b) { + return f(a, b); + })); } function reduceReverseU(a, x, f) { @@ -456,7 +483,9 @@ function reduceReverseU(a, x, f) { } function reduceReverse(a, x, f) { - return reduceReverseU(a, x, Curry.__2(f)); + return reduceReverseU(a, x, (function (a, b) { + return f(a, b); + })); } function reduceReverse2U(a, b, x, f) { @@ -469,7 +498,9 @@ function reduceReverse2U(a, b, x, f) { } function reduceReverse2(a, b, x, f) { - return reduceReverse2U(a, b, x, Curry.__3(f)); + return reduceReverse2U(a, b, x, (function (a, b, c) { + return f(a, b, c); + })); } function reduceWithIndexU(a, x, f) { @@ -481,7 +512,9 @@ function reduceWithIndexU(a, x, f) { } function reduceWithIndex(a, x, f) { - return reduceWithIndexU(a, x, Curry.__3(f)); + return reduceWithIndexU(a, x, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(arr, b) { @@ -501,7 +534,9 @@ function everyU(arr, b) { } function every(arr, f) { - return everyU(arr, Curry.__1(f)); + return everyU(arr, (function (b) { + return f(b); + })); } function someU(arr, b) { @@ -521,7 +556,9 @@ function someU(arr, b) { } function some(arr, f) { - return someU(arr, Curry.__1(f)); + return someU(arr, (function (b) { + return f(b); + })); } function everyAux2(arr1, arr2, _i, b, len) { @@ -543,7 +580,9 @@ function every2U(a, b, p) { } function every2(a, b, p) { - return every2U(a, b, Curry.__2(p)); + return every2U(a, b, (function (a, b) { + return p(a, b); + })); } function some2U(a, b, p) { @@ -563,7 +602,9 @@ function some2U(a, b, p) { } function some2(a, b, p) { - return some2U(a, b, Curry.__2(p)); + return some2U(a, b, (function (a, b) { + return p(a, b); + })); } function eqU(a, b, p) { @@ -577,7 +618,9 @@ function eqU(a, b, p) { } function eq(a, b, p) { - return eqU(a, b, Curry.__2(p)); + return eqU(a, b, (function (a, b) { + return p(a, b); + })); } function cmpU(a, b, p) { @@ -605,7 +648,9 @@ function cmpU(a, b, p) { } function cmp(a, b, p) { - return cmpU(a, b, Curry.__2(p)); + return cmpU(a, b, (function (a, b) { + return p(a, b); + })); } function partitionU(a, f) { @@ -633,7 +678,9 @@ function partitionU(a, f) { } function partition(a, f) { - return partitionU(a, Curry.__1(f)); + return partitionU(a, (function (x) { + return f(x); + })); } function unzip(a) { @@ -672,7 +719,9 @@ function joinWithU(a, sep, toString) { } function joinWith(a, sep, toString) { - return joinWithU(a, sep, Curry.__1(toString)); + return joinWithU(a, sep, (function (x) { + return toString(x); + })); } function initU(n, f) { @@ -684,7 +733,9 @@ function initU(n, f) { } function init(n, f) { - return initU(n, Curry.__1(f)); + return initU(n, (function (i) { + return f(i); + })); } export { diff --git a/lib/es6/belt_HashMapInt.js b/lib/es6/belt_HashMapInt.js index 2d1d6c8537..905f88bcd7 100644 --- a/lib/es6/belt_HashMapInt.js +++ b/lib/es6/belt_HashMapInt.js @@ -193,7 +193,7 @@ function size(h) { function fromArray(arr) { let len = arr.length; - let v = Belt_internalBucketsType.make(undefined, undefined, len); + let v = make(len); for(let i = 0; i < len; ++i){ let match = arr[i]; set(v, match[0], match[1]); diff --git a/lib/es6/belt_HashMapString.js b/lib/es6/belt_HashMapString.js index c4352164cb..041b2e8ace 100644 --- a/lib/es6/belt_HashMapString.js +++ b/lib/es6/belt_HashMapString.js @@ -193,7 +193,7 @@ function size(h) { function fromArray(arr) { let len = arr.length; - let v = Belt_internalBucketsType.make(undefined, undefined, len); + let v = make(len); for(let i = 0; i < len; ++i){ let match = arr[i]; set(v, match[0], match[1]); diff --git a/lib/es6/belt_Id.js b/lib/es6/belt_Id.js index ff1ebbb299..562e578fb4 100644 --- a/lib/es6/belt_Id.js +++ b/lib/es6/belt_Id.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; function MakeComparableU(M) { return M; @@ -8,7 +7,9 @@ function MakeComparableU(M) { function MakeComparable(M) { let cmp = M.cmp; - let cmp$1 = Curry.__2(cmp); + let cmp$1 = function (a, b) { + return cmp(a, b); + }; return { cmp: cmp$1 }; @@ -21,7 +22,9 @@ function comparableU(cmp) { } function comparable(cmp) { - let cmp$1 = Curry.__2(cmp); + let cmp$1 = function (a, b) { + return cmp(a, b); + }; return { cmp: cmp$1 }; @@ -33,9 +36,13 @@ function MakeHashableU(M) { function MakeHashable(M) { let hash = M.hash; - let hash$1 = Curry.__1(hash); + let hash$1 = function (a) { + return hash(a); + }; let eq = M.eq; - let eq$1 = Curry.__2(eq); + let eq$1 = function (a, b) { + return eq(a, b); + }; return { hash: hash$1, eq: eq$1 @@ -50,8 +57,12 @@ function hashableU(hash, eq) { } function hashable(hash, eq) { - let hash$1 = Curry.__1(hash); - let eq$1 = Curry.__2(eq); + let hash$1 = function (a) { + return hash(a); + }; + let eq$1 = function (a, b) { + return eq(a, b); + }; return { hash: hash$1, eq: eq$1 diff --git a/lib/es6/belt_List.js b/lib/es6/belt_List.js index 888b61b2ab..926592fb82 100644 --- a/lib/es6/belt_List.js +++ b/lib/es6/belt_List.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_Array from "./belt_Array.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_SortArray from "./belt_SortArray.js"; @@ -523,7 +522,9 @@ function mapU(xs, f) { } function map(xs, f) { - return mapU(xs, Curry.__1(f)); + return mapU(xs, (function (x) { + return f(x); + })); } function zipByU(l1, l2, f) { @@ -542,7 +543,9 @@ function zipByU(l1, l2, f) { } function zipBy(l1, l2, f) { - return zipByU(l1, l2, Curry.__2(f)); + return zipByU(l1, l2, (function (x, y) { + return f(x, y); + })); } function mapWithIndexU(xs, f) { @@ -558,7 +561,9 @@ function mapWithIndexU(xs, f) { } function mapWithIndex(xs, f) { - return mapWithIndexU(xs, Curry.__2(f)); + return mapWithIndexU(xs, (function (i, x) { + return f(i, x); + })); } function makeByU(n, f) { @@ -584,7 +589,9 @@ function makeByU(n, f) { } function makeBy(n, f) { - return makeByU(n, Curry.__1(f)); + return makeByU(n, (function (x) { + return f(x); + })); } function make(n, v) { @@ -758,7 +765,9 @@ function mapReverseU(l, f) { } function mapReverse(l, f) { - return mapReverseU(l, Curry.__1(f)); + return mapReverseU(l, (function (x) { + return f(x); + })); } function forEachU(_xs, f) { @@ -774,7 +783,9 @@ function forEachU(_xs, f) { } function forEach(xs, f) { - forEachU(xs, Curry.__1(f)); + forEachU(xs, (function (x) { + return f(x); + })); } function forEachWithIndexU(l, f) { @@ -794,7 +805,9 @@ function forEachWithIndexU(l, f) { } function forEachWithIndex(l, f) { - forEachWithIndexU(l, Curry.__2(f)); + forEachWithIndexU(l, (function (i, x) { + return f(i, x); + })); } function reduceU(_l, _accu, f) { @@ -811,7 +824,9 @@ function reduceU(_l, _accu, f) { } function reduce(l, accu, f) { - return reduceU(l, accu, Curry.__2(f)); + return reduceU(l, accu, (function (acc, x) { + return f(acc, x); + })); } function reduceReverseUnsafeU(l, accu, f) { @@ -832,7 +847,9 @@ function reduceReverseU(l, acc, f) { } function reduceReverse(l, accu, f) { - return reduceReverseU(l, accu, Curry.__2(f)); + return reduceReverseU(l, accu, (function (a, b) { + return f(a, b); + })); } function reduceWithIndexU(l, acc, f) { @@ -854,7 +871,9 @@ function reduceWithIndexU(l, acc, f) { } function reduceWithIndex(l, acc, f) { - return reduceWithIndexU(l, acc, Curry.__3(f)); + return reduceWithIndexU(l, acc, (function (acc, x, i) { + return f(acc, x, i); + })); } function mapReverse2U(l1, l2, f) { @@ -882,7 +901,9 @@ function mapReverse2U(l1, l2, f) { } function mapReverse2(l1, l2, f) { - return mapReverse2U(l1, l2, Curry.__2(f)); + return mapReverse2U(l1, l2, (function (a, b) { + return f(a, b); + })); } function forEach2U(_l1, _l2, f) { @@ -903,7 +924,9 @@ function forEach2U(_l1, _l2, f) { } function forEach2(l1, l2, f) { - forEach2U(l1, l2, Curry.__2(f)); + forEach2U(l1, l2, (function (a, b) { + return f(a, b); + })); } function reduce2U(_l1, _l2, _accu, f) { @@ -925,7 +948,9 @@ function reduce2U(_l1, _l2, _accu, f) { } function reduce2(l1, l2, acc, f) { - return reduce2U(l1, l2, acc, Curry.__3(f)); + return reduce2U(l1, l2, acc, (function (a, b, c) { + return f(a, b, c); + })); } function reduceReverse2UnsafeU(l1, l2, accu, f) { @@ -946,7 +971,9 @@ function reduceReverse2U(l1, l2, acc, f) { } function reduceReverse2(l1, l2, acc, f) { - return reduceReverse2U(l1, l2, acc, Curry.__3(f)); + return reduceReverse2U(l1, l2, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(_xs, p) { @@ -964,7 +991,9 @@ function everyU(_xs, p) { } function every(xs, p) { - return everyU(xs, Curry.__1(p)); + return everyU(xs, (function (x) { + return p(x); + })); } function someU(_xs, p) { @@ -982,7 +1011,9 @@ function someU(_xs, p) { } function some(xs, p) { - return someU(xs, Curry.__1(p)); + return someU(xs, (function (x) { + return p(x); + })); } function every2U(_l1, _l2, p) { @@ -1005,7 +1036,9 @@ function every2U(_l1, _l2, p) { } function every2(l1, l2, p) { - return every2U(l1, l2, Curry.__2(p)); + return every2U(l1, l2, (function (a, b) { + return p(a, b); + })); } function cmpByLength(_l1, _l2) { @@ -1053,7 +1086,9 @@ function cmpU(_l1, _l2, p) { } function cmp(l1, l2, f) { - return cmpU(l1, l2, Curry.__2(f)); + return cmpU(l1, l2, (function (x, y) { + return f(x, y); + })); } function eqU(_l1, _l2, p) { @@ -1080,7 +1115,9 @@ function eqU(_l1, _l2, p) { } function eq(l1, l2, f) { - return eqU(l1, l2, Curry.__2(f)); + return eqU(l1, l2, (function (x, y) { + return f(x, y); + })); } function some2U(_l1, _l2, p) { @@ -1103,7 +1140,9 @@ function some2U(_l1, _l2, p) { } function some2(l1, l2, p) { - return some2U(l1, l2, Curry.__2(p)); + return some2U(l1, l2, (function (a, b) { + return p(a, b); + })); } function hasU(_xs, x, eq) { @@ -1121,7 +1160,9 @@ function hasU(_xs, x, eq) { } function has(xs, x, eq) { - return hasU(xs, x, Curry.__2(eq)); + return hasU(xs, x, (function (a, b) { + return eq(a, b); + })); } function getAssocU(_xs, x, eq) { @@ -1140,7 +1181,9 @@ function getAssocU(_xs, x, eq) { } function getAssoc(xs, x, eq) { - return getAssocU(xs, x, Curry.__2(eq)); + return getAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function hasAssocU(_xs, x, eq) { @@ -1158,7 +1201,9 @@ function hasAssocU(_xs, x, eq) { } function hasAssoc(xs, x, eq) { - return hasAssocU(xs, x, Curry.__2(eq)); + return hasAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function removeAssocU(xs, x, eq) { @@ -1183,7 +1228,9 @@ function removeAssocU(xs, x, eq) { } function removeAssoc(xs, x, eq) { - return removeAssocU(xs, x, Curry.__2(eq)); + return removeAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function setAssocU(xs, x, k, eq) { @@ -1226,7 +1273,9 @@ function setAssocU(xs, x, k, eq) { } function setAssoc(xs, x, k, eq) { - return setAssocU(xs, x, k, Curry.__2(eq)); + return setAssocU(xs, x, k, (function (a, b) { + return eq(a, b); + })); } function sortU(xs, cmp) { @@ -1236,7 +1285,9 @@ function sortU(xs, cmp) { } function sort(xs, cmp) { - return sortU(xs, Curry.__2(cmp)); + return sortU(xs, (function (x, y) { + return cmp(x, y); + })); } function getByU(_xs, p) { @@ -1255,7 +1306,9 @@ function getByU(_xs, p) { } function getBy(xs, p) { - return getByU(xs, Curry.__1(p)); + return getByU(xs, (function (a) { + return p(a); + })); } function keepU(_xs, p) { @@ -1280,7 +1333,9 @@ function keepU(_xs, p) { } function keep(xs, p) { - return keepU(xs, Curry.__1(p)); + return keepU(xs, (function (x) { + return p(x); + })); } function keepWithIndexU(xs, p) { @@ -1309,7 +1364,9 @@ function keepWithIndexU(xs, p) { } function keepWithIndex(xs, p) { - return keepWithIndexU(xs, Curry.__2(p)); + return keepWithIndexU(xs, (function (x, i) { + return p(x, i); + })); } function keepMapU(_xs, p) { @@ -1334,7 +1391,9 @@ function keepMapU(_xs, p) { } function keepMap(xs, p) { - return keepMapU(xs, Curry.__1(p)); + return keepMapU(xs, (function (x) { + return p(x); + })); } function partitionU(l, p) { @@ -1369,7 +1428,9 @@ function partitionU(l, p) { } function partition(l, p) { - return partitionU(l, Curry.__1(p)); + return partitionU(l, (function (x) { + return p(x); + })); } function unzip(xs) { diff --git a/lib/es6/belt_Map.js b/lib/es6/belt_Map.js index 8234a5b949..9c811ba7fe 100644 --- a/lib/es6/belt_Map.js +++ b/lib/es6/belt_Map.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_MapDict from "./belt_MapDict.js"; function fromArray(data, id) { @@ -59,7 +58,9 @@ function updateU(m, key, f) { } function update(m, key, f) { - return updateU(m, key, Curry.__1(f)); + return updateU(m, key, (function (a) { + return f(a); + })); } function split(m, x) { @@ -90,7 +91,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function make(id) { @@ -109,7 +112,9 @@ function findFirstByU(m, f) { } function findFirstBy(m, f) { - return Belt_MapDict.findFirstByU(m.data, Curry.__2(f)); + return findFirstByU(m, (function (a, b) { + return f(a, b); + })); } function forEachU(m, f) { @@ -117,7 +122,9 @@ function forEachU(m, f) { } function forEach(m, f) { - Belt_MapDict.forEachU(m.data, Curry.__2(f)); + forEachU(m, (function (a, b) { + f(a, b); + })); } function reduceU(m, acc, f) { @@ -125,7 +132,9 @@ function reduceU(m, acc, f) { } function reduce(m, acc, f) { - return reduceU(m, acc, Curry.__3(f)); + return reduceU(m, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(m, f) { @@ -133,7 +142,9 @@ function everyU(m, f) { } function every(m, f) { - return Belt_MapDict.everyU(m.data, Curry.__2(f)); + return everyU(m, (function (a, b) { + return f(a, b); + })); } function someU(m, f) { @@ -141,7 +152,9 @@ function someU(m, f) { } function some(m, f) { - return Belt_MapDict.someU(m.data, Curry.__2(f)); + return someU(m, (function (a, b) { + return f(a, b); + })); } function keepU(m, f) { @@ -152,7 +165,9 @@ function keepU(m, f) { } function keep(m, f) { - return keepU(m, Curry.__2(f)); + return keepU(m, (function (a, b) { + return f(a, b); + })); } function partitionU(m, p) { @@ -171,7 +186,9 @@ function partitionU(m, p) { } function partition(m, p) { - return partitionU(m, Curry.__2(p)); + return partitionU(m, (function (a, b) { + return p(a, b); + })); } function mapU(m, f) { @@ -182,7 +199,9 @@ function mapU(m, f) { } function map(m, f) { - return mapU(m, Curry.__1(f)); + return mapU(m, (function (a) { + return f(a); + })); } function mapWithKeyU(m, f) { @@ -193,7 +212,9 @@ function mapWithKeyU(m, f) { } function mapWithKey(m, f) { - return mapWithKeyU(m, Curry.__2(f)); + return mapWithKeyU(m, (function (a, b) { + return f(a, b); + })); } function size(map) { @@ -277,7 +298,9 @@ function eqU(m1, m2, veq) { } function eq(m1, m2, veq) { - return eqU(m1, m2, Curry.__2(veq)); + return eqU(m1, m2, (function (a, b) { + return veq(a, b); + })); } function cmpU(m1, m2, vcmp) { @@ -285,7 +308,9 @@ function cmpU(m1, m2, vcmp) { } function cmp(m1, m2, vcmp) { - return cmpU(m1, m2, Curry.__2(vcmp)); + return cmpU(m1, m2, (function (a, b) { + return vcmp(a, b); + })); } function getData(m) { diff --git a/lib/es6/belt_MapDict.js b/lib/es6/belt_MapDict.js index c2fa88f3c7..ad544897de 100644 --- a/lib/es6/belt_MapDict.js +++ b/lib/es6/belt_MapDict.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; @@ -76,7 +75,9 @@ function updateU(t, newK, f, cmp) { } function update(t, newK, f, cmp) { - return updateU(t, newK, Curry.__1(f), cmp); + return updateU(t, newK, (function (a) { + return f(a); + }), cmp); } function removeAux0(n, x, cmp) { @@ -244,7 +245,9 @@ function mergeU(s1, s2, f, cmp) { } function merge(s1, s2, f, cmp) { - return mergeU(s1, s2, Curry.__3(f), cmp); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + }), cmp); } function removeMany(t, keys, cmp) { diff --git a/lib/es6/belt_MapInt.js b/lib/es6/belt_MapInt.js index 69c1a3dbc5..ced1b1814e 100644 --- a/lib/es6/belt_MapInt.js +++ b/lib/es6/belt_MapInt.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalMapInt from "./belt_internalMapInt.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; @@ -73,7 +72,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - return updateU(t, x, Curry.__1(f)); + return updateU(t, x, (function (a) { + return f(a); + })); } function removeAux(n, x) { diff --git a/lib/es6/belt_MapString.js b/lib/es6/belt_MapString.js index d2201ef572..0880dca3cd 100644 --- a/lib/es6/belt_MapString.js +++ b/lib/es6/belt_MapString.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; import * as Belt_internalMapString from "./belt_internalMapString.js"; @@ -73,7 +72,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - return updateU(t, x, Curry.__1(f)); + return updateU(t, x, (function (a) { + return f(a); + })); } function removeAux(n, x) { diff --git a/lib/es6/belt_MutableMap.js b/lib/es6/belt_MutableMap.js index 1c88e14fc3..df575d99d5 100644 --- a/lib/es6/belt_MutableMap.js +++ b/lib/es6/belt_MutableMap.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; @@ -137,7 +136,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function make(id) { @@ -152,8 +153,7 @@ function clear(m) { } function isEmpty(d) { - let x = d.data; - return x === undefined; + return d.data === undefined; } function minKey(m) { @@ -193,7 +193,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function reduceU(d, acc, cb) { @@ -201,7 +203,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__3(cb)); + return reduceU(d, acc, (function (a, b, c) { + return cb(a, b, c); + })); } function everyU(d, p) { @@ -209,7 +213,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(p)); + return everyU(d, (function (a, b) { + return p(a, b); + })); } function someU(d, p) { @@ -217,7 +223,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(p)); + return someU(d, (function (a, b) { + return p(a, b); + })); } function size(d) { @@ -249,7 +257,9 @@ function cmpU(m1, m2, cmp) { } function cmp(m1, m2, cmp$1) { - return cmpU(m1, m2, Curry.__2(cmp$1)); + return cmpU(m1, m2, (function (a, b) { + return cmp$1(a, b); + })); } function eqU(m1, m2, cmp) { @@ -257,7 +267,9 @@ function eqU(m1, m2, cmp) { } function eq(m1, m2, cmp) { - return eqU(m1, m2, Curry.__2(cmp)); + return eqU(m1, m2, (function (a, b) { + return cmp(a, b); + })); } function mapU(m, f) { @@ -268,7 +280,9 @@ function mapU(m, f) { } function map(m, f) { - return mapU(m, Curry.__1(f)); + return mapU(m, (function (a) { + return f(a); + })); } function mapWithKeyU(m, f) { @@ -279,7 +293,9 @@ function mapWithKeyU(m, f) { } function mapWithKey(m, f) { - return mapWithKeyU(m, Curry.__2(f)); + return mapWithKeyU(m, (function (a, b) { + return f(a, b); + })); } function get(m, x) { diff --git a/lib/es6/belt_MutableMapInt.js b/lib/es6/belt_MutableMapInt.js index e3155c0fa2..dc792430ed 100644 --- a/lib/es6/belt_MutableMapInt.js +++ b/lib/es6/belt_MutableMapInt.js @@ -1,19 +1,17 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalMapInt from "./belt_internalMapInt.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; -function make(param) { +function make() { return { data: undefined }; } function isEmpty(m) { - let x = m.data; - return x === undefined; + return m.data === undefined; } function clear(m) { @@ -67,7 +65,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function mapU(d, f) { @@ -77,7 +77,9 @@ function mapU(d, f) { } function map(d, f) { - return mapU(d, Curry.__1(f)); + return mapU(d, (function (a) { + return f(a); + })); } function mapWithKeyU(d, f) { @@ -87,7 +89,9 @@ function mapWithKeyU(d, f) { } function mapWithKey(d, f) { - return mapWithKeyU(d, Curry.__2(f)); + return mapWithKeyU(d, (function (a, b) { + return f(a, b); + })); } function reduceU(d, acc, f) { @@ -95,7 +99,9 @@ function reduceU(d, acc, f) { } function reduce(d, acc, f) { - return reduceU(d, acc, Curry.__3(f)); + return reduceU(d, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(d, f) { @@ -103,7 +109,9 @@ function everyU(d, f) { } function every(d, f) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(f)); + return everyU(d, (function (a, b) { + return f(a, b); + })); } function someU(d, f) { @@ -111,7 +119,9 @@ function someU(d, f) { } function some(d, f) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(f)); + return someU(d, (function (a, b) { + return f(a, b); + })); } function size(d) { @@ -240,7 +250,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function removeArrayMutateAux(_t, xs, _i, len) { @@ -286,7 +298,9 @@ function cmpU(d0, d1, f) { } function cmp(d0, d1, f) { - return cmpU(d0, d1, Curry.__2(f)); + return cmpU(d0, d1, (function (a, b) { + return f(a, b); + })); } function eqU(d0, d1, f) { @@ -294,7 +308,9 @@ function eqU(d0, d1, f) { } function eq(d0, d1, f) { - return eqU(d0, d1, Curry.__2(f)); + return eqU(d0, d1, (function (a, b) { + return f(a, b); + })); } function get(d, x) { diff --git a/lib/es6/belt_MutableMapString.js b/lib/es6/belt_MutableMapString.js index ed42d2cf98..b0d77bb7e7 100644 --- a/lib/es6/belt_MutableMapString.js +++ b/lib/es6/belt_MutableMapString.js @@ -1,19 +1,17 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; import * as Belt_internalMapString from "./belt_internalMapString.js"; -function make(param) { +function make() { return { data: undefined }; } function isEmpty(m) { - let x = m.data; - return x === undefined; + return m.data === undefined; } function clear(m) { @@ -67,7 +65,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function mapU(d, f) { @@ -77,7 +77,9 @@ function mapU(d, f) { } function map(d, f) { - return mapU(d, Curry.__1(f)); + return mapU(d, (function (a) { + return f(a); + })); } function mapWithKeyU(d, f) { @@ -87,7 +89,9 @@ function mapWithKeyU(d, f) { } function mapWithKey(d, f) { - return mapWithKeyU(d, Curry.__2(f)); + return mapWithKeyU(d, (function (a, b) { + return f(a, b); + })); } function reduceU(d, acc, f) { @@ -95,7 +99,9 @@ function reduceU(d, acc, f) { } function reduce(d, acc, f) { - return reduceU(d, acc, Curry.__3(f)); + return reduceU(d, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(d, f) { @@ -103,7 +109,9 @@ function everyU(d, f) { } function every(d, f) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(f)); + return everyU(d, (function (a, b) { + return f(a, b); + })); } function someU(d, f) { @@ -111,7 +119,9 @@ function someU(d, f) { } function some(d, f) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(f)); + return someU(d, (function (a, b) { + return f(a, b); + })); } function size(d) { @@ -240,7 +250,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function removeArrayMutateAux(_t, xs, _i, len) { @@ -286,7 +298,9 @@ function cmpU(d0, d1, f) { } function cmp(d0, d1, f) { - return cmpU(d0, d1, Curry.__2(f)); + return cmpU(d0, d1, (function (a, b) { + return f(a, b); + })); } function eqU(d0, d1, f) { @@ -294,7 +308,9 @@ function eqU(d0, d1, f) { } function eq(d0, d1, f) { - return eqU(d0, d1, Curry.__2(f)); + return eqU(d0, d1, (function (a, b) { + return f(a, b); + })); } function get(d, x) { diff --git a/lib/es6/belt_MutableQueue.js b/lib/es6/belt_MutableQueue.js index 046f2e155c..a0773e3a24 100644 --- a/lib/es6/belt_MutableQueue.js +++ b/lib/es6/belt_MutableQueue.js @@ -1,9 +1,8 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; -function make(param) { +function make() { return { length: 0, first: undefined, @@ -175,7 +174,9 @@ function mapU(q, f) { } function map(q, f) { - return mapU(q, Curry.__1(f)); + return mapU(q, (function (a) { + return f(a); + })); } function isEmpty(q) { @@ -200,7 +201,9 @@ function forEachU(q, f) { } function forEach(q, f) { - forEachU(q, Curry.__1(f)); + forEachU(q, (function (a) { + f(a); + })); } function reduceU(q, accu, f) { @@ -220,7 +223,9 @@ function reduceU(q, accu, f) { } function reduce(q, accu, f) { - return reduceU(q, accu, Curry.__2(f)); + return reduceU(q, accu, (function (a, b) { + return f(a, b); + })); } function transfer(q1, q2) { diff --git a/lib/es6/belt_MutableSet.js b/lib/es6/belt_MutableSet.js index 982de5b409..05ed011852 100644 --- a/lib/es6/belt_MutableSet.js +++ b/lib/es6/belt_MutableSet.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_SortArray from "./belt_SortArray.js"; import * as Belt_internalAVLset from "./belt_internalAVLset.js"; @@ -193,8 +192,7 @@ function make(id) { } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -218,7 +216,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -226,7 +226,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -234,7 +236,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -242,7 +246,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -340,7 +346,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -359,7 +367,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/es6/belt_MutableSetInt.js b/lib/es6/belt_MutableSetInt.js index 77eb5949fe..47ff473614 100644 --- a/lib/es6/belt_MutableSetInt.js +++ b/lib/es6/belt_MutableSetInt.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_SortArrayInt from "./belt_SortArrayInt.js"; import * as Belt_internalAVLset from "./belt_internalAVLset.js"; import * as Belt_internalSetInt from "./belt_internalSetInt.js"; @@ -183,15 +182,14 @@ function mergeMany(d, arr) { d.data = addArrayMutate(d.data, arr); } -function make(param) { +function make() { return { data: undefined }; } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -215,7 +213,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -223,7 +223,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -231,7 +233,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -239,7 +243,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -328,7 +334,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -344,7 +352,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/es6/belt_MutableSetString.js b/lib/es6/belt_MutableSetString.js index a39db395c8..d8a217d1ef 100644 --- a/lib/es6/belt_MutableSetString.js +++ b/lib/es6/belt_MutableSetString.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_internalAVLset from "./belt_internalAVLset.js"; import * as Belt_SortArrayString from "./belt_SortArrayString.js"; import * as Belt_internalSetString from "./belt_internalSetString.js"; @@ -183,15 +182,14 @@ function mergeMany(d, arr) { d.data = addArrayMutate(d.data, arr); } -function make(param) { +function make() { return { data: undefined }; } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -215,7 +213,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -223,7 +223,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -231,7 +233,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -239,7 +243,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -328,7 +334,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -344,7 +352,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/es6/belt_MutableStack.js b/lib/es6/belt_MutableStack.js index 93650f0b49..1197f56c81 100644 --- a/lib/es6/belt_MutableStack.js +++ b/lib/es6/belt_MutableStack.js @@ -1,9 +1,8 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; -function make(param) { +function make() { return { root: undefined }; @@ -99,7 +98,9 @@ function forEachU(s, f) { } function forEach(s, f) { - forEachU(s, Curry.__1(f)); + forEachU(s, (function (x) { + f(x); + })); } function dynamicPopIterU(s, f) { @@ -115,7 +116,9 @@ function dynamicPopIterU(s, f) { } function dynamicPopIter(s, f) { - dynamicPopIterU(s, Curry.__1(f)); + dynamicPopIterU(s, (function (x) { + f(x); + })); } export { diff --git a/lib/es6/belt_Option.js b/lib/es6/belt_Option.js index 5b84c6d20e..5195786c5a 100644 --- a/lib/es6/belt_Option.js +++ b/lib/es6/belt_Option.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; function keepU(opt, p) { @@ -11,7 +10,9 @@ function keepU(opt, p) { } function keep(opt, p) { - return keepU(opt, Curry.__1(p)); + return keepU(opt, (function (x) { + return p(x); + })); } function forEachU(opt, f) { @@ -22,7 +23,9 @@ function forEachU(opt, f) { } function forEach(opt, f) { - forEachU(opt, Curry.__1(f)); + forEachU(opt, (function (x) { + f(x); + })); } function getExn(x) { @@ -44,7 +47,9 @@ function mapWithDefaultU(opt, $$default, f) { } function mapWithDefault(opt, $$default, f) { - return mapWithDefaultU(opt, $$default, Curry.__1(f)); + return mapWithDefaultU(opt, $$default, (function (x) { + return f(x); + })); } function mapU(opt, f) { @@ -55,7 +60,9 @@ function mapU(opt, f) { } function map(opt, f) { - return mapU(opt, Curry.__1(f)); + return mapU(opt, (function (x) { + return f(x); + })); } function flatMapU(opt, f) { @@ -66,7 +73,9 @@ function flatMapU(opt, f) { } function flatMap(opt, f) { - return flatMapU(opt, Curry.__1(f)); + return flatMapU(opt, (function (x) { + return f(x); + })); } function getWithDefault(opt, $$default) { @@ -106,7 +115,9 @@ function eqU(a, b, f) { } function eq(a, b, f) { - return eqU(a, b, Curry.__2(f)); + return eqU(a, b, (function (x, y) { + return f(x, y); + })); } function cmpU(a, b, f) { @@ -124,7 +135,9 @@ function cmpU(a, b, f) { } function cmp(a, b, f) { - return cmpU(a, b, Curry.__2(f)); + return cmpU(a, b, (function (x, y) { + return f(x, y); + })); } export { diff --git a/lib/es6/belt_Range.js b/lib/es6/belt_Range.js index 19919e7847..6dc8c014d2 100644 --- a/lib/es6/belt_Range.js +++ b/lib/es6/belt_Range.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; function forEachU(s, f, action) { for(let i = s; i <= f; ++i){ @@ -9,7 +8,9 @@ function forEachU(s, f, action) { } function forEach(s, f, action) { - forEachU(s, f, Curry.__1(action)); + forEachU(s, f, (function (a) { + action(a); + })); } function everyU(_s, f, p) { @@ -27,7 +28,9 @@ function everyU(_s, f, p) { } function every(s, f, p) { - return everyU(s, f, Curry.__1(p)); + return everyU(s, f, (function (a) { + return p(a); + })); } function everyByU(s, f, step, p) { @@ -50,7 +53,9 @@ function everyByU(s, f, step, p) { } function everyBy(s, f, step, p) { - return everyByU(s, f, step, Curry.__1(p)); + return everyByU(s, f, step, (function (a) { + return p(a); + })); } function someU(_s, f, p) { @@ -68,7 +73,9 @@ function someU(_s, f, p) { } function some(s, f, p) { - return someU(s, f, Curry.__1(p)); + return someU(s, f, (function (a) { + return p(a); + })); } function someByU(s, f, step, p) { @@ -91,7 +98,9 @@ function someByU(s, f, step, p) { } function someBy(s, f, step, p) { - return someByU(s, f, step, Curry.__1(p)); + return someByU(s, f, step, (function (a) { + return p(a); + })); } export { diff --git a/lib/es6/belt_Result.js b/lib/es6/belt_Result.js index 1d6f823624..cba34cf036 100644 --- a/lib/es6/belt_Result.js +++ b/lib/es6/belt_Result.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; function getExn(x) { if (x.TAG === "Ok") { @@ -21,7 +20,9 @@ function mapWithDefaultU(opt, $$default, f) { } function mapWithDefault(opt, $$default, f) { - return mapWithDefaultU(opt, $$default, Curry.__1(f)); + return mapWithDefaultU(opt, $$default, (function (x) { + return f(x); + })); } function mapU(opt, f) { @@ -39,7 +40,9 @@ function mapU(opt, f) { } function map(opt, f) { - return mapU(opt, Curry.__1(f)); + return mapU(opt, (function (x) { + return f(x); + })); } function flatMapU(opt, f) { @@ -54,7 +57,9 @@ function flatMapU(opt, f) { } function flatMap(opt, f) { - return flatMapU(opt, Curry.__1(f)); + return flatMapU(opt, (function (x) { + return f(x); + })); } function getWithDefault(opt, $$default) { @@ -96,7 +101,9 @@ function eqU(a, b, f) { } function eq(a, b, f) { - return eqU(a, b, Curry.__2(f)); + return eqU(a, b, (function (x, y) { + return f(x, y); + })); } function cmpU(a, b, f) { @@ -114,7 +121,9 @@ function cmpU(a, b, f) { } function cmp(a, b, f) { - return cmpU(a, b, Curry.__2(f)); + return cmpU(a, b, (function (x, y) { + return f(x, y); + })); } export { diff --git a/lib/es6/belt_Set.js b/lib/es6/belt_Set.js index 816c874348..c68c9f5b85 100644 --- a/lib/es6/belt_Set.js +++ b/lib/es6/belt_Set.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_SetDict from "./belt_SetDict.js"; function fromArray(data, id) { @@ -128,7 +127,9 @@ function forEachU(m, f) { } function forEach(m, f) { - Belt_SetDict.forEachU(m.data, Curry.__1(f)); + forEachU(m, (function (a) { + f(a); + })); } function reduceU(m, acc, f) { @@ -136,7 +137,9 @@ function reduceU(m, acc, f) { } function reduce(m, acc, f) { - return reduceU(m, acc, Curry.__2(f)); + return reduceU(m, acc, (function (a, b) { + return f(a, b); + })); } function everyU(m, f) { @@ -144,7 +147,9 @@ function everyU(m, f) { } function every(m, f) { - return Belt_SetDict.everyU(m.data, Curry.__1(f)); + return everyU(m, (function (a) { + return f(a); + })); } function someU(m, f) { @@ -152,7 +157,9 @@ function someU(m, f) { } function some(m, f) { - return Belt_SetDict.someU(m.data, Curry.__1(f)); + return someU(m, (function (a) { + return f(a); + })); } function keepU(m, f) { @@ -163,7 +170,9 @@ function keepU(m, f) { } function keep(m, f) { - return keepU(m, Curry.__1(f)); + return keepU(m, (function (a) { + return f(a); + })); } function partitionU(m, f) { @@ -182,7 +191,9 @@ function partitionU(m, f) { } function partition(m, f) { - return partitionU(m, Curry.__1(f)); + return partitionU(m, (function (a) { + return f(a); + })); } function size(m) { diff --git a/lib/es6/belt_SortArray.js b/lib/es6/belt_SortArray.js index 8cb252b911..11810837e4 100644 --- a/lib/es6/belt_SortArray.js +++ b/lib/es6/belt_SortArray.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_Array from "./belt_Array.js"; function sortedLengthAuxMore(xs, _prec, _acc, len, lt) { @@ -52,7 +51,9 @@ function strictlySortedLengthU(xs, lt) { } function strictlySortedLength(xs, lt) { - return strictlySortedLengthU(xs, Curry.__2(lt)); + return strictlySortedLengthU(xs, (function (x, y) { + return lt(x, y); + })); } function isSortedU(a, cmp) { @@ -77,7 +78,9 @@ function isSortedU(a, cmp) { } function isSorted(a, cmp) { - return isSortedU(a, Curry.__2(cmp)); + return isSortedU(a, (function (x, y) { + return cmp(x, y); + })); } function merge(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -181,7 +184,9 @@ function unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) } function union(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -234,7 +239,9 @@ function intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, } function intersect(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -293,7 +300,9 @@ function diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) } function diff(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function insertionSort(src, srcofs, dst, dstofs, len, cmp) { @@ -333,7 +342,9 @@ function stableSortInPlaceByU(a, cmp) { } function stableSortInPlaceBy(a, cmp) { - stableSortInPlaceByU(a, Curry.__2(cmp)); + stableSortInPlaceByU(a, (function (x, y) { + return cmp(x, y); + })); } function stableSortByU(a, cmp) { @@ -343,7 +354,9 @@ function stableSortByU(a, cmp) { } function stableSortBy(a, cmp) { - return stableSortByU(a, Curry.__2(cmp)); + return stableSortByU(a, (function (x, y) { + return cmp(x, y); + })); } function binarySearchByU(sorted, key, cmp) { @@ -397,7 +410,9 @@ function binarySearchByU(sorted, key, cmp) { } function binarySearchBy(sorted, key, cmp) { - return binarySearchByU(sorted, key, Curry.__2(cmp)); + return binarySearchByU(sorted, key, (function (x, y) { + return cmp(x, y); + })); } let Int; diff --git a/lib/es6/belt_internalAVLset.js b/lib/es6/belt_internalAVLset.js index 7c3ed870c4..3db293a48f 100644 --- a/lib/es6/belt_internalAVLset.js +++ b/lib/es6/belt_internalAVLset.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_SortArray from "./belt_SortArray.js"; @@ -178,7 +177,9 @@ function forEachU(_n, f) { } function forEach(n, f) { - forEachU(n, Curry.__1(f)); + forEachU(n, (function (a) { + f(a); + })); } function reduceU(_s, _accu, f) { @@ -195,7 +196,9 @@ function reduceU(_s, _accu, f) { } function reduce(s, accu, f) { - return reduceU(s, accu, Curry.__2(f)); + return reduceU(s, accu, (function (a, b) { + return f(a, b); + })); } function everyU(_n, p) { @@ -216,7 +219,9 @@ function everyU(_n, p) { } function every(n, p) { - return everyU(n, Curry.__1(p)); + return everyU(n, (function (a) { + return p(a); + })); } function someU(_n, p) { @@ -237,7 +242,9 @@ function someU(_n, p) { } function some(n, p) { - return someU(n, Curry.__1(p)); + return someU(n, (function (a) { + return p(a); + })); } function addMinElement(n, v) { @@ -317,7 +324,9 @@ function partitionSharedU(n, p) { } function partitionShared(n, p) { - return partitionSharedU(n, Curry.__1(p)); + return partitionSharedU(n, (function (a) { + return p(a); + })); } function lengthNode(n) { @@ -553,7 +562,9 @@ function keepSharedU(n, p) { } function keepShared(n, p) { - return keepSharedU(n, Curry.__1(p)); + return keepSharedU(n, (function (a) { + return p(a); + })); } function keepCopyU(n, p) { @@ -567,7 +578,9 @@ function keepCopyU(n, p) { } function keepCopy(n, p) { - return keepCopyU(n, Curry.__1(p)); + return keepCopyU(n, (function (x) { + return p(x); + })); } function partitionCopyU(n, p) { @@ -593,7 +606,9 @@ function partitionCopyU(n, p) { } function partitionCopy(n, p) { - return partitionCopyU(n, Curry.__1(p)); + return partitionCopyU(n, (function (a) { + return p(a); + })); } function has(_t, x, cmp) { diff --git a/lib/es6/belt_internalAVLtree.js b/lib/es6/belt_internalAVLtree.js index 1b58f322b7..11421d0adf 100644 --- a/lib/es6/belt_internalAVLtree.js +++ b/lib/es6/belt_internalAVLtree.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_SortArray from "./belt_SortArray.js"; @@ -270,7 +269,9 @@ function findFirstByU(n, p) { } function findFirstBy(n, p) { - return findFirstByU(n, Curry.__2(p)); + return findFirstByU(n, (function (a, b) { + return p(a, b); + })); } function forEachU(_n, f) { @@ -287,7 +288,9 @@ function forEachU(_n, f) { } function forEach(n, f) { - forEachU(n, Curry.__2(f)); + forEachU(n, (function (a, b) { + f(a, b); + })); } function mapU(n, f) { @@ -307,7 +310,9 @@ function mapU(n, f) { } function map(n, f) { - return mapU(n, Curry.__1(f)); + return mapU(n, (function (a) { + return f(a); + })); } function mapWithKeyU(n, f) { @@ -328,7 +333,9 @@ function mapWithKeyU(n, f) { } function mapWithKey(n, f) { - return mapWithKeyU(n, Curry.__2(f)); + return mapWithKeyU(n, (function (a, b) { + return f(a, b); + })); } function reduceU(_m, _accu, f) { @@ -349,7 +356,9 @@ function reduceU(_m, _accu, f) { } function reduce(m, accu, f) { - return reduceU(m, accu, Curry.__3(f)); + return reduceU(m, accu, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(_n, p) { @@ -370,7 +379,9 @@ function everyU(_n, p) { } function every(n, p) { - return everyU(n, Curry.__2(p)); + return everyU(n, (function (a, b) { + return p(a, b); + })); } function someU(_n, p) { @@ -391,7 +402,9 @@ function someU(_n, p) { } function some(n, p) { - return someU(n, Curry.__2(p)); + return someU(n, (function (a, b) { + return p(a, b); + })); } function addMinElement(n, k, v) { @@ -478,7 +491,9 @@ function keepSharedU(n, p) { } function keepShared(n, p) { - return keepSharedU(n, Curry.__2(p)); + return keepSharedU(n, (function (a, b) { + return p(a, b); + })); } function keepMapU(n, p) { @@ -498,7 +513,9 @@ function keepMapU(n, p) { } function keepMap(n, p) { - return keepMapU(n, Curry.__2(p)); + return keepMapU(n, (function (a, b) { + return p(a, b); + })); } function partitionSharedU(n, p) { @@ -531,7 +548,9 @@ function partitionSharedU(n, p) { } function partitionShared(n, p) { - return partitionSharedU(n, Curry.__2(p)); + return partitionSharedU(n, (function (a, b) { + return p(a, b); + })); } function lengthNode(n) { @@ -817,7 +836,9 @@ function cmpU(s1, s2, kcmp, vcmp) { } function cmp(s1, s2, kcmp, vcmp) { - return cmpU(s1, s2, kcmp, Curry.__2(vcmp)); + return cmpU(s1, s2, kcmp, (function (a, b) { + return vcmp(a, b); + })); } function eqU(s1, s2, kcmp, veq) { @@ -850,7 +871,9 @@ function eqU(s1, s2, kcmp, veq) { } function eq(s1, s2, kcmp, veq) { - return eqU(s1, s2, kcmp, Curry.__2(veq)); + return eqU(s1, s2, kcmp, (function (a, b) { + return veq(a, b); + })); } function get(_n, x, cmp) { diff --git a/lib/es6/belt_internalBuckets.js b/lib/es6/belt_internalBuckets.js index c78b17f237..43299a9adc 100644 --- a/lib/es6/belt_internalBuckets.js +++ b/lib/es6/belt_internalBuckets.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_Array from "./belt_Array.js"; import * as Caml_option from "./caml_option.js"; @@ -87,7 +86,9 @@ function forEachU(h, f) { } function forEach(h, f) { - forEachU(h, Curry.__2(f)); + forEachU(h, (function (a, b) { + return f(a, b); + })); } function do_bucket_fold(f, _b, _accu) { @@ -113,7 +114,9 @@ function reduceU(h, init, f) { } function reduce(h, init, f) { - return reduceU(h, init, Curry.__3(f)); + return reduceU(h, init, (function (a, b, c) { + return f(a, b, c); + })); } function getMaxBucketLength(h) { @@ -195,7 +198,9 @@ function keepMapInPlaceU(h, f) { } function keepMapInPlace(h, f) { - keepMapInPlaceU(h, Curry.__2(f)); + keepMapInPlaceU(h, (function (a, b) { + return f(a, b); + })); } function fillArray(_i, arr, _cell) { diff --git a/lib/es6/belt_internalMapInt.js b/lib/es6/belt_internalMapInt.js index 29491a4b1e..fe16cd20d1 100644 --- a/lib/es6/belt_internalMapInt.js +++ b/lib/es6/belt_internalMapInt.js @@ -1,7 +1,6 @@ import * as Caml from "./caml.js"; -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_SortArray from "./belt_SortArray.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; @@ -209,7 +208,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function compareAux(_e1, _e2, vcmp) { @@ -251,7 +252,9 @@ function cmpU(s1, s2, cmp) { } function cmp(s1, s2, f) { - return cmpU(s1, s2, Curry.__2(f)); + return cmpU(s1, s2, (function (a, b) { + return f(a, b); + })); } function eqAux(_e1, _e2, eq) { @@ -286,7 +289,9 @@ function eqU(s1, s2, eq) { } function eq(s1, s2, f) { - return eqU(s1, s2, Curry.__2(f)); + return eqU(s1, s2, (function (a, b) { + return f(a, b); + })); } function addMutate(t, x, data) { diff --git a/lib/es6/belt_internalMapString.js b/lib/es6/belt_internalMapString.js index 519c56a02b..ace4eabac3 100644 --- a/lib/es6/belt_internalMapString.js +++ b/lib/es6/belt_internalMapString.js @@ -1,7 +1,6 @@ import * as Caml from "./caml.js"; -import * as Curry from "./curry.js"; import * as Caml_option from "./caml_option.js"; import * as Belt_SortArray from "./belt_SortArray.js"; import * as Belt_internalAVLtree from "./belt_internalAVLtree.js"; @@ -209,7 +208,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function compareAux(_e1, _e2, vcmp) { @@ -251,7 +252,9 @@ function cmpU(s1, s2, cmp) { } function cmp(s1, s2, f) { - return cmpU(s1, s2, Curry.__2(f)); + return cmpU(s1, s2, (function (a, b) { + return f(a, b); + })); } function eqAux(_e1, _e2, eq) { @@ -286,7 +289,9 @@ function eqU(s1, s2, eq) { } function eq(s1, s2, f) { - return eqU(s1, s2, Curry.__2(f)); + return eqU(s1, s2, (function (a, b) { + return f(a, b); + })); } function addMutate(t, x, data) { diff --git a/lib/es6/belt_internalSetBuckets.js b/lib/es6/belt_internalSetBuckets.js index 191dcb2d82..e4b289dd09 100644 --- a/lib/es6/belt_internalSetBuckets.js +++ b/lib/es6/belt_internalSetBuckets.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Belt_Array from "./belt_Array.js"; function copyAuxCont(_c, _prec) { @@ -84,7 +83,9 @@ function forEachU(h, f) { } function forEach(h, f) { - forEachU(h, Curry.__1(f)); + forEachU(h, (function (a) { + f(a); + })); } function fillArray(_i, arr, _cell) { @@ -139,7 +140,9 @@ function reduceU(h, init, f) { } function reduce(h, init, f) { - return reduceU(h, init, Curry.__2(f)); + return reduceU(h, init, (function (a, b) { + return f(a, b); + })); } function getMaxBucketLength(h) { diff --git a/lib/es6/caml.js b/lib/es6/caml.js index a85e2555f3..65242212b2 100644 --- a/lib/es6/caml.js +++ b/lib/es6/caml.js @@ -166,10 +166,10 @@ function i64_le(x, y) { } function i64_min(x, y) { - if (i64_ge(x, y)) { - return y; - } else { + if (i64_lt(x, y)) { return x; + } else { + return y; } } diff --git a/lib/es6/caml_obj.js b/lib/es6/caml_obj.js index 0e56757bd4..b40f738dd1 100644 --- a/lib/es6/caml_obj.js +++ b/lib/es6/caml_obj.js @@ -225,21 +225,19 @@ function aux_obj_compare(a, b) { return; } }; - let partial_arg = [ - a, - b, - min_key_rhs - ]; - let do_key_a = function (param) { - return do_key(partial_arg, param); + let do_key_a = function (extra) { + return do_key([ + a, + b, + min_key_rhs + ], extra); }; - let partial_arg$1 = [ - b, - a, - min_key_lhs - ]; - let do_key_b = function (param) { - return do_key(partial_arg$1, param); + let do_key_b = function (extra) { + return do_key([ + b, + a, + min_key_lhs + ], extra); }; for_in(a, do_key_a); for_in(b, do_key_b); diff --git a/lib/es6/caml_sys.js b/lib/es6/caml_sys.js index e898165039..864a14fabf 100644 --- a/lib/es6/caml_sys.js +++ b/lib/es6/caml_sys.js @@ -27,7 +27,7 @@ let os_type = (function(_){ } }); -function sys_time(param) { +function sys_time() { if (typeof process === "undefined" || process.uptime === undefined) { return -1; } else { @@ -42,7 +42,7 @@ let sys_getcwd = (function(param){ return process.cwd() }); -function sys_get_argv(param) { +function sys_get_argv() { if (typeof process === "undefined") { return [ "", diff --git a/lib/es6/curry.js b/lib/es6/curry.js index 6ce524794b..ef86cd689d 100644 --- a/lib/es6/curry.js +++ b/lib/es6/curry.js @@ -33,29 +33,29 @@ function _1(o, a0) { case 1 : return o(a0); case 2 : - return function (param) { - return o(a0, param); - }; + return (function (prim0, prim1, prim2) { + return prim0(prim1, prim2); + })(o, a0); case 3 : - return function (param, param$1) { - return o(a0, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3) { + return prim0(prim1, prim2, prim3); + })(o, a0); case 4 : - return function (param, param$1, param$2) { - return o(a0, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0); case 5 : - return function (param, param$1, param$2, param$3) { - return o(a0, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0); case 6 : - return function (param, param$1, param$2, param$3, param$4) { - return o(a0, param, param$1, param$2, param$3, param$4); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0); case 7 : - return function (param, param$1, param$2, param$3, param$4, param$5) { - return o(a0, param, param$1, param$2, param$3, param$4, param$5); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0); default: return app(o, [a0]); } @@ -84,25 +84,25 @@ function _2(o, a0, a1) { case 2 : return o(a0, a1); case 3 : - return function (param) { - return o(a0, a1, param); - }; + return (function (prim0, prim1, prim2, prim3) { + return prim0(prim1, prim2, prim3); + })(o, a0, a1); case 4 : - return function (param, param$1) { - return o(a0, a1, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0, a1); case 5 : - return function (param, param$1, param$2) { - return o(a0, a1, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1); case 6 : - return function (param, param$1, param$2, param$3) { - return o(a0, a1, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1); case 7 : - return function (param, param$1, param$2, param$3, param$4) { - return o(a0, a1, param, param$1, param$2, param$3, param$4); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1); default: return app(o, [ a0, @@ -139,21 +139,21 @@ function _3(o, a0, a1, a2) { case 3 : return o(a0, a1, a2); case 4 : - return function (param) { - return o(a0, a1, a2, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0, a1, a2); case 5 : - return function (param, param$1) { - return o(a0, a1, a2, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1, a2); case 6 : - return function (param, param$1, param$2) { - return o(a0, a1, a2, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2); case 7 : - return function (param, param$1, param$2, param$3) { - return o(a0, a1, a2, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2); default: return app(o, [ a0, @@ -197,17 +197,17 @@ function _4(o, a0, a1, a2, a3) { case 4 : return o(a0, a1, a2, a3); case 5 : - return function (param) { - return o(a0, a1, a2, a3, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1, a2, a3); case 6 : - return function (param, param$1) { - return o(a0, a1, a2, a3, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2, a3); case 7 : - return function (param, param$1, param$2) { - return o(a0, a1, a2, a3, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3); default: return app(o, [ a0, @@ -259,13 +259,13 @@ function _5(o, a0, a1, a2, a3, a4) { case 5 : return o(a0, a1, a2, a3, a4); case 6 : - return function (param) { - return o(a0, a1, a2, a3, a4, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2, a3, a4); case 7 : - return function (param, param$1) { - return o(a0, a1, a2, a3, a4, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3, a4); default: return app(o, [ a0, @@ -326,9 +326,9 @@ function _6(o, a0, a1, a2, a3, a4, a5) { case 6 : return o(a0, a1, a2, a3, a4, a5); case 7 : - return function (param) { - return o(a0, a1, a2, a3, a4, a5, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3, a4, a5); default: return app(o, [ a0, diff --git a/lib/es6/js_array.js b/lib/es6/js_array.js index 9a90149cb2..ae1b9f17e6 100644 --- a/lib/es6/js_array.js +++ b/lib/es6/js_array.js @@ -1,223 +1 @@ - - -import * as Curry from "./curry.js"; -import * as Caml_option from "./caml_option.js"; -import * as Caml_splice_call from "./caml_splice_call.js"; - -function copyWithin(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function push(arg1, obj) { - return obj.push(arg1); -} - -function pushMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "push", [arg1]); -} - -function sortInPlaceWith(arg1, obj) { - return obj.sort(Curry.__2(arg1)); -} - -function spliceInPlace(pos, remove, add, obj) { - return Caml_splice_call.spliceObjApply(obj, "splice", [ - pos, - remove, - add - ]); -} - -function removeFromInPlace(pos, obj) { - return obj.splice(pos); -} - -function removeCountInPlace(pos, count, obj) { - return obj.splice(pos, count); -} - -function unshift(arg1, obj) { - return obj.unshift(arg1); -} - -function unshiftMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "unshift", [arg1]); -} - -function concat(arg1, obj) { - return obj.concat(arg1); -} - -function concatMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "concat", [arg1]); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom(arg1, obj) { - return obj.slice(arg1); -} - -function every(arg1, obj) { - return obj.every(Curry.__1(arg1)); -} - -function everyi(arg1, obj) { - return obj.every(Curry.__2(arg1)); -} - -function filter(arg1, obj) { - return obj.filter(Curry.__1(arg1)); -} - -function filteri(arg1, obj) { - return obj.filter(Curry.__2(arg1)); -} - -function find(arg1, obj) { - return Caml_option.undefined_to_opt(obj.find(Curry.__1(arg1))); -} - -function findi(arg1, obj) { - return Caml_option.undefined_to_opt(obj.find(Curry.__2(arg1))); -} - -function findIndex(arg1, obj) { - return obj.findIndex(Curry.__1(arg1)); -} - -function findIndexi(arg1, obj) { - return obj.findIndex(Curry.__2(arg1)); -} - -function forEach(arg1, obj) { - obj.forEach(Curry.__1(arg1)); -} - -function forEachi(arg1, obj) { - obj.forEach(Curry.__2(arg1)); -} - -function map(arg1, obj) { - return obj.map(Curry.__1(arg1)); -} - -function mapi(arg1, obj) { - return obj.map(Curry.__2(arg1)); -} - -function reduce(arg1, arg2, obj) { - return obj.reduce(Curry.__2(arg1), arg2); -} - -function reducei(arg1, arg2, obj) { - return obj.reduce(Curry.__3(arg1), arg2); -} - -function reduceRight(arg1, arg2, obj) { - return obj.reduceRight(Curry.__2(arg1), arg2); -} - -function reduceRighti(arg1, arg2, obj) { - return obj.reduceRight(Curry.__3(arg1), arg2); -} - -function some(arg1, obj) { - return obj.some(Curry.__1(arg1)); -} - -function somei(arg1, obj) { - return obj.some(Curry.__2(arg1)); -} - -export { - copyWithin, - copyWithinFrom, - copyWithinFromRange, - fillInPlace, - fillFromInPlace, - fillRangeInPlace, - push, - pushMany, - sortInPlaceWith, - spliceInPlace, - removeFromInPlace, - removeCountInPlace, - unshift, - unshiftMany, - concat, - concatMany, - includes, - indexOf, - indexOfFrom, - joinWith, - lastIndexOf, - lastIndexOfFrom, - slice, - sliceFrom, - every, - everyi, - filter, - filteri, - find, - findi, - findIndex, - findIndexi, - forEach, - forEachi, - map, - mapi, - reduce, - reducei, - reduceRight, - reduceRighti, - some, - somei, -} -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/es6/js_promise.js b/lib/es6/js_promise.js index 9b4b0bf80a..ae1b9f17e6 100644 --- a/lib/es6/js_promise.js +++ b/lib/es6/js_promise.js @@ -1,17 +1 @@ - - -import * as Curry from "./curry.js"; - -function then_(arg1, obj) { - return obj.then(Curry.__1(arg1)); -} - -function $$catch(arg1, obj) { - return obj.catch(Curry.__1(arg1)); -} - -export { - then_, - $$catch, -} -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/es6/js_string.js b/lib/es6/js_string.js index 22c26408bb..ae1b9f17e6 100644 --- a/lib/es6/js_string.js +++ b/lib/es6/js_string.js @@ -1,199 +1 @@ - - -import * as Curry from "./curry.js"; -import * as Caml_option from "./caml_option.js"; -import * as Caml_splice_call from "./caml_splice_call.js"; - -function charAt(arg1, obj) { - return obj.charAt(arg1); -} - -function charCodeAt(arg1, obj) { - return obj.charCodeAt(arg1); -} - -function codePointAt(arg1, obj) { - return obj.codePointAt(arg1); -} - -function concat(arg1, obj) { - return obj.concat(arg1); -} - -function concatMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "concat", [arg1]); -} - -function endsWith(arg1, obj) { - return obj.endsWith(arg1); -} - -function endsWithFrom(arg1, arg2, obj) { - return obj.endsWith(arg1, arg2); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function includesFrom(arg1, arg2, obj) { - return obj.includes(arg1, arg2); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, arg2, obj) { - return obj.indexOf(arg1, arg2); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, arg2, obj) { - return obj.lastIndexOf(arg1, arg2); -} - -function localeCompare(arg1, obj) { - return obj.localeCompare(arg1); -} - -function match_(arg1, obj) { - return Caml_option.null_to_opt(obj.match(arg1)); -} - -function normalizeByForm(arg1, obj) { - return obj.normalize(arg1); -} - -function repeat(arg1, obj) { - return obj.repeat(arg1); -} - -function replace(arg1, arg2, obj) { - return obj.replace(arg1, arg2); -} - -function replaceByRe(arg1, arg2, obj) { - return obj.replace(arg1, arg2); -} - -function unsafeReplaceBy0(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__3(arg2)); -} - -function unsafeReplaceBy1(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__4(arg2)); -} - -function unsafeReplaceBy2(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__5(arg2)); -} - -function unsafeReplaceBy3(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__6(arg2)); -} - -function search(arg1, obj) { - return obj.search(arg1); -} - -function slice(from, to_, obj) { - return obj.slice(from, to_); -} - -function sliceToEnd(from, obj) { - return obj.slice(from); -} - -function split(arg1, obj) { - return obj.split(arg1); -} - -function splitAtMost(arg1, limit, obj) { - return obj.split(arg1, limit); -} - -function splitByRe(arg1, obj) { - return obj.split(arg1); -} - -function splitByReAtMost(arg1, limit, obj) { - return obj.split(arg1, limit); -} - -function startsWith(arg1, obj) { - return obj.startsWith(arg1); -} - -function startsWithFrom(arg1, arg2, obj) { - return obj.startsWith(arg1, arg2); -} - -function substr(from, obj) { - return obj.substr(from); -} - -function substrAtMost(from, length, obj) { - return obj.substr(from, length); -} - -function substring(from, to_, obj) { - return obj.substring(from, to_); -} - -function substringToEnd(from, obj) { - return obj.substring(from); -} - -function anchor(arg1, obj) { - return obj.anchor(arg1); -} - -function link(arg1, obj) { - return obj.link(arg1); -} - -export { - charAt, - charCodeAt, - codePointAt, - concat, - concatMany, - endsWith, - endsWithFrom, - includes, - includesFrom, - indexOf, - indexOfFrom, - lastIndexOf, - lastIndexOfFrom, - localeCompare, - match_, - normalizeByForm, - repeat, - replace, - replaceByRe, - unsafeReplaceBy0, - unsafeReplaceBy1, - unsafeReplaceBy2, - unsafeReplaceBy3, - search, - slice, - sliceToEnd, - split, - splitAtMost, - splitByRe, - splitByReAtMost, - startsWith, - startsWithFrom, - substr, - substrAtMost, - substring, - substringToEnd, - anchor, - link, -} -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/es6/js_typed_array.js b/lib/es6/js_typed_array.js index 3516646992..5e2a72d2d9 100644 --- a/lib/es6/js_typed_array.js +++ b/lib/es6/js_typed_array.js @@ -1,1710 +1,25 @@ -function slice(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom(arg1, obj) { - return obj.slice(arg1); -} - -let $$ArrayBuffer = { - slice: slice, - sliceFrom: sliceFrom -}; - -function setArray(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith(arg1, obj) { - return obj.sort(arg1); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$1(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$1(arg1, obj) { - return obj.slice(arg1); -} - -function subarray(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom(arg1, obj) { - return obj.subarray(arg1); -} - -function every(arg1, obj) { - return obj.every(arg1); -} - -function everyi(arg1, obj) { - return obj.every(arg1); -} - -function filter(arg1, obj) { - return obj.filter(arg1); -} - -function filteri(arg1, obj) { - return obj.filter(arg1); -} - -function find(arg1, obj) { - return obj.find(arg1); -} - -function findi(arg1, obj) { - return obj.find(arg1); -} - -function findIndex(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi(arg1, obj) { - obj.forEach(arg1); -} - -function map(arg1, obj) { - return obj.map(arg1); -} - -function mapi(arg1, obj) { - return obj.map(arg1); -} - -function reduce(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some(arg1, obj) { - return obj.some(arg1); -} - -function somei(arg1, obj) { - return obj.some(arg1); -} - -let $$Int8Array = { - setArray: setArray, - setArrayOffset: setArrayOffset, - copyWithin: copyWithin, - copyWithinFrom: copyWithinFrom, - copyWithinFromRange: copyWithinFromRange, - fillInPlace: fillInPlace, - fillFromInPlace: fillFromInPlace, - fillRangeInPlace: fillRangeInPlace, - sortInPlaceWith: sortInPlaceWith, - includes: includes, - indexOf: indexOf, - indexOfFrom: indexOfFrom, - joinWith: joinWith, - lastIndexOf: lastIndexOf, - lastIndexOfFrom: lastIndexOfFrom, - slice: slice$1, - sliceFrom: sliceFrom$1, - subarray: subarray, - subarrayFrom: subarrayFrom, - every: every, - everyi: everyi, - filter: filter, - filteri: filteri, - find: find, - findi: findi, - findIndex: findIndex, - findIndexi: findIndexi, - forEach: forEach, - forEachi: forEachi, - map: map, - mapi: mapi, - reduce: reduce, - reducei: reducei, - reduceRight: reduceRight, - reduceRighti: reduceRighti, - some: some, - somei: somei -}; - -function setArray$1(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$1(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$1(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$1(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$1(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$1(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$1(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$1(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$1(arg1, obj) { - return obj.sort(arg1); -} - -function includes$1(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$1(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$1(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$1(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$1(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$1(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$2(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$2(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$1(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$1(arg1, obj) { - return obj.subarray(arg1); -} - -function every$1(arg1, obj) { - return obj.every(arg1); -} - -function everyi$1(arg1, obj) { - return obj.every(arg1); -} - -function filter$1(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$1(arg1, obj) { - return obj.filter(arg1); -} - -function find$1(arg1, obj) { - return obj.find(arg1); -} - -function findi$1(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$1(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$1(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$1(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$1(arg1, obj) { - obj.forEach(arg1); -} - -function map$1(arg1, obj) { - return obj.map(arg1); -} - -function mapi$1(arg1, obj) { - return obj.map(arg1); -} - -function reduce$1(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$1(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$1(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$1(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$1(arg1, obj) { - return obj.some(arg1); -} - -function somei$1(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint8Array = { - setArray: setArray$1, - setArrayOffset: setArrayOffset$1, - copyWithin: copyWithin$1, - copyWithinFrom: copyWithinFrom$1, - copyWithinFromRange: copyWithinFromRange$1, - fillInPlace: fillInPlace$1, - fillFromInPlace: fillFromInPlace$1, - fillRangeInPlace: fillRangeInPlace$1, - sortInPlaceWith: sortInPlaceWith$1, - includes: includes$1, - indexOf: indexOf$1, - indexOfFrom: indexOfFrom$1, - joinWith: joinWith$1, - lastIndexOf: lastIndexOf$1, - lastIndexOfFrom: lastIndexOfFrom$1, - slice: slice$2, - sliceFrom: sliceFrom$2, - subarray: subarray$1, - subarrayFrom: subarrayFrom$1, - every: every$1, - everyi: everyi$1, - filter: filter$1, - filteri: filteri$1, - find: find$1, - findi: findi$1, - findIndex: findIndex$1, - findIndexi: findIndexi$1, - forEach: forEach$1, - forEachi: forEachi$1, - map: map$1, - mapi: mapi$1, - reduce: reduce$1, - reducei: reducei$1, - reduceRight: reduceRight$1, - reduceRighti: reduceRighti$1, - some: some$1, - somei: somei$1 -}; - -function setArray$2(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$2(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$2(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$2(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$2(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$2(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$2(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$2(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$2(arg1, obj) { - return obj.sort(arg1); -} - -function includes$2(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$2(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$2(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$2(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$2(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$2(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$3(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$3(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$2(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$2(arg1, obj) { - return obj.subarray(arg1); -} - -function every$2(arg1, obj) { - return obj.every(arg1); -} - -function everyi$2(arg1, obj) { - return obj.every(arg1); -} - -function filter$2(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$2(arg1, obj) { - return obj.filter(arg1); -} - -function find$2(arg1, obj) { - return obj.find(arg1); -} - -function findi$2(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$2(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$2(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$2(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$2(arg1, obj) { - obj.forEach(arg1); -} - -function map$2(arg1, obj) { - return obj.map(arg1); -} - -function mapi$2(arg1, obj) { - return obj.map(arg1); -} - -function reduce$2(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$2(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$2(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$2(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$2(arg1, obj) { - return obj.some(arg1); -} - -function somei$2(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint8ClampedArray = { - setArray: setArray$2, - setArrayOffset: setArrayOffset$2, - copyWithin: copyWithin$2, - copyWithinFrom: copyWithinFrom$2, - copyWithinFromRange: copyWithinFromRange$2, - fillInPlace: fillInPlace$2, - fillFromInPlace: fillFromInPlace$2, - fillRangeInPlace: fillRangeInPlace$2, - sortInPlaceWith: sortInPlaceWith$2, - includes: includes$2, - indexOf: indexOf$2, - indexOfFrom: indexOfFrom$2, - joinWith: joinWith$2, - lastIndexOf: lastIndexOf$2, - lastIndexOfFrom: lastIndexOfFrom$2, - slice: slice$3, - sliceFrom: sliceFrom$3, - subarray: subarray$2, - subarrayFrom: subarrayFrom$2, - every: every$2, - everyi: everyi$2, - filter: filter$2, - filteri: filteri$2, - find: find$2, - findi: findi$2, - findIndex: findIndex$2, - findIndexi: findIndexi$2, - forEach: forEach$2, - forEachi: forEachi$2, - map: map$2, - mapi: mapi$2, - reduce: reduce$2, - reducei: reducei$2, - reduceRight: reduceRight$2, - reduceRighti: reduceRighti$2, - some: some$2, - somei: somei$2 -}; - -function setArray$3(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$3(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$3(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$3(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$3(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$3(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$3(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$3(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$3(arg1, obj) { - return obj.sort(arg1); -} - -function includes$3(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$3(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$3(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$3(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$3(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$3(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$4(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$4(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$3(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$3(arg1, obj) { - return obj.subarray(arg1); -} - -function every$3(arg1, obj) { - return obj.every(arg1); -} - -function everyi$3(arg1, obj) { - return obj.every(arg1); -} - -function filter$3(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$3(arg1, obj) { - return obj.filter(arg1); -} - -function find$3(arg1, obj) { - return obj.find(arg1); -} - -function findi$3(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$3(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$3(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$3(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$3(arg1, obj) { - obj.forEach(arg1); -} - -function map$3(arg1, obj) { - return obj.map(arg1); -} - -function mapi$3(arg1, obj) { - return obj.map(arg1); -} - -function reduce$3(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$3(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$3(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$3(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$3(arg1, obj) { - return obj.some(arg1); -} - -function somei$3(arg1, obj) { - return obj.some(arg1); -} - -let $$Int16Array = { - setArray: setArray$3, - setArrayOffset: setArrayOffset$3, - copyWithin: copyWithin$3, - copyWithinFrom: copyWithinFrom$3, - copyWithinFromRange: copyWithinFromRange$3, - fillInPlace: fillInPlace$3, - fillFromInPlace: fillFromInPlace$3, - fillRangeInPlace: fillRangeInPlace$3, - sortInPlaceWith: sortInPlaceWith$3, - includes: includes$3, - indexOf: indexOf$3, - indexOfFrom: indexOfFrom$3, - joinWith: joinWith$3, - lastIndexOf: lastIndexOf$3, - lastIndexOfFrom: lastIndexOfFrom$3, - slice: slice$4, - sliceFrom: sliceFrom$4, - subarray: subarray$3, - subarrayFrom: subarrayFrom$3, - every: every$3, - everyi: everyi$3, - filter: filter$3, - filteri: filteri$3, - find: find$3, - findi: findi$3, - findIndex: findIndex$3, - findIndexi: findIndexi$3, - forEach: forEach$3, - forEachi: forEachi$3, - map: map$3, - mapi: mapi$3, - reduce: reduce$3, - reducei: reducei$3, - reduceRight: reduceRight$3, - reduceRighti: reduceRighti$3, - some: some$3, - somei: somei$3 -}; - -function setArray$4(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$4(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$4(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$4(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$4(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$4(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$4(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$4(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$4(arg1, obj) { - return obj.sort(arg1); -} - -function includes$4(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$4(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$4(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$4(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$4(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$4(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$5(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$5(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$4(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$4(arg1, obj) { - return obj.subarray(arg1); -} - -function every$4(arg1, obj) { - return obj.every(arg1); -} - -function everyi$4(arg1, obj) { - return obj.every(arg1); -} - -function filter$4(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$4(arg1, obj) { - return obj.filter(arg1); -} - -function find$4(arg1, obj) { - return obj.find(arg1); -} - -function findi$4(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$4(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$4(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$4(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$4(arg1, obj) { - obj.forEach(arg1); -} - -function map$4(arg1, obj) { - return obj.map(arg1); -} - -function mapi$4(arg1, obj) { - return obj.map(arg1); -} - -function reduce$4(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$4(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$4(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$4(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$4(arg1, obj) { - return obj.some(arg1); -} - -function somei$4(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint16Array = { - setArray: setArray$4, - setArrayOffset: setArrayOffset$4, - copyWithin: copyWithin$4, - copyWithinFrom: copyWithinFrom$4, - copyWithinFromRange: copyWithinFromRange$4, - fillInPlace: fillInPlace$4, - fillFromInPlace: fillFromInPlace$4, - fillRangeInPlace: fillRangeInPlace$4, - sortInPlaceWith: sortInPlaceWith$4, - includes: includes$4, - indexOf: indexOf$4, - indexOfFrom: indexOfFrom$4, - joinWith: joinWith$4, - lastIndexOf: lastIndexOf$4, - lastIndexOfFrom: lastIndexOfFrom$4, - slice: slice$5, - sliceFrom: sliceFrom$5, - subarray: subarray$4, - subarrayFrom: subarrayFrom$4, - every: every$4, - everyi: everyi$4, - filter: filter$4, - filteri: filteri$4, - find: find$4, - findi: findi$4, - findIndex: findIndex$4, - findIndexi: findIndexi$4, - forEach: forEach$4, - forEachi: forEachi$4, - map: map$4, - mapi: mapi$4, - reduce: reduce$4, - reducei: reducei$4, - reduceRight: reduceRight$4, - reduceRighti: reduceRighti$4, - some: some$4, - somei: somei$4 -}; - -function setArray$5(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$5(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$5(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$5(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$5(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$5(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$5(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$5(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$5(arg1, obj) { - return obj.sort(arg1); -} - -function includes$5(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$5(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$5(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$5(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$5(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$5(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$6(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$6(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$5(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$5(arg1, obj) { - return obj.subarray(arg1); -} - -function every$5(arg1, obj) { - return obj.every(arg1); -} - -function everyi$5(arg1, obj) { - return obj.every(arg1); -} - -function filter$5(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$5(arg1, obj) { - return obj.filter(arg1); -} - -function find$5(arg1, obj) { - return obj.find(arg1); -} - -function findi$5(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$5(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$5(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$5(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$5(arg1, obj) { - obj.forEach(arg1); -} - -function map$5(arg1, obj) { - return obj.map(arg1); -} - -function mapi$5(arg1, obj) { - return obj.map(arg1); -} - -function reduce$5(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$5(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$5(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$5(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$5(arg1, obj) { - return obj.some(arg1); -} - -function somei$5(arg1, obj) { - return obj.some(arg1); -} - -let $$Int32Array = { - setArray: setArray$5, - setArrayOffset: setArrayOffset$5, - copyWithin: copyWithin$5, - copyWithinFrom: copyWithinFrom$5, - copyWithinFromRange: copyWithinFromRange$5, - fillInPlace: fillInPlace$5, - fillFromInPlace: fillFromInPlace$5, - fillRangeInPlace: fillRangeInPlace$5, - sortInPlaceWith: sortInPlaceWith$5, - includes: includes$5, - indexOf: indexOf$5, - indexOfFrom: indexOfFrom$5, - joinWith: joinWith$5, - lastIndexOf: lastIndexOf$5, - lastIndexOfFrom: lastIndexOfFrom$5, - slice: slice$6, - sliceFrom: sliceFrom$6, - subarray: subarray$5, - subarrayFrom: subarrayFrom$5, - every: every$5, - everyi: everyi$5, - filter: filter$5, - filteri: filteri$5, - find: find$5, - findi: findi$5, - findIndex: findIndex$5, - findIndexi: findIndexi$5, - forEach: forEach$5, - forEachi: forEachi$5, - map: map$5, - mapi: mapi$5, - reduce: reduce$5, - reducei: reducei$5, - reduceRight: reduceRight$5, - reduceRighti: reduceRighti$5, - some: some$5, - somei: somei$5 -}; - -function setArray$6(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$6(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$6(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$6(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$6(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$6(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$6(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$6(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$6(arg1, obj) { - return obj.sort(arg1); -} - -function includes$6(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$6(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$6(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$6(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$6(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$6(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$7(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$7(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$6(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$6(arg1, obj) { - return obj.subarray(arg1); -} - -function every$6(arg1, obj) { - return obj.every(arg1); -} - -function everyi$6(arg1, obj) { - return obj.every(arg1); -} - -function filter$6(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$6(arg1, obj) { - return obj.filter(arg1); -} - -function find$6(arg1, obj) { - return obj.find(arg1); -} - -function findi$6(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$6(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$6(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$6(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$6(arg1, obj) { - obj.forEach(arg1); -} - -function map$6(arg1, obj) { - return obj.map(arg1); -} - -function mapi$6(arg1, obj) { - return obj.map(arg1); -} - -function reduce$6(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$6(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$6(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$6(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$6(arg1, obj) { - return obj.some(arg1); -} - -function somei$6(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint32Array = { - setArray: setArray$6, - setArrayOffset: setArrayOffset$6, - copyWithin: copyWithin$6, - copyWithinFrom: copyWithinFrom$6, - copyWithinFromRange: copyWithinFromRange$6, - fillInPlace: fillInPlace$6, - fillFromInPlace: fillFromInPlace$6, - fillRangeInPlace: fillRangeInPlace$6, - sortInPlaceWith: sortInPlaceWith$6, - includes: includes$6, - indexOf: indexOf$6, - indexOfFrom: indexOfFrom$6, - joinWith: joinWith$6, - lastIndexOf: lastIndexOf$6, - lastIndexOfFrom: lastIndexOfFrom$6, - slice: slice$7, - sliceFrom: sliceFrom$7, - subarray: subarray$6, - subarrayFrom: subarrayFrom$6, - every: every$6, - everyi: everyi$6, - filter: filter$6, - filteri: filteri$6, - find: find$6, - findi: findi$6, - findIndex: findIndex$6, - findIndexi: findIndexi$6, - forEach: forEach$6, - forEachi: forEachi$6, - map: map$6, - mapi: mapi$6, - reduce: reduce$6, - reducei: reducei$6, - reduceRight: reduceRight$6, - reduceRighti: reduceRighti$6, - some: some$6, - somei: somei$6 -}; - -function setArray$7(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$7(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$7(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$7(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$7(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$7(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$7(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$7(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$7(arg1, obj) { - return obj.sort(arg1); -} - -function includes$7(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$7(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$7(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$7(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$7(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$7(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$8(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$8(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$7(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$7(arg1, obj) { - return obj.subarray(arg1); -} - -function every$7(arg1, obj) { - return obj.every(arg1); -} - -function everyi$7(arg1, obj) { - return obj.every(arg1); -} - -function filter$7(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$7(arg1, obj) { - return obj.filter(arg1); -} - -function find$7(arg1, obj) { - return obj.find(arg1); -} - -function findi$7(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$7(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$7(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$7(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$7(arg1, obj) { - obj.forEach(arg1); -} - -function map$7(arg1, obj) { - return obj.map(arg1); -} - -function mapi$7(arg1, obj) { - return obj.map(arg1); -} - -function reduce$7(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$7(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$7(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$7(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$7(arg1, obj) { - return obj.some(arg1); -} - -function somei$7(arg1, obj) { - return obj.some(arg1); -} - -let $$Float32Array = { - setArray: setArray$7, - setArrayOffset: setArrayOffset$7, - copyWithin: copyWithin$7, - copyWithinFrom: copyWithinFrom$7, - copyWithinFromRange: copyWithinFromRange$7, - fillInPlace: fillInPlace$7, - fillFromInPlace: fillFromInPlace$7, - fillRangeInPlace: fillRangeInPlace$7, - sortInPlaceWith: sortInPlaceWith$7, - includes: includes$7, - indexOf: indexOf$7, - indexOfFrom: indexOfFrom$7, - joinWith: joinWith$7, - lastIndexOf: lastIndexOf$7, - lastIndexOfFrom: lastIndexOfFrom$7, - slice: slice$8, - sliceFrom: sliceFrom$8, - subarray: subarray$7, - subarrayFrom: subarrayFrom$7, - every: every$7, - everyi: everyi$7, - filter: filter$7, - filteri: filteri$7, - find: find$7, - findi: findi$7, - findIndex: findIndex$7, - findIndexi: findIndexi$7, - forEach: forEach$7, - forEachi: forEachi$7, - map: map$7, - mapi: mapi$7, - reduce: reduce$7, - reducei: reducei$7, - reduceRight: reduceRight$7, - reduceRighti: reduceRighti$7, - some: some$7, - somei: somei$7 -}; - -function setArray$8(arg1, obj) { - obj.set(arg1); -} +let $$ArrayBuffer = {}; -function setArrayOffset$8(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$8(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$8(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$8(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$8(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$8(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$8(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$8(arg1, obj) { - return obj.sort(arg1); -} - -function includes$8(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$8(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$8(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$8(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$8(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$8(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$9(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$9(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$8(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$8(arg1, obj) { - return obj.subarray(arg1); -} - -function every$8(arg1, obj) { - return obj.every(arg1); -} - -function everyi$8(arg1, obj) { - return obj.every(arg1); -} - -function filter$8(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$8(arg1, obj) { - return obj.filter(arg1); -} - -function find$8(arg1, obj) { - return obj.find(arg1); -} - -function findi$8(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$8(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$8(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$8(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$8(arg1, obj) { - obj.forEach(arg1); -} - -function map$8(arg1, obj) { - return obj.map(arg1); -} +let $$Int8Array = {}; -function mapi$8(arg1, obj) { - return obj.map(arg1); -} +let $$Uint8Array = {}; -function reduce$8(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} +let $$Uint8ClampedArray = {}; -function reducei$8(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} +let $$Int16Array = {}; -function reduceRight$8(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} +let $$Uint16Array = {}; -function reduceRighti$8(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} +let $$Int32Array = {}; -function some$8(arg1, obj) { - return obj.some(arg1); -} +let $$Uint32Array = {}; -function somei$8(arg1, obj) { - return obj.some(arg1); -} +let $$Float32Array = {}; -let $$Float64Array = { - setArray: setArray$8, - setArrayOffset: setArrayOffset$8, - copyWithin: copyWithin$8, - copyWithinFrom: copyWithinFrom$8, - copyWithinFromRange: copyWithinFromRange$8, - fillInPlace: fillInPlace$8, - fillFromInPlace: fillFromInPlace$8, - fillRangeInPlace: fillRangeInPlace$8, - sortInPlaceWith: sortInPlaceWith$8, - includes: includes$8, - indexOf: indexOf$8, - indexOfFrom: indexOfFrom$8, - joinWith: joinWith$8, - lastIndexOf: lastIndexOf$8, - lastIndexOfFrom: lastIndexOfFrom$8, - slice: slice$9, - sliceFrom: sliceFrom$9, - subarray: subarray$8, - subarrayFrom: subarrayFrom$8, - every: every$8, - everyi: everyi$8, - filter: filter$8, - filteri: filteri$8, - find: find$8, - findi: findi$8, - findIndex: findIndex$8, - findIndexi: findIndexi$8, - forEach: forEach$8, - forEachi: forEachi$8, - map: map$8, - mapi: mapi$8, - reduce: reduce$8, - reducei: reducei$8, - reduceRight: reduceRight$8, - reduceRighti: reduceRighti$8, - some: some$8, - somei: somei$8 -}; +let $$Float64Array = {}; let $$DataView = {}; diff --git a/lib/es6/pervasives.js b/lib/es6/pervasives.js index b78aff7d9c..62711d8580 100644 --- a/lib/es6/pervasives.js +++ b/lib/es6/pervasives.js @@ -1,6 +1,5 @@ -import * as Curry from "./curry.js"; import * as Caml_sys from "./caml_sys.js"; import * as Caml_format from "./caml_format.js"; import * as Caml_string from "./caml_string.js"; @@ -171,11 +170,11 @@ function $at(l1, l2) { } } -function print_newline(param) { +function print_newline() { console.log(""); } -function prerr_newline(param) { +function prerr_newline() { console.error(""); } @@ -184,7 +183,7 @@ function print_int(i) { } function print_float(i) { - console.log(valid_float_lexem(Caml_format.format_float("%.12g", i))); + console.log(string_of_float(i)); } function print_string(prim) { @@ -199,14 +198,14 @@ let exit_function = { function at_exit(f) { let g = exit_function.contents; - exit_function.contents = (function (param) { - Curry._1(f, undefined); - Curry._1(g, undefined); + exit_function.contents = (function () { + f(); + g(); }); } function exit(retcode) { - Curry._1(exit_function.contents, undefined); + exit_function.contents(); return Caml_sys.sys_exit(retcode); } diff --git a/lib/js/belt_Array.js b/lib/js/belt_Array.js index c20902dd62..b805fdd91b 100644 --- a/lib/js/belt_Array.js +++ b/lib/js/belt_Array.js @@ -1,7 +1,6 @@ 'use strict'; let Caml = require("./caml.js"); -let Curry = require("./curry.js"); let Js_math = require("./js_math.js"); let Caml_option = require("./caml_option.js"); @@ -110,7 +109,9 @@ function makeByU(l, f) { } function makeBy(l, f) { - return makeByU(l, Curry.__1(f)); + return makeByU(l, (function (a) { + return f(a); + })); } function makeByAndShuffleU(l, f) { @@ -120,7 +121,9 @@ function makeByAndShuffleU(l, f) { } function makeByAndShuffle(l, f) { - return makeByAndShuffleU(l, Curry.__1(f)); + return makeByAndShuffleU(l, (function (a) { + return f(a); + })); } function range(start, finish) { @@ -176,7 +179,9 @@ function zipByU(xs, ys, f) { } function zipBy(xs, ys, f) { - return zipByU(xs, ys, Curry.__2(f)); + return zipByU(xs, ys, (function (a, b) { + return f(a, b); + })); } function concat(a1, a2) { @@ -291,7 +296,9 @@ function forEachU(a, f) { } function forEach(a, f) { - forEachU(a, Curry.__1(f)); + forEachU(a, (function (a) { + f(a); + })); } function mapU(a, f) { @@ -304,7 +311,9 @@ function mapU(a, f) { } function map(a, f) { - return mapU(a, Curry.__1(f)); + return mapU(a, (function (a) { + return f(a); + })); } function flatMapU(a, f) { @@ -312,7 +321,9 @@ function flatMapU(a, f) { } function flatMap(a, f) { - return concatMany(mapU(a, Curry.__1(f))); + return flatMapU(a, (function (a) { + return f(a); + })); } function getByU(a, p) { @@ -330,7 +341,9 @@ function getByU(a, p) { } function getBy(a, p) { - return getByU(a, Curry.__1(p)); + return getByU(a, (function (a) { + return p(a); + })); } function getIndexByU(a, p) { @@ -348,7 +361,9 @@ function getIndexByU(a, p) { } function getIndexBy(a, p) { - return getIndexByU(a, Curry.__1(p)); + return getIndexByU(a, (function (a) { + return p(a); + })); } function keepU(a, f) { @@ -368,7 +383,9 @@ function keepU(a, f) { } function keep(a, f) { - return keepU(a, Curry.__1(f)); + return keepU(a, (function (a) { + return f(a); + })); } function keepWithIndexU(a, f) { @@ -388,7 +405,9 @@ function keepWithIndexU(a, f) { } function keepWithIndex(a, f) { - return keepWithIndexU(a, Curry.__2(f)); + return keepWithIndexU(a, (function (a, i) { + return f(a, i); + })); } function keepMapU(a, f) { @@ -409,7 +428,9 @@ function keepMapU(a, f) { } function keepMap(a, f) { - return keepMapU(a, Curry.__1(f)); + return keepMapU(a, (function (a) { + return f(a); + })); } function forEachWithIndexU(a, f) { @@ -419,7 +440,9 @@ function forEachWithIndexU(a, f) { } function forEachWithIndex(a, f) { - forEachWithIndexU(a, Curry.__2(f)); + forEachWithIndexU(a, (function (a, b) { + f(a, b); + })); } function mapWithIndexU(a, f) { @@ -432,7 +455,9 @@ function mapWithIndexU(a, f) { } function mapWithIndex(a, f) { - return mapWithIndexU(a, Curry.__2(f)); + return mapWithIndexU(a, (function (a, b) { + return f(a, b); + })); } function reduceU(a, x, f) { @@ -444,7 +469,9 @@ function reduceU(a, x, f) { } function reduce(a, x, f) { - return reduceU(a, x, Curry.__2(f)); + return reduceU(a, x, (function (a, b) { + return f(a, b); + })); } function reduceReverseU(a, x, f) { @@ -456,7 +483,9 @@ function reduceReverseU(a, x, f) { } function reduceReverse(a, x, f) { - return reduceReverseU(a, x, Curry.__2(f)); + return reduceReverseU(a, x, (function (a, b) { + return f(a, b); + })); } function reduceReverse2U(a, b, x, f) { @@ -469,7 +498,9 @@ function reduceReverse2U(a, b, x, f) { } function reduceReverse2(a, b, x, f) { - return reduceReverse2U(a, b, x, Curry.__3(f)); + return reduceReverse2U(a, b, x, (function (a, b, c) { + return f(a, b, c); + })); } function reduceWithIndexU(a, x, f) { @@ -481,7 +512,9 @@ function reduceWithIndexU(a, x, f) { } function reduceWithIndex(a, x, f) { - return reduceWithIndexU(a, x, Curry.__3(f)); + return reduceWithIndexU(a, x, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(arr, b) { @@ -501,7 +534,9 @@ function everyU(arr, b) { } function every(arr, f) { - return everyU(arr, Curry.__1(f)); + return everyU(arr, (function (b) { + return f(b); + })); } function someU(arr, b) { @@ -521,7 +556,9 @@ function someU(arr, b) { } function some(arr, f) { - return someU(arr, Curry.__1(f)); + return someU(arr, (function (b) { + return f(b); + })); } function everyAux2(arr1, arr2, _i, b, len) { @@ -543,7 +580,9 @@ function every2U(a, b, p) { } function every2(a, b, p) { - return every2U(a, b, Curry.__2(p)); + return every2U(a, b, (function (a, b) { + return p(a, b); + })); } function some2U(a, b, p) { @@ -563,7 +602,9 @@ function some2U(a, b, p) { } function some2(a, b, p) { - return some2U(a, b, Curry.__2(p)); + return some2U(a, b, (function (a, b) { + return p(a, b); + })); } function eqU(a, b, p) { @@ -577,7 +618,9 @@ function eqU(a, b, p) { } function eq(a, b, p) { - return eqU(a, b, Curry.__2(p)); + return eqU(a, b, (function (a, b) { + return p(a, b); + })); } function cmpU(a, b, p) { @@ -605,7 +648,9 @@ function cmpU(a, b, p) { } function cmp(a, b, p) { - return cmpU(a, b, Curry.__2(p)); + return cmpU(a, b, (function (a, b) { + return p(a, b); + })); } function partitionU(a, f) { @@ -633,7 +678,9 @@ function partitionU(a, f) { } function partition(a, f) { - return partitionU(a, Curry.__1(f)); + return partitionU(a, (function (x) { + return f(x); + })); } function unzip(a) { @@ -672,7 +719,9 @@ function joinWithU(a, sep, toString) { } function joinWith(a, sep, toString) { - return joinWithU(a, sep, Curry.__1(toString)); + return joinWithU(a, sep, (function (x) { + return toString(x); + })); } function initU(n, f) { @@ -684,7 +733,9 @@ function initU(n, f) { } function init(n, f) { - return initU(n, Curry.__1(f)); + return initU(n, (function (i) { + return f(i); + })); } exports.get = get; diff --git a/lib/js/belt_HashMapInt.js b/lib/js/belt_HashMapInt.js index 7c91e287d5..69e651f5a1 100644 --- a/lib/js/belt_HashMapInt.js +++ b/lib/js/belt_HashMapInt.js @@ -193,7 +193,7 @@ function size(h) { function fromArray(arr) { let len = arr.length; - let v = Belt_internalBucketsType.make(undefined, undefined, len); + let v = make(len); for(let i = 0; i < len; ++i){ let match = arr[i]; set(v, match[0], match[1]); diff --git a/lib/js/belt_HashMapString.js b/lib/js/belt_HashMapString.js index 258b989a29..ee4a0d8f31 100644 --- a/lib/js/belt_HashMapString.js +++ b/lib/js/belt_HashMapString.js @@ -193,7 +193,7 @@ function size(h) { function fromArray(arr) { let len = arr.length; - let v = Belt_internalBucketsType.make(undefined, undefined, len); + let v = make(len); for(let i = 0; i < len; ++i){ let match = arr[i]; set(v, match[0], match[1]); diff --git a/lib/js/belt_Id.js b/lib/js/belt_Id.js index 2a855d8e40..04d2ce0b37 100644 --- a/lib/js/belt_Id.js +++ b/lib/js/belt_Id.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); function MakeComparableU(M) { return M; @@ -8,7 +7,9 @@ function MakeComparableU(M) { function MakeComparable(M) { let cmp = M.cmp; - let cmp$1 = Curry.__2(cmp); + let cmp$1 = function (a, b) { + return cmp(a, b); + }; return { cmp: cmp$1 }; @@ -21,7 +22,9 @@ function comparableU(cmp) { } function comparable(cmp) { - let cmp$1 = Curry.__2(cmp); + let cmp$1 = function (a, b) { + return cmp(a, b); + }; return { cmp: cmp$1 }; @@ -33,9 +36,13 @@ function MakeHashableU(M) { function MakeHashable(M) { let hash = M.hash; - let hash$1 = Curry.__1(hash); + let hash$1 = function (a) { + return hash(a); + }; let eq = M.eq; - let eq$1 = Curry.__2(eq); + let eq$1 = function (a, b) { + return eq(a, b); + }; return { hash: hash$1, eq: eq$1 @@ -50,8 +57,12 @@ function hashableU(hash, eq) { } function hashable(hash, eq) { - let hash$1 = Curry.__1(hash); - let eq$1 = Curry.__2(eq); + let hash$1 = function (a) { + return hash(a); + }; + let eq$1 = function (a, b) { + return eq(a, b); + }; return { hash: hash$1, eq: eq$1 diff --git a/lib/js/belt_List.js b/lib/js/belt_List.js index 35818de614..569aba693a 100644 --- a/lib/js/belt_List.js +++ b/lib/js/belt_List.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_Array = require("./belt_Array.js"); let Caml_option = require("./caml_option.js"); let Belt_SortArray = require("./belt_SortArray.js"); @@ -523,7 +522,9 @@ function mapU(xs, f) { } function map(xs, f) { - return mapU(xs, Curry.__1(f)); + return mapU(xs, (function (x) { + return f(x); + })); } function zipByU(l1, l2, f) { @@ -542,7 +543,9 @@ function zipByU(l1, l2, f) { } function zipBy(l1, l2, f) { - return zipByU(l1, l2, Curry.__2(f)); + return zipByU(l1, l2, (function (x, y) { + return f(x, y); + })); } function mapWithIndexU(xs, f) { @@ -558,7 +561,9 @@ function mapWithIndexU(xs, f) { } function mapWithIndex(xs, f) { - return mapWithIndexU(xs, Curry.__2(f)); + return mapWithIndexU(xs, (function (i, x) { + return f(i, x); + })); } function makeByU(n, f) { @@ -584,7 +589,9 @@ function makeByU(n, f) { } function makeBy(n, f) { - return makeByU(n, Curry.__1(f)); + return makeByU(n, (function (x) { + return f(x); + })); } function make(n, v) { @@ -758,7 +765,9 @@ function mapReverseU(l, f) { } function mapReverse(l, f) { - return mapReverseU(l, Curry.__1(f)); + return mapReverseU(l, (function (x) { + return f(x); + })); } function forEachU(_xs, f) { @@ -774,7 +783,9 @@ function forEachU(_xs, f) { } function forEach(xs, f) { - forEachU(xs, Curry.__1(f)); + forEachU(xs, (function (x) { + return f(x); + })); } function forEachWithIndexU(l, f) { @@ -794,7 +805,9 @@ function forEachWithIndexU(l, f) { } function forEachWithIndex(l, f) { - forEachWithIndexU(l, Curry.__2(f)); + forEachWithIndexU(l, (function (i, x) { + return f(i, x); + })); } function reduceU(_l, _accu, f) { @@ -811,7 +824,9 @@ function reduceU(_l, _accu, f) { } function reduce(l, accu, f) { - return reduceU(l, accu, Curry.__2(f)); + return reduceU(l, accu, (function (acc, x) { + return f(acc, x); + })); } function reduceReverseUnsafeU(l, accu, f) { @@ -832,7 +847,9 @@ function reduceReverseU(l, acc, f) { } function reduceReverse(l, accu, f) { - return reduceReverseU(l, accu, Curry.__2(f)); + return reduceReverseU(l, accu, (function (a, b) { + return f(a, b); + })); } function reduceWithIndexU(l, acc, f) { @@ -854,7 +871,9 @@ function reduceWithIndexU(l, acc, f) { } function reduceWithIndex(l, acc, f) { - return reduceWithIndexU(l, acc, Curry.__3(f)); + return reduceWithIndexU(l, acc, (function (acc, x, i) { + return f(acc, x, i); + })); } function mapReverse2U(l1, l2, f) { @@ -882,7 +901,9 @@ function mapReverse2U(l1, l2, f) { } function mapReverse2(l1, l2, f) { - return mapReverse2U(l1, l2, Curry.__2(f)); + return mapReverse2U(l1, l2, (function (a, b) { + return f(a, b); + })); } function forEach2U(_l1, _l2, f) { @@ -903,7 +924,9 @@ function forEach2U(_l1, _l2, f) { } function forEach2(l1, l2, f) { - forEach2U(l1, l2, Curry.__2(f)); + forEach2U(l1, l2, (function (a, b) { + return f(a, b); + })); } function reduce2U(_l1, _l2, _accu, f) { @@ -925,7 +948,9 @@ function reduce2U(_l1, _l2, _accu, f) { } function reduce2(l1, l2, acc, f) { - return reduce2U(l1, l2, acc, Curry.__3(f)); + return reduce2U(l1, l2, acc, (function (a, b, c) { + return f(a, b, c); + })); } function reduceReverse2UnsafeU(l1, l2, accu, f) { @@ -946,7 +971,9 @@ function reduceReverse2U(l1, l2, acc, f) { } function reduceReverse2(l1, l2, acc, f) { - return reduceReverse2U(l1, l2, acc, Curry.__3(f)); + return reduceReverse2U(l1, l2, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(_xs, p) { @@ -964,7 +991,9 @@ function everyU(_xs, p) { } function every(xs, p) { - return everyU(xs, Curry.__1(p)); + return everyU(xs, (function (x) { + return p(x); + })); } function someU(_xs, p) { @@ -982,7 +1011,9 @@ function someU(_xs, p) { } function some(xs, p) { - return someU(xs, Curry.__1(p)); + return someU(xs, (function (x) { + return p(x); + })); } function every2U(_l1, _l2, p) { @@ -1005,7 +1036,9 @@ function every2U(_l1, _l2, p) { } function every2(l1, l2, p) { - return every2U(l1, l2, Curry.__2(p)); + return every2U(l1, l2, (function (a, b) { + return p(a, b); + })); } function cmpByLength(_l1, _l2) { @@ -1053,7 +1086,9 @@ function cmpU(_l1, _l2, p) { } function cmp(l1, l2, f) { - return cmpU(l1, l2, Curry.__2(f)); + return cmpU(l1, l2, (function (x, y) { + return f(x, y); + })); } function eqU(_l1, _l2, p) { @@ -1080,7 +1115,9 @@ function eqU(_l1, _l2, p) { } function eq(l1, l2, f) { - return eqU(l1, l2, Curry.__2(f)); + return eqU(l1, l2, (function (x, y) { + return f(x, y); + })); } function some2U(_l1, _l2, p) { @@ -1103,7 +1140,9 @@ function some2U(_l1, _l2, p) { } function some2(l1, l2, p) { - return some2U(l1, l2, Curry.__2(p)); + return some2U(l1, l2, (function (a, b) { + return p(a, b); + })); } function hasU(_xs, x, eq) { @@ -1121,7 +1160,9 @@ function hasU(_xs, x, eq) { } function has(xs, x, eq) { - return hasU(xs, x, Curry.__2(eq)); + return hasU(xs, x, (function (a, b) { + return eq(a, b); + })); } function getAssocU(_xs, x, eq) { @@ -1140,7 +1181,9 @@ function getAssocU(_xs, x, eq) { } function getAssoc(xs, x, eq) { - return getAssocU(xs, x, Curry.__2(eq)); + return getAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function hasAssocU(_xs, x, eq) { @@ -1158,7 +1201,9 @@ function hasAssocU(_xs, x, eq) { } function hasAssoc(xs, x, eq) { - return hasAssocU(xs, x, Curry.__2(eq)); + return hasAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function removeAssocU(xs, x, eq) { @@ -1183,7 +1228,9 @@ function removeAssocU(xs, x, eq) { } function removeAssoc(xs, x, eq) { - return removeAssocU(xs, x, Curry.__2(eq)); + return removeAssocU(xs, x, (function (a, b) { + return eq(a, b); + })); } function setAssocU(xs, x, k, eq) { @@ -1226,7 +1273,9 @@ function setAssocU(xs, x, k, eq) { } function setAssoc(xs, x, k, eq) { - return setAssocU(xs, x, k, Curry.__2(eq)); + return setAssocU(xs, x, k, (function (a, b) { + return eq(a, b); + })); } function sortU(xs, cmp) { @@ -1236,7 +1285,9 @@ function sortU(xs, cmp) { } function sort(xs, cmp) { - return sortU(xs, Curry.__2(cmp)); + return sortU(xs, (function (x, y) { + return cmp(x, y); + })); } function getByU(_xs, p) { @@ -1255,7 +1306,9 @@ function getByU(_xs, p) { } function getBy(xs, p) { - return getByU(xs, Curry.__1(p)); + return getByU(xs, (function (a) { + return p(a); + })); } function keepU(_xs, p) { @@ -1280,7 +1333,9 @@ function keepU(_xs, p) { } function keep(xs, p) { - return keepU(xs, Curry.__1(p)); + return keepU(xs, (function (x) { + return p(x); + })); } function keepWithIndexU(xs, p) { @@ -1309,7 +1364,9 @@ function keepWithIndexU(xs, p) { } function keepWithIndex(xs, p) { - return keepWithIndexU(xs, Curry.__2(p)); + return keepWithIndexU(xs, (function (x, i) { + return p(x, i); + })); } function keepMapU(_xs, p) { @@ -1334,7 +1391,9 @@ function keepMapU(_xs, p) { } function keepMap(xs, p) { - return keepMapU(xs, Curry.__1(p)); + return keepMapU(xs, (function (x) { + return p(x); + })); } function partitionU(l, p) { @@ -1369,7 +1428,9 @@ function partitionU(l, p) { } function partition(l, p) { - return partitionU(l, Curry.__1(p)); + return partitionU(l, (function (x) { + return p(x); + })); } function unzip(xs) { diff --git a/lib/js/belt_Map.js b/lib/js/belt_Map.js index eb96116851..3db312ce0c 100644 --- a/lib/js/belt_Map.js +++ b/lib/js/belt_Map.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_MapDict = require("./belt_MapDict.js"); function fromArray(data, id) { @@ -59,7 +58,9 @@ function updateU(m, key, f) { } function update(m, key, f) { - return updateU(m, key, Curry.__1(f)); + return updateU(m, key, (function (a) { + return f(a); + })); } function split(m, x) { @@ -90,7 +91,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function make(id) { @@ -109,7 +112,9 @@ function findFirstByU(m, f) { } function findFirstBy(m, f) { - return Belt_MapDict.findFirstByU(m.data, Curry.__2(f)); + return findFirstByU(m, (function (a, b) { + return f(a, b); + })); } function forEachU(m, f) { @@ -117,7 +122,9 @@ function forEachU(m, f) { } function forEach(m, f) { - Belt_MapDict.forEachU(m.data, Curry.__2(f)); + forEachU(m, (function (a, b) { + f(a, b); + })); } function reduceU(m, acc, f) { @@ -125,7 +132,9 @@ function reduceU(m, acc, f) { } function reduce(m, acc, f) { - return reduceU(m, acc, Curry.__3(f)); + return reduceU(m, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(m, f) { @@ -133,7 +142,9 @@ function everyU(m, f) { } function every(m, f) { - return Belt_MapDict.everyU(m.data, Curry.__2(f)); + return everyU(m, (function (a, b) { + return f(a, b); + })); } function someU(m, f) { @@ -141,7 +152,9 @@ function someU(m, f) { } function some(m, f) { - return Belt_MapDict.someU(m.data, Curry.__2(f)); + return someU(m, (function (a, b) { + return f(a, b); + })); } function keepU(m, f) { @@ -152,7 +165,9 @@ function keepU(m, f) { } function keep(m, f) { - return keepU(m, Curry.__2(f)); + return keepU(m, (function (a, b) { + return f(a, b); + })); } function partitionU(m, p) { @@ -171,7 +186,9 @@ function partitionU(m, p) { } function partition(m, p) { - return partitionU(m, Curry.__2(p)); + return partitionU(m, (function (a, b) { + return p(a, b); + })); } function mapU(m, f) { @@ -182,7 +199,9 @@ function mapU(m, f) { } function map(m, f) { - return mapU(m, Curry.__1(f)); + return mapU(m, (function (a) { + return f(a); + })); } function mapWithKeyU(m, f) { @@ -193,7 +212,9 @@ function mapWithKeyU(m, f) { } function mapWithKey(m, f) { - return mapWithKeyU(m, Curry.__2(f)); + return mapWithKeyU(m, (function (a, b) { + return f(a, b); + })); } function size(map) { @@ -277,7 +298,9 @@ function eqU(m1, m2, veq) { } function eq(m1, m2, veq) { - return eqU(m1, m2, Curry.__2(veq)); + return eqU(m1, m2, (function (a, b) { + return veq(a, b); + })); } function cmpU(m1, m2, vcmp) { @@ -285,7 +308,9 @@ function cmpU(m1, m2, vcmp) { } function cmp(m1, m2, vcmp) { - return cmpU(m1, m2, Curry.__2(vcmp)); + return cmpU(m1, m2, (function (a, b) { + return vcmp(a, b); + })); } function getData(m) { diff --git a/lib/js/belt_MapDict.js b/lib/js/belt_MapDict.js index 6109ffbccf..f906153838 100644 --- a/lib/js/belt_MapDict.js +++ b/lib/js/belt_MapDict.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); @@ -76,7 +75,9 @@ function updateU(t, newK, f, cmp) { } function update(t, newK, f, cmp) { - return updateU(t, newK, Curry.__1(f), cmp); + return updateU(t, newK, (function (a) { + return f(a); + }), cmp); } function removeAux0(n, x, cmp) { @@ -244,7 +245,9 @@ function mergeU(s1, s2, f, cmp) { } function merge(s1, s2, f, cmp) { - return mergeU(s1, s2, Curry.__3(f), cmp); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + }), cmp); } function removeMany(t, keys, cmp) { diff --git a/lib/js/belt_MapInt.js b/lib/js/belt_MapInt.js index e0b7e488e7..9143413026 100644 --- a/lib/js/belt_MapInt.js +++ b/lib/js/belt_MapInt.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalMapInt = require("./belt_internalMapInt.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); @@ -73,7 +72,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - return updateU(t, x, Curry.__1(f)); + return updateU(t, x, (function (a) { + return f(a); + })); } function removeAux(n, x) { diff --git a/lib/js/belt_MapString.js b/lib/js/belt_MapString.js index 8503c91b0d..d5f2530092 100644 --- a/lib/js/belt_MapString.js +++ b/lib/js/belt_MapString.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); let Belt_internalMapString = require("./belt_internalMapString.js"); @@ -73,7 +72,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - return updateU(t, x, Curry.__1(f)); + return updateU(t, x, (function (a) { + return f(a); + })); } function removeAux(n, x) { diff --git a/lib/js/belt_MutableMap.js b/lib/js/belt_MutableMap.js index e08b10898c..13e20ff3c9 100644 --- a/lib/js/belt_MutableMap.js +++ b/lib/js/belt_MutableMap.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); @@ -137,7 +136,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function make(id) { @@ -152,8 +153,7 @@ function clear(m) { } function isEmpty(d) { - let x = d.data; - return x === undefined; + return d.data === undefined; } function minKey(m) { @@ -193,7 +193,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function reduceU(d, acc, cb) { @@ -201,7 +203,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__3(cb)); + return reduceU(d, acc, (function (a, b, c) { + return cb(a, b, c); + })); } function everyU(d, p) { @@ -209,7 +213,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(p)); + return everyU(d, (function (a, b) { + return p(a, b); + })); } function someU(d, p) { @@ -217,7 +223,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(p)); + return someU(d, (function (a, b) { + return p(a, b); + })); } function size(d) { @@ -249,7 +257,9 @@ function cmpU(m1, m2, cmp) { } function cmp(m1, m2, cmp$1) { - return cmpU(m1, m2, Curry.__2(cmp$1)); + return cmpU(m1, m2, (function (a, b) { + return cmp$1(a, b); + })); } function eqU(m1, m2, cmp) { @@ -257,7 +267,9 @@ function eqU(m1, m2, cmp) { } function eq(m1, m2, cmp) { - return eqU(m1, m2, Curry.__2(cmp)); + return eqU(m1, m2, (function (a, b) { + return cmp(a, b); + })); } function mapU(m, f) { @@ -268,7 +280,9 @@ function mapU(m, f) { } function map(m, f) { - return mapU(m, Curry.__1(f)); + return mapU(m, (function (a) { + return f(a); + })); } function mapWithKeyU(m, f) { @@ -279,7 +293,9 @@ function mapWithKeyU(m, f) { } function mapWithKey(m, f) { - return mapWithKeyU(m, Curry.__2(f)); + return mapWithKeyU(m, (function (a, b) { + return f(a, b); + })); } function get(m, x) { diff --git a/lib/js/belt_MutableMapInt.js b/lib/js/belt_MutableMapInt.js index 273d4d634c..abc68b02b1 100644 --- a/lib/js/belt_MutableMapInt.js +++ b/lib/js/belt_MutableMapInt.js @@ -1,19 +1,17 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalMapInt = require("./belt_internalMapInt.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); -function make(param) { +function make() { return { data: undefined }; } function isEmpty(m) { - let x = m.data; - return x === undefined; + return m.data === undefined; } function clear(m) { @@ -67,7 +65,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function mapU(d, f) { @@ -77,7 +77,9 @@ function mapU(d, f) { } function map(d, f) { - return mapU(d, Curry.__1(f)); + return mapU(d, (function (a) { + return f(a); + })); } function mapWithKeyU(d, f) { @@ -87,7 +89,9 @@ function mapWithKeyU(d, f) { } function mapWithKey(d, f) { - return mapWithKeyU(d, Curry.__2(f)); + return mapWithKeyU(d, (function (a, b) { + return f(a, b); + })); } function reduceU(d, acc, f) { @@ -95,7 +99,9 @@ function reduceU(d, acc, f) { } function reduce(d, acc, f) { - return reduceU(d, acc, Curry.__3(f)); + return reduceU(d, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(d, f) { @@ -103,7 +109,9 @@ function everyU(d, f) { } function every(d, f) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(f)); + return everyU(d, (function (a, b) { + return f(a, b); + })); } function someU(d, f) { @@ -111,7 +119,9 @@ function someU(d, f) { } function some(d, f) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(f)); + return someU(d, (function (a, b) { + return f(a, b); + })); } function size(d) { @@ -240,7 +250,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function removeArrayMutateAux(_t, xs, _i, len) { @@ -286,7 +298,9 @@ function cmpU(d0, d1, f) { } function cmp(d0, d1, f) { - return cmpU(d0, d1, Curry.__2(f)); + return cmpU(d0, d1, (function (a, b) { + return f(a, b); + })); } function eqU(d0, d1, f) { @@ -294,7 +308,9 @@ function eqU(d0, d1, f) { } function eq(d0, d1, f) { - return eqU(d0, d1, Curry.__2(f)); + return eqU(d0, d1, (function (a, b) { + return f(a, b); + })); } function get(d, x) { diff --git a/lib/js/belt_MutableMapString.js b/lib/js/belt_MutableMapString.js index ac8297c272..0db5237044 100644 --- a/lib/js/belt_MutableMapString.js +++ b/lib/js/belt_MutableMapString.js @@ -1,19 +1,17 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); let Belt_internalMapString = require("./belt_internalMapString.js"); -function make(param) { +function make() { return { data: undefined }; } function isEmpty(m) { - let x = m.data; - return x === undefined; + return m.data === undefined; } function clear(m) { @@ -67,7 +65,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLtree.forEachU(d.data, Curry.__2(f)); + forEachU(d, (function (a, b) { + f(a, b); + })); } function mapU(d, f) { @@ -77,7 +77,9 @@ function mapU(d, f) { } function map(d, f) { - return mapU(d, Curry.__1(f)); + return mapU(d, (function (a) { + return f(a); + })); } function mapWithKeyU(d, f) { @@ -87,7 +89,9 @@ function mapWithKeyU(d, f) { } function mapWithKey(d, f) { - return mapWithKeyU(d, Curry.__2(f)); + return mapWithKeyU(d, (function (a, b) { + return f(a, b); + })); } function reduceU(d, acc, f) { @@ -95,7 +99,9 @@ function reduceU(d, acc, f) { } function reduce(d, acc, f) { - return reduceU(d, acc, Curry.__3(f)); + return reduceU(d, acc, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(d, f) { @@ -103,7 +109,9 @@ function everyU(d, f) { } function every(d, f) { - return Belt_internalAVLtree.everyU(d.data, Curry.__2(f)); + return everyU(d, (function (a, b) { + return f(a, b); + })); } function someU(d, f) { @@ -111,7 +119,9 @@ function someU(d, f) { } function some(d, f) { - return Belt_internalAVLtree.someU(d.data, Curry.__2(f)); + return someU(d, (function (a, b) { + return f(a, b); + })); } function size(d) { @@ -240,7 +250,9 @@ function updateU(t, x, f) { } function update(t, x, f) { - updateU(t, x, Curry.__1(f)); + updateU(t, x, (function (a) { + return f(a); + })); } function removeArrayMutateAux(_t, xs, _i, len) { @@ -286,7 +298,9 @@ function cmpU(d0, d1, f) { } function cmp(d0, d1, f) { - return cmpU(d0, d1, Curry.__2(f)); + return cmpU(d0, d1, (function (a, b) { + return f(a, b); + })); } function eqU(d0, d1, f) { @@ -294,7 +308,9 @@ function eqU(d0, d1, f) { } function eq(d0, d1, f) { - return eqU(d0, d1, Curry.__2(f)); + return eqU(d0, d1, (function (a, b) { + return f(a, b); + })); } function get(d, x) { diff --git a/lib/js/belt_MutableQueue.js b/lib/js/belt_MutableQueue.js index 4503e343bc..ada059b414 100644 --- a/lib/js/belt_MutableQueue.js +++ b/lib/js/belt_MutableQueue.js @@ -1,9 +1,8 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); -function make(param) { +function make() { return { length: 0, first: undefined, @@ -175,7 +174,9 @@ function mapU(q, f) { } function map(q, f) { - return mapU(q, Curry.__1(f)); + return mapU(q, (function (a) { + return f(a); + })); } function isEmpty(q) { @@ -200,7 +201,9 @@ function forEachU(q, f) { } function forEach(q, f) { - forEachU(q, Curry.__1(f)); + forEachU(q, (function (a) { + f(a); + })); } function reduceU(q, accu, f) { @@ -220,7 +223,9 @@ function reduceU(q, accu, f) { } function reduce(q, accu, f) { - return reduceU(q, accu, Curry.__2(f)); + return reduceU(q, accu, (function (a, b) { + return f(a, b); + })); } function transfer(q1, q2) { diff --git a/lib/js/belt_MutableSet.js b/lib/js/belt_MutableSet.js index a1c57a4c22..6b94e54528 100644 --- a/lib/js/belt_MutableSet.js +++ b/lib/js/belt_MutableSet.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_SortArray = require("./belt_SortArray.js"); let Belt_internalAVLset = require("./belt_internalAVLset.js"); @@ -193,8 +192,7 @@ function make(id) { } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -218,7 +216,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -226,7 +226,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -234,7 +236,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -242,7 +246,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -340,7 +346,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -359,7 +367,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/js/belt_MutableSetInt.js b/lib/js/belt_MutableSetInt.js index bca51950bb..691e015f3e 100644 --- a/lib/js/belt_MutableSetInt.js +++ b/lib/js/belt_MutableSetInt.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_SortArrayInt = require("./belt_SortArrayInt.js"); let Belt_internalAVLset = require("./belt_internalAVLset.js"); let Belt_internalSetInt = require("./belt_internalSetInt.js"); @@ -183,15 +182,14 @@ function mergeMany(d, arr) { d.data = addArrayMutate(d.data, arr); } -function make(param) { +function make() { return { data: undefined }; } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -215,7 +213,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -223,7 +223,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -231,7 +233,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -239,7 +243,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -328,7 +334,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -344,7 +352,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/js/belt_MutableSetString.js b/lib/js/belt_MutableSetString.js index 90bc7b9b06..c13ba1c2dc 100644 --- a/lib/js/belt_MutableSetString.js +++ b/lib/js/belt_MutableSetString.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_internalAVLset = require("./belt_internalAVLset.js"); let Belt_SortArrayString = require("./belt_SortArrayString.js"); let Belt_internalSetString = require("./belt_internalSetString.js"); @@ -183,15 +182,14 @@ function mergeMany(d, arr) { d.data = addArrayMutate(d.data, arr); } -function make(param) { +function make() { return { data: undefined }; } function isEmpty(d) { - let n = d.data; - return n === undefined; + return d.data === undefined; } function minimum(d) { @@ -215,7 +213,9 @@ function forEachU(d, f) { } function forEach(d, f) { - Belt_internalAVLset.forEachU(d.data, Curry.__1(f)); + forEachU(d, (function (a) { + f(a); + })); } function reduceU(d, acc, cb) { @@ -223,7 +223,9 @@ function reduceU(d, acc, cb) { } function reduce(d, acc, cb) { - return reduceU(d, acc, Curry.__2(cb)); + return reduceU(d, acc, (function (a, b) { + return cb(a, b); + })); } function everyU(d, p) { @@ -231,7 +233,9 @@ function everyU(d, p) { } function every(d, p) { - return Belt_internalAVLset.everyU(d.data, Curry.__1(p)); + return everyU(d, (function (a) { + return p(a); + })); } function someU(d, p) { @@ -239,7 +243,9 @@ function someU(d, p) { } function some(d, p) { - return Belt_internalAVLset.someU(d.data, Curry.__1(p)); + return someU(d, (function (a) { + return p(a); + })); } function size(d) { @@ -328,7 +334,9 @@ function keepU(d, p) { } function keep(d, p) { - return keepU(d, Curry.__1(p)); + return keepU(d, (function (a) { + return p(a); + })); } function partitionU(d, p) { @@ -344,7 +352,9 @@ function partitionU(d, p) { } function partition(d, p) { - return partitionU(d, Curry.__1(p)); + return partitionU(d, (function (a) { + return p(a); + })); } function subset(a, b) { diff --git a/lib/js/belt_MutableStack.js b/lib/js/belt_MutableStack.js index c7e373880e..aa95d97032 100644 --- a/lib/js/belt_MutableStack.js +++ b/lib/js/belt_MutableStack.js @@ -1,9 +1,8 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); -function make(param) { +function make() { return { root: undefined }; @@ -99,7 +98,9 @@ function forEachU(s, f) { } function forEach(s, f) { - forEachU(s, Curry.__1(f)); + forEachU(s, (function (x) { + f(x); + })); } function dynamicPopIterU(s, f) { @@ -115,7 +116,9 @@ function dynamicPopIterU(s, f) { } function dynamicPopIter(s, f) { - dynamicPopIterU(s, Curry.__1(f)); + dynamicPopIterU(s, (function (x) { + f(x); + })); } exports.make = make; diff --git a/lib/js/belt_Option.js b/lib/js/belt_Option.js index 3f526210c8..08e72edbc3 100644 --- a/lib/js/belt_Option.js +++ b/lib/js/belt_Option.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); function keepU(opt, p) { @@ -11,7 +10,9 @@ function keepU(opt, p) { } function keep(opt, p) { - return keepU(opt, Curry.__1(p)); + return keepU(opt, (function (x) { + return p(x); + })); } function forEachU(opt, f) { @@ -22,7 +23,9 @@ function forEachU(opt, f) { } function forEach(opt, f) { - forEachU(opt, Curry.__1(f)); + forEachU(opt, (function (x) { + f(x); + })); } function getExn(x) { @@ -44,7 +47,9 @@ function mapWithDefaultU(opt, $$default, f) { } function mapWithDefault(opt, $$default, f) { - return mapWithDefaultU(opt, $$default, Curry.__1(f)); + return mapWithDefaultU(opt, $$default, (function (x) { + return f(x); + })); } function mapU(opt, f) { @@ -55,7 +60,9 @@ function mapU(opt, f) { } function map(opt, f) { - return mapU(opt, Curry.__1(f)); + return mapU(opt, (function (x) { + return f(x); + })); } function flatMapU(opt, f) { @@ -66,7 +73,9 @@ function flatMapU(opt, f) { } function flatMap(opt, f) { - return flatMapU(opt, Curry.__1(f)); + return flatMapU(opt, (function (x) { + return f(x); + })); } function getWithDefault(opt, $$default) { @@ -106,7 +115,9 @@ function eqU(a, b, f) { } function eq(a, b, f) { - return eqU(a, b, Curry.__2(f)); + return eqU(a, b, (function (x, y) { + return f(x, y); + })); } function cmpU(a, b, f) { @@ -124,7 +135,9 @@ function cmpU(a, b, f) { } function cmp(a, b, f) { - return cmpU(a, b, Curry.__2(f)); + return cmpU(a, b, (function (x, y) { + return f(x, y); + })); } exports.keepU = keepU; diff --git a/lib/js/belt_Range.js b/lib/js/belt_Range.js index d269d3cc4a..f5b60d1289 100644 --- a/lib/js/belt_Range.js +++ b/lib/js/belt_Range.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); function forEachU(s, f, action) { for(let i = s; i <= f; ++i){ @@ -9,7 +8,9 @@ function forEachU(s, f, action) { } function forEach(s, f, action) { - forEachU(s, f, Curry.__1(action)); + forEachU(s, f, (function (a) { + action(a); + })); } function everyU(_s, f, p) { @@ -27,7 +28,9 @@ function everyU(_s, f, p) { } function every(s, f, p) { - return everyU(s, f, Curry.__1(p)); + return everyU(s, f, (function (a) { + return p(a); + })); } function everyByU(s, f, step, p) { @@ -50,7 +53,9 @@ function everyByU(s, f, step, p) { } function everyBy(s, f, step, p) { - return everyByU(s, f, step, Curry.__1(p)); + return everyByU(s, f, step, (function (a) { + return p(a); + })); } function someU(_s, f, p) { @@ -68,7 +73,9 @@ function someU(_s, f, p) { } function some(s, f, p) { - return someU(s, f, Curry.__1(p)); + return someU(s, f, (function (a) { + return p(a); + })); } function someByU(s, f, step, p) { @@ -91,7 +98,9 @@ function someByU(s, f, step, p) { } function someBy(s, f, step, p) { - return someByU(s, f, step, Curry.__1(p)); + return someByU(s, f, step, (function (a) { + return p(a); + })); } exports.forEachU = forEachU; diff --git a/lib/js/belt_Result.js b/lib/js/belt_Result.js index b48d49f92a..4dbb5140c4 100644 --- a/lib/js/belt_Result.js +++ b/lib/js/belt_Result.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); function getExn(x) { if (x.TAG === "Ok") { @@ -21,7 +20,9 @@ function mapWithDefaultU(opt, $$default, f) { } function mapWithDefault(opt, $$default, f) { - return mapWithDefaultU(opt, $$default, Curry.__1(f)); + return mapWithDefaultU(opt, $$default, (function (x) { + return f(x); + })); } function mapU(opt, f) { @@ -39,7 +40,9 @@ function mapU(opt, f) { } function map(opt, f) { - return mapU(opt, Curry.__1(f)); + return mapU(opt, (function (x) { + return f(x); + })); } function flatMapU(opt, f) { @@ -54,7 +57,9 @@ function flatMapU(opt, f) { } function flatMap(opt, f) { - return flatMapU(opt, Curry.__1(f)); + return flatMapU(opt, (function (x) { + return f(x); + })); } function getWithDefault(opt, $$default) { @@ -96,7 +101,9 @@ function eqU(a, b, f) { } function eq(a, b, f) { - return eqU(a, b, Curry.__2(f)); + return eqU(a, b, (function (x, y) { + return f(x, y); + })); } function cmpU(a, b, f) { @@ -114,7 +121,9 @@ function cmpU(a, b, f) { } function cmp(a, b, f) { - return cmpU(a, b, Curry.__2(f)); + return cmpU(a, b, (function (x, y) { + return f(x, y); + })); } exports.getExn = getExn; diff --git a/lib/js/belt_Set.js b/lib/js/belt_Set.js index a48d9ad746..f159790896 100644 --- a/lib/js/belt_Set.js +++ b/lib/js/belt_Set.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_SetDict = require("./belt_SetDict.js"); function fromArray(data, id) { @@ -128,7 +127,9 @@ function forEachU(m, f) { } function forEach(m, f) { - Belt_SetDict.forEachU(m.data, Curry.__1(f)); + forEachU(m, (function (a) { + f(a); + })); } function reduceU(m, acc, f) { @@ -136,7 +137,9 @@ function reduceU(m, acc, f) { } function reduce(m, acc, f) { - return reduceU(m, acc, Curry.__2(f)); + return reduceU(m, acc, (function (a, b) { + return f(a, b); + })); } function everyU(m, f) { @@ -144,7 +147,9 @@ function everyU(m, f) { } function every(m, f) { - return Belt_SetDict.everyU(m.data, Curry.__1(f)); + return everyU(m, (function (a) { + return f(a); + })); } function someU(m, f) { @@ -152,7 +157,9 @@ function someU(m, f) { } function some(m, f) { - return Belt_SetDict.someU(m.data, Curry.__1(f)); + return someU(m, (function (a) { + return f(a); + })); } function keepU(m, f) { @@ -163,7 +170,9 @@ function keepU(m, f) { } function keep(m, f) { - return keepU(m, Curry.__1(f)); + return keepU(m, (function (a) { + return f(a); + })); } function partitionU(m, f) { @@ -182,7 +191,9 @@ function partitionU(m, f) { } function partition(m, f) { - return partitionU(m, Curry.__1(f)); + return partitionU(m, (function (a) { + return f(a); + })); } function size(m) { diff --git a/lib/js/belt_SortArray.js b/lib/js/belt_SortArray.js index c925c261ba..2ae3650d58 100644 --- a/lib/js/belt_SortArray.js +++ b/lib/js/belt_SortArray.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_Array = require("./belt_Array.js"); function sortedLengthAuxMore(xs, _prec, _acc, len, lt) { @@ -52,7 +51,9 @@ function strictlySortedLengthU(xs, lt) { } function strictlySortedLength(xs, lt) { - return strictlySortedLengthU(xs, Curry.__2(lt)); + return strictlySortedLengthU(xs, (function (x, y) { + return lt(x, y); + })); } function isSortedU(a, cmp) { @@ -77,7 +78,9 @@ function isSortedU(a, cmp) { } function isSorted(a, cmp) { - return isSortedU(a, Curry.__2(cmp)); + return isSortedU(a, (function (x, y) { + return cmp(x, y); + })); } function merge(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -181,7 +184,9 @@ function unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) } function union(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return unionU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -234,7 +239,9 @@ function intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, } function intersect(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return intersectU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { @@ -293,7 +300,9 @@ function diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) } function diff(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, cmp) { - return diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, Curry.__2(cmp)); + return diffU(src, src1ofs, src1len, src2, src2ofs, src2len, dst, dstofs, (function (x, y) { + return cmp(x, y); + })); } function insertionSort(src, srcofs, dst, dstofs, len, cmp) { @@ -333,7 +342,9 @@ function stableSortInPlaceByU(a, cmp) { } function stableSortInPlaceBy(a, cmp) { - stableSortInPlaceByU(a, Curry.__2(cmp)); + stableSortInPlaceByU(a, (function (x, y) { + return cmp(x, y); + })); } function stableSortByU(a, cmp) { @@ -343,7 +354,9 @@ function stableSortByU(a, cmp) { } function stableSortBy(a, cmp) { - return stableSortByU(a, Curry.__2(cmp)); + return stableSortByU(a, (function (x, y) { + return cmp(x, y); + })); } function binarySearchByU(sorted, key, cmp) { @@ -397,7 +410,9 @@ function binarySearchByU(sorted, key, cmp) { } function binarySearchBy(sorted, key, cmp) { - return binarySearchByU(sorted, key, Curry.__2(cmp)); + return binarySearchByU(sorted, key, (function (x, y) { + return cmp(x, y); + })); } let Int; diff --git a/lib/js/belt_internalAVLset.js b/lib/js/belt_internalAVLset.js index a68efe2605..1398e9c47e 100644 --- a/lib/js/belt_internalAVLset.js +++ b/lib/js/belt_internalAVLset.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_SortArray = require("./belt_SortArray.js"); @@ -178,7 +177,9 @@ function forEachU(_n, f) { } function forEach(n, f) { - forEachU(n, Curry.__1(f)); + forEachU(n, (function (a) { + f(a); + })); } function reduceU(_s, _accu, f) { @@ -195,7 +196,9 @@ function reduceU(_s, _accu, f) { } function reduce(s, accu, f) { - return reduceU(s, accu, Curry.__2(f)); + return reduceU(s, accu, (function (a, b) { + return f(a, b); + })); } function everyU(_n, p) { @@ -216,7 +219,9 @@ function everyU(_n, p) { } function every(n, p) { - return everyU(n, Curry.__1(p)); + return everyU(n, (function (a) { + return p(a); + })); } function someU(_n, p) { @@ -237,7 +242,9 @@ function someU(_n, p) { } function some(n, p) { - return someU(n, Curry.__1(p)); + return someU(n, (function (a) { + return p(a); + })); } function addMinElement(n, v) { @@ -317,7 +324,9 @@ function partitionSharedU(n, p) { } function partitionShared(n, p) { - return partitionSharedU(n, Curry.__1(p)); + return partitionSharedU(n, (function (a) { + return p(a); + })); } function lengthNode(n) { @@ -553,7 +562,9 @@ function keepSharedU(n, p) { } function keepShared(n, p) { - return keepSharedU(n, Curry.__1(p)); + return keepSharedU(n, (function (a) { + return p(a); + })); } function keepCopyU(n, p) { @@ -567,7 +578,9 @@ function keepCopyU(n, p) { } function keepCopy(n, p) { - return keepCopyU(n, Curry.__1(p)); + return keepCopyU(n, (function (x) { + return p(x); + })); } function partitionCopyU(n, p) { @@ -593,7 +606,9 @@ function partitionCopyU(n, p) { } function partitionCopy(n, p) { - return partitionCopyU(n, Curry.__1(p)); + return partitionCopyU(n, (function (a) { + return p(a); + })); } function has(_t, x, cmp) { diff --git a/lib/js/belt_internalAVLtree.js b/lib/js/belt_internalAVLtree.js index 2d7e6c11c2..f5847da1ce 100644 --- a/lib/js/belt_internalAVLtree.js +++ b/lib/js/belt_internalAVLtree.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_SortArray = require("./belt_SortArray.js"); @@ -270,7 +269,9 @@ function findFirstByU(n, p) { } function findFirstBy(n, p) { - return findFirstByU(n, Curry.__2(p)); + return findFirstByU(n, (function (a, b) { + return p(a, b); + })); } function forEachU(_n, f) { @@ -287,7 +288,9 @@ function forEachU(_n, f) { } function forEach(n, f) { - forEachU(n, Curry.__2(f)); + forEachU(n, (function (a, b) { + f(a, b); + })); } function mapU(n, f) { @@ -307,7 +310,9 @@ function mapU(n, f) { } function map(n, f) { - return mapU(n, Curry.__1(f)); + return mapU(n, (function (a) { + return f(a); + })); } function mapWithKeyU(n, f) { @@ -328,7 +333,9 @@ function mapWithKeyU(n, f) { } function mapWithKey(n, f) { - return mapWithKeyU(n, Curry.__2(f)); + return mapWithKeyU(n, (function (a, b) { + return f(a, b); + })); } function reduceU(_m, _accu, f) { @@ -349,7 +356,9 @@ function reduceU(_m, _accu, f) { } function reduce(m, accu, f) { - return reduceU(m, accu, Curry.__3(f)); + return reduceU(m, accu, (function (a, b, c) { + return f(a, b, c); + })); } function everyU(_n, p) { @@ -370,7 +379,9 @@ function everyU(_n, p) { } function every(n, p) { - return everyU(n, Curry.__2(p)); + return everyU(n, (function (a, b) { + return p(a, b); + })); } function someU(_n, p) { @@ -391,7 +402,9 @@ function someU(_n, p) { } function some(n, p) { - return someU(n, Curry.__2(p)); + return someU(n, (function (a, b) { + return p(a, b); + })); } function addMinElement(n, k, v) { @@ -478,7 +491,9 @@ function keepSharedU(n, p) { } function keepShared(n, p) { - return keepSharedU(n, Curry.__2(p)); + return keepSharedU(n, (function (a, b) { + return p(a, b); + })); } function keepMapU(n, p) { @@ -498,7 +513,9 @@ function keepMapU(n, p) { } function keepMap(n, p) { - return keepMapU(n, Curry.__2(p)); + return keepMapU(n, (function (a, b) { + return p(a, b); + })); } function partitionSharedU(n, p) { @@ -531,7 +548,9 @@ function partitionSharedU(n, p) { } function partitionShared(n, p) { - return partitionSharedU(n, Curry.__2(p)); + return partitionSharedU(n, (function (a, b) { + return p(a, b); + })); } function lengthNode(n) { @@ -817,7 +836,9 @@ function cmpU(s1, s2, kcmp, vcmp) { } function cmp(s1, s2, kcmp, vcmp) { - return cmpU(s1, s2, kcmp, Curry.__2(vcmp)); + return cmpU(s1, s2, kcmp, (function (a, b) { + return vcmp(a, b); + })); } function eqU(s1, s2, kcmp, veq) { @@ -850,7 +871,9 @@ function eqU(s1, s2, kcmp, veq) { } function eq(s1, s2, kcmp, veq) { - return eqU(s1, s2, kcmp, Curry.__2(veq)); + return eqU(s1, s2, kcmp, (function (a, b) { + return veq(a, b); + })); } function get(_n, x, cmp) { diff --git a/lib/js/belt_internalBuckets.js b/lib/js/belt_internalBuckets.js index eb5269f858..21423c0177 100644 --- a/lib/js/belt_internalBuckets.js +++ b/lib/js/belt_internalBuckets.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_Array = require("./belt_Array.js"); let Caml_option = require("./caml_option.js"); @@ -87,7 +86,9 @@ function forEachU(h, f) { } function forEach(h, f) { - forEachU(h, Curry.__2(f)); + forEachU(h, (function (a, b) { + return f(a, b); + })); } function do_bucket_fold(f, _b, _accu) { @@ -113,7 +114,9 @@ function reduceU(h, init, f) { } function reduce(h, init, f) { - return reduceU(h, init, Curry.__3(f)); + return reduceU(h, init, (function (a, b, c) { + return f(a, b, c); + })); } function getMaxBucketLength(h) { @@ -195,7 +198,9 @@ function keepMapInPlaceU(h, f) { } function keepMapInPlace(h, f) { - keepMapInPlaceU(h, Curry.__2(f)); + keepMapInPlaceU(h, (function (a, b) { + return f(a, b); + })); } function fillArray(_i, arr, _cell) { diff --git a/lib/js/belt_internalMapInt.js b/lib/js/belt_internalMapInt.js index 023bb494f0..8b05835f9b 100644 --- a/lib/js/belt_internalMapInt.js +++ b/lib/js/belt_internalMapInt.js @@ -1,7 +1,6 @@ 'use strict'; let Caml = require("./caml.js"); -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_SortArray = require("./belt_SortArray.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); @@ -209,7 +208,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function compareAux(_e1, _e2, vcmp) { @@ -251,7 +252,9 @@ function cmpU(s1, s2, cmp) { } function cmp(s1, s2, f) { - return cmpU(s1, s2, Curry.__2(f)); + return cmpU(s1, s2, (function (a, b) { + return f(a, b); + })); } function eqAux(_e1, _e2, eq) { @@ -286,7 +289,9 @@ function eqU(s1, s2, eq) { } function eq(s1, s2, f) { - return eqU(s1, s2, Curry.__2(f)); + return eqU(s1, s2, (function (a, b) { + return f(a, b); + })); } function addMutate(t, x, data) { diff --git a/lib/js/belt_internalMapString.js b/lib/js/belt_internalMapString.js index bd5107501a..fe06d43b4d 100644 --- a/lib/js/belt_internalMapString.js +++ b/lib/js/belt_internalMapString.js @@ -1,7 +1,6 @@ 'use strict'; let Caml = require("./caml.js"); -let Curry = require("./curry.js"); let Caml_option = require("./caml_option.js"); let Belt_SortArray = require("./belt_SortArray.js"); let Belt_internalAVLtree = require("./belt_internalAVLtree.js"); @@ -209,7 +208,9 @@ function mergeU(s1, s2, f) { } function merge(s1, s2, f) { - return mergeU(s1, s2, Curry.__3(f)); + return mergeU(s1, s2, (function (a, b, c) { + return f(a, b, c); + })); } function compareAux(_e1, _e2, vcmp) { @@ -251,7 +252,9 @@ function cmpU(s1, s2, cmp) { } function cmp(s1, s2, f) { - return cmpU(s1, s2, Curry.__2(f)); + return cmpU(s1, s2, (function (a, b) { + return f(a, b); + })); } function eqAux(_e1, _e2, eq) { @@ -286,7 +289,9 @@ function eqU(s1, s2, eq) { } function eq(s1, s2, f) { - return eqU(s1, s2, Curry.__2(f)); + return eqU(s1, s2, (function (a, b) { + return f(a, b); + })); } function addMutate(t, x, data) { diff --git a/lib/js/belt_internalSetBuckets.js b/lib/js/belt_internalSetBuckets.js index 8e2bf8ff4f..95789558f2 100644 --- a/lib/js/belt_internalSetBuckets.js +++ b/lib/js/belt_internalSetBuckets.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Belt_Array = require("./belt_Array.js"); function copyAuxCont(_c, _prec) { @@ -84,7 +83,9 @@ function forEachU(h, f) { } function forEach(h, f) { - forEachU(h, Curry.__1(f)); + forEachU(h, (function (a) { + f(a); + })); } function fillArray(_i, arr, _cell) { @@ -139,7 +140,9 @@ function reduceU(h, init, f) { } function reduce(h, init, f) { - return reduceU(h, init, Curry.__2(f)); + return reduceU(h, init, (function (a, b) { + return f(a, b); + })); } function getMaxBucketLength(h) { diff --git a/lib/js/caml.js b/lib/js/caml.js index c3729dc091..15e8b80485 100644 --- a/lib/js/caml.js +++ b/lib/js/caml.js @@ -166,10 +166,10 @@ function i64_le(x, y) { } function i64_min(x, y) { - if (i64_ge(x, y)) { - return y; - } else { + if (i64_lt(x, y)) { return x; + } else { + return y; } } diff --git a/lib/js/caml_obj.js b/lib/js/caml_obj.js index 83c4bdf22e..4ca466842c 100644 --- a/lib/js/caml_obj.js +++ b/lib/js/caml_obj.js @@ -225,21 +225,19 @@ function aux_obj_compare(a, b) { return; } }; - let partial_arg = [ - a, - b, - min_key_rhs - ]; - let do_key_a = function (param) { - return do_key(partial_arg, param); + let do_key_a = function (extra) { + return do_key([ + a, + b, + min_key_rhs + ], extra); }; - let partial_arg$1 = [ - b, - a, - min_key_lhs - ]; - let do_key_b = function (param) { - return do_key(partial_arg$1, param); + let do_key_b = function (extra) { + return do_key([ + b, + a, + min_key_lhs + ], extra); }; for_in(a, do_key_a); for_in(b, do_key_b); diff --git a/lib/js/caml_sys.js b/lib/js/caml_sys.js index aede4c5f7a..d2b6072de6 100644 --- a/lib/js/caml_sys.js +++ b/lib/js/caml_sys.js @@ -27,7 +27,7 @@ let os_type = (function(_){ } }); -function sys_time(param) { +function sys_time() { if (typeof process === "undefined" || process.uptime === undefined) { return -1; } else { @@ -42,7 +42,7 @@ let sys_getcwd = (function(param){ return process.cwd() }); -function sys_get_argv(param) { +function sys_get_argv() { if (typeof process === "undefined") { return [ "", diff --git a/lib/js/curry.js b/lib/js/curry.js index df8a8980c4..51db824ba7 100644 --- a/lib/js/curry.js +++ b/lib/js/curry.js @@ -33,29 +33,29 @@ function _1(o, a0) { case 1 : return o(a0); case 2 : - return function (param) { - return o(a0, param); - }; + return (function (prim0, prim1, prim2) { + return prim0(prim1, prim2); + })(o, a0); case 3 : - return function (param, param$1) { - return o(a0, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3) { + return prim0(prim1, prim2, prim3); + })(o, a0); case 4 : - return function (param, param$1, param$2) { - return o(a0, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0); case 5 : - return function (param, param$1, param$2, param$3) { - return o(a0, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0); case 6 : - return function (param, param$1, param$2, param$3, param$4) { - return o(a0, param, param$1, param$2, param$3, param$4); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0); case 7 : - return function (param, param$1, param$2, param$3, param$4, param$5) { - return o(a0, param, param$1, param$2, param$3, param$4, param$5); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0); default: return app(o, [a0]); } @@ -84,25 +84,25 @@ function _2(o, a0, a1) { case 2 : return o(a0, a1); case 3 : - return function (param) { - return o(a0, a1, param); - }; + return (function (prim0, prim1, prim2, prim3) { + return prim0(prim1, prim2, prim3); + })(o, a0, a1); case 4 : - return function (param, param$1) { - return o(a0, a1, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0, a1); case 5 : - return function (param, param$1, param$2) { - return o(a0, a1, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1); case 6 : - return function (param, param$1, param$2, param$3) { - return o(a0, a1, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1); case 7 : - return function (param, param$1, param$2, param$3, param$4) { - return o(a0, a1, param, param$1, param$2, param$3, param$4); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1); default: return app(o, [ a0, @@ -139,21 +139,21 @@ function _3(o, a0, a1, a2) { case 3 : return o(a0, a1, a2); case 4 : - return function (param) { - return o(a0, a1, a2, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4) { + return prim0(prim1, prim2, prim3, prim4); + })(o, a0, a1, a2); case 5 : - return function (param, param$1) { - return o(a0, a1, a2, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1, a2); case 6 : - return function (param, param$1, param$2) { - return o(a0, a1, a2, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2); case 7 : - return function (param, param$1, param$2, param$3) { - return o(a0, a1, a2, param, param$1, param$2, param$3); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2); default: return app(o, [ a0, @@ -197,17 +197,17 @@ function _4(o, a0, a1, a2, a3) { case 4 : return o(a0, a1, a2, a3); case 5 : - return function (param) { - return o(a0, a1, a2, a3, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5) { + return prim0(prim1, prim2, prim3, prim4, prim5); + })(o, a0, a1, a2, a3); case 6 : - return function (param, param$1) { - return o(a0, a1, a2, a3, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2, a3); case 7 : - return function (param, param$1, param$2) { - return o(a0, a1, a2, a3, param, param$1, param$2); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3); default: return app(o, [ a0, @@ -259,13 +259,13 @@ function _5(o, a0, a1, a2, a3, a4) { case 5 : return o(a0, a1, a2, a3, a4); case 6 : - return function (param) { - return o(a0, a1, a2, a3, a4, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6); + })(o, a0, a1, a2, a3, a4); case 7 : - return function (param, param$1) { - return o(a0, a1, a2, a3, a4, param, param$1); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3, a4); default: return app(o, [ a0, @@ -326,9 +326,9 @@ function _6(o, a0, a1, a2, a3, a4, a5) { case 6 : return o(a0, a1, a2, a3, a4, a5); case 7 : - return function (param) { - return o(a0, a1, a2, a3, a4, a5, param); - }; + return (function (prim0, prim1, prim2, prim3, prim4, prim5, prim6, prim7) { + return prim0(prim1, prim2, prim3, prim4, prim5, prim6, prim7); + })(o, a0, a1, a2, a3, a4, a5); default: return app(o, [ a0, diff --git a/lib/js/js_array.js b/lib/js/js_array.js index 8da31ce1cf..ae1b9f17e6 100644 --- a/lib/js/js_array.js +++ b/lib/js/js_array.js @@ -1,221 +1 @@ -'use strict'; - -let Curry = require("./curry.js"); -let Caml_option = require("./caml_option.js"); -let Caml_splice_call = require("./caml_splice_call.js"); - -function copyWithin(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function push(arg1, obj) { - return obj.push(arg1); -} - -function pushMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "push", [arg1]); -} - -function sortInPlaceWith(arg1, obj) { - return obj.sort(Curry.__2(arg1)); -} - -function spliceInPlace(pos, remove, add, obj) { - return Caml_splice_call.spliceObjApply(obj, "splice", [ - pos, - remove, - add - ]); -} - -function removeFromInPlace(pos, obj) { - return obj.splice(pos); -} - -function removeCountInPlace(pos, count, obj) { - return obj.splice(pos, count); -} - -function unshift(arg1, obj) { - return obj.unshift(arg1); -} - -function unshiftMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "unshift", [arg1]); -} - -function concat(arg1, obj) { - return obj.concat(arg1); -} - -function concatMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "concat", [arg1]); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom(arg1, obj) { - return obj.slice(arg1); -} - -function every(arg1, obj) { - return obj.every(Curry.__1(arg1)); -} - -function everyi(arg1, obj) { - return obj.every(Curry.__2(arg1)); -} - -function filter(arg1, obj) { - return obj.filter(Curry.__1(arg1)); -} - -function filteri(arg1, obj) { - return obj.filter(Curry.__2(arg1)); -} - -function find(arg1, obj) { - return Caml_option.undefined_to_opt(obj.find(Curry.__1(arg1))); -} - -function findi(arg1, obj) { - return Caml_option.undefined_to_opt(obj.find(Curry.__2(arg1))); -} - -function findIndex(arg1, obj) { - return obj.findIndex(Curry.__1(arg1)); -} - -function findIndexi(arg1, obj) { - return obj.findIndex(Curry.__2(arg1)); -} - -function forEach(arg1, obj) { - obj.forEach(Curry.__1(arg1)); -} - -function forEachi(arg1, obj) { - obj.forEach(Curry.__2(arg1)); -} - -function map(arg1, obj) { - return obj.map(Curry.__1(arg1)); -} - -function mapi(arg1, obj) { - return obj.map(Curry.__2(arg1)); -} - -function reduce(arg1, arg2, obj) { - return obj.reduce(Curry.__2(arg1), arg2); -} - -function reducei(arg1, arg2, obj) { - return obj.reduce(Curry.__3(arg1), arg2); -} - -function reduceRight(arg1, arg2, obj) { - return obj.reduceRight(Curry.__2(arg1), arg2); -} - -function reduceRighti(arg1, arg2, obj) { - return obj.reduceRight(Curry.__3(arg1), arg2); -} - -function some(arg1, obj) { - return obj.some(Curry.__1(arg1)); -} - -function somei(arg1, obj) { - return obj.some(Curry.__2(arg1)); -} - -exports.copyWithin = copyWithin; -exports.copyWithinFrom = copyWithinFrom; -exports.copyWithinFromRange = copyWithinFromRange; -exports.fillInPlace = fillInPlace; -exports.fillFromInPlace = fillFromInPlace; -exports.fillRangeInPlace = fillRangeInPlace; -exports.push = push; -exports.pushMany = pushMany; -exports.sortInPlaceWith = sortInPlaceWith; -exports.spliceInPlace = spliceInPlace; -exports.removeFromInPlace = removeFromInPlace; -exports.removeCountInPlace = removeCountInPlace; -exports.unshift = unshift; -exports.unshiftMany = unshiftMany; -exports.concat = concat; -exports.concatMany = concatMany; -exports.includes = includes; -exports.indexOf = indexOf; -exports.indexOfFrom = indexOfFrom; -exports.joinWith = joinWith; -exports.lastIndexOf = lastIndexOf; -exports.lastIndexOfFrom = lastIndexOfFrom; -exports.slice = slice; -exports.sliceFrom = sliceFrom; -exports.every = every; -exports.everyi = everyi; -exports.filter = filter; -exports.filteri = filteri; -exports.find = find; -exports.findi = findi; -exports.findIndex = findIndex; -exports.findIndexi = findIndexi; -exports.forEach = forEach; -exports.forEachi = forEachi; -exports.map = map; -exports.mapi = mapi; -exports.reduce = reduce; -exports.reducei = reducei; -exports.reduceRight = reduceRight; -exports.reduceRighti = reduceRighti; -exports.some = some; -exports.somei = somei; -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/js/js_promise.js b/lib/js/js_promise.js index 41895787db..ae1b9f17e6 100644 --- a/lib/js/js_promise.js +++ b/lib/js/js_promise.js @@ -1,15 +1 @@ -'use strict'; - -let Curry = require("./curry.js"); - -function then_(arg1, obj) { - return obj.then(Curry.__1(arg1)); -} - -function $$catch(arg1, obj) { - return obj.catch(Curry.__1(arg1)); -} - -exports.then_ = then_; -exports.$$catch = $$catch; -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/js/js_string.js b/lib/js/js_string.js index 74854d2836..ae1b9f17e6 100644 --- a/lib/js/js_string.js +++ b/lib/js/js_string.js @@ -1,197 +1 @@ -'use strict'; - -let Curry = require("./curry.js"); -let Caml_option = require("./caml_option.js"); -let Caml_splice_call = require("./caml_splice_call.js"); - -function charAt(arg1, obj) { - return obj.charAt(arg1); -} - -function charCodeAt(arg1, obj) { - return obj.charCodeAt(arg1); -} - -function codePointAt(arg1, obj) { - return obj.codePointAt(arg1); -} - -function concat(arg1, obj) { - return obj.concat(arg1); -} - -function concatMany(arg1, obj) { - return Caml_splice_call.spliceObjApply(obj, "concat", [arg1]); -} - -function endsWith(arg1, obj) { - return obj.endsWith(arg1); -} - -function endsWithFrom(arg1, arg2, obj) { - return obj.endsWith(arg1, arg2); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function includesFrom(arg1, arg2, obj) { - return obj.includes(arg1, arg2); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, arg2, obj) { - return obj.indexOf(arg1, arg2); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, arg2, obj) { - return obj.lastIndexOf(arg1, arg2); -} - -function localeCompare(arg1, obj) { - return obj.localeCompare(arg1); -} - -function match_(arg1, obj) { - return Caml_option.null_to_opt(obj.match(arg1)); -} - -function normalizeByForm(arg1, obj) { - return obj.normalize(arg1); -} - -function repeat(arg1, obj) { - return obj.repeat(arg1); -} - -function replace(arg1, arg2, obj) { - return obj.replace(arg1, arg2); -} - -function replaceByRe(arg1, arg2, obj) { - return obj.replace(arg1, arg2); -} - -function unsafeReplaceBy0(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__3(arg2)); -} - -function unsafeReplaceBy1(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__4(arg2)); -} - -function unsafeReplaceBy2(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__5(arg2)); -} - -function unsafeReplaceBy3(arg1, arg2, obj) { - return obj.replace(arg1, Curry.__6(arg2)); -} - -function search(arg1, obj) { - return obj.search(arg1); -} - -function slice(from, to_, obj) { - return obj.slice(from, to_); -} - -function sliceToEnd(from, obj) { - return obj.slice(from); -} - -function split(arg1, obj) { - return obj.split(arg1); -} - -function splitAtMost(arg1, limit, obj) { - return obj.split(arg1, limit); -} - -function splitByRe(arg1, obj) { - return obj.split(arg1); -} - -function splitByReAtMost(arg1, limit, obj) { - return obj.split(arg1, limit); -} - -function startsWith(arg1, obj) { - return obj.startsWith(arg1); -} - -function startsWithFrom(arg1, arg2, obj) { - return obj.startsWith(arg1, arg2); -} - -function substr(from, obj) { - return obj.substr(from); -} - -function substrAtMost(from, length, obj) { - return obj.substr(from, length); -} - -function substring(from, to_, obj) { - return obj.substring(from, to_); -} - -function substringToEnd(from, obj) { - return obj.substring(from); -} - -function anchor(arg1, obj) { - return obj.anchor(arg1); -} - -function link(arg1, obj) { - return obj.link(arg1); -} - -exports.charAt = charAt; -exports.charCodeAt = charCodeAt; -exports.codePointAt = codePointAt; -exports.concat = concat; -exports.concatMany = concatMany; -exports.endsWith = endsWith; -exports.endsWithFrom = endsWithFrom; -exports.includes = includes; -exports.includesFrom = includesFrom; -exports.indexOf = indexOf; -exports.indexOfFrom = indexOfFrom; -exports.lastIndexOf = lastIndexOf; -exports.lastIndexOfFrom = lastIndexOfFrom; -exports.localeCompare = localeCompare; -exports.match_ = match_; -exports.normalizeByForm = normalizeByForm; -exports.repeat = repeat; -exports.replace = replace; -exports.replaceByRe = replaceByRe; -exports.unsafeReplaceBy0 = unsafeReplaceBy0; -exports.unsafeReplaceBy1 = unsafeReplaceBy1; -exports.unsafeReplaceBy2 = unsafeReplaceBy2; -exports.unsafeReplaceBy3 = unsafeReplaceBy3; -exports.search = search; -exports.slice = slice; -exports.sliceToEnd = sliceToEnd; -exports.split = split; -exports.splitAtMost = splitAtMost; -exports.splitByRe = splitByRe; -exports.splitByReAtMost = splitByReAtMost; -exports.startsWith = startsWith; -exports.startsWithFrom = startsWithFrom; -exports.substr = substr; -exports.substrAtMost = substrAtMost; -exports.substring = substring; -exports.substringToEnd = substringToEnd; -exports.anchor = anchor; -exports.link = link; -/* No side effect */ +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/lib/js/js_typed_array.js b/lib/js/js_typed_array.js index cadb668ff9..e0a5cdac2d 100644 --- a/lib/js/js_typed_array.js +++ b/lib/js/js_typed_array.js @@ -1,1710 +1,25 @@ 'use strict'; -function slice(start, end_, obj) { - return obj.slice(start, end_); -} +let $$ArrayBuffer = {}; -function sliceFrom(arg1, obj) { - return obj.slice(arg1); -} +let $$Int8Array = {}; -let $$ArrayBuffer = { - slice: slice, - sliceFrom: sliceFrom -}; +let $$Uint8Array = {}; -function setArray(arg1, obj) { - obj.set(arg1); -} +let $$Uint8ClampedArray = {}; -function setArrayOffset(arg1, arg2, obj) { - obj.set(arg1, arg2); -} +let $$Int16Array = {}; -function copyWithin(to_, obj) { - return obj.copyWithin(to_); -} +let $$Uint16Array = {}; -function copyWithinFrom(to_, from, obj) { - return obj.copyWithin(to_, from); -} +let $$Int32Array = {}; -function copyWithinFromRange(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} +let $$Uint32Array = {}; -function fillInPlace(arg1, obj) { - return obj.fill(arg1); -} +let $$Float32Array = {}; -function fillFromInPlace(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith(arg1, obj) { - return obj.sort(arg1); -} - -function includes(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$1(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$1(arg1, obj) { - return obj.slice(arg1); -} - -function subarray(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom(arg1, obj) { - return obj.subarray(arg1); -} - -function every(arg1, obj) { - return obj.every(arg1); -} - -function everyi(arg1, obj) { - return obj.every(arg1); -} - -function filter(arg1, obj) { - return obj.filter(arg1); -} - -function filteri(arg1, obj) { - return obj.filter(arg1); -} - -function find(arg1, obj) { - return obj.find(arg1); -} - -function findi(arg1, obj) { - return obj.find(arg1); -} - -function findIndex(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi(arg1, obj) { - obj.forEach(arg1); -} - -function map(arg1, obj) { - return obj.map(arg1); -} - -function mapi(arg1, obj) { - return obj.map(arg1); -} - -function reduce(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some(arg1, obj) { - return obj.some(arg1); -} - -function somei(arg1, obj) { - return obj.some(arg1); -} - -let $$Int8Array = { - setArray: setArray, - setArrayOffset: setArrayOffset, - copyWithin: copyWithin, - copyWithinFrom: copyWithinFrom, - copyWithinFromRange: copyWithinFromRange, - fillInPlace: fillInPlace, - fillFromInPlace: fillFromInPlace, - fillRangeInPlace: fillRangeInPlace, - sortInPlaceWith: sortInPlaceWith, - includes: includes, - indexOf: indexOf, - indexOfFrom: indexOfFrom, - joinWith: joinWith, - lastIndexOf: lastIndexOf, - lastIndexOfFrom: lastIndexOfFrom, - slice: slice$1, - sliceFrom: sliceFrom$1, - subarray: subarray, - subarrayFrom: subarrayFrom, - every: every, - everyi: everyi, - filter: filter, - filteri: filteri, - find: find, - findi: findi, - findIndex: findIndex, - findIndexi: findIndexi, - forEach: forEach, - forEachi: forEachi, - map: map, - mapi: mapi, - reduce: reduce, - reducei: reducei, - reduceRight: reduceRight, - reduceRighti: reduceRighti, - some: some, - somei: somei -}; - -function setArray$1(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$1(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$1(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$1(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$1(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$1(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$1(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$1(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$1(arg1, obj) { - return obj.sort(arg1); -} - -function includes$1(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$1(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$1(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$1(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$1(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$1(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$2(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$2(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$1(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$1(arg1, obj) { - return obj.subarray(arg1); -} - -function every$1(arg1, obj) { - return obj.every(arg1); -} - -function everyi$1(arg1, obj) { - return obj.every(arg1); -} - -function filter$1(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$1(arg1, obj) { - return obj.filter(arg1); -} - -function find$1(arg1, obj) { - return obj.find(arg1); -} - -function findi$1(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$1(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$1(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$1(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$1(arg1, obj) { - obj.forEach(arg1); -} - -function map$1(arg1, obj) { - return obj.map(arg1); -} - -function mapi$1(arg1, obj) { - return obj.map(arg1); -} - -function reduce$1(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$1(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$1(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$1(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$1(arg1, obj) { - return obj.some(arg1); -} - -function somei$1(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint8Array = { - setArray: setArray$1, - setArrayOffset: setArrayOffset$1, - copyWithin: copyWithin$1, - copyWithinFrom: copyWithinFrom$1, - copyWithinFromRange: copyWithinFromRange$1, - fillInPlace: fillInPlace$1, - fillFromInPlace: fillFromInPlace$1, - fillRangeInPlace: fillRangeInPlace$1, - sortInPlaceWith: sortInPlaceWith$1, - includes: includes$1, - indexOf: indexOf$1, - indexOfFrom: indexOfFrom$1, - joinWith: joinWith$1, - lastIndexOf: lastIndexOf$1, - lastIndexOfFrom: lastIndexOfFrom$1, - slice: slice$2, - sliceFrom: sliceFrom$2, - subarray: subarray$1, - subarrayFrom: subarrayFrom$1, - every: every$1, - everyi: everyi$1, - filter: filter$1, - filteri: filteri$1, - find: find$1, - findi: findi$1, - findIndex: findIndex$1, - findIndexi: findIndexi$1, - forEach: forEach$1, - forEachi: forEachi$1, - map: map$1, - mapi: mapi$1, - reduce: reduce$1, - reducei: reducei$1, - reduceRight: reduceRight$1, - reduceRighti: reduceRighti$1, - some: some$1, - somei: somei$1 -}; - -function setArray$2(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$2(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$2(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$2(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$2(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$2(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$2(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$2(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$2(arg1, obj) { - return obj.sort(arg1); -} - -function includes$2(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$2(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$2(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$2(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$2(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$2(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$3(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$3(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$2(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$2(arg1, obj) { - return obj.subarray(arg1); -} - -function every$2(arg1, obj) { - return obj.every(arg1); -} - -function everyi$2(arg1, obj) { - return obj.every(arg1); -} - -function filter$2(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$2(arg1, obj) { - return obj.filter(arg1); -} - -function find$2(arg1, obj) { - return obj.find(arg1); -} - -function findi$2(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$2(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$2(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$2(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$2(arg1, obj) { - obj.forEach(arg1); -} - -function map$2(arg1, obj) { - return obj.map(arg1); -} - -function mapi$2(arg1, obj) { - return obj.map(arg1); -} - -function reduce$2(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$2(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$2(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$2(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$2(arg1, obj) { - return obj.some(arg1); -} - -function somei$2(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint8ClampedArray = { - setArray: setArray$2, - setArrayOffset: setArrayOffset$2, - copyWithin: copyWithin$2, - copyWithinFrom: copyWithinFrom$2, - copyWithinFromRange: copyWithinFromRange$2, - fillInPlace: fillInPlace$2, - fillFromInPlace: fillFromInPlace$2, - fillRangeInPlace: fillRangeInPlace$2, - sortInPlaceWith: sortInPlaceWith$2, - includes: includes$2, - indexOf: indexOf$2, - indexOfFrom: indexOfFrom$2, - joinWith: joinWith$2, - lastIndexOf: lastIndexOf$2, - lastIndexOfFrom: lastIndexOfFrom$2, - slice: slice$3, - sliceFrom: sliceFrom$3, - subarray: subarray$2, - subarrayFrom: subarrayFrom$2, - every: every$2, - everyi: everyi$2, - filter: filter$2, - filteri: filteri$2, - find: find$2, - findi: findi$2, - findIndex: findIndex$2, - findIndexi: findIndexi$2, - forEach: forEach$2, - forEachi: forEachi$2, - map: map$2, - mapi: mapi$2, - reduce: reduce$2, - reducei: reducei$2, - reduceRight: reduceRight$2, - reduceRighti: reduceRighti$2, - some: some$2, - somei: somei$2 -}; - -function setArray$3(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$3(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$3(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$3(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$3(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$3(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$3(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$3(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$3(arg1, obj) { - return obj.sort(arg1); -} - -function includes$3(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$3(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$3(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$3(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$3(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$3(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$4(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$4(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$3(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$3(arg1, obj) { - return obj.subarray(arg1); -} - -function every$3(arg1, obj) { - return obj.every(arg1); -} - -function everyi$3(arg1, obj) { - return obj.every(arg1); -} - -function filter$3(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$3(arg1, obj) { - return obj.filter(arg1); -} - -function find$3(arg1, obj) { - return obj.find(arg1); -} - -function findi$3(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$3(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$3(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$3(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$3(arg1, obj) { - obj.forEach(arg1); -} - -function map$3(arg1, obj) { - return obj.map(arg1); -} - -function mapi$3(arg1, obj) { - return obj.map(arg1); -} - -function reduce$3(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$3(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$3(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$3(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$3(arg1, obj) { - return obj.some(arg1); -} - -function somei$3(arg1, obj) { - return obj.some(arg1); -} - -let $$Int16Array = { - setArray: setArray$3, - setArrayOffset: setArrayOffset$3, - copyWithin: copyWithin$3, - copyWithinFrom: copyWithinFrom$3, - copyWithinFromRange: copyWithinFromRange$3, - fillInPlace: fillInPlace$3, - fillFromInPlace: fillFromInPlace$3, - fillRangeInPlace: fillRangeInPlace$3, - sortInPlaceWith: sortInPlaceWith$3, - includes: includes$3, - indexOf: indexOf$3, - indexOfFrom: indexOfFrom$3, - joinWith: joinWith$3, - lastIndexOf: lastIndexOf$3, - lastIndexOfFrom: lastIndexOfFrom$3, - slice: slice$4, - sliceFrom: sliceFrom$4, - subarray: subarray$3, - subarrayFrom: subarrayFrom$3, - every: every$3, - everyi: everyi$3, - filter: filter$3, - filteri: filteri$3, - find: find$3, - findi: findi$3, - findIndex: findIndex$3, - findIndexi: findIndexi$3, - forEach: forEach$3, - forEachi: forEachi$3, - map: map$3, - mapi: mapi$3, - reduce: reduce$3, - reducei: reducei$3, - reduceRight: reduceRight$3, - reduceRighti: reduceRighti$3, - some: some$3, - somei: somei$3 -}; - -function setArray$4(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$4(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$4(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$4(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$4(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$4(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$4(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$4(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$4(arg1, obj) { - return obj.sort(arg1); -} - -function includes$4(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$4(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$4(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$4(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$4(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$4(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$5(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$5(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$4(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$4(arg1, obj) { - return obj.subarray(arg1); -} - -function every$4(arg1, obj) { - return obj.every(arg1); -} - -function everyi$4(arg1, obj) { - return obj.every(arg1); -} - -function filter$4(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$4(arg1, obj) { - return obj.filter(arg1); -} - -function find$4(arg1, obj) { - return obj.find(arg1); -} - -function findi$4(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$4(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$4(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$4(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$4(arg1, obj) { - obj.forEach(arg1); -} - -function map$4(arg1, obj) { - return obj.map(arg1); -} - -function mapi$4(arg1, obj) { - return obj.map(arg1); -} - -function reduce$4(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$4(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$4(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$4(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$4(arg1, obj) { - return obj.some(arg1); -} - -function somei$4(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint16Array = { - setArray: setArray$4, - setArrayOffset: setArrayOffset$4, - copyWithin: copyWithin$4, - copyWithinFrom: copyWithinFrom$4, - copyWithinFromRange: copyWithinFromRange$4, - fillInPlace: fillInPlace$4, - fillFromInPlace: fillFromInPlace$4, - fillRangeInPlace: fillRangeInPlace$4, - sortInPlaceWith: sortInPlaceWith$4, - includes: includes$4, - indexOf: indexOf$4, - indexOfFrom: indexOfFrom$4, - joinWith: joinWith$4, - lastIndexOf: lastIndexOf$4, - lastIndexOfFrom: lastIndexOfFrom$4, - slice: slice$5, - sliceFrom: sliceFrom$5, - subarray: subarray$4, - subarrayFrom: subarrayFrom$4, - every: every$4, - everyi: everyi$4, - filter: filter$4, - filteri: filteri$4, - find: find$4, - findi: findi$4, - findIndex: findIndex$4, - findIndexi: findIndexi$4, - forEach: forEach$4, - forEachi: forEachi$4, - map: map$4, - mapi: mapi$4, - reduce: reduce$4, - reducei: reducei$4, - reduceRight: reduceRight$4, - reduceRighti: reduceRighti$4, - some: some$4, - somei: somei$4 -}; - -function setArray$5(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$5(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$5(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$5(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$5(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$5(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$5(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$5(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$5(arg1, obj) { - return obj.sort(arg1); -} - -function includes$5(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$5(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$5(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$5(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$5(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$5(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$6(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$6(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$5(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$5(arg1, obj) { - return obj.subarray(arg1); -} - -function every$5(arg1, obj) { - return obj.every(arg1); -} - -function everyi$5(arg1, obj) { - return obj.every(arg1); -} - -function filter$5(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$5(arg1, obj) { - return obj.filter(arg1); -} - -function find$5(arg1, obj) { - return obj.find(arg1); -} - -function findi$5(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$5(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$5(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$5(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$5(arg1, obj) { - obj.forEach(arg1); -} - -function map$5(arg1, obj) { - return obj.map(arg1); -} - -function mapi$5(arg1, obj) { - return obj.map(arg1); -} - -function reduce$5(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$5(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$5(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$5(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$5(arg1, obj) { - return obj.some(arg1); -} - -function somei$5(arg1, obj) { - return obj.some(arg1); -} - -let $$Int32Array = { - setArray: setArray$5, - setArrayOffset: setArrayOffset$5, - copyWithin: copyWithin$5, - copyWithinFrom: copyWithinFrom$5, - copyWithinFromRange: copyWithinFromRange$5, - fillInPlace: fillInPlace$5, - fillFromInPlace: fillFromInPlace$5, - fillRangeInPlace: fillRangeInPlace$5, - sortInPlaceWith: sortInPlaceWith$5, - includes: includes$5, - indexOf: indexOf$5, - indexOfFrom: indexOfFrom$5, - joinWith: joinWith$5, - lastIndexOf: lastIndexOf$5, - lastIndexOfFrom: lastIndexOfFrom$5, - slice: slice$6, - sliceFrom: sliceFrom$6, - subarray: subarray$5, - subarrayFrom: subarrayFrom$5, - every: every$5, - everyi: everyi$5, - filter: filter$5, - filteri: filteri$5, - find: find$5, - findi: findi$5, - findIndex: findIndex$5, - findIndexi: findIndexi$5, - forEach: forEach$5, - forEachi: forEachi$5, - map: map$5, - mapi: mapi$5, - reduce: reduce$5, - reducei: reducei$5, - reduceRight: reduceRight$5, - reduceRighti: reduceRighti$5, - some: some$5, - somei: somei$5 -}; - -function setArray$6(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$6(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$6(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$6(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$6(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$6(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$6(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$6(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$6(arg1, obj) { - return obj.sort(arg1); -} - -function includes$6(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$6(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$6(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$6(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$6(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$6(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$7(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$7(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$6(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$6(arg1, obj) { - return obj.subarray(arg1); -} - -function every$6(arg1, obj) { - return obj.every(arg1); -} - -function everyi$6(arg1, obj) { - return obj.every(arg1); -} - -function filter$6(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$6(arg1, obj) { - return obj.filter(arg1); -} - -function find$6(arg1, obj) { - return obj.find(arg1); -} - -function findi$6(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$6(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$6(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$6(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$6(arg1, obj) { - obj.forEach(arg1); -} - -function map$6(arg1, obj) { - return obj.map(arg1); -} - -function mapi$6(arg1, obj) { - return obj.map(arg1); -} - -function reduce$6(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$6(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$6(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$6(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$6(arg1, obj) { - return obj.some(arg1); -} - -function somei$6(arg1, obj) { - return obj.some(arg1); -} - -let $$Uint32Array = { - setArray: setArray$6, - setArrayOffset: setArrayOffset$6, - copyWithin: copyWithin$6, - copyWithinFrom: copyWithinFrom$6, - copyWithinFromRange: copyWithinFromRange$6, - fillInPlace: fillInPlace$6, - fillFromInPlace: fillFromInPlace$6, - fillRangeInPlace: fillRangeInPlace$6, - sortInPlaceWith: sortInPlaceWith$6, - includes: includes$6, - indexOf: indexOf$6, - indexOfFrom: indexOfFrom$6, - joinWith: joinWith$6, - lastIndexOf: lastIndexOf$6, - lastIndexOfFrom: lastIndexOfFrom$6, - slice: slice$7, - sliceFrom: sliceFrom$7, - subarray: subarray$6, - subarrayFrom: subarrayFrom$6, - every: every$6, - everyi: everyi$6, - filter: filter$6, - filteri: filteri$6, - find: find$6, - findi: findi$6, - findIndex: findIndex$6, - findIndexi: findIndexi$6, - forEach: forEach$6, - forEachi: forEachi$6, - map: map$6, - mapi: mapi$6, - reduce: reduce$6, - reducei: reducei$6, - reduceRight: reduceRight$6, - reduceRighti: reduceRighti$6, - some: some$6, - somei: somei$6 -}; - -function setArray$7(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$7(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$7(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$7(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$7(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$7(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$7(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$7(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$7(arg1, obj) { - return obj.sort(arg1); -} - -function includes$7(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$7(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$7(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$7(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$7(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$7(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$8(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$8(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$7(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$7(arg1, obj) { - return obj.subarray(arg1); -} - -function every$7(arg1, obj) { - return obj.every(arg1); -} - -function everyi$7(arg1, obj) { - return obj.every(arg1); -} - -function filter$7(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$7(arg1, obj) { - return obj.filter(arg1); -} - -function find$7(arg1, obj) { - return obj.find(arg1); -} - -function findi$7(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$7(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$7(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$7(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$7(arg1, obj) { - obj.forEach(arg1); -} - -function map$7(arg1, obj) { - return obj.map(arg1); -} - -function mapi$7(arg1, obj) { - return obj.map(arg1); -} - -function reduce$7(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$7(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$7(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$7(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$7(arg1, obj) { - return obj.some(arg1); -} - -function somei$7(arg1, obj) { - return obj.some(arg1); -} - -let $$Float32Array = { - setArray: setArray$7, - setArrayOffset: setArrayOffset$7, - copyWithin: copyWithin$7, - copyWithinFrom: copyWithinFrom$7, - copyWithinFromRange: copyWithinFromRange$7, - fillInPlace: fillInPlace$7, - fillFromInPlace: fillFromInPlace$7, - fillRangeInPlace: fillRangeInPlace$7, - sortInPlaceWith: sortInPlaceWith$7, - includes: includes$7, - indexOf: indexOf$7, - indexOfFrom: indexOfFrom$7, - joinWith: joinWith$7, - lastIndexOf: lastIndexOf$7, - lastIndexOfFrom: lastIndexOfFrom$7, - slice: slice$8, - sliceFrom: sliceFrom$8, - subarray: subarray$7, - subarrayFrom: subarrayFrom$7, - every: every$7, - everyi: everyi$7, - filter: filter$7, - filteri: filteri$7, - find: find$7, - findi: findi$7, - findIndex: findIndex$7, - findIndexi: findIndexi$7, - forEach: forEach$7, - forEachi: forEachi$7, - map: map$7, - mapi: mapi$7, - reduce: reduce$7, - reducei: reducei$7, - reduceRight: reduceRight$7, - reduceRighti: reduceRighti$7, - some: some$7, - somei: somei$7 -}; - -function setArray$8(arg1, obj) { - obj.set(arg1); -} - -function setArrayOffset$8(arg1, arg2, obj) { - obj.set(arg1, arg2); -} - -function copyWithin$8(to_, obj) { - return obj.copyWithin(to_); -} - -function copyWithinFrom$8(to_, from, obj) { - return obj.copyWithin(to_, from); -} - -function copyWithinFromRange$8(to_, start, end_, obj) { - return obj.copyWithin(to_, start, end_); -} - -function fillInPlace$8(arg1, obj) { - return obj.fill(arg1); -} - -function fillFromInPlace$8(arg1, from, obj) { - return obj.fill(arg1, from); -} - -function fillRangeInPlace$8(arg1, start, end_, obj) { - return obj.fill(arg1, start, end_); -} - -function sortInPlaceWith$8(arg1, obj) { - return obj.sort(arg1); -} - -function includes$8(arg1, obj) { - return obj.includes(arg1); -} - -function indexOf$8(arg1, obj) { - return obj.indexOf(arg1); -} - -function indexOfFrom$8(arg1, from, obj) { - return obj.indexOf(arg1, from); -} - -function joinWith$8(arg1, obj) { - return obj.join(arg1); -} - -function lastIndexOf$8(arg1, obj) { - return obj.lastIndexOf(arg1); -} - -function lastIndexOfFrom$8(arg1, from, obj) { - return obj.lastIndexOf(arg1, from); -} - -function slice$9(start, end_, obj) { - return obj.slice(start, end_); -} - -function sliceFrom$9(arg1, obj) { - return obj.slice(arg1); -} - -function subarray$8(start, end_, obj) { - return obj.subarray(start, end_); -} - -function subarrayFrom$8(arg1, obj) { - return obj.subarray(arg1); -} - -function every$8(arg1, obj) { - return obj.every(arg1); -} - -function everyi$8(arg1, obj) { - return obj.every(arg1); -} - -function filter$8(arg1, obj) { - return obj.filter(arg1); -} - -function filteri$8(arg1, obj) { - return obj.filter(arg1); -} - -function find$8(arg1, obj) { - return obj.find(arg1); -} - -function findi$8(arg1, obj) { - return obj.find(arg1); -} - -function findIndex$8(arg1, obj) { - return obj.findIndex(arg1); -} - -function findIndexi$8(arg1, obj) { - return obj.findIndex(arg1); -} - -function forEach$8(arg1, obj) { - obj.forEach(arg1); -} - -function forEachi$8(arg1, obj) { - obj.forEach(arg1); -} - -function map$8(arg1, obj) { - return obj.map(arg1); -} - -function mapi$8(arg1, obj) { - return obj.map(arg1); -} - -function reduce$8(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reducei$8(arg1, arg2, obj) { - return obj.reduce(arg1, arg2); -} - -function reduceRight$8(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function reduceRighti$8(arg1, arg2, obj) { - return obj.reduceRight(arg1, arg2); -} - -function some$8(arg1, obj) { - return obj.some(arg1); -} - -function somei$8(arg1, obj) { - return obj.some(arg1); -} - -let $$Float64Array = { - setArray: setArray$8, - setArrayOffset: setArrayOffset$8, - copyWithin: copyWithin$8, - copyWithinFrom: copyWithinFrom$8, - copyWithinFromRange: copyWithinFromRange$8, - fillInPlace: fillInPlace$8, - fillFromInPlace: fillFromInPlace$8, - fillRangeInPlace: fillRangeInPlace$8, - sortInPlaceWith: sortInPlaceWith$8, - includes: includes$8, - indexOf: indexOf$8, - indexOfFrom: indexOfFrom$8, - joinWith: joinWith$8, - lastIndexOf: lastIndexOf$8, - lastIndexOfFrom: lastIndexOfFrom$8, - slice: slice$9, - sliceFrom: sliceFrom$9, - subarray: subarray$8, - subarrayFrom: subarrayFrom$8, - every: every$8, - everyi: everyi$8, - filter: filter$8, - filteri: filteri$8, - find: find$8, - findi: findi$8, - findIndex: findIndex$8, - findIndexi: findIndexi$8, - forEach: forEach$8, - forEachi: forEachi$8, - map: map$8, - mapi: mapi$8, - reduce: reduce$8, - reducei: reducei$8, - reduceRight: reduceRight$8, - reduceRighti: reduceRighti$8, - some: some$8, - somei: somei$8 -}; +let $$Float64Array = {}; let $$DataView = {}; diff --git a/lib/js/pervasives.js b/lib/js/pervasives.js index 7adf63be04..b4c2a0df7a 100644 --- a/lib/js/pervasives.js +++ b/lib/js/pervasives.js @@ -1,6 +1,5 @@ 'use strict'; -let Curry = require("./curry.js"); let Caml_sys = require("./caml_sys.js"); let Caml_format = require("./caml_format.js"); let Caml_string = require("./caml_string.js"); @@ -171,11 +170,11 @@ function $at(l1, l2) { } } -function print_newline(param) { +function print_newline() { console.log(""); } -function prerr_newline(param) { +function prerr_newline() { console.error(""); } @@ -184,7 +183,7 @@ function print_int(i) { } function print_float(i) { - console.log(valid_float_lexem(Caml_format.format_float("%.12g", i))); + console.log(string_of_float(i)); } function print_string(prim) { @@ -199,14 +198,14 @@ let exit_function = { function at_exit(f) { let g = exit_function.contents; - exit_function.contents = (function (param) { - Curry._1(f, undefined); - Curry._1(g, undefined); + exit_function.contents = (function () { + f(); + g(); }); } function exit(retcode) { - Curry._1(exit_function.contents, undefined); + exit_function.contents(); return Caml_sys.sys_exit(retcode); }