From 2aac2e01f81e5bc5c395033276adef4bafe9d3ff Mon Sep 17 00:00:00 2001 From: Sam Mohr Date: Sat, 4 Jan 2025 03:27:16 -0800 Subject: [PATCH 01/20] Move builtins to snake_case with auto-case conversion --- crates/compiler/builtins/roc/Bool.roc | 56 +- crates/compiler/builtins/roc/Box.roc | 4 +- crates/compiler/builtins/roc/Decode.roc | 70 +- crates/compiler/builtins/roc/Dict.roc | 1860 +++++++++-------- crates/compiler/builtins/roc/Encode.roc | 34 +- crates/compiler/builtins/roc/Hash.roc | 108 +- crates/compiler/builtins/roc/Inspect.roc | 385 ++-- crates/compiler/builtins/roc/List.roc | 1191 +++++------ crates/compiler/builtins/roc/Num.roc | 799 ++++--- crates/compiler/builtins/roc/Result.roc | 126 +- crates/compiler/builtins/roc/Set.roc | 462 ++-- crates/compiler/builtins/roc/Str.roc | 768 +++---- crates/compiler/builtins/roc/Task.roc | 229 +- .../collections/src/small_string_interner.rs | 53 +- crates/compiler/load/build.rs | 2 + crates/compiler/module/src/symbol.rs | 556 ++--- 16 files changed, 3387 insertions(+), 3316 deletions(-) diff --git a/crates/compiler/builtins/roc/Bool.roc b/crates/compiler/builtins/roc/Bool.roc index d53d80e55ca..e31f535a1b4 100644 --- a/crates/compiler/builtins/roc/Bool.roc +++ b/crates/compiler/builtins/roc/Bool.roc @@ -1,9 +1,9 @@ -module [Bool, Eq, true, false, and, or, not, isEq, isNotEq] +module [Bool, Eq, true, false, and, or, not, is_eq, is_not_eq] ## Defines a type that can be compared for total equality. ## ## Total equality means that all values of the type can be compared to each -## other, and two values `a`, `b` are identical if and only if `isEq a b` is +## other, and two values `a`, `b` are identical if and only if `isEq(a, b)` is ## `Bool.true`. ## ## Not all types support total equality. For example, [`F32`](../Num#F32) and [`F64`](../Num#F64) can @@ -14,9 +14,9 @@ Eq implements ## Returns `Bool.true` if the input values are equal. This is ## equivalent to the logic ## [XNOR](https://en.wikipedia.org/wiki/Logical_equality) gate. The infix - ## operator `==` can be used as shorthand for `Bool.isEq`. + ## operator `==` can be used as shorthand for `Bool.is_eq`. ## - ## **Note** that when `isEq` is determined by the Roc compiler, values are + ## **Note** that when `is_eq` is determined by the Roc compiler, values are ## compared using structural equality. The rules for this are as follows: ## ## 1. Tags are equal if their name and also contents are equal. @@ -24,25 +24,25 @@ Eq implements ## 3. The collections [Str], [List], [Dict], and [Set] are equal iff they ## are the same length and their elements are equal. ## 4. [Num] values are equal if their numbers are equal. However, if both - ## inputs are *NaN* then `isEq` returns `Bool.false`. Refer to `Num.isNaN` + ## inputs are *NaN* then `is_eq` returns `Bool.false`. Refer to `Num.is_nan` ## for more detail. ## 5. Functions cannot be compared for structural equality, therefore Roc - ## cannot derive `isEq` for types that contain functions. - isEq : a, a -> Bool where a implements Eq + ## cannot derive `is_eq` for types that contain functions. + is_eq : a, a -> Bool where a implements Eq ## Represents the boolean true and false using an opaque type. ## `Bool` implements the `Eq` ability. -Bool := [True, False] implements [Eq { isEq: boolIsEq }] +Bool := [True, False] implements [Eq { is_eq: bool_is_eq }] -boolIsEq = \@Bool b1, @Bool b2 -> structuralEq b1 b2 +bool_is_eq = \@Bool b1, @Bool b2 -> structural_eq b1 b2 ## The boolean true value. true : Bool -true = @Bool True +true = @Bool (True) ## The boolean false value. false : Bool -false = @Bool False +false = @Bool (False) ## Returns `Bool.true` when both inputs are `Bool.true`. This is equivalent to ## the logic [AND](https://en.wikipedia.org/wiki/Logical_conjunction) @@ -50,7 +50,7 @@ false = @Bool False ## `Bool.and`. ## ## ```roc -## expect (Bool.and Bool.true Bool.true) == Bool.true +## expect Bool.and(Bool.true, Bool.true) == Bool.true ## expect (Bool.true && Bool.true) == Bool.true ## expect (Bool.false && Bool.true) == Bool.false ## expect (Bool.true && Bool.false) == Bool.false @@ -63,10 +63,10 @@ false = @Bool False ## other function. However, in some languages `&&` and `||` are special-cased. ## In these languages the compiler will skip evaluating the expression after the ## first operator under certain circumstances. For example an expression like -## `enablePets && likesDogs user` would compile to. +## `enable_pets && likes_dogs(user)` would compile to. ## ```roc -## if enablePets then -## likesDogs user +## if enable_pets then +## likes_dogs(user) ## else ## Bool.false ## ``` @@ -79,7 +79,7 @@ and : Bool, Bool -> Bool ## the logic [OR](https://en.wikipedia.org/wiki/Logical_disjunction) gate. ## The infix operator `||` can also be used as shorthand for `Bool.or`. ## ```roc -## expect (Bool.or Bool.false Bool.true) == Bool.true +## expect Bool.or(Bool.false, Bool.true) == Bool.true ## expect (Bool.true || Bool.true) == Bool.true ## expect (Bool.false || Bool.true) == Bool.true ## expect (Bool.true || Bool.false) == Bool.true @@ -97,30 +97,30 @@ or : Bool, Bool -> Bool ## equivalent to the logic [NOT](https://en.wikipedia.org/wiki/Negation) ## gate. The operator `!` can also be used as shorthand for `Bool.not`. ## ```roc -## expect (Bool.not Bool.false) == Bool.true -## expect (!Bool.false) == Bool.true +## expect Bool.not(Bool.false) == Bool.true +## expect !Bool.false == Bool.true ## ``` not : Bool -> Bool -## This will call the function `Bool.isEq` on the inputs, and then `Bool.not` +## This will call the function `Bool.is_eq` on the inputs, and then `Bool.not` ## on the result. The is equivalent to the logic ## [XOR](https://en.wikipedia.org/wiki/Exclusive_or) gate. The infix operator -## `!=` can also be used as shorthand for `Bool.isNotEq`. +## `!=` can also be used as shorthand for `Bool.is_not_eq`. ## -## **Note** that `isNotEq` does not accept arguments whose types contain +## **Note** that `is_not_eq` does not accept arguments whose types contain ## functions. ## ```roc -## expect (Bool.isNotEq Bool.false Bool.true) == Bool.true +## expect Bool.is_not_eq(Bool.false, Bool.true) == Bool.true ## expect (Bool.false != Bool.false) == Bool.false ## expect "Apples" != "Oranges" ## ``` -isNotEq : a, a -> Bool where a implements Eq -isNotEq = \a, b -> structuralNotEq a b +is_not_eq : a, a -> Bool where a implements Eq +is_not_eq = \a, b -> structural_not_eq(a, b) -# INTERNAL COMPILER USE ONLY: used to lower calls to `isEq` to structural +# INTERNAL COMPILER USE ONLY: used to lower calls to `is_eq` to structural # equality via the `Eq` low-level for derived types. -structuralEq : a, a -> Bool +structural_eq : a, a -> Bool -# INTERNAL COMPILER USE ONLY: used to lower calls to `isNotEq` to structural +# INTERNAL COMPILER USE ONLY: used to lower calls to `is_not_eq` to structural # inequality via the `NotEq` low-level for derived types. -structuralNotEq : a, a -> Bool +structural_not_eq : a, a -> Bool diff --git a/crates/compiler/builtins/roc/Box.roc b/crates/compiler/builtins/roc/Box.roc index 4812a4e0cde..482ebe75be4 100644 --- a/crates/compiler/builtins/roc/Box.roc +++ b/crates/compiler/builtins/roc/Box.roc @@ -9,13 +9,13 @@ module [box, unbox] ## optimization for advanced use cases with large values. A platform may require ## that some values are boxed. ## ```roc -## expect Box.unbox (Box.box "Stack Faster") == "Stack Faster" +## expect Box.unbox(Box.box("Stack Faster")) == "Stack Faster" ## ``` box : a -> Box a ## Returns a boxed value. ## ```roc -## expect Box.unbox (Box.box "Stack Faster") == "Stack Faster" +## expect Box.unbox(Box.box("Stack Faster") == "Stack Faster" ## ``` unbox : Box a -> a diff --git a/crates/compiler/builtins/roc/Decode.roc b/crates/compiler/builtins/roc/Decode.roc index 71e330c4b1b..8390c010e5c 100644 --- a/crates/compiler/builtins/roc/Decode.roc +++ b/crates/compiler/builtins/roc/Decode.roc @@ -24,10 +24,10 @@ module [ record, tuple, custom, - decodeWith, - fromBytesPartial, - fromBytes, - mapResult, + decode_with, + from_bytes_partial, + from_bytes, + map_result, ] import List @@ -55,13 +55,13 @@ DecodeError : [TooShort] ## Return type of a [Decoder]. ## ## This can be useful when creating a [custom](#custom) decoder or when -## using [fromBytesPartial](#fromBytesPartial). For example writing unit tests, +## using [from_bytes_partial](#from_bytes_partial). For example writing unit tests, ## such as; ## ```roc ## expect ## input = "\"hello\", " |> Str.toUtf8 -## actual = Decode.fromBytesPartial input Json.json -## expected = Ok "hello" +## actual = Decode.from_bytes_partial(input, Json.json) +## expected = Ok("hello") ## ## actual.result == expected ## ``` @@ -95,51 +95,51 @@ DecoderFormatting implements string : Decoder Str fmt where fmt implements DecoderFormatting list : Decoder elem fmt -> Decoder (List elem) fmt where fmt implements DecoderFormatting - ## `record state stepField finalizer` decodes a record field-by-field. + ## `record(state, step_field, finalizer)` decodes a record field-by-field. ## - ## `stepField` returns a decoder for the given field in the record, or + ## `step_field` returns a decoder for the given field in the record, or ## `Skip` if the field is not a part of the decoded record. ## ## `finalizer` should produce the record value from the decoded `state`. record : state, (state, Str -> [Keep (Decoder state fmt), Skip]), (state, fmt -> Result val DecodeError) -> Decoder val fmt where fmt implements DecoderFormatting - ## `tuple state stepElem finalizer` decodes a tuple element-by-element. + ## `tuple(state, step_elem, finalizer)` decodes a tuple element-by-element. ## - ## `stepElem` returns a decoder for the nth index in the tuple, or + ## `step_elem` returns a decoder for the nth index in the tuple, or ## `TooLong` if the index is larger than the expected size of the tuple. The - ## index passed to `stepElem` is 0-indexed. + ## index passed to `step_elem` is 0-indexed. ## ## `finalizer` should produce the tuple value from the decoded `state`. tuple : state, (state, U64 -> [Next (Decoder state fmt), TooLong]), (state -> Result val DecodeError) -> Decoder val fmt where fmt implements DecoderFormatting ## Build a custom [Decoder] function. For example the implementation of -## `decodeBool` could be defined as follows; +## `decode_bool` could be defined as follows; ## ## ```roc -## decodeBool = Decode.custom \bytes, @Json {} -> +## decode_bool = Decode.custom \bytes, @Json({}) -> ## when bytes is -## ['f', 'a', 'l', 's', 'e', ..] -> { result: Ok Bool.false, rest: List.dropFirst bytes 5 } -## ['t', 'r', 'u', 'e', ..] -> { result: Ok Bool.true, rest: List.dropFirst bytes 4 } -## _ -> { result: Err TooShort, rest: bytes } +## ['f', 'a', 'l', 's', 'e', ..] -> { result: Ok(Bool.false), rest: List.drop_first(bytes, 5) } +## ['t', 'r', 'u', 'e', ..] -> { result: Ok Bool.true, rest: List.drop_first(bytes, 4) } +## _ -> { result: Err(TooShort), rest: bytes } ## ``` custom : (List U8, fmt -> DecodeResult val) -> Decoder val fmt where fmt implements DecoderFormatting -custom = \decode -> @Decoder decode +custom = \decode -> @Decoder(decode) ## Decode a `List U8` utf-8 bytes using a specific [Decoder] function -decodeWith : List U8, Decoder val fmt, fmt -> DecodeResult val where fmt implements DecoderFormatting -decodeWith = \bytes, @Decoder decode, fmt -> decode bytes fmt +decode_with : List U8, Decoder val fmt, fmt -> DecodeResult val where fmt implements DecoderFormatting +decode_with = \bytes, @Decoder(decode), fmt -> decode(bytes, fmt) ## Decode a `List U8` utf-8 bytes and return a [DecodeResult](#DecodeResult) ## ```roc ## expect ## input = "\"hello\", " |> Str.toUtf8 -## actual = Decode.fromBytesPartial input Json.json -## expected = Ok "hello" +## actual = Decode.from_bytes_partial(input Json.json) +## expected = Ok("hello") ## ## actual.result == expected ## ``` -fromBytesPartial : List U8, fmt -> DecodeResult val where val implements Decoding, fmt implements DecoderFormatting -fromBytesPartial = \bytes, fmt -> decodeWith bytes decoder fmt +from_bytes_partial : List U8, fmt -> DecodeResult val where val implements Decoding, fmt implements DecoderFormatting +from_bytes_partial = \bytes, fmt -> decode_with(bytes, decoder, fmt) ## Decode a `List U8` utf-8 bytes and return a [Result] with no leftover bytes ## expected. If successful returns `Ok val`, however, if there are bytes @@ -147,22 +147,22 @@ fromBytesPartial = \bytes, fmt -> decodeWith bytes decoder fmt ## ```roc ## expect ## input = "\"hello\", " |> Str.toUtf8 -## actual = Decode.fromBytes input Json.json -## expected = Ok "hello" +## actual = Decode.from_bytes(input, Json.json) +## expected = Ok("hello") ## ## actual == expected ## ``` -fromBytes : List U8, fmt -> Result val [Leftover (List U8)]DecodeError where val implements Decoding, fmt implements DecoderFormatting -fromBytes = \bytes, fmt -> - when fromBytesPartial bytes fmt is +from_bytes : List U8, fmt -> Result val [Leftover (List U8)]DecodeError where val implements Decoding, fmt implements DecoderFormatting +from_bytes = \bytes, fmt -> + when from_bytes_partial(bytes, fmt) is { result, rest } -> - if List.isEmpty rest then + if List.is_empty(rest) then when result is - Ok val -> Ok val - Err TooShort -> Err TooShort + Ok val -> Ok (val) + Err TooShort -> Err (TooShort) else - Err (Leftover rest) + Err (Leftover (rest)) ## Transform the `val` of a [DecodeResult] -mapResult : DecodeResult a, (a -> b) -> DecodeResult b -mapResult = \{ result, rest }, mapper -> { result: Result.map result mapper, rest } +map_result : DecodeResult a, (a -> b) -> DecodeResult b +map_result = \{ result, rest }, mapper -> { result: Result.map(result, mapper), rest } diff --git a/crates/compiler/builtins/roc/Dict.roc b/crates/compiler/builtins/roc/Dict.roc index c5e99c8b787..5c6964bbd90 100644 --- a/crates/compiler/builtins/roc/Dict.roc +++ b/crates/compiler/builtins/roc/Dict.roc @@ -1,32 +1,32 @@ module [ Dict, empty, - withCapacity, + with_capacity, single, clear, capacity, reserve, - releaseExcessCapacity, + release_excess_capacity, len, - isEmpty, + is_empty, get, contains, insert, remove, update, walk, - walkUntil, - keepIf, - dropIf, - toList, - fromList, + walk_until, + keep_if, + drop_if, + to_list, + from_list, keys, values, - insertAll, - keepShared, - removeAll, + insert_all, + keep_shared, + remove_all, map, - joinMap, + join_map, ] import Bool exposing [Bool, Eq] @@ -52,13 +52,13 @@ import Inspect exposing [Inspect, Inspector, InspectFormatter] ## Here's an example of a dictionary which uses a city's name as the key, and ## its population as the associated value. ## ```roc -## populationByCity = -## Dict.empty {} -## |> Dict.insert "London" 8_961_989 -## |> Dict.insert "Philadelphia" 1_603_797 -## |> Dict.insert "Shanghai" 24_870_895 -## |> Dict.insert "Delhi" 16_787_941 -## |> Dict.insert "Amsterdam" 872_680 +## population_by_city = +## Dict.empty({}) +## |> Dict.insert("London", 8_961_989) +## |> Dict.insert("Philadelphia", 1_603_797) +## |> Dict.insert("Shanghai", 24_870_895) +## |> Dict.insert("Delhi", 16_787_941) +## |> Dict.insert("Amsterdam", 872_680) ## ``` ## ## Accessing keys or values ## @@ -73,8 +73,8 @@ import Inspect exposing [Inspect, Inspector, InspectFormatter] ## ## We can remove an element from the dictionary, like so: ## ```roc -## populationByCity -## |> Dict.remove "Philadelphia" +## population_by_city +## |> Dict.remove("Philadelphia") ## |> Dict.keys ## == ## ["London", "Amsterdam", "Shanghai", "Delhi"] @@ -95,138 +95,139 @@ import Inspect exposing [Inspect, Inspector, InspectFormatter] Dict k v := { buckets : List Bucket, data : List (k, v), - maxBucketCapacity : U64, - maxLoadFactor : F32, + max_bucket_capacity : U64, + max_load_factor : F32, shifts : U8, } where k implements Hash & Eq implements [ Eq { - isEq, + is_eq, }, Hash { - hash: hashDict, + hash: hash_dict, }, Inspect { - toInspector: toInspectorDict, + to_inspector: to_inspector_dict, }, ] -isEq : Dict k v, Dict k v -> Bool where v implements Eq -isEq = \xs, ys -> - if len xs != len ys then +is_eq : Dict k v, Dict k v -> Bool where v implements Eq +is_eq = \xs, ys -> + if len(xs) != len(ys) then Bool.false else - walkUntil xs Bool.true \_, k, xVal -> - when get ys k is - Ok yVal if yVal == xVal -> + walk_until(xs, Bool.true, (\_, k, x_val -> + when get(ys, k) is + Ok y_val if y_val == x_val -> Continue Bool.true _ -> Break Bool.false + )) -hashDict : hasher, Dict k v -> hasher where v implements Hash, hasher implements Hasher -hashDict = \hasher, dict -> Hash.hashUnordered hasher (toList dict) List.walk +hash_dict : hasher, Dict k v -> hasher where v implements Hash, hasher implements Hasher +hash_dict = \hasher, dict -> Hash.hash_unordered(hasher, to_list(dict), List.walk) -toInspectorDict : Dict k v -> Inspector f where k implements Inspect & Hash & Eq, v implements Inspect, f implements InspectFormatter -toInspectorDict = \dict -> +to_inspector_dict : Dict k v -> Inspector f where k implements Inspect & Hash & Eq, v implements Inspect, f implements InspectFormatter +to_inspector_dict = \dict -> Inspect.custom \fmt -> - Inspect.apply (Inspect.dict dict walk Inspect.toInspector Inspect.toInspector) fmt + Inspect.apply(Inspect.dict(dict, walk, Inspect.to_inspector, Inspect.to_inspector) fmt) ## Return an empty dictionary. ## ```roc -## emptyDict = Dict.empty {} +## emptyDict = Dict.empty({}) ## ``` empty : {} -> Dict * * empty = \{} -> - @Dict { + @Dict({ buckets: [], data: [], - maxBucketCapacity: 0, - maxLoadFactor: defaultMaxLoadFactor, - shifts: initialShifts, - } + max_bucket_capacity: 0, + max_load_factor: default_max_load_factor, + shifts: initial_shifts, + }) ## Return a dictionary with space allocated for a number of entries. This ## may provide a performance optimization if you know how many entries will be ## inserted. -withCapacity : U64 -> Dict * * -withCapacity = \requested -> - empty {} - |> reserve requested +with_capacity : U64 -> Dict * * +with_capacity = \requested -> + empty({}) + |> reserve(requested) ## Enlarge the dictionary for at least capacity additional elements reserve : Dict k v, U64 -> Dict k v -reserve = \@Dict { buckets, data, maxBucketCapacity: originalMaxBucketCapacity, maxLoadFactor, shifts }, requested -> - currentSize = List.len data - requestedSize = Num.addWrap currentSize requested - size = Num.min requestedSize maxSize - - requestedShifts = calcShiftsForSize size maxLoadFactor - if (List.isEmpty buckets) || requestedShifts > shifts then - (buckets0, maxBucketCapacity) = allocBucketsFromShift requestedShifts maxLoadFactor - buckets1 = fillBucketsFromData buckets0 data requestedShifts - @Dict { +reserve = \@Dict { buckets, data, max_bucket_capacity: original_max_bucket_capacity, max_load_factor, shifts }, requested -> + current_size = List.len(data) + requested_size = Num.add_wrap(current_size, requested) + size = Num.min(requested_size, max_size) + + requested_shifts = calc_shifts_for_size(size, max_load_factor) + if List.is_empty(buckets) || requested_shifts > shifts then + (buckets0, max_bucket_capacity) = alloc_buckets_from_shift(requested_shifts, max_load_factor) + buckets1 = fill_buckets_from_data(buckets0, data, requested_shifts) + @Dict({ buckets: buckets1, - data: List.reserve data (Num.subSaturated size currentSize), - maxBucketCapacity, - maxLoadFactor, - shifts: requestedShifts, - } + data: List.reserve(data, Num.sub_saturated(size, current_size)), + max_bucket_capacity, + max_load_factor, + shifts: requested_shifts, + }) else - @Dict { buckets, data, maxBucketCapacity: originalMaxBucketCapacity, maxLoadFactor, shifts } + @Dict({ buckets, data, max_bucket_capacity: original_max_bucket_capacity, max_load_factor, shifts }) ## Shrink the memory footprint of a dictionary such that capacity is as small as possible. ## This function will require regenerating the metadata if the size changes. ## There will still be some overhead due to dictionary metadata always being a power of 2. -releaseExcessCapacity : Dict k v -> Dict k v -releaseExcessCapacity = \@Dict { buckets, data, maxBucketCapacity: originalMaxBucketCapacity, maxLoadFactor, shifts } -> - size = List.len data +release_excess_capacity : Dict k v -> Dict k v +release_excess_capacity = \@Dict { buckets, data, max_bucket_capacity: original_max_bucket_capacity, max_load_factor, shifts } -> + size = List.len(data) # NOTE: If we want, we technically could increase the load factor here to potentially minimize size more. - minShifts = calcShiftsForSize size maxLoadFactor - if minShifts < shifts then - (buckets0, maxBucketCapacity) = allocBucketsFromShift minShifts maxLoadFactor - buckets1 = fillBucketsFromData buckets0 data minShifts - @Dict { + min_shifts = calc_shifts_for_size(size, max_load_factor) + if min_shifts < shifts then + (buckets0, max_bucket_capacity) = alloc_buckets_from_shift(min_shifts, max_load_factor) + buckets1 = fill_buckets_from_data(buckets0, data, min_shifts) + @Dict({ buckets: buckets1, - data: List.releaseExcessCapacity data, - maxBucketCapacity, - maxLoadFactor, - shifts: minShifts, - } + data: List.release_excess_capacity(data), + max_bucket_capacity, + max_load_factor, + shifts: min_shifts, + }) else - @Dict { buckets, data, maxBucketCapacity: originalMaxBucketCapacity, maxLoadFactor, shifts } + @Dict({ buckets, data, max_bucket_capacity: original_max_bucket_capacity, max_load_factor, shifts }) ## Returns the max number of elements the dictionary can hold before requiring a rehash. ## ```roc -## foodDict = -## Dict.empty {} -## |> Dict.insert "apple" "fruit" +## food_dict = +## Dict.empty({}) +## |> Dict.insert("apple", "fruit") ## -## capacityOfDict = Dict.capacity foodDict +## capacity_of_dict = Dict.capacity(food_dict) ## ``` capacity : Dict * * -> U64 -capacity = \@Dict { maxBucketCapacity } -> - maxBucketCapacity +capacity = \@Dict({ max_bucket_capacity }) -> + max_bucket_capacity ## Returns a dictionary containing the key and value provided as input. ## ```roc ## expect -## Dict.single "A" "B" -## |> Bool.isEq (Dict.insert (Dict.empty {}) "A" "B") +## Dict.single("A", "B") +## |> Bool.is_eq(Dict.empty({}) |> Dict.insert("A", "B")) ## ``` single : k, v -> Dict k v single = \k, v -> - insert (empty {}) k v + insert(empty({}), k, v) ## Returns dictionary with the keys and values specified by the input [List]. ## ```roc ## expect -## Dict.single 1 "One" -## |> Dict.insert 2 "Two" -## |> Dict.insert 3 "Three" -## |> Dict.insert 4 "Four" -## |> Bool.isEq (Dict.fromList [(1, "One"), (2, "Two"), (3, "Three"), (4, "Four")]) +## Dict.single(1, "One") +## |> Dict.insert(2, "Two") +## |> Dict.insert(3, "Three") +## |> Dict.insert(4, "Four") +## |> Bool.is_eq(Dict.from_list([(1, "One"), (2, "Two"), (3, "Three"), (4, "Four")])) ## ``` ## ## ## Performance Details @@ -234,93 +235,95 @@ single = \k, v -> ## This will build up from an empty dictionary to minimize totally memory use. ## If the list has few duplicate keys, it would be faster to allocate a dictionary ## with the same capacity of the list and walk it calling [Dict.insert] -fromList : List (k, v) -> Dict k v -fromList = \data -> - List.walk data (empty {}) (\dict, (k, v) -> insert dict k v) +from_list : List (k, v) -> Dict k v +from_list = \data -> + List.walk(data, empty({}), (\dict, (k, v) -> insert(dict, k, v))) ## Returns the number of values in the dictionary. ## ```roc ## expect -## Dict.empty {} -## |> Dict.insert "One" "A Song" -## |> Dict.insert "Two" "Candy Canes" -## |> Dict.insert "Three" "Boughs of Holly" +## Dict.empty({}) +## |> Dict.insert("One", "A Song") +## |> Dict.insert("Two", "Candy Canes") +## |> Dict.insert("Three", "Boughs of Holly") ## |> Dict.len -## |> Bool.isEq 3 +## |> Bool.is_eq(3) ## ``` len : Dict * * -> U64 len = \@Dict { data } -> - List.len data + List.len(data) ## Check if the dictionary is empty. ## ```roc -## Dict.isEmpty (Dict.empty {} |> Dict.insert "key" 42) +## Dict.is_empty(Dict.empty({}) |> Dict.insert("key", 42)) ## -## Dict.isEmpty (Dict.empty {}) +## Dict.is_empty(Dict.empty({})) ## ``` -isEmpty : Dict * * -> Bool -isEmpty = \@Dict { data } -> - List.isEmpty data +is_empty : Dict * * -> Bool +is_empty = \@Dict({ data }) -> + List.is_empty(data) ## Clears all elements from a dictionary keeping around the allocation if it isn't huge. ## ```roc ## songs = -## Dict.empty {} -## |> Dict.insert "One" "A Song" -## |> Dict.insert "Two" "Candy Canes" -## |> Dict.insert "Three" "Boughs of Holly" +## Dict.empty({}) +## |> Dict.insert("One", "A Song") +## |> Dict.insert("Two", "Candy Canes") +## |> Dict.insert("Three", "Boughs of Holly") ## -## clearSongs = Dict.clear songs +## clear_songs = Dict.clear(songs) ## -## expect Dict.len clearSongs == 0 +## expect Dict.len(clear_songs) == 0 ## ``` clear : Dict k v -> Dict k v -clear = \@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts } -> - @Dict { - buckets: List.map buckets \_ -> emptyBucket, - # use takeFirst to keep around the capacity - data: List.takeFirst data 0, - maxBucketCapacity, - maxLoadFactor, +clear = \@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }) -> + @Dict({ + buckets: List.map(buckets, (\_ -> empty_bucket)), + # use take_first to keep around the capacity + data: List.take_first(data, 0), + max_bucket_capacity, + max_load_factor, shifts, - } + }) ## Convert each value in the dictionary to something new, by calling a conversion ## function on each of them which receives both the key and the old value. Then return a ## new dictionary containing the same keys and the converted values. map : Dict k a, (k, a -> b) -> Dict k b map = \dict, transform -> - init = withCapacity (capacity dict) + init = with_capacity(capacity(dict)) - walk dict init \answer, k, v -> - insert answer k (transform k v) + walk(dict, init, (\answer, k, v -> + insert(answer, k, transform(k, v)) + )) ## Like [Dict.map], except the transformation function wraps the return value ## in a dictionary. At the end, all the dictionaries get joined together -## (using [Dict.insertAll]) into one dictionary. +## (using [Dict.insert_all]) into one dictionary. ## -## You may know a similar function named `concatMap` in other languages. -joinMap : Dict a b, (a, b -> Dict x y) -> Dict x y -joinMap = \dict, transform -> - init = withCapacity (capacity dict) # Might be a pessimization +## You may know a similar function named `concat_map` in other languages. +join_map : Dict a b, (a, b -> Dict x y) -> Dict x y +join_map = \dict, transform -> + init = with_capacity(capacity(dict)) # Might be a pessimization - walk dict init \answer, k, v -> - insertAll answer (transform k v) + walk(dict, init, (\answer, k, v -> + insert_all(answer, transform(k, v)) + )) ## Iterate through the keys and values in the dictionary and call the provided ## function with signature `state, k, v -> state` for each value, with an ## initial `state` value provided for the first call. ## ```roc ## expect -## Dict.empty {} -## |> Dict.insert "Apples" 12 -## |> Dict.insert "Orange" 24 -## |> Dict.walk 0 (\count, _, qty -> count + qty) -## |> Bool.isEq 36 +## Dict.empty({}) +## |> Dict.insert("Apples", 12) +## |> Dict.insert("Orange", 24) +## |> Dict.walk(0, (\count, _, qty -> count + qty)) +## |> Bool.is_eq(36) ## ``` walk : Dict k v, state, (state, k, v -> state) -> state -walk = \@Dict { data }, initialState, transform -> - List.walk data initialState (\state, (k, v) -> transform state k v) +walk = \@Dict({ data }), initial_state, transform -> + List.walk(data, initial_state, (\state, (k, v) -> transform(state, k, v))) ## Same as [Dict.walk], except you can stop walking early. ## @@ -335,284 +338,285 @@ walk = \@Dict { data }, initialState, transform -> ## if returning `Break` earlier than the last element is expected to be common. ## ```roc ## people = -## Dict.empty {} -## |> Dict.insert "Alice" 17 -## |> Dict.insert "Bob" 18 -## |> Dict.insert "Charlie" 19 +## Dict.empty({}) +## |> Dict.insert("Alice", 17) +## |> Dict.insert("Bob", 18) +## |> Dict.insert("Charlie", 19) ## -## isAdult = \_, _, age -> -## if age >= 18 then -## Break Bool.true -## else -## Continue Bool.false +## is_adult = \_, _, age -> +## if age >= 18 then +## Break(Bool.true) +## else +## Continue(Bool.false) ## -## someoneIsAnAdult = Dict.walkUntil people Bool.false isAdult +## someone_is_an_adult = Dict.walk_until(people, Bool.false, is_adult) ## -## expect someoneIsAnAdult == Bool.true +## expect someone_is_an_adult == Bool.true ## ``` -walkUntil : Dict k v, state, (state, k, v -> [Continue state, Break state]) -> state -walkUntil = \@Dict { data }, initialState, transform -> - List.walkUntil data initialState (\state, (k, v) -> transform state k v) +walk_until : Dict k v, state, (state, k, v -> [Continue state, Break state]) -> state +walk_until = \@Dict({ data }), initial_state, transform -> + List.walk_until(data, initial_state, (\state, (k, v) -> transform(state, k, v))) ## Run the given function on each key-value pair of a dictionary, and return ## a dictionary with just the pairs for which the function returned `Bool.true`. ## ```roc -## expect Dict.empty {} -## |> Dict.insert "Alice" 17 -## |> Dict.insert "Bob" 18 -## |> Dict.insert "Charlie" 19 -## |> Dict.keepIf \(_k, v) -> v >= 18 +## expect Dict.empty({}) +## |> Dict.insert("Alice", 17) +## |> Dict.insert("Bob", 18) +## |> Dict.insert("Charlie", 19) +## |> Dict.keep_if(\(_k, v) -> v >= 18) ## |> Dict.len -## |> Bool.isEq 2 +## |> Bool.is_eq(2) ## ``` -keepIf : Dict k v, ((k, v) -> Bool) -> Dict k v -keepIf = \dict, predicate -> - keepIfHelp dict predicate 0 (Dict.len dict) +keep_if : Dict k v, ((k, v) -> Bool) -> Dict k v +keep_if = \dict, predicate -> + keep_if_help(dict, predicate, 0, Dict.len(dict)) -keepIfHelp : Dict k v, ((k, v) -> Bool), U64, U64 -> Dict k v -keepIfHelp = \@Dict dict, predicate, index, length -> +keep_if_help : Dict k v, ((k, v) -> Bool), U64, U64 -> Dict k v +keep_if_help = \@Dict(dict), predicate, index, length -> if index < length then - (key, value) = listGetUnsafe dict.data index - if predicate (key, value) then - keepIfHelp (@Dict dict) predicate (index |> Num.addWrap 1) length + (key, value) = list_get_unsafe(dict.data, index) + if predicate(key, value) then + keep_if_help(@Dict(dict), predicate, Num.add_wrap(index, 1), length) else - keepIfHelp (Dict.remove (@Dict dict) key) predicate index (length |> Num.subWrap 1) + keep_if_help(Dict.remove(@Dict(dict), key), predicate, index, Num.sub_wrap(length, 1)) else - @Dict dict + @Dict(dict) ## Run the given function on each key-value pair of a dictionary, and return ## a dictionary with just the pairs for which the function returned `Bool.false`. ## ```roc -## expect Dict.empty {} -## |> Dict.insert "Alice" 17 -## |> Dict.insert "Bob" 18 -## |> Dict.insert "Charlie" 19 -## |> Dict.dropIf \(_k, v) -> v >= 18 +## expect Dict.empty({}) +## |> Dict.insert("Alice", 17) +## |> Dict.insert("Bob", 18) +## |> Dict.insert("Charlie", 19) +## |> Dict.drop_if(\(_k, v) -> v >= 18) ## |> Dict.len -## |> Bool.isEq 1 +## |> Bool.is_eq(1) ## ``` -dropIf : Dict k v, ((k, v) -> Bool) -> Dict k v -dropIf = \dict, predicate -> - Dict.keepIf dict (\e -> Bool.not (predicate e)) +drop_if : Dict k v, ((k, v) -> Bool) -> Dict k v +drop_if = \dict, predicate -> + Dict.keep_if(dict, (\e -> Bool.not(predicate(e)))) ## Get the value for a given key. If there is a value for the specified key it ## will return [Ok value], otherwise return [Err KeyNotFound]. ## ```roc ## dictionary = -## Dict.empty {} -## |> Dict.insert 1 "Apple" -## |> Dict.insert 2 "Orange" +## Dict.empty({}) +## |> Dict.insert(1,s "Apple") +## |> Dict.insert(2,s "Orange") ## -## expect Dict.get dictionary 1 == Ok "Apple" -## expect Dict.get dictionary 2000 == Err KeyNotFound +## expect Dict.get(dictionary, 1) == Ok("Apple") +## expect Dict.get(dictionary, 2000) == Err(KeyNotFound) ## ``` get : Dict k v, k -> Result v [KeyNotFound] get = \dict, key -> - find dict key + find(dict, key) |> .result ## Check if the dictionary has a value for a specified key. ## ```roc ## expect -## Dict.empty {} -## |> Dict.insert 1234 "5678" -## |> Dict.contains 1234 -## |> Bool.isEq Bool.true +## Dict.empty({}) +## |> Dict.insert(1234, "5678") +## |> Dict.contains(1234) +## |> Bool.is_eq(Bool.true) ## ``` contains : Dict k v, k -> Bool contains = \dict, key -> - find dict key + find(dict, key) |> .result |> Result.isOk ## Insert a value into the dictionary at a specified key. ## ```roc ## expect -## Dict.empty {} -## |> Dict.insert "Apples" 12 -## |> Dict.get "Apples" -## |> Bool.isEq (Ok 12) +## Dict.empty({}) +## |> Dict.insert("Apples", 12) +## |> Dict.get("Apples") +## |> Bool.is_eq(Ok(12)) ## ``` insert : Dict k v, k, v -> Dict k v insert = \dict, key, value -> - (@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }) = - if len dict < capacity dict then + @Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }) = + if len(dict) < capacity(dict) then dict else - increaseSize dict - - hash = hashKey key - distAndFingerprint = distAndFingerprintFromHash hash - bucketIndex = bucketIndexFromHash hash shifts - - insertHelper buckets data bucketIndex distAndFingerprint key value maxBucketCapacity maxLoadFactor shifts - -insertHelper : List Bucket, List (k, v), U64, U32, k, v, U64, F32, U8 -> Dict k v -insertHelper = \buckets0, data0, bucketIndex0, distAndFingerprint0, key, value, maxBucketCapacity, maxLoadFactor, shifts -> - loaded = listGetUnsafe buckets0 bucketIndex0 - if distAndFingerprint0 == loaded.distAndFingerprint then - (foundKey, _) = listGetUnsafe data0 (Num.toU64 loaded.dataIndex) - if foundKey == key then - data1 = List.set data0 (Num.toU64 loaded.dataIndex) (key, value) - @Dict { buckets: buckets0, data: data1, maxBucketCapacity, maxLoadFactor, shifts } + increase_size(dict) + + hash = hash_key(key) + dist_and_fingerprint = dist_and_fingerprint_from_hash(hash) + bucket_index = bucket_index_from_hash(hash, shifts) + + # TODO: put these args in a record for organization? + insert_helper(buckets, data, bucket_index, dist_and_fingerprint, key, value, max_bucket_capacity, max_load_factor, shifts) + +insert_helper : List Bucket, List (k, v), U64, U32, k, v, U64, F32, U8 -> Dict k v +insert_helper = \buckets0, data0, bucket_index0, dist_and_fingerprint0, key, value, max_bucket_capacity, max_load_factor, shifts -> + loaded = list_get_unsafe(buckets0, bucket_index0) + if dist_and_fingerprint0 == loaded.dist_and_fingerprint then + (found_key, _) = list_get_unsafe(data0, Num.to_u64(loaded.data_index)) + if found_key == key then + data1 = List.set(data0, Num.to_u64(loaded.data_index), (key, value)) + @Dict({ buckets: buckets0, data: data1, max_bucket_capacity, max_load_factor, shifts }) else - bucketIndex1 = nextBucketIndex bucketIndex0 (List.len buckets0) - distAndFingerprint1 = incrementDist distAndFingerprint0 - insertHelper buckets0 data0 bucketIndex1 distAndFingerprint1 key value maxBucketCapacity maxLoadFactor shifts - else if distAndFingerprint0 > loaded.distAndFingerprint then - data1 = List.append data0 (key, value) - dataIndex = (List.len data1) |> Num.subWrap 1 - buckets1 = placeAndShiftUp buckets0 { distAndFingerprint: distAndFingerprint0, dataIndex: Num.toU32 dataIndex } bucketIndex0 - @Dict { buckets: buckets1, data: data1, maxBucketCapacity, maxLoadFactor, shifts } + bucket_index1 = next_bucket_index(bucket_index0, List.len(buckets0)) + dist_and_fingerprint1 = increment_dist(dist_and_fingerprint0) + insert_helper(buckets0, data0, bucket_index1, dist_and_fingerprint1, key, value, max_bucket_capacity, max_load_factor, shifts) + else if dist_and_fingerprint0 > loaded.dist_and_fingerprint then + data1 = List.append(data0, (key, value)) + data_index = List.len(data1) |> Num.sub_wrap(1) + buckets1 = place_and_shift_up(buckets0, { dist_and_fingerprint: dist_and_fingerprint0, data_index: Num.to_u32(data_index) }, bucket_index0) + @Dict({ buckets: buckets1, data: data1, max_bucket_capacity, max_load_factor, shifts }) else - bucketIndex1 = nextBucketIndex bucketIndex0 (List.len buckets0) - distAndFingerprint1 = incrementDist distAndFingerprint0 - insertHelper buckets0 data0 bucketIndex1 distAndFingerprint1 key value maxBucketCapacity maxLoadFactor shifts + bucket_index1 = next_bucket_index(bucket_index0, List.len(buckets0)) + dist_and_fingerprint1 = increment_dist(dist_and_fingerprint0) + insert_helper(buckets0, data0, bucket_index1, dist_and_fingerprint1, key, value, max_bucket_capacity, max_load_factor, shifts) ## Remove a value from the dictionary for a specified key. ## ```roc ## expect -## Dict.empty {} -## |> Dict.insert "Some" "Value" -## |> Dict.remove "Some" +## Dict.empty({}) +## |> Dict.insert("Some", "Value") +## |> Dict.remove("Some") ## |> Dict.len -## |> Bool.isEq 0 +## |> Bool.is_eq(0) ## ``` remove : Dict k v, k -> Dict k v -remove = \@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }, key -> - if !(List.isEmpty data) then - (bucketIndex0, distAndFingerprint0) = nextWhileLess buckets key shifts - (bucketIndex1, distAndFingerprint1) = removeHelper buckets bucketIndex0 distAndFingerprint0 data key - - bucket = listGetUnsafe buckets bucketIndex1 - if distAndFingerprint1 != bucket.distAndFingerprint then - @Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts } +remove = \@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), key -> + if !(List.is_empty(data)) then + (bucket_index0, dist_and_fingerprint0) = next_while_less(buckets, key, shifts) + (bucket_index1, dist_and_fingerprint1) = remove_helper(buckets, bucket_index0, dist_and_fingerprint0, data, key) + + bucket = list_get_unsafe(buckets, bucket_index1) + if dist_and_fingerprint1 != bucket.dist_and_fingerprint then + @Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }) else - removeBucket (@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }) bucketIndex1 + remove_bucket(@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), bucket_index1) else - @Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts } - -removeHelper : List Bucket, U64, U32, List (k, *), k -> (U64, U32) where k implements Eq -removeHelper = \buckets, bucketIndex, distAndFingerprint, data, key -> - bucket = listGetUnsafe buckets bucketIndex - if distAndFingerprint == bucket.distAndFingerprint then - (foundKey, _) = listGetUnsafe data (Num.toU64 bucket.dataIndex) - if foundKey == key then - (bucketIndex, distAndFingerprint) + @Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }) + +remove_helper : List Bucket, U64, U32, List (k, *), k -> (U64, U32) where k implements Eq +remove_helper = \buckets, bucket_index, dist_and_fingerprint, data, key -> + bucket = list_get_unsafe(buckets, bucket_index) + if dist_and_fingerprint == bucket.dist_and_fingerprint then + (found_key, _) = list_get_unsafe(data, Num.to_u64(bucket.data_index)) + if found_key == key then + (bucket_index, dist_and_fingerprint) else - removeHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key + remove_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) else - (bucketIndex, distAndFingerprint) + (bucket_index, dist_and_fingerprint) ## Insert or remove a value for a specified key. This function enables a ## performance optimization for the use case of providing a default when a value ## is missing. This is more efficient than doing both a `Dict.get` and then a ## `Dict.insert` call, and supports being piped. ## ```roc -## alterValue : Result Bool [Missing] -> Result Bool [Missing] -## alterValue = \possibleValue -> -## when possibleValue is -## Err Missing -> Ok Bool.false -## Ok value -> if value then Err Missing else Ok Bool.true +## alter_value : Result Bool [Missing] -> Result Bool [Missing] +## alter_value = \possible_value -> +## when possible_value is +## Err Missing -> Ok(Bool.false) +## Ok value -> if value then Err(Missing) else Ok(Bool.true) ## -## expect Dict.update (Dict.empty {}) "a" alterValue == Dict.single "a" Bool.false -## expect Dict.update (Dict.single "a" Bool.false) "a" alterValue == Dict.single "a" Bool.true -## expect Dict.update (Dict.single "a" Bool.true) "a" alterValue == Dict.empty {} +## expect Dict.update(Dict.empty({}), "a", alter_value) == Dict.single("a", Bool.false) +## expect Dict.update(Dict.single("a", Bool.false), "a", alter_value) == Dict.single("a", Bool.true) +## expect Dict.update(Dict.single("a", Bool.true), "a", alter_value) == Dict.empty({}) ## ``` update : Dict k v, k, (Result v [Missing] -> Result v [Missing]) -> Dict k v -update = \@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }, key, alter -> - { bucketIndex, result } = find (@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }) key +update = \@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), key, alter -> + { bucket_index, result } = find(@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), key) when result is Ok value -> - when alter (Ok value) is - Ok newValue -> - bucket = listGetUnsafe buckets bucketIndex - newData = List.set data (Num.toU64 bucket.dataIndex) (key, newValue) - @Dict { buckets, data: newData, maxBucketCapacity, maxLoadFactor, shifts } + when alter(Ok(value)) is + Ok(new_value) -> + bucket = list_get_unsafe(buckets, bucket_index) + new_data = List.set(data, Num.to_u64(bucket.data_index), (key, new_value)) + @Dict({ buckets, data: new_data, max_bucket_capacity, max_load_factor, shifts }) - Err Missing -> - removeBucket (@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }) bucketIndex + Err(Missing) -> + remove_bucket(@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), bucket_index) Err KeyNotFound -> - when alter (Err Missing) is - Ok newValue -> - if List.len data >= maxBucketCapacity then + when alter(Err(Missing)) is + Ok(new_value) -> + if List.len(data) >= max_bucket_capacity then # Need to reallocate let regular insert handle that. - insert (@Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts }) key newValue + insert(@Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }), key, new_value) else # Can skip work by jumping staight to the found bucket. # That will be the location we want to insert in. - hash = hashKey key - baseDistAndFingerprint = distAndFingerprintFromHash hash - baseBucketIndex = bucketIndexFromHash hash shifts + hash = hash_key(key) + base_dist_and_fingerprint = dist_and_fingerprint_from_hash(hash) + base_bucket_index = bucket_index_from_hash(hash, shifts) # Due to the unrolling of loops in find along with loop optimizations, - # The bucketIndex is not guaranteed to be correct here. + # The bucket_index is not guaranteed to be correct here. # It is only correct if we have traversed past the number of find unrolls. - dist = circularDist baseBucketIndex bucketIndex (List.len buckets) - if dist <= findManualUnrolls then - insertHelper buckets data baseBucketIndex baseDistAndFingerprint key newValue maxBucketCapacity maxLoadFactor shifts + dist = circular_dist(base_bucket_index, bucket_index, List.len(buckets)) + if dist <= find_manual_unrolls then + insert_helper(buckets, data, base_bucket_index, base_dist_and_fingerprint, key, new_value, max_bucket_capacity, max_load_factor, shifts) else - distAndFingerprint = incrementDistN baseDistAndFingerprint (Num.toU32 dist) - insertHelper buckets data bucketIndex distAndFingerprint key newValue maxBucketCapacity maxLoadFactor shifts + dist_and_fingerprint = increment_dist_n(base_dist_and_fingerprint, Num.to_u32(dist)) + insert_helper(buckets, data, bucket_index, dist_and_fingerprint, key, new_value, max_bucket_capacity, max_load_factor, shifts) - Err Missing -> - @Dict { buckets, data, maxBucketCapacity, maxLoadFactor, shifts } + Err(Missing) -> + @Dict({ buckets, data, max_bucket_capacity, max_load_factor, shifts }) -circularDist = \start, end, size -> +circular_dist = \start, end, size -> correction = if start > end then size else 0 end - |> Num.subWrap start - |> Num.addWrap correction + |> Num.sub_wrap(start) + |> Num.add_wrap(correction) ## Returns the keys and values of a dictionary as a [List]. -## This requires allocating a temporary list, prefer using [Dict.toList] or [Dict.walk] instead. +## This requires allocating a temporary list, prefer using [Dict.to_list] or [Dict.walk] instead. ## ```roc ## expect -## Dict.single 1 "One" -## |> Dict.insert 2 "Two" -## |> Dict.insert 3 "Three" -## |> Dict.insert 4 "Four" -## |> Dict.toList -## |> Bool.isEq [(1, "One"), (2, "Two"), (3, "Three"), (4, "Four")] +## Dict.single(1, "One") +## |> Dict.insert(2, "Two") +## |> Dict.insert(3, "Three") +## |> Dict.insert(4, "Four") +## |> Dict.to_list +## |> Bool.is_eq([(1, "One"), (2, "Two"), (3, "Three"), (4, "Four")]) ## ``` -toList : Dict k v -> List (k, v) -toList = \@Dict { data } -> +to_list : Dict k v -> List (k, v) +to_list = \@Dict({ data }) -> data ## Returns the keys of a dictionary as a [List]. -## This requires allocating a temporary [List], prefer using [Dict.toList] or [Dict.walk] instead. +## This requires allocating a temporary [List], prefer using [Dict.to_list] or [Dict.walk] instead. ## ```roc ## expect -## Dict.single 1 "One" -## |> Dict.insert 2 "Two" -## |> Dict.insert 3 "Three" -## |> Dict.insert 4 "Four" +## Dict.single(1, "One") +## |> Dict.insert(2, "Two") +## |> Dict.insert(3, "Three") +## |> Dict.insert(4, "Four") ## |> Dict.keys -## |> Bool.isEq [1,2,3,4] +## |> Bool.is_eq([1,2,3,4]) ## ``` keys : Dict k v -> List k -keys = \@Dict { data } -> - List.map data (\(k, _) -> k) +keys = \@Dict({ data }) -> + List.map(data, (\(k, _) -> k)) ## Returns the values of a dictionary as a [List]. -## This requires allocating a temporary [List], prefer using [Dict.toList] or [Dict.walk] instead. +## This requires allocating a temporary [List], prefer using [Dict.to_list] or [Dict.walk] instead. ## ```roc ## expect -## Dict.single 1 "One" -## |> Dict.insert 2 "Two" -## |> Dict.insert 3 "Three" -## |> Dict.insert 4 "Four" +## Dict.single(1, "One") +## |> Dict.insert(2, "Two") +## |> Dict.insert(3, "Three") +## |> Dict.insert(4, "Four") ## |> Dict.values -## |> Bool.isEq ["One","Two","Three","Four"] +## |> Bool.is_eq(["One","Two","Three","Four"]) ## ``` values : Dict k v -> List v -values = \@Dict { data } -> - List.map data (\(_, v) -> v) +values = \@Dict({ data }) -> + List.map(data, (\(_, v) -> v)) ## Combine two dictionaries by keeping the [union](https://en.wikipedia.org/wiki/Union_(set_theory)) ## of all the key-value pairs. This means that all the key-value pairs in @@ -621,69 +625,67 @@ values = \@Dict { data } -> ## retained, and the value in the first input will be removed. ## ```roc ## first = -## Dict.single 1 "Not Me" -## |> Dict.insert 2 "And Me" +## Dict.single(1, "Not Me") +## |> Dict.insert(2, "And Me") ## ## second = -## Dict.single 1 "Keep Me" -## |> Dict.insert 3 "Me Too" -## |> Dict.insert 4 "And Also Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(3, "Me Too") +## |> Dict.insert(4, "And Also Me") ## ## expected = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" -## |> Dict.insert 3 "Me Too" -## |> Dict.insert 4 "And Also Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") +## |> Dict.insert(3, "Me Too") +## |> Dict.insert(4, "And Also Me") ## ## expect -## Dict.insertAll first second == expected +## Dict.insert_all(first, second) == expected ## ``` -insertAll : Dict k v, Dict k v -> Dict k v -insertAll = \xs, ys -> - if len ys > len xs then - insertAll ys xs +insert_all : Dict k v, Dict k v -> Dict k v +insert_all = \xs, ys -> + if len(ys) > len(xs) then + insert_all(ys, xs) else - walk ys xs insert + walk(ys, xs, insert) ## Combine two dictionaries by keeping the [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory)) ## of all the key-value pairs. This means that we keep only those pairs ## that are in both dictionaries. Both the key and value must match to be kept. ## ```roc ## first = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" -## |> Dict.insert 3 "Not this one" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") +## |> Dict.insert(3, "Not this one") ## ## second = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" -## |> Dict.insert 3 "This has a different value" -## |> Dict.insert 4 "Or Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") +## |> Dict.insert(3, "This has a different value") +## |> Dict.insert(4, "Or Me") ## ## expected = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") ## -## expect Dict.keepShared first second == expected +## expect Dict.keep_shared(first, second) == expected ## ``` -keepShared : Dict k v, Dict k v -> Dict k v where v implements Eq -keepShared = \xs0, ys0 -> +keep_shared : Dict k v, Dict k v -> Dict k v where v implements Eq +keep_shared = \xs0, ys0 -> (xs1, ys1) = - if len ys0 < len xs0 then + if len(ys0) < len(xs0) then (ys0, xs0) else (xs0, ys0) - walk - xs1 - (withCapacity (len xs1)) - (\state, k, v -> - when get ys1 k is - Ok yv if v == yv -> - insert state k v - _ -> - state - ) + walk(xs1, with_capacity(len(xs1)), (\state, k, v -> + when get(ys1, k) is + Ok(yv) if v == yv -> + insert(state, k, v) + + _ -> + state + )) ## Remove the key-value pairs in the first input that are also in the second ## using the [set difference](https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement) @@ -691,384 +693,385 @@ keepShared = \xs0, ys0 -> ## are in the first dictionary and whose keys are not in the second. ## ```roc ## first = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" -## |> Dict.insert 3 "Remove Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") +## |> Dict.insert(3, "Remove Me") ## ## second = -## Dict.single 3 "Remove Me" -## |> Dict.insert 4 "I do nothing..." +## Dict.single(3, "Remove Me") +## |> Dict.insert(4, "I do nothing...") ## ## expected = -## Dict.single 1 "Keep Me" -## |> Dict.insert 2 "And Me" +## Dict.single(1, "Keep Me") +## |> Dict.insert(2, "And Me") ## -## expect Dict.removeAll first second == expected +## expect Dict.remove_all(first, second) == expected ## ``` -removeAll : Dict k v, Dict k v -> Dict k v -removeAll = \xs, ys -> - walk ys xs (\state, k, _ -> remove state k) +remove_all : Dict k v, Dict k v -> Dict k v +remove_all = \xs, ys -> + walk(ys, xs, (\state, k, _ -> remove(state, k))) # Below here is a list of generic helpers and internal data types for Dict Bucket : { - distAndFingerprint : U32, # upper 3 byte: distance to original bucket. lower byte: fingerprint from hash - dataIndex : U32, # index into the data list. + dist_and_fingerprint : U32, # upper 3 byte: distance to original bucket. lower byte: fingerprint from hash + data_index : U32, # index into the data list. } -emptyBucket = { distAndFingerprint: 0, dataIndex: 0 } -distInc = Num.shiftLeftBy 1u32 8 # skip 1 byte fingerprint -fingerprintMask = Num.subWrap distInc 1 # mask for 1 byte of fingerprint -defaultMaxLoadFactor = 0.8 -initialShifts = 64 |> Num.subWrap 3 # 2^(64-shifts) number of buckets -maxSize = Num.shiftLeftBy 1u64 32 -maxBucketCount = maxSize +empty_bucket = { dist_and_fingerprint: 0, data_index: 0 } +dist_inc = Num.shift_left_by(1u32, 8) # skip 1 byte fingerprint +fingerprint_mask = Num.sub_wrap(dist_inc, 1) # mask for 1 byte of fingerprint +default_max_load_factor = 0.8 +initial_shifts = Num.sub_wrap(64, 3) # 2^(64-shifts) number of buckets +max_size = Num.shift_left_by(1u64, 32) +max_bucket_count = max_size -incrementDist = \distAndFingerprint -> - Num.addWrap distAndFingerprint distInc +increment_dist = \dist_and_fingerprint -> + Num.add_wrap(dist_and_fingerprint, dist_inc) -incrementDistN = \distAndFingerprint, n -> - Num.addWrap distAndFingerprint (Num.mulWrap n distInc) +increment_dist_n = \dist_and_fingerprint, n -> + Num.add_wrap(dist_and_fingerprint, Num.mul_wrap(n, dist_inc)) -decrementDist = \distAndFingerprint -> - distAndFingerprint |> Num.subWrap distInc +decrement_dist = \dist_and_fingerprint -> + Num.sub_wrap(dist_and_fingerprint, dist_inc) -find : Dict k v, k -> { bucketIndex : U64, result : Result v [KeyNotFound] } -find = \@Dict { buckets, data, shifts }, key -> - hash = hashKey key - distAndFingerprint = distAndFingerprintFromHash hash - bucketIndex = bucketIndexFromHash hash shifts +find : Dict k v, k -> { bucket_index : U64, result : Result v [KeyNotFound] } +find = \@Dict({ buckets, data, shifts }), key -> + hash = hash_key(key) + dist_and_fingerprint = dist_and_fingerprint_from_hash(hash) + bucket_index = bucket_index_from_hash(hash, shifts) - if !(List.isEmpty data) then + if !(List.is_empty(data)) then # TODO: this is true in the C++ code, confirm it in Roc as well. # unrolled loop. *Always* check a few directly, then enter the loop. This is faster. - findFirstUnroll buckets bucketIndex distAndFingerprint data key + find_first_unroll(buckets, bucket_index, dist_and_fingerprint, data, key) else - { bucketIndex, result: Err KeyNotFound } + { bucket_index, result: Err(KeyNotFound) } -findManualUnrolls = 2 +find_manual_unrolls = 2 -findFirstUnroll : List Bucket, U64, U32, List (k, v), k -> { bucketIndex : U64, result : Result v [KeyNotFound] } where k implements Eq -findFirstUnroll = \buckets, bucketIndex, distAndFingerprint, data, key -> +find_first_unroll : List Bucket, U64, U32, List (k, v), k -> { bucket_index : U64, result : Result v [KeyNotFound] } where k implements Eq +find_first_unroll = \buckets, bucket_index, dist_and_fingerprint, data, key -> # TODO: once we have short circuit evaluation, use it here and other similar locations in this file. # Avoid the nested if with else block inconvenience. - bucket = listGetUnsafe buckets bucketIndex - if distAndFingerprint == bucket.distAndFingerprint then - (foundKey, value) = listGetUnsafe data (Num.toU64 bucket.dataIndex) - if foundKey == key then - { bucketIndex, result: Ok value } + bucket = list_get_unsafe(buckets, bucket_index) + if dist_and_fingerprint == bucket.dist_and_fingerprint then + (found_key, value) = list_get_unsafe(data, Num.to_u64(bucket.data_index)) + if found_key == key then + { bucket_index, result: Ok(value) } else - findSecondUnroll buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key + find_second_unroll(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) else - findSecondUnroll buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key - -findSecondUnroll : List Bucket, U64, U32, List (k, v), k -> { bucketIndex : U64, result : Result v [KeyNotFound] } where k implements Eq -findSecondUnroll = \buckets, bucketIndex, distAndFingerprint, data, key -> - bucket = listGetUnsafe buckets bucketIndex - if distAndFingerprint == bucket.distAndFingerprint then - (foundKey, value) = listGetUnsafe data (Num.toU64 bucket.dataIndex) - if foundKey == key then - { bucketIndex, result: Ok value } + find_second_unroll(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) + +find_second_unroll : List Bucket, U64, U32, List (k, v), k -> { bucket_index : U64, result : Result v [KeyNotFound] } where k implements Eq +find_second_unroll = \buckets, bucket_index, dist_and_fingerprint, data, key -> + bucket = list_get_unsafe(buckets, bucket_index) + if dist_and_fingerprint == bucket.dist_and_fingerprint then + (found_key, value) = list_get_unsafe(data, Num.to_u64(bucket.data_index)) + if found_key == key then + { bucket_index, result: Ok(value) } else - findHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key + find_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) else - findHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key - -findHelper : List Bucket, U64, U32, List (k, v), k -> { bucketIndex : U64, result : Result v [KeyNotFound] } where k implements Eq -findHelper = \buckets, bucketIndex, distAndFingerprint, data, key -> - bucket = listGetUnsafe buckets bucketIndex - if distAndFingerprint == bucket.distAndFingerprint then - (foundKey, value) = listGetUnsafe data (Num.toU64 bucket.dataIndex) - if foundKey == key then - { bucketIndex, result: Ok value } + find_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) + +find_helper : List Bucket, U64, U32, List (k, v), k -> { bucket_index : U64, result : Result v [KeyNotFound] } where k implements Eq +find_helper = \buckets, bucket_index, dist_and_fingerprint, data, key -> + bucket = list_get_unsafe(buckets, bucket_index) + if dist_and_fingerprint == bucket.dist_and_fingerprint then + (found_key, value) = list_get_unsafe(data, Num.to_u64(bucket.data_index)) + if found_key == key then + { bucket_index, result: Ok(value) } else - findHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key - else if distAndFingerprint > bucket.distAndFingerprint then - { bucketIndex, result: Err KeyNotFound } + find_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) + else if dist_and_fingerprint > bucket.dist_and_fingerprint then + { bucket_index, result: Err(KeyNotFound) } else - findHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) data key + find_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint), data, key) -removeBucket : Dict k v, U64 -> Dict k v -removeBucket = \@Dict { buckets: buckets0, data: data0, maxBucketCapacity, maxLoadFactor, shifts }, bucketIndex0 -> - dataIndexToRemove = (listGetUnsafe buckets0 bucketIndex0).dataIndex - dataIndexToRemoveU64 = Num.toU64 dataIndexToRemove +remove_bucket : Dict k v, U64 -> Dict k v +remove_bucket = \@Dict({ buckets: buckets0, data: data0, max_bucket_capacity, max_load_factor, shifts }), bucket_index0 -> + data_index_to_remove = list_get_unsafe(buckets0, bucket_index0).data_index + data_index_to_remove_u64 = Num.to_u64(data_index_to_remove) - (buckets1, bucketIndex1) = removeBucketHelper buckets0 bucketIndex0 - buckets2 = List.set buckets1 bucketIndex1 emptyBucket + (buckets1, bucket_index1) = remove_bucket_helper(buckets0, bucket_index0) + buckets2 = List.set(buckets1, bucket_index1, empty_bucket) - lastDataIndex = List.len data0 |> Num.subWrap 1 - if dataIndexToRemoveU64 != lastDataIndex then + last_data_index = List.len(data0) |> Num.sub_wrap(1) + if data_index_to_remove_u64 != last_data_index then # Swap removed item to the end - data1 = List.swap data0 dataIndexToRemoveU64 lastDataIndex - (key, _) = listGetUnsafe data1 dataIndexToRemoveU64 + data1 = List.swap(data0, data_index_to_remove_u64, last_data_index) + (key, _) = list_get_unsafe(data1, data_index_to_remove_u64) # Update the data index of the new value. - hash = hashKey key - bucketIndex2 = bucketIndexFromHash hash shifts - - bucketIndex3 = scanForIndex buckets2 bucketIndex2 (Num.toU32 lastDataIndex) - swapBucket = listGetUnsafe buckets2 bucketIndex3 - @Dict { - buckets: List.set buckets2 bucketIndex3 { swapBucket & dataIndex: dataIndexToRemove }, - data: List.dropLast data1 1, - maxBucketCapacity, - maxLoadFactor, + hash = hash_key(key) + bucket_index2 = bucket_index_from_hash(hash, shifts) + + bucket_index3 = scan_for_index(buckets2, bucket_index2, Num.to_u32(last_data_index)) + swap_bucket = list_get_unsafe(buckets2, bucket_index3) + + @Dict({ + buckets: List.set(buckets2, bucket_index3, { swap_bucket & data_index: data_index_to_remove }), + data: List.drop_last(data1, 1), + max_bucket_capacity, + max_load_factor, shifts, - } + }) else - @Dict { + @Dict({ buckets: buckets2, - data: List.dropLast data0 1, - maxBucketCapacity, - maxLoadFactor, + data: List.drop_last(data0, 1), + max_bucket_capacity, + max_load_factor, shifts, - } + }) -scanForIndex : List Bucket, U64, U32 -> U64 -scanForIndex = \buckets, bucketIndex, dataIndex -> - bucket = listGetUnsafe buckets bucketIndex - if bucket.dataIndex != dataIndex then - scanForIndex buckets (nextBucketIndex bucketIndex (List.len buckets)) dataIndex +scan_for_index : List Bucket, U64, U32 -> U64 +scan_for_index = \buckets, bucket_index, data_index -> + bucket = list_get_unsafe(buckets, bucket_index) + if bucket.data_index != data_index then + scan_for_index(buckets, next_bucket_index(bucket_index, List.len(buckets)), data_index) else - bucketIndex + bucket_index -removeBucketHelper : List Bucket, U64 -> (List Bucket, U64) -removeBucketHelper = \buckets, bucketIndex -> - nextIndex = nextBucketIndex bucketIndex (List.len buckets) - nextBucket = listGetUnsafe buckets nextIndex +remove_bucket_helper : List Bucket, U64 -> (List Bucket, U64) +remove_bucket_helper = \buckets, bucket_index -> + next_index = next_bucket_index(bucket_index, List.len(buckets)) + next_bucket = list_get_unsafe(buckets, next_index) # shift down until either empty or an element with correct spot is found - if nextBucket.distAndFingerprint >= Num.mulWrap distInc 2 then - List.set buckets bucketIndex { nextBucket & distAndFingerprint: decrementDist nextBucket.distAndFingerprint } - |> removeBucketHelper nextIndex + if next_bucket.dist_and_fingerprint >= Num.mul_wrap(dist_inc, 2) then + List.set(buckets, bucket_index, { next_bucket & dist_and_fingerprint: decrement_dist(next_bucket.dist_and_fingerprint) }) + |> remove_bucket_helper(next_index) else - (buckets, bucketIndex) - -increaseSize : Dict k v -> Dict k v -increaseSize = \@Dict { data, maxBucketCapacity, maxLoadFactor, shifts } -> - if maxBucketCapacity != maxBucketCount then - newShifts = shifts |> Num.subWrap 1 - (buckets0, newMaxBucketCapacity) = allocBucketsFromShift newShifts maxLoadFactor - buckets1 = fillBucketsFromData buckets0 data newShifts - @Dict { + (buckets, bucket_index) + +increase_size : Dict k v -> Dict k v +increase_size = \@Dict({ data, max_bucket_capacity, max_load_factor, shifts }) -> + if max_bucket_capacity != max_bucket_count then + new_shifts = shifts |> Num.sub_wrap(1) + (buckets0, new_max_bucket_capacity) = alloc_buckets_from_shift(new_shifts, max_load_factor) + buckets1 = fill_buckets_from_data(buckets0, data, new_shifts) + @Dict({ buckets: buckets1, data, - maxBucketCapacity: newMaxBucketCapacity, - maxLoadFactor, - shifts: newShifts, - } + max_bucket_capacity: new_max_bucket_capacity, + max_load_factor, + shifts: new_shifts, + }) else - crash "Dict hit limit of $(Num.toStr maxBucketCount) elements. Unable to grow more." + crash("Dict hit limit of $(Num.toStr(max_bucket_count)) elements. Unable to grow more.") -allocBucketsFromShift : U8, F32 -> (List Bucket, U64) -allocBucketsFromShift = \shifts, maxLoadFactor -> - bucketCount = calcNumBuckets shifts - if bucketCount == maxBucketCount then +alloc_buckets_from_shift : U8, F32 -> (List Bucket, U64) +alloc_buckets_from_shift = \shifts, max_load_factor -> + bucket_count = calc_num_buckets(shifts) + if bucket_count == max_bucket_count then # reached the maximum, make sure we can use each bucket - (List.repeat emptyBucket maxBucketCount, maxBucketCount) + (List.repeat(empty_bucket, max_bucket_count), max_bucket_count) else - maxBucketCapacity = - bucketCount - |> Num.toF32 - |> Num.mul maxLoadFactor + max_bucket_capacity = + bucket_count + |> Num.to_f32 + |> Num.mul(max_load_factor) |> Num.floor - (List.repeat emptyBucket bucketCount, maxBucketCapacity) -calcShiftsForSize : U64, F32 -> U8 -calcShiftsForSize = \size, maxLoadFactor -> - calcShiftsForSizeHelper initialShifts size maxLoadFactor + (List.repeat(empty_bucket, bucket_count), max_bucket_capacity) -calcShiftsForSizeHelper = \shifts, size, maxLoadFactor -> - maxBucketCapacity = +calc_shifts_for_size : U64, F32 -> U8 +calc_shifts_for_size = \size, max_load_factor -> + calc_shifts_for_size_helper(initial_shifts, size, max_load_factor) + +calc_shifts_for_size_helper = \shifts, size, max_load_factor -> + max_bucket_capacity = shifts - |> calcNumBuckets - |> Num.toF32 - |> Num.mul maxLoadFactor + |> calc_num_buckets + |> Num.to_f32 + |> Num.mul(max_load_factor) |> Num.floor - if shifts > 0 && maxBucketCapacity < size then - calcShiftsForSizeHelper (shifts |> Num.subWrap 1) size maxLoadFactor + if shifts > 0 && max_bucket_capacity < size then + calc_shifts_for_size_helper(Num.sub_wrap(shifts, 1), size, max_load_factor) else shifts -calcNumBuckets = \shifts -> - Num.min - (Num.shiftLeftBy 1 (64 |> Num.subWrap shifts)) - maxBucketCount +calc_num_buckets = \shifts -> + Num.min(Num.shift_left_by(1, Num.sub_wrap(64, shifts)), max_bucket_count) -fillBucketsFromData = \buckets0, data, shifts -> - List.walkWithIndex data buckets0 \buckets1, (key, _), dataIndex -> - (bucketIndex, distAndFingerprint) = nextWhileLess buckets1 key shifts - placeAndShiftUp buckets1 { distAndFingerprint, dataIndex: Num.toU32 dataIndex } bucketIndex +fill_buckets_from_data = \buckets0, data, shifts -> + List.walk_with_index(data, buckets0, (\buckets1, (key, _), data_index -> + (bucket_index, dist_and_fingerprint) = next_while_less(buckets1, key, shifts) + place_and_shift_up(buckets1, { dist_and_fingerprint, data_index: Num.to_u32(data_index) }, bucket_index) + )) -nextWhileLess : List Bucket, k, U8 -> (U64, U32) where k implements Hash & Eq -nextWhileLess = \buckets, key, shifts -> - hash = hashKey key - distAndFingerprint = distAndFingerprintFromHash hash - bucketIndex = bucketIndexFromHash hash shifts +next_while_less : List Bucket, k, U8 -> (U64, U32) where k implements Hash & Eq +next_while_less = \buckets, key, shifts -> + hash = hash_key(key) + dist_and_fingerprint = dist_and_fingerprint_from_hash(hash) + bucket_index = bucket_index_from_hash(hash, shifts) - nextWhileLessHelper buckets bucketIndex distAndFingerprint + next_while_less_helper(buckets, bucket_index, dist_and_fingerprint) -nextWhileLessHelper = \buckets, bucketIndex, distAndFingerprint -> - loaded = listGetUnsafe buckets bucketIndex - if distAndFingerprint < loaded.distAndFingerprint then - nextWhileLessHelper buckets (nextBucketIndex bucketIndex (List.len buckets)) (incrementDist distAndFingerprint) +next_while_less_helper = \buckets, bucket_index, dist_and_fingerprint -> + loaded = list_get_unsafe(buckets, bucket_index) + if dist_and_fingerprint < loaded.dist_and_fingerprint then + next_while_less_helper(buckets, next_bucket_index(bucket_index, List.len(buckets)), increment_dist(dist_and_fingerprint)) else - (bucketIndex, distAndFingerprint) - -placeAndShiftUp = \buckets0, bucket, bucketIndex -> - loaded = listGetUnsafe buckets0 bucketIndex - if loaded.distAndFingerprint != 0 then - buckets1 = List.set buckets0 bucketIndex bucket - placeAndShiftUp - buckets1 - { loaded & distAndFingerprint: incrementDist loaded.distAndFingerprint } - (nextBucketIndex bucketIndex (List.len buckets1)) + (bucket_index, dist_and_fingerprint) + +place_and_shift_up = \buckets0, bucket, bucket_index -> + loaded = list_get_unsafe(buckets0, bucket_index) + if loaded.dist_and_fingerprint != 0 then + buckets1 = List.set(buckets0, bucket_index, bucket) + place_and_shift_up( + buckets1, + { loaded & dist_and_fingerprint: increment_dist(loaded.dist_and_fingerprint) }, + next_bucket_index(bucket_index, List.len(buckets1)), + ) else - List.set buckets0 bucketIndex bucket + List.set(buckets0, bucket_index, bucket) -nextBucketIndex = \bucketIndex, maxBuckets -> +next_bucket_index = \bucket_index, max_buckets -> # I just ported this impl directly. # I am a bit confused why it is using an if over a mask. # Maybe compilers are smart enough to optimize this well. # Maybe the unlikely annotation is super important - if Num.addWrap bucketIndex 1 != maxBuckets then - Num.addWrap bucketIndex 1 + if Num.add_wrap(bucket_index, 1) != max_buckets then + Num.add_wrap(bucket_index, 1) else 0 -hashKey = \key -> - createLowLevelHasher PseudoRandSeed - |> Hash.hash key +hash_key = \key -> + create_low_level_hasher(PseudoRandSeed) + |> Hash.hash(key) |> complete -distAndFingerprintFromHash : U64 -> U32 -distAndFingerprintFromHash = \hash -> +dist_and_fingerprint_from_hash : U64 -> U32 +dist_and_fingerprint_from_hash = \hash -> hash - |> Num.toU32 - |> Num.bitwiseAnd fingerprintMask - |> Num.bitwiseOr distInc + |> Num.to_u32 + |> Num.bitwise_and(fingerprint_mask) + |> Num.bitwise_or(dist_inc) -bucketIndexFromHash : U64, U8 -> U64 -bucketIndexFromHash = \hash, shifts -> - hash - |> Num.shiftRightZfBy shifts +bucket_index_from_hash : U64, U8 -> U64 +bucket_index_from_hash = \hash, shifts -> + Num.shift_right_zf_by(hash, shifts) expect val = - empty {} - |> insert "foo" "bar" - |> get "foo" + empty({}) + |> insert("foo", "bar") + |> get("foo") - val == Ok "bar" + val == Ok("bar") expect dict1 = - empty {} - |> insert 1 "bar" - |> insert 2 "baz" + empty({}) + |> insert(1, "bar") + |> insert(2, "baz") dict2 = - empty {} - |> insert 2 "baz" - |> insert 1 "bar" + empty({}) + |> insert(2, "baz") + |> insert(1, "bar") dict1 == dict2 expect dict1 = - empty {} - |> insert 1 "bar" - |> insert 2 "baz" + empty({}) + |> insert(1, "bar") + |> insert(2, "baz") dict2 = - empty {} - |> insert 1 "bar" - |> insert 2 "baz!" + empty({}) + |> insert(1, "bar") + |> insert(2, "baz!") dict1 != dict2 expect inner1 = - empty {} - |> insert 1 "bar" - |> insert 2 "baz" + empty({}) + |> insert(1, "bar") + |> insert(2, "baz") inner2 = - empty {} - |> insert 2 "baz" - |> insert 1 "bar" + empty({}) + |> insert(2, "baz") + |> insert(1, "bar") outer = - empty {} - |> insert inner1 "wrong" - |> insert inner2 "right" + empty({}) + |> insert(inner1, "wrong") + |> insert(inner2, "right") - get outer inner1 == Ok "right" + get(outer, inner1) == Ok("right") expect inner1 = - empty {} - |> insert 1 "bar" - |> insert 2 "baz" + empty({}) + |> insert(1, "bar") + |> insert(2, "baz") inner2 = - empty {} - |> insert 2 "baz" - |> insert 1 "bar" + empty({}) + |> insert(2, "baz") + |> insert(1, "bar") outer1 = - empty {} - |> insert inner1 "val" + empty({}) + |> insert(inner1, "val") outer2 = - empty {} - |> insert inner2 "val" + empty({}) + |> insert(inner2, "val") outer1 == outer2 expect val = - empty {} - |> insert "foo" "bar" - |> insert "foo" "baz" - |> get "foo" + empty({}) + |> insert("foo", "bar") + |> insert("foo", "baz") + |> get("foo") - val == Ok "baz" + val == Ok("baz") expect val = - empty {} - |> insert "foo" "bar" - |> get "bar" + empty({}) + |> insert("foo", "bar") + |> get("bar") - val == Err KeyNotFound + val == Err(KeyNotFound) expect - empty {} - |> insert "foo" {} - |> contains "foo" + empty({}) + |> insert("foo", {}) + |> contains("foo") expect dict = - empty {} - |> insert "foo" {} - |> insert "bar" {} - |> insert "baz" {} + empty({}) + |> insert("foo", {}) + |> insert("bar", {}) + |> insert("baz", {}) - contains dict "baz" && Bool.not (contains dict "other") + contains(dict, "baz") && !contains(dict, "other") expect dict = - fromList [(1u8, 1u8), (2, 2), (3, 3)] - |> remove 1 - |> remove 3 + from_list([(1u8, 1u8), (2, 2), (3, 3)]) + |> remove(1) + |> remove(3) - keys dict == [2] + keys(dict) == [2] expect list = - fromList [(1u8, 1u8), (2u8, 2u8), (3, 3)] - |> remove 1 - |> insert 0 0 - |> remove 3 + from_list([(1u8, 1u8), (2u8, 2u8), (3, 3)]) + |> remove(1) + |> insert(0, 0) + |> remove(3) |> keys list == [0, 2] @@ -1076,19 +1079,19 @@ expect # Reach capacity, no rehash. expect val = - empty {} - |> insert "a" 0 - |> insert "b" 1 - |> insert "c" 2 - |> insert "d" 3 - |> insert "e" 4 - |> insert "f" 5 - |> insert "g" 6 - |> insert "h" 7 - |> insert "i" 8 - |> insert "j" 9 - |> insert "k" 10 - |> insert "l" 11 + empty({}) + |> insert("a", 0) + |> insert("b", 1) + |> insert("c", 2) + |> insert("d", 3) + |> insert("e", 4) + |> insert("f", 5) + |> insert("g", 6) + |> insert("h", 7) + |> insert("i", 8) + |> insert("j", 9) + |> insert("k", 10) + |> insert("l", 11) |> capacity val == 12 @@ -1096,50 +1099,50 @@ expect # Reach capacity, all elements still exist expect dict = - empty {} - |> insert "a" 0 - |> insert "b" 1 - |> insert "c" 2 - |> insert "d" 3 - |> insert "e" 4 - |> insert "f" 5 - |> insert "g" 6 - |> insert "h" 7 - |> insert "i" 8 - |> insert "j" 9 - |> insert "k" 10 - |> insert "l" 11 - - (get dict "a" == Ok 0) - && (get dict "b" == Ok 1) - && (get dict "c" == Ok 2) - && (get dict "d" == Ok 3) - && (get dict "e" == Ok 4) - && (get dict "f" == Ok 5) - && (get dict "g" == Ok 6) - && (get dict "h" == Ok 7) - && (get dict "i" == Ok 8) - && (get dict "j" == Ok 9) - && (get dict "k" == Ok 10) - && (get dict "l" == Ok 11) + empty({}) + |> insert("a", 0) + |> insert("b", 1) + |> insert("c", 2) + |> insert("d", 3) + |> insert("e", 4) + |> insert("f", 5) + |> insert("g", 6) + |> insert("h", 7) + |> insert("i", 8) + |> insert("j", 9) + |> insert("k", 10) + |> insert("l", 11) + + (get(dict, "a") == Ok(0)) + && (get(dict, "b") == Ok(1)) + && (get(dict, "c") == Ok(2)) + && (get(dict, "d") == Ok(3)) + && (get(dict, "e") == Ok(4)) + && (get(dict, "f") == Ok(5)) + && (get(dict, "g") == Ok(6)) + && (get(dict, "h") == Ok(7)) + && (get(dict, "i") == Ok(8)) + && (get(dict, "j") == Ok(9)) + && (get(dict, "k") == Ok(10)) + && (get(dict, "l") == Ok(11)) # Force rehash. expect val = - empty {} - |> insert "a" 0 - |> insert "b" 1 - |> insert "c" 2 - |> insert "d" 3 - |> insert "e" 4 - |> insert "f" 5 - |> insert "g" 6 - |> insert "h" 7 - |> insert "i" 8 - |> insert "j" 9 - |> insert "k" 10 - |> insert "l" 11 - |> insert "m" 12 + empty({}) + |> insert("a", 0) + |> insert("b", 1) + |> insert("c", 2) + |> insert("d", 3) + |> insert("e", 4) + |> insert("f", 5) + |> insert("g", 6) + |> insert("h", 7) + |> insert("i", 8) + |> insert("j", 9) + |> insert("k", 10) + |> insert("l", 11) + |> insert("m", 12) |> capacity val == 25 @@ -1147,87 +1150,90 @@ expect # Force rehash, all elements still exist expect dict = - empty {} - |> insert "a" 0 - |> insert "b" 1 - |> insert "c" 2 - |> insert "d" 3 - |> insert "e" 4 - |> insert "f" 5 - |> insert "g" 6 - |> insert "h" 7 - |> insert "i" 8 - |> insert "j" 9 - |> insert "k" 10 - |> insert "l" 11 - |> insert "m" 12 - - (get dict "a" == Ok 0) - && (get dict "b" == Ok 1) - && (get dict "c" == Ok 2) - && (get dict "d" == Ok 3) - && (get dict "e" == Ok 4) - && (get dict "f" == Ok 5) - && (get dict "g" == Ok 6) - && (get dict "h" == Ok 7) - && (get dict "i" == Ok 8) - && (get dict "j" == Ok 9) - && (get dict "k" == Ok 10) - && (get dict "l" == Ok 11) - && (get dict "m" == Ok 12) + empty({}) + |> insert("a", 0) + |> insert("b", 1) + |> insert("c", 2) + |> insert("d", 3) + |> insert("e", 4) + |> insert("f", 5) + |> insert("g", 6) + |> insert("h", 7) + |> insert("i", 8) + |> insert("j", 9) + |> insert("k", 10) + |> insert("l", 11) + |> insert("m", 12) + + (get(dict, "a") == Ok(0)) + && (get(dict, "b") == Ok(1)) + && (get(dict, "c") == Ok(2)) + && (get(dict, "d") == Ok(3)) + && (get(dict, "e") == Ok(4)) + && (get(dict, "f") == Ok(5)) + && (get(dict, "g") == Ok(6)) + && (get(dict, "h") == Ok(7)) + && (get(dict, "i") == Ok(8)) + && (get(dict, "j") == Ok(9)) + && (get(dict, "k") == Ok(10)) + && (get(dict, "l") == Ok(11)) + && (get(dict, "m") == Ok(12)) expect - empty {} - |> insert "Some" "Value" - |> remove "Some" + empty({}) + |> insert("Some", "Value") + |> remove("Some") |> len - |> Bool.isEq 0 + |> Bool.is_eq(0) # All BadKey's hash to the same location. # This is needed to test some robinhood logic. BadKey := U64 implements [ Eq, Hash { - hash: hashBadKey, + hash: hash_bad_key, }, ] -hashBadKey : hasher, BadKey -> hasher where hasher implements Hasher -hashBadKey = \hasher, _ -> Hash.hash hasher 0 +hash_bad_key : hasher, BadKey -> hasher where hasher implements Hasher +hash_bad_key = \hasher, _ -> Hash.hash(hasher, 0) expect - badKeys = [ - @BadKey 0, - @BadKey 1, - @BadKey 2, - @BadKey 3, - @BadKey 4, - @BadKey 5, - @BadKey 6, - @BadKey 5, - @BadKey 4, - @BadKey 3, - @BadKey 3, - @BadKey 3, - @BadKey 10, + bad_keys = [ + @BadKey(0), + @BadKey(1), + @BadKey(2), + @BadKey(3), + @BadKey(4), + @BadKey(5), + @BadKey(6), + @BadKey(5), + @BadKey(4), + @BadKey(3), + @BadKey(3), + @BadKey(3), + @BadKey(10), ] dict = - List.walk badKeys (Dict.empty {}) \acc, k -> - Dict.update acc k \val -> + List.walk(bad_keys, Dict.empty({}), (\acc, k -> + Dict.update(acc, k, (\val -> when val is - Ok p -> Ok (p |> Num.addWrap 1) - Err Missing -> Ok 0 + Ok(p) -> Ok(Num.add_wrap(p, 1)) + Err(Missing) -> Ok(0) + )) + )) - allInsertedCorrectly = - List.walk badKeys Bool.true \acc, k -> - acc && Dict.contains dict k + all_inserted_correctly = + List.walk(bad_keys, Bool.true, (\acc, k -> + acc && Dict.contains(dict, k) + )) - allInsertedCorrectly + all_inserted_correctly # Note, there are a number of places we should probably use set and replace unsafe. # unsafe primitive that does not perform a bounds check -listGetUnsafe : List a, U64 -> a +list_get_unsafe : List a, U64 -> a # We have decided not to expose the standard roc hashing algorithm. # This is to avoid external dependence and the need for versioning. @@ -1236,160 +1242,164 @@ listGetUnsafe : List a, U64 -> a # TODO: wyhash is slow for large keys, use something like cityhash if the keys are too long. # TODO: Add a builtin to distinguish big endian systems and change loading orders. # TODO: Switch out Wymum on systems with slow 128bit multiplication. -LowLevelHasher := { initializedSeed : U64, state : U64 } implements [ +LowLevelHasher := { initialized_seed : U64, state : U64 } implements [ Hasher { - addBytes, - addU8, - addU16, - addU32, - addU64, - addU128, + add_bytes, + add_u8, + add_u16, + add_u32, + add_u64, + add_u128, complete, }, ] # Returns a application specific pseudo random seed for Dict. # This avoids trivial DOS attacks. -pseudoSeed : {} -> U64 +pseudo_seed : {} -> U64 -createLowLevelHasher : [PseudoRandSeed, WithSeed U64] -> LowLevelHasher -createLowLevelHasher = \seedOpt -> +create_low_level_hasher : [PseudoRandSeed, WithSeed U64] -> LowLevelHasher +create_low_level_hasher = \seed_opt -> seed = - when seedOpt is - PseudoRandSeed -> pseudoSeed {} - WithSeed s -> s - @LowLevelHasher { initializedSeed: initSeed seed, state: seed } + when seed_opt is + PseudoRandSeed -> pseudo_seed({}) + WithSeed(s) -> s + @LowLevelHasher({ initialized_seed: init_seed(seed), state: seed }) -combineState : LowLevelHasher, { a : U64, b : U64, seed : U64, length : U64 } -> LowLevelHasher -combineState = \@LowLevelHasher { initializedSeed, state }, { a, b, seed, length } -> +combine_state : LowLevelHasher, { a : U64, b : U64, seed : U64, length : U64 } -> LowLevelHasher +combine_state = \@LowLevelHasher({ initialized_seed, state }), { a, b, seed, length } -> mum = a - |> Num.bitwiseXor wyp1 - |> wymum (Num.bitwiseXor b seed) + |> Num.bitwise_xor(wyp1) + |> wymum(Num.bitwise_xor(b, seed)) nexta = mum.lower - |> Num.bitwiseXor wyp0 - |> Num.bitwiseXor length + |> Num.bitwise_xor(wyp0) + |> Num.bitwise_xor(length) nextb = mum.upper - |> Num.bitwiseXor wyp1 - hash = wymix nexta nextb + |> Num.bitwise_xor(wyp1) + hash = wymix(nexta, nextb) - @LowLevelHasher { initializedSeed, state: wymix state hash } + @LowLevelHasher({ initialized_seed, state: wymix(state, hash) }) -initSeed = \seed -> +init_seed = \seed -> seed - |> Num.bitwiseXor wyp0 - |> wymix wyp1 - |> Num.bitwiseXor seed + |> Num.bitwise_xor(wyp0) + |> wymix(wyp1) + |> Num.bitwise_xor(seed) -complete = \@LowLevelHasher { state } -> state +complete = \@LowLevelHasher({ state }) -> state # These implementations hash each value individually with the seed and then mix # the resulting hash with the state. There are other options that may be faster # like using the output of the last hash as the seed to the current hash. # I am simply not sure the tradeoffs here. Theoretically this method is more sound. # Either way, the performance will be similar and we can change this later. -addU8 = \@LowLevelHasher { initializedSeed, state }, u8 -> - p0 = Num.toU64 u8 +add_u8 = \@LowLevelHasher({ initialized_seed, state }), u8 -> + p0 = Num.to_u64(u8) a = - Num.shiftLeftBy p0 16 - |> Num.bitwiseOr (Num.shiftLeftBy p0 8) - |> Num.bitwiseOr p0 + Num.shift_left_by(p0, 16) + |> Num.bitwise_or(Num.shift_left_by(p0, 8)) + |> Num.bitwise_or(p0) b = 0 - combineState (@LowLevelHasher { initializedSeed, state }) { a, b, seed: initializedSeed, length: 1 } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a, b, seed: initialized_seed, length: 1 }) -addU16 = \@LowLevelHasher { initializedSeed, state }, u16 -> - p0 = Num.bitwiseAnd u16 0xFF |> Num.toU64 - p1 = Num.shiftRightZfBy u16 8 |> Num.toU64 +add_u16 = \@LowLevelHasher({ initialized_seed, state }), u16 -> + p0 = Num.bitwise_and(u16, 0xFF) |> Num.to_u64 + p1 = Num.shift_right_zf_by(u16, 8) |> Num.to_u64 a = - Num.shiftLeftBy p0 16 - |> Num.bitwiseOr (Num.shiftLeftBy p1 8) - |> Num.bitwiseOr p1 + Num.shift_left_by(p0, 16) + |> Num.bitwise_or(Num.shift_left_by(p1, 8)) + |> Num.bitwise_or(p1) b = 0 - combineState (@LowLevelHasher { initializedSeed, state }) { a, b, seed: initializedSeed, length: 2 } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a, b, seed: initialized_seed, length: 2 }) -addU32 = \@LowLevelHasher { initializedSeed, state }, u32 -> - p0 = Num.toU64 u32 - a = Num.shiftLeftBy p0 32 |> Num.bitwiseOr p0 +add_u32 = \@LowLevelHasher({ initialized_seed, state }), u32 -> + p0 = Num.to_u64(u32) + a = Num.shift_left_by(p0, 32) |> Num.bitwise_or(p0) - combineState (@LowLevelHasher { initializedSeed, state }) { a, b: a, seed: initializedSeed, length: 4 } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a, b: a, seed: initialized_seed, length: 4 }) -addU64 = \@LowLevelHasher { initializedSeed, state }, u64 -> - p0 = Num.bitwiseAnd 0xFFFF_FFFF u64 - p1 = Num.shiftRightZfBy u64 32 - a = Num.shiftLeftBy p0 32 |> Num.bitwiseOr p1 - b = Num.shiftLeftBy p1 32 |> Num.bitwiseOr p0 +add_u64 = \@LowLevelHasher({ initialized_seed, state }), u64 -> + p0 = Num.bitwise_and 0xFFFF_FFFF u64 + p1 = Num.shift_right_zf_by u64 32 + a = Num.shift_left_by p0 32 |> Num.bitwise_or p1 + b = Num.shift_left_by p1 32 |> Num.bitwise_or p0 - combineState (@LowLevelHasher { initializedSeed, state }) { a, b, seed: initializedSeed, length: 8 } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a, b, seed: initialized_seed, length: 8 }) -addU128 = \@LowLevelHasher { initializedSeed, state }, u128 -> - lower = u128 |> Num.toU64 - upper = Num.shiftRightZfBy u128 64 |> Num.toU64 - p0 = Num.bitwiseAnd 0xFFFF_FFFF lower - p1 = Num.shiftRightZfBy lower 32 |> Num.bitwiseAnd 0xFFFF_FFFF - p2 = Num.bitwiseAnd 0xFFFF_FFFF upper - p3 = Num.shiftRightZfBy upper 32 |> Num.bitwiseAnd 0xFFFF_FFFF - a = Num.shiftLeftBy p0 32 |> Num.bitwiseOr p2 - b = Num.shiftLeftBy p3 32 |> Num.bitwiseOr p1 +add_u128 = \@LowLevelHasher({ initialized_seed, state }), u128 -> + lower = u128 |> Num.to_u64 + upper = Num.shift_right_zf_by(u128, 64) |> Num.to_u64 + p0 = Num.bitwise_and(0xFFFF_FFFF, lower) + p1 = Num.shift_right_zf_by(lower, 32) |> Num.bitwise_and(0xFFFF_FFFF) + p2 = Num.bitwise_and(0xFFFF_FFFF, upper) + p3 = Num.shift_right_zf_by(upper, 32) |> Num.bitwise_and(0xFFFF_FFFF) + a = Num.shift_left_by(p0, 32) |> Num.bitwise_or(p2) + b = Num.shift_left_by(p3, 32) |> Num.bitwise_or(p1) - combineState (@LowLevelHasher { initializedSeed, state }) { a, b, seed: initializedSeed, length: 16 } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a, b, seed: initialized_seed, length: 16 }) -addBytes : LowLevelHasher, List U8 -> LowLevelHasher -addBytes = \@LowLevelHasher { initializedSeed, state }, list -> - length = List.len list +add_bytes : LowLevelHasher, List U8 -> LowLevelHasher +add_bytes = \@LowLevelHasher({ initialized_seed, state }), list -> + length = List.len(list) abs = if length <= 16 then if length >= 4 then - x = Num.shiftRightZfBy length 3 |> Num.shiftLeftBy 2 - a = Num.bitwiseOr (wyr4 list 0 |> Num.shiftLeftBy 32) (wyr4 list x) + x = Num.shift_right_zf_by(length, 3) |> Num.shift_left_by(2) + a = Num.bitwise_or(wyr4(list, 0) |> Num.shift_left_by(32), wyr4(list, x)) b = - (wyr4 list (Num.subWrap length 4) |> Num.shiftLeftBy 32) - |> Num.bitwiseOr (wyr4 list (Num.subWrap length 4 |> Num.subWrap x)) + wyr4(list, Num.sub_wrap(length, 4)) + |> Num.shift_left_by(32) + |> Num.bitwise_or(wyr4(list, Num.sub_wrap(length, 4) |> Num.sub_wrap(x))) - { a, b, seed: initializedSeed } + { a, b, seed: initialized_seed } else if length > 0 then - { a: wyr3 list 0 length, b: 0, seed: initializedSeed } + { a: wyr3(list, 0, length), b: 0, seed: initialized_seed } else - { a: 0, b: 0, seed: initializedSeed } + { a: 0, b: 0, seed: initialized_seed } else if length <= 48 then - hashBytesHelper16 initializedSeed list 0 length + hash_bytes_helper16(initialized_seed, list, 0, length) else - hashBytesHelper48 initializedSeed initializedSeed initializedSeed list 0 length + hash_bytes_helper48(initialized_seed, initialized_seed, initialized_seed, list, 0, length) - combineState (@LowLevelHasher { initializedSeed, state }) { a: abs.a, b: abs.b, seed: abs.seed, length } + combine_state(@LowLevelHasher({ initialized_seed, state }), { a: abs.a, b: abs.b, seed: abs.seed, length }) -hashBytesHelper48 : U64, U64, U64, List U8, U64, U64 -> { a : U64, b : U64, seed : U64 } -hashBytesHelper48 = \seed, see1, see2, list, index, remaining -> - newSeed = wymix (Num.bitwiseXor (wyr8 list index) wyp1) (Num.bitwiseXor (wyr8 list (Num.addWrap index 8)) seed) - newSee1 = wymix (Num.bitwiseXor (wyr8 list (Num.addWrap index 16)) wyp2) (Num.bitwiseXor (wyr8 list (Num.addWrap index 24)) see1) - newSee2 = wymix (Num.bitwiseXor (wyr8 list (Num.addWrap index 32)) wyp3) (Num.bitwiseXor (wyr8 list (Num.addWrap index 40)) see2) - newRemaining = Num.subWrap remaining 48 - newIndex = Num.addWrap index 48 +hash_bytes_helper48 : U64, U64, U64, List U8, U64, U64 -> { a : U64, b : U64, seed : U64 } +hash_bytes_helper48 = \seed, see1, see2, list, index, remaining -> + # TODO: update!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + new_seed = wymix (Num.bitwise_xor (wyr8 list index) wyp1) (Num.bitwise_xor (wyr8 list (Num.add_wrap index 8)) seed) + new_see1 = wymix (Num.bitwise_xor (wyr8 list (Num.add_wrap index 16)) wyp2) (Num.bitwise_xor (wyr8 list (Num.add_wrap index 24)) see1) + new_see2 = wymix (Num.bitwise_xor (wyr8 list (Num.add_wrap index 32)) wyp3) (Num.bitwise_xor (wyr8 list (Num.add_wrap index 40)) see2) + new_remaining = Num.sub_wrap remaining 48 + new_index = Num.add_wrap index 48 - if newRemaining > 48 then - hashBytesHelper48 newSeed newSee1 newSee2 list newIndex newRemaining - else if newRemaining > 16 then - finalSeed = Num.bitwiseXor newSee2 (Num.bitwiseXor newSee1 newSeed) + if new_remaining > 48 then + hash_bytes_helper48 new_seed new_see1 new_see2 list new_index new_remaining + else if new_remaining > 16 then + final_seed = Num.bitwise_xor new_see2 (Num.bitwise_xor new_see1 new_seed) - hashBytesHelper16 finalSeed list newIndex newRemaining + hash_bytes_helper16 final_seed list new_index new_remaining else - finalSeed = Num.bitwiseXor newSee2 (Num.bitwiseXor newSee1 newSeed) + final_seed = Num.bitwise_xor new_see2 (Num.bitwise_xor new_see1 new_seed) - { a: wyr8 list (Num.subWrap newRemaining 16 |> Num.addWrap newIndex), b: wyr8 list (Num.subWrap newRemaining 8 |> Num.addWrap newIndex), seed: finalSeed } + { a: wyr8 list (Num.sub_wrap new_remaining 16 |> Num.add_wrap new_index), b: wyr8 list (Num.sub_wrap new_remaining 8 |> Num.add_wrap new_index), seed: final_seed } -hashBytesHelper16 : U64, List U8, U64, U64 -> { a : U64, b : U64, seed : U64 } -hashBytesHelper16 = \seed, list, index, remaining -> - newSeed = wymix (Num.bitwiseXor (wyr8 list index) wyp1) (Num.bitwiseXor (wyr8 list (Num.addWrap index 8)) seed) - newRemaining = Num.subWrap remaining 16 - newIndex = Num.addWrap index 16 +hash_bytes_helper16 : U64, List U8, U64, U64 -> { a : U64, b : U64, seed : U64 } +hash_bytes_helper16 = \seed, list, index, remaining -> + new_seed = wymix (Num.bitwise_xor (wyr8 list index) wyp1) (Num.bitwise_xor (wyr8 list (Num.add_wrap index 8)) seed) + new_remaining = Num.sub_wrap remaining 16 + new_index = Num.add_wrap index 16 - if newRemaining <= 16 then - { a: wyr8 list (Num.subWrap newRemaining 16 |> Num.addWrap newIndex), b: wyr8 list (Num.subWrap newRemaining 8 |> Num.addWrap newIndex), seed: newSeed } + if new_remaining <= 16 then + { a: wyr8 list (Num.sub_wrap new_remaining 16 |> Num.add_wrap new_index), b: wyr8 list (Num.sub_wrap new_remaining 8 |> Num.add_wrap new_index), seed: new_seed } else - hashBytesHelper16 newSeed list newIndex newRemaining + hash_bytes_helper16 new_seed list new_index new_remaining + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! wyp0 : U64 wyp0 = 0xa0761d6478bd642f @@ -1402,202 +1412,202 @@ wyp3 = 0x589965cc75374cc3 wymix : U64, U64 -> U64 wymix = \a, b -> - { lower, upper } = wymum a b + { lower, upper } = wymum(a, b) - Num.bitwiseXor lower upper + Num.bitwise_xor(lower, upper) wymum : U64, U64 -> { lower : U64, upper : U64 } wymum = \a, b -> - r = Num.mulWrap (Num.toU128 a) (Num.toU128 b) - lower = Num.toU64 r - upper = Num.shiftRightZfBy r 64 |> Num.toU64 + r = Num.mul_wrap(Num.toU128(a), Num.toU128(b)) + lower = Num.to_u64(r) + upper = Num.shift_right_zf_by(r, 64) |> Num.to_u64 # This is the more robust form, which we may look into later - # { lower: Num.bitwiseXor a lower, upper: Num.bitwiseXor b upper } + # { lower: Num.bitwise_xor(a, lower), upper: Num.bitwise_xor(b, upper) } { lower, upper } # Get the next 8 bytes as a U64 wyr8 : List U8, U64 -> U64 wyr8 = \list, index -> - # With seamless slices and Num.fromBytes, this should be possible to make faster and nicer. + # With seamless slices and Num.from_bytes, this should be possible to make faster and nicer. # It would also deal with the fact that on big endian systems we want to invert the order here. - # Without seamless slices, we would need fromBytes to take an index. - p1 = listGetUnsafe list index |> Num.toU64 - p2 = listGetUnsafe list (Num.addWrap index 1) |> Num.toU64 - p3 = listGetUnsafe list (Num.addWrap index 2) |> Num.toU64 - p4 = listGetUnsafe list (Num.addWrap index 3) |> Num.toU64 - p5 = listGetUnsafe list (Num.addWrap index 4) |> Num.toU64 - p6 = listGetUnsafe list (Num.addWrap index 5) |> Num.toU64 - p7 = listGetUnsafe list (Num.addWrap index 6) |> Num.toU64 - p8 = listGetUnsafe list (Num.addWrap index 7) |> Num.toU64 - a = Num.bitwiseOr p1 (Num.shiftLeftBy p2 8) - b = Num.bitwiseOr (Num.shiftLeftBy p3 16) (Num.shiftLeftBy p4 24) - c = Num.bitwiseOr (Num.shiftLeftBy p5 32) (Num.shiftLeftBy p6 40) - d = Num.bitwiseOr (Num.shiftLeftBy p7 48) (Num.shiftLeftBy p8 56) - - Num.bitwiseOr (Num.bitwiseOr a b) (Num.bitwiseOr c d) + # Without seamless slices, we would need from_bytes to take an index. + p1 = list_get_unsafe(list, index) |> Num.to_u64 + p2 = list_get_unsafe(list, Num.add_wrap(index, 1)) |> Num.to_u64 + p3 = list_get_unsafe(list, Num.add_wrap(index, 2)) |> Num.to_u64 + p4 = list_get_unsafe(list, Num.add_wrap(index, 3)) |> Num.to_u64 + p5 = list_get_unsafe(list, Num.add_wrap(index, 4)) |> Num.to_u64 + p6 = list_get_unsafe(list, Num.add_wrap(index, 5)) |> Num.to_u64 + p7 = list_get_unsafe(list, Num.add_wrap(index, 6)) |> Num.to_u64 + p8 = list_get_unsafe(list, Num.add_wrap(index, 7)) |> Num.to_u64 + a = Num.bitwise_or(p1, Num.shift_left_by(p2, 8)) + b = Num.bitwise_or(Num.shift_left_by(p3, 16), Num.shift_left_by(p4, 24)) + c = Num.bitwise_or(Num.shift_left_by(p5, 32), Num.shift_left_by(p6, 40)) + d = Num.bitwise_or(Num.shift_left_by(p7, 48), Num.shift_left_by(p8, 56)) + + Num.bitwise_or(Num.bitwise_or(a, b), Num.bitwise_or(c, d)) # Get the next 4 bytes as a U64 with some shifting. wyr4 : List U8, U64 -> U64 wyr4 = \list, index -> - p1 = listGetUnsafe list index |> Num.toU64 - p2 = listGetUnsafe list (Num.addWrap index 1) |> Num.toU64 - p3 = listGetUnsafe list (Num.addWrap index 2) |> Num.toU64 - p4 = listGetUnsafe list (Num.addWrap index 3) |> Num.toU64 - a = Num.bitwiseOr p1 (Num.shiftLeftBy p2 8) - b = Num.bitwiseOr (Num.shiftLeftBy p3 16) (Num.shiftLeftBy p4 24) + p1 = list_get_unsafe(list, index) |> Num.to_u64 + p2 = list_get_unsafe(list, Num.add_wrap(index, 1)) |> Num.to_u64 + p3 = list_get_unsafe(list, Num.add_wrap(index, 2)) |> Num.to_u64 + p4 = list_get_unsafe(list, Num.add_wrap(index, 3)) |> Num.to_u64 + a = Num.bitwise_or(p1, Num.shift_left_by(p2, 8)) + b = Num.bitwise_or(Num.shift_left_by(p3, 16), Num.shift_left_by(p4, 24)) - Num.bitwiseOr a b + Num.bitwise_or(a, b) # Get the next K bytes with some shifting. # K must be 3 or less. wyr3 : List U8, U64, U64 -> U64 wyr3 = \list, index, k -> # ((uint64_t)p[0])<<16)|(((uint64_t)p[k>>1])<<8)|p[k-1] - p1 = listGetUnsafe list index |> Num.toU64 - p2 = listGetUnsafe list (Num.shiftRightZfBy k 1 |> Num.addWrap index) |> Num.toU64 - p3 = listGetUnsafe list (Num.subWrap k 1 |> Num.addWrap index) |> Num.toU64 - a = Num.bitwiseOr (Num.shiftLeftBy p1 16) (Num.shiftLeftBy p2 8) + p1 = list_get_unsafe(list, index) |> Num.to_u64 + p2 = list_get_unsafe(list, Num.shift_right_zf_by(k, 1) |> Num.add_wrap(index)) |> Num.to_u64 + p3 = list_get_unsafe(list, Num.sub_wrap(k, 1) |> Num.add_wrap(index)) |> Num.to_u64 + a = Num.bitwise_or(Num.shift_left_by(p1, 16), Num.shift_left_by(p2, 8)) - Num.bitwiseOr a p3 + Num.bitwise_or(a, p3) -testSeed = WithSeed 0x526F_6352_616E_643F +test_seed = WithSeed(0x526F_6352_616E_643F) # TODO: would be great to have table driven expects for this. # Would also be great to have some sort of property based hasher -# where we can compare `addU*` functions to the `addBytes` function. +# where we can compare `add_u*` functions to the `add_bytes` function. expect hash = - createLowLevelHasher testSeed - |> addBytes [] + create_low_level_hasher(test_seed) + |> add_bytes([]) |> complete hash == 0xD59C59757DBBE6B3 expect hash = - createLowLevelHasher testSeed - |> addBytes [0x42] + create_low_level_hasher(test_seed) + |> add_bytes([0x42]) |> complete hash == 0x38CE03D0E61AF963 expect hash = - createLowLevelHasher testSeed - |> addU8 0x42 + create_low_level_hasher(test_seed) + |> add_u8(0x42) |> complete hash == 0x38CE03D0E61AF963 expect hash = - createLowLevelHasher testSeed - |> addBytes [0xFF, 0xFF] + create_low_level_hasher(test_seed) + |> add_bytes([0xFF, 0xFF]) |> complete hash == 0xE1CB2FA0D6A64113 expect hash = - createLowLevelHasher testSeed - |> addU16 0xFFFF + create_low_level_hasher(test_seed) + |> add_u16(0xFFFF) |> complete hash == 0xE1CB2FA0D6A64113 expect hash = - createLowLevelHasher testSeed - |> addBytes [0x36, 0xA7] + create_low_level_hasher(test_seed) + |> add_bytes([0x36, 0xA7]) |> complete hash == 0x26B8319EDAF81B15 expect hash = - createLowLevelHasher testSeed - |> addU16 0xA736 + create_low_level_hasher(test_seed) + |> add_u16(0xA736) |> complete hash == 0x26B8319EDAF81B15 expect hash = - createLowLevelHasher testSeed - |> addBytes [0x00, 0x00, 0x00, 0x00] + create_low_level_hasher(test_seed) + |> add_bytes([0x00, 0x00, 0x00, 0x00]) |> complete hash == 0xA187D7CA074F9EE7 expect hash = - createLowLevelHasher testSeed - |> addU32 0x0000_0000 + create_low_level_hasher(test_seed) + |> add_u32(0x0000_0000) |> complete hash == 0xA187D7CA074F9EE7 expect hash = - createLowLevelHasher testSeed - |> addBytes [0xA9, 0x2F, 0xEE, 0x21] + create_low_level_hasher(test_seed) + |> add_bytes([0xA9, 0x2F, 0xEE, 0x21]) |> complete hash == 0xA499EFE4C1454D09 expect hash = - createLowLevelHasher testSeed - |> addU32 0x21EE_2FA9 + create_low_level_hasher(test_seed) + |> add_u32(0x21EE_2FA9) |> complete hash == 0xA499EFE4C1454D09 expect hash = - createLowLevelHasher testSeed - |> addBytes [0x5D, 0x66, 0xB1, 0x8F, 0x68, 0x44, 0xC7, 0x03, 0xE1, 0xDD, 0x23, 0x34, 0xBB, 0x9A, 0x42, 0xA7] + create_low_level_hasher(test_seed) + |> add_bytes([0x5D, 0x66, 0xB1, 0x8F, 0x68, 0x44, 0xC7, 0x03, 0xE1, 0xDD, 0x23, 0x34, 0xBB, 0x9A, 0x42, 0xA7]) |> complete hash == 0xDD39A206AED64C73 expect hash = - createLowLevelHasher testSeed - |> addU128 0xA742_9ABB_3423_DDE1_03C7_4468_8FB1_665D + create_low_level_hasher(test_seed) + |> add_u128(0xA742_9ABB_3423_DDE1_03C7_4468_8FB1_665D) |> complete hash == 0xDD39A206AED64C73 expect hash = - createLowLevelHasher testSeed - |> Hash.hashStrBytes "abcdefghijklmnopqrstuvwxyz" + create_low_level_hasher(test_seed) + |> Hash.hash_str_bytes("abcdefghijklmnopqrstuvwxyz") |> complete hash == 0x51C59DF5B1D15F40 expect hash = - createLowLevelHasher testSeed - |> Hash.hashStrBytes "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + create_low_level_hasher(test_seed) + |> Hash.hash_str_bytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") |> complete hash == 0xD8D0A129D97A4E95 expect hash = - createLowLevelHasher testSeed - |> Hash.hashStrBytes "1234567890123456789012345678901234567890123456789012345678901234567890" + create_low_level_hasher(test_seed) + |> Hash.hash_str_bytes("1234567890123456789012345678901234567890123456789012345678901234567890") |> complete hash == 0x8188065B44FB4AAA expect hash = - createLowLevelHasher testSeed - |> addBytes (List.repeat 0x77 100) + create_low_level_hasher(test_seed) + |> add_bytes(List.repeat(0x77, 100)) |> complete hash == 0x47A2A606EADF3378 @@ -1606,124 +1616,124 @@ expect # Apparently it won't pick the default integer. expect hash = - createLowLevelHasher testSeed - |> Hash.hashUnordered [8u8, 82u8, 3u8, 8u8, 24u8] List.walk + create_low_level_hasher(test_seed) + |> Hash.hash_unordered([8u8, 82u8, 3u8, 8u8, 24u8], List.walk) |> complete hash == 0xB2E8254C08F16B20 expect hash1 = - createLowLevelHasher testSeed - |> Hash.hashUnordered ([0u8, 1u8, 2u8, 3u8, 4u8]) List.walk + create_low_level_hasher(test_seed) + |> Hash.hash_unordered([0u8, 1u8, 2u8, 3u8, 4u8], List.walk) |> complete hash2 = - createLowLevelHasher testSeed - |> Hash.hashUnordered [4u8, 3u8, 2u8, 1u8, 0u8] List.walk + create_low_level_hasher(test_seed) + |> Hash.hash_unordered([4u8, 3u8, 2u8, 1u8, 0u8], List.walk) |> complete hash1 == hash2 expect hash1 = - createLowLevelHasher testSeed - |> Hash.hashUnordered [0u8, 1u8, 2u8, 3u8, 4u8] List.walk + create_low_level_hasher(test_seed) + |> Hash.hash_unordered([0u8, 1u8, 2u8, 3u8, 4u8], List.walk) |> complete hash2 = - createLowLevelHasher testSeed - |> Hash.hashUnordered [4u8, 3u8, 2u8, 1u8, 0u8, 0u8] List.walk + create_low_level_hasher(test_seed) + |> Hash.hash_unordered([4u8, 3u8, 2u8, 1u8, 0u8, 0u8], List.walk) |> complete hash1 != hash2 expect - empty {} + empty({}) |> len - |> Bool.isEq 0 + |> Bool.is_eq(0) expect - empty {} - |> insert "One" "A Song" - |> insert "Two" "Candy Canes" - |> insert "Three" "Boughs of Holly" + empty({}) + |> insert("One", "A Song") + |> insert("Two", "Candy Canes") + |> insert("Three", "Boughs of Holly") |> clear |> len - |> Bool.isEq 0 + |> Bool.is_eq(0) expect - Dict.empty {} - |> Dict.insert "Alice" 17 - |> Dict.insert "Bob" 18 - |> Dict.insert "Charlie" 19 - |> Dict.walkUntil Bool.false (\_, _, age -> if age >= 18 then Break Bool.true else Continue Bool.false) - |> Bool.isEq Bool.true + Dict.empty({}) + |> Dict.insert("Alice", 17) + |> Dict.insert("Bob", 18) + |> Dict.insert("Charlie", 19) + |> Dict.walk_until(Bool.false, (\_, _, age -> if age >= 18 then Break(Bool.true) else Continue(Bool.false))) + |> Bool.is_eq(Bool.true) expect d1 = - Dict.empty {} - |> Dict.insert "Alice" 17 - |> Dict.insert "Bob" 18 - |> Dict.insert "Charlie" 19 - |> Dict.keepIf \(_k, v) -> v >= 18 + Dict.empty({}) + |> Dict.insert("Alice", 17) + |> Dict.insert("Bob", 18) + |> Dict.insert("Charlie", 19) + |> Dict.keep_if(\(_k, v) -> v >= 18) d2 = - Dict.empty {} - |> Dict.insert "Bob" 18 - |> Dict.insert "Charlie" 19 + Dict.empty({}) + |> Dict.insert("Bob", 18) + |> Dict.insert("Charlie", 19) d1 == d2 expect d1 = - Dict.empty {} - |> Dict.insert "Alice" 17 - |> Dict.insert "Bob" 18 - |> Dict.insert "Charlie" 19 - |> Dict.keepIf \(k, _v) -> Str.endsWith k "e" + Dict.empty({}) + |> Dict.insert("Alice", 17) + |> Dict.insert("Bob", 18) + |> Dict.insert("Charlie", 19) + |> Dict.keep_if(\(k, _v) -> Str.endsWith(k, "e")) d2 = - Dict.empty {} - |> Dict.insert "Alice" 17 - |> Dict.insert "Charlie" 19 + Dict.empty({}) + |> Dict.insert("Alice", 17) + |> Dict.insert("Charlie", 19) d1 == d2 expect - keysToDelete = [1, 2] + keys_to_delete = [1, 2] d1 = - Dict.empty {} - |> Dict.insert 0 0 - |> Dict.insert 1 1 - |> Dict.insert 2 2 - |> Dict.insert 3 3 - |> Dict.insert 4 4 - |> Dict.keepIf (\(k, _v) -> List.contains keysToDelete k |> Bool.not) + Dict.empty({}) + |> Dict.insert(0, 0) + |> Dict.insert(1, 1) + |> Dict.insert(2, 2) + |> Dict.insert(3, 3) + |> Dict.insert(4, 4) + |> Dict.keep_if(\(k, _v) -> !List.contains(keys_to_delete, k)) d2 = - Dict.empty {} - |> Dict.insert 0 0 - |> Dict.insert 3 3 - |> Dict.insert 4 4 + Dict.empty({}) + |> Dict.insert(0, 0) + |> Dict.insert(3, 3) + |> Dict.insert(4, 4) d1 == d2 expect - keysToDelete = [2, 4] + keys_to_delete = [2, 4] d1 = - Dict.empty {} - |> Dict.insert 0 0 - |> Dict.insert 1 1 - |> Dict.insert 2 2 - |> Dict.insert 3 3 - |> Dict.insert 4 4 - |> Dict.keepIf (\(k, _v) -> List.contains keysToDelete k |> Bool.not) + Dict.empty({}) + |> Dict.insert(0, 0) + |> Dict.insert(1, 1) + |> Dict.insert(2, 2) + |> Dict.insert(3, 3) + |> Dict.insert(4, 4) + |> Dict.keep_if(\(k, _v) -> !List.contains(keys_to_delete, k)) d2 = - Dict.empty {} - |> Dict.insert 0 0 - |> Dict.insert 1 1 - |> Dict.insert 3 3 + Dict.empty({}) + |> Dict.insert(0, 0) + |> Dict.insert(1, 1) + |> Dict.insert(3, 3) d1 == d2 diff --git a/crates/compiler/builtins/roc/Encode.roc b/crates/compiler/builtins/roc/Encode.roc index b63ad2f35ba..2a091c26979 100644 --- a/crates/compiler/builtins/roc/Encode.roc +++ b/crates/compiler/builtins/roc/Encode.roc @@ -1,7 +1,7 @@ module [ Encoder, Encoding, - toEncoder, + to_encoder, EncoderFormatting, u8, u16, @@ -23,9 +23,9 @@ module [ tag, tuple, custom, - appendWith, + append_with, append, - toBytes, + to_bytes, ] import Num exposing [ @@ -48,7 +48,7 @@ import Bool exposing [Bool] Encoder fmt := List U8, fmt -> List U8 where fmt implements EncoderFormatting Encoding implements - toEncoder : val -> Encoder fmt where val implements Encoding, fmt implements EncoderFormatting + to_encoder : val -> Encoder fmt where val implements Encoding, fmt implements EncoderFormatting EncoderFormatting implements u8 : U8 -> Encoder fmt where fmt implements EncoderFormatting @@ -76,41 +76,41 @@ EncoderFormatting implements ## ```roc ## expect ## # Appends the byte 42 -## customEncoder = Encode.custom (\bytes, _fmt -> List.append bytes 42) +## custom_encoder = Encode.custom(\bytes, _fmt -> List.append(bytes, 42)) ## -## actual = Encode.appendWith [] customEncoder Core.json +## actual = Encode.append_with([], custom_encoder, Core.json) ## expected = [42] # Expected result is a list with a single byte, 42 ## ## actual == expected ## ``` custom : (List U8, fmt -> List U8) -> Encoder fmt where fmt implements EncoderFormatting -custom = \encoder -> @Encoder encoder +custom = \encoder -> @Encoder(encoder) -appendWith : List U8, Encoder fmt, fmt -> List U8 where fmt implements EncoderFormatting -appendWith = \lst, @Encoder doEncoding, fmt -> doEncoding lst fmt +append_with : List U8, Encoder fmt, fmt -> List U8 where fmt implements EncoderFormatting +append_with = \lst, @Encoder(do_encoding), fmt -> do_encoding(lst, fmt) ## Appends the encoded representation of a value to an existing list of bytes. ## ## ```roc ## expect -## actual = Encode.append [] { foo: 43 } Core.json -## expected = Str.toUtf8 """{"foo":43}""" +## actual = Encode.append([], { foo: 43 }, Core.json) +## expected = Str.to_utf8("""{"foo":43}""") ## ## actual == expected ## ``` append : List U8, val, fmt -> List U8 where val implements Encoding, fmt implements EncoderFormatting -append = \lst, val, fmt -> appendWith lst (toEncoder val) fmt +append = \lst, val, fmt -> append_with(lst, to_encoder(val), fmt) ## Encodes a value to a list of bytes (`List U8`) according to the specified format. ## ## ```roc ## expect -## fooRec = { foo: 42 } +## foo_rec = { foo: 42 } ## -## actual = Encode.toBytes fooRec Core.json -## expected = Str.toUtf8 """{"foo":42}""" +## actual = Encode.to_bytes(foo_rec, Core.json) +## expected = Str.to_utf8("""{"foo":42}""") ## ## actual == expected ## ``` -toBytes : val, fmt -> List U8 where val implements Encoding, fmt implements EncoderFormatting -toBytes = \val, fmt -> appendWith [] (toEncoder val) fmt +to_bytes : val, fmt -> List U8 where val implements Encoding, fmt implements EncoderFormatting +to_bytes = \val, fmt -> append_with([], to_encoder(val), fmt) diff --git a/crates/compiler/builtins/roc/Hash.roc b/crates/compiler/builtins/roc/Hash.roc index 8dfa548c7dc..f8def888546 100644 --- a/crates/compiler/builtins/roc/Hash.roc +++ b/crates/compiler/builtins/roc/Hash.roc @@ -2,23 +2,23 @@ module [ Hash, Hasher, hash, - addBytes, - addU8, - addU16, - addU32, - addU64, - addU128, - hashBool, - hashI8, - hashI16, - hashI32, - hashI64, - hashI128, - hashDec, + add_bytes, + add_u8, + add_u16, + add_u32, + add_u64, + add_u128, + hash_bool, + hash_i8, + hash_i16, + hash_i32, + hash_i64, + hash_i128, + hash_dec, complete, - hashStrBytes, - hashList, - hashUnordered, + hash_str_bytes, + hash_list, + hash_unordered, ] import Bool exposing [Bool] @@ -52,86 +52,88 @@ Hash implements ## cryptographically-secure hashing. Hasher implements ## Adds a list of bytes to the hasher. - addBytes : a, List U8 -> a where a implements Hasher + add_bytes : a, List U8 -> a where a implements Hasher ## Adds a single U8 to the hasher. - addU8 : a, U8 -> a where a implements Hasher + add_u8 : a, U8 -> a where a implements Hasher ## Adds a single U16 to the hasher. - addU16 : a, U16 -> a where a implements Hasher + add_u16 : a, U16 -> a where a implements Hasher ## Adds a single U32 to the hasher. - addU32 : a, U32 -> a where a implements Hasher + add_u32 : a, U32 -> a where a implements Hasher ## Adds a single U64 to the hasher. - addU64 : a, U64 -> a where a implements Hasher + add_u64 : a, U64 -> a where a implements Hasher ## Adds a single U128 to the hasher. - addU128 : a, U128 -> a where a implements Hasher + add_u128 : a, U128 -> a where a implements Hasher ## Completes the hasher, extracting a hash value from its ## accumulated hash state. complete : a -> U64 where a implements Hasher ## Adds a string into a [Hasher] by hashing its UTF-8 bytes. -hashStrBytes = \hasher, s -> - addBytes hasher (Str.toUtf8 s) +hash_str_bytes = \hasher, s -> + add_bytes(hasher, Str.to_utf8(s)) ## Adds a list of [Hash]able elements to a [Hasher] by hashing each element. -hashList = \hasher, lst -> - List.walk lst hasher \accumHasher, elem -> - hash accumHasher elem +hash_list = \hasher, lst -> + List.walk(lst, hasher, (\accum_hasher, elem -> + hash(accum_hasher, elem) + )) ## Adds a single [Bool] to a hasher. -hashBool : a, Bool -> a where a implements Hasher -hashBool = \hasher, b -> - asU8 = if b then 1 else 0 - addU8 hasher asU8 +hash_bool : a, Bool -> a where a implements Hasher +hash_bool = \hasher, b -> + as_u8 = if b then 1 else 0 + add_u8(hasher, as_u8) ## Adds a single I8 to a hasher. -hashI8 : a, I8 -> a where a implements Hasher -hashI8 = \hasher, n -> addU8 hasher (Num.toU8 n) +hash_i8 : a, I8 -> a where a implements Hasher +hash_i8 = \hasher, n -> add_u8(hasher, Num.to_u8(n)) ## Adds a single I16 to a hasher. -hashI16 : a, I16 -> a where a implements Hasher -hashI16 = \hasher, n -> addU16 hasher (Num.toU16 n) +hash_i16 : a, I16 -> a where a implements Hasher +hash_i16 = \hasher, n -> add_u16(hasher, Num.to_u16(n)) ## Adds a single I32 to a hasher. -hashI32 : a, I32 -> a where a implements Hasher -hashI32 = \hasher, n -> addU32 hasher (Num.toU32 n) +hash_i32 : a, I32 -> a where a implements Hasher +hash_i32 = \hasher, n -> add_u32(hasher, Num.to_u32(n)) ## Adds a single I64 to a hasher. -hashI64 : a, I64 -> a where a implements Hasher -hashI64 = \hasher, n -> addU64 hasher (Num.toU64 n) +hash_i64 : a, I64 -> a where a implements Hasher +hash_i64 = \hasher, n -> add_u64(hasher, Num.to_u64(n)) ## Adds a single I128 to a hasher. -hashI128 : a, I128 -> a where a implements Hasher -hashI128 = \hasher, n -> addU128 hasher (Num.toU128 n) +hash_i128 : a, I128 -> a where a implements Hasher +hash_i128 = \hasher, n -> add_u128(hasher, Num.to_u128(n)) ## Adds a single [Dec] to a hasher. -hashDec : a, Dec -> a where a implements Hasher -hashDec = \hasher, n -> hashI128 hasher (Num.withoutDecimalPoint n) +hash_dec : a, Dec -> a where a implements Hasher +hash_dec = \hasher, n -> hash_i128(hasher, Num.without_decimal_point(n)) ## Adds a container of [Hash]able elements to a [Hasher] by hashing each element. ## The container is iterated using the walk method passed in. ## The order of the elements does not affect the final hash. -hashUnordered = \hasher, container, walk -> - walk - container - 0 +hash_unordered = \hasher, container, walk -> + walk( + container, + 0, (\accum, elem -> x = # Note, we intentionally copy the hasher in every iteration. # Having the same base state is required for unordered hashing. hasher - |> hash elem + |> hash(elem) |> complete - nextAccum = Num.addWrap accum x + next_accum = Num.add_wrap(accum, x) - if nextAccum < accum then + if next_accum < accum then # we don't want to lose a bit of entropy on overflow, so add it back in. - Num.addWrap nextAccum 1 + Num.add_wrap(next_accum, 1) else - nextAccum + next_accum ) - |> \accum -> addU64 hasher accum + ) + |> \accum -> add_u64(hasher, accum) diff --git a/crates/compiler/builtins/roc/Inspect.roc b/crates/compiler/builtins/roc/Inspect.roc index ed7db5369e7..4a5b3fbc3e2 100644 --- a/crates/compiler/builtins/roc/Inspect.roc +++ b/crates/compiler/builtins/roc/Inspect.roc @@ -31,8 +31,8 @@ module [ dec, custom, apply, - toInspector, - toStr, + to_inspector, + to_str, ] import Bool exposing [Bool] @@ -81,24 +81,24 @@ InspectFormatter implements Inspector f := f -> f where f implements InspectFormatter custom : (f -> f) -> Inspector f where f implements InspectFormatter -custom = \fn -> @Inspector fn +custom = \fn -> @Inspector(fn) apply : Inspector f, f -> f where f implements InspectFormatter -apply = \@Inspector fn, fmt -> fn fmt +apply = \@Inspector fn, fmt -> fn(fmt) Inspect implements - toInspector : val -> Inspector f where val implements Inspect, f implements InspectFormatter + to_inspector : val -> Inspector f where val implements Inspect, f implements InspectFormatter inspect : val -> f where val implements Inspect, f implements InspectFormatter inspect = \val -> - (@Inspector valFn) = toInspector val - valFn (init {}) + @Inspector(val_fn) = to_inspector(val) + val_fn(init({})) -toStr : val -> Str where val implements Inspect -toStr = \val -> +to_str : val -> Str where val implements Inspect +to_str = \val -> val |> inspect - |> toDbgStr + |> to_dbg_str # The current default formatter for inspect. # This just returns a simple string for debugging. @@ -106,239 +106,232 @@ toStr = \val -> DbgFormatter := { data : Str } implements [ InspectFormatter { - init: dbgInit, - list: dbgList, - set: dbgSet, - dict: dbgDict, - tag: dbgTag, - tuple: dbgTuple, - record: dbgRecord, - bool: dbgBool, - str: dbgStr, - opaque: dbgOpaque, - function: dbgFunction, - u8: dbgU8, - i8: dbgI8, - u16: dbgU16, - i16: dbgI16, - u32: dbgU32, - i32: dbgI32, - u64: dbgU64, - i64: dbgI64, - u128: dbgU128, - i128: dbgI128, - f32: dbgF32, - f64: dbgF64, - dec: dbgDec, + init: dbg_init, + list: dbg_list, + set: dbg_set, + dict: dbg_dict, + tag: dbg_tag, + tuple: dbg_tuple, + record: dbg_record, + bool: dbg_bool, + str: dbg_str, + opaque: dbg_opaque, + function: dbg_function, + u8: dbg_u8, + i8: dbg_i8, + u16: dbg_u16, + i16: dbg_i16, + u32: dbg_u32, + i32: dbg_i32, + u64: dbg_u64, + i64: dbg_i64, + u128: dbg_u128, + i128: dbg_i128, + f32: dbg_f32, + f64: dbg_f64, + dec: dbg_dec, }, ] -dbgInit : {} -> DbgFormatter -dbgInit = \{} -> @DbgFormatter { data: "" } +dbg_init : {} -> DbgFormatter +dbg_init = \{} -> @DbgFormatter({ data: "" }) -dbgList : list, ElemWalker (DbgFormatter, Bool) list elem, (elem -> Inspector DbgFormatter) -> Inspector DbgFormatter -dbgList = \content, walkFn, toDbgInspector -> - custom \f0 -> - dbgWrite f0 "[" +dbg_list : list, ElemWalker (DbgFormatter, Bool) list elem, (elem -> Inspector DbgFormatter) -> Inspector DbgFormatter +dbg_list = \content, walk_fn, to_dbg_inspector -> + custom(\f0 -> + dbg_write(f0, "[") |> \f1 -> - walkFn content (f1, Bool.false) \(f2, prependSep), elem -> + walk_fn(content, (f1, Bool.false), (\(f2, prepend_sep), elem -> f3 = - if prependSep then - dbgWrite f2 ", " + if prepend_sep then + dbg_write(f2, ", ") else f2 elem - |> toDbgInspector - |> apply f3 + |> to_dbg_inspector + |> apply(f3) |> \f4 -> (f4, Bool.true) + )) |> .0 - |> dbgWrite "]" + |> dbg_write("]") + ) -dbgSet : set, ElemWalker (DbgFormatter, Bool) set elem, (elem -> Inspector DbgFormatter) -> Inspector DbgFormatter -dbgSet = \content, walkFn, toDbgInspector -> - custom \f0 -> - dbgWrite f0 "{" +dbg_set : set, ElemWalker (DbgFormatter, Bool) set elem, (elem -> Inspector DbgFormatter) -> Inspector DbgFormatter +dbg_set = \content, walk_fn, to_dbg_inspector -> + custom(\f0 -> + dbg_write(f0, "{") |> \f1 -> - walkFn content (f1, Bool.false) \(f2, prependSep), elem -> + walk_fn(content, (f1, Bool.false), (\(f2, prepend_sep), elem -> f3 = - if prependSep then - dbgWrite f2 ", " + if prepend_sep then + dbg_write(f2, ", ") else f2 elem - |> toDbgInspector - |> apply f3 + |> to_dbg_inspector + |> apply(f3) |> \f4 -> (f4, Bool.true) + )) |> .0 - |> dbgWrite "}" + |> dbg_write("}") + ) -dbgDict : dict, KeyValWalker (DbgFormatter, Bool) dict key value, (key -> Inspector DbgFormatter), (value -> Inspector DbgFormatter) -> Inspector DbgFormatter -dbgDict = \d, walkFn, keyToInspector, valueToInspector -> - custom \f0 -> - dbgWrite f0 "{" +dbg_dict : dict, KeyValWalker (DbgFormatter, Bool) dict key value, (key -> Inspector DbgFormatter), (value -> Inspector DbgFormatter) -> Inspector DbgFormatter +dbg_dict = \d, walk_fn, key_to_inspector, value_to_inspector -> + custom(\f0 -> + dbg_write(f0, "{") |> \f1 -> - walkFn d (f1, Bool.false) \(f2, prependSep), key, value -> + walk_fn(d, (f1, Bool.false), (\(f2, prepend_sep), key, value -> f3 = - if prependSep then - dbgWrite f2 ", " + if prepend_sep then + dbg_write(f2, ", ") else f2 - apply (keyToInspector key) f3 - |> dbgWrite ": " - |> \x -> apply (valueToInspector value) x + apply(key_to_inspector(key), f3) + |> dbg_write(": ") + |> \x -> apply(value_to_inspector(value), x) |> \f4 -> (f4, Bool.true) + )) |> .0 - |> dbgWrite "}" + |> dbg_write("}") + ) -dbgTag : Str, List (Inspector DbgFormatter) -> Inspector DbgFormatter -dbgTag = \name, fields -> - if List.isEmpty fields then - custom \f0 -> - dbgWrite f0 name +dbg_tag : Str, List (Inspector DbgFormatter) -> Inspector DbgFormatter +dbg_tag = \name, fields -> + if List.is_empty(fields) then + custom(\f0 -> dbg_write(f0, name)) else - custom \f0 -> - dbgWrite f0 "(" - |> dbgWrite name + custom(\f0 -> + dbg_write(f0, "(") + |> dbg_write(name) |> \f1 -> - List.walk fields f1 \f2, inspector -> - dbgWrite f2 " " - |> \x -> apply inspector x - |> dbgWrite ")" - -dbgTuple : List (Inspector DbgFormatter) -> Inspector DbgFormatter -dbgTuple = \fields -> - custom \f0 -> - dbgWrite f0 "(" + List.walk(fields, f1, (\f2, inspector -> + dbg_write(f2, " ") + |> \x -> apply(inspector, x) + )) + |> dbg_write(")") + ) + +dbg_tuple : List (Inspector DbgFormatter) -> Inspector DbgFormatter +dbg_tuple = \fields -> + custom(\f0 -> + dbg_write(f0, "(") |> \f1 -> - List.walk fields (f1, Bool.false) \(f2, prependSep), inspector -> + (List.walk, fields, (f1, Bool.false), (\(f2, prepend_sep), inspector -> f3 = - if prependSep then - dbgWrite f2 ", " + if prepend_sep then + dbg_write(f2, ", ") else f2 - apply inspector f3 + apply(inspector, f3) |> \f4 -> (f4, Bool.true) + )) |> .0 - |> dbgWrite ")" + |> dbg_write(")") + ) -dbgRecord : List { key : Str, value : Inspector DbgFormatter } -> Inspector DbgFormatter -dbgRecord = \fields -> - custom \f0 -> - dbgWrite f0 "{" +dbg_record : List { key : Str, value : Inspector DbgFormatter } -> Inspector DbgFormatter +dbg_record = \fields -> + custom(\f0 -> + dbg_write(f0, "{") |> \f1 -> - List.walk fields (f1, Bool.false) \(f2, prependSep), { key, value } -> + List.walk(fields, (f1, Bool.false), (\(f2, prepend_sep), { key, value } -> f3 = - if prependSep then - dbgWrite f2 ", " + if prepend_sep then + dbg_write(f2, ", ") else f2 - dbgWrite f3 key - |> dbgWrite ": " - |> \x -> apply value x + dbg_write(f3, key) + |> dbg_write(": ") + |> \x -> apply(value, x) |> \f4 -> (f4, Bool.true) + )) |> .0 - |> dbgWrite "}" + |> dbg_write("}") + ) -dbgBool : Bool -> Inspector DbgFormatter -dbgBool = \b -> - if b then - custom \f0 -> - dbgWrite f0 "Bool.true" - else - custom \f0 -> - dbgWrite f0 "Bool.false" +dbg_bool : Bool -> Inspector DbgFormatter +dbg_bool = \b -> + text = if b then "Bool.true" else "Bool.false" + custom(\f0 -> dbg_write(f0, text)) -dbgStr : Str -> Inspector DbgFormatter -dbgStr = \s -> - custom \f0 -> +dbg_str : Str -> Inspector DbgFormatter +dbg_str = \s -> + custom(\f0 -> f0 - |> dbgWrite "\"" - |> dbgWrite s # TODO: Should we be escaping strings for dbg/logging? - |> dbgWrite "\"" - -dbgOpaque : * -> Inspector DbgFormatter -dbgOpaque = \_ -> - custom \f0 -> - dbgWrite f0 "" - -dbgFunction : * -> Inspector DbgFormatter -dbgFunction = \_ -> - custom \f0 -> - dbgWrite f0 "" - -dbgU8 : U8 -> Inspector DbgFormatter -dbgU8 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgI8 : I8 -> Inspector DbgFormatter -dbgI8 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgU16 : U16 -> Inspector DbgFormatter -dbgU16 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgI16 : I16 -> Inspector DbgFormatter -dbgI16 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgU32 : U32 -> Inspector DbgFormatter -dbgU32 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgI32 : I32 -> Inspector DbgFormatter -dbgI32 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgU64 : U64 -> Inspector DbgFormatter -dbgU64 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgI64 : I64 -> Inspector DbgFormatter -dbgI64 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgU128 : U128 -> Inspector DbgFormatter -dbgU128 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgI128 : I128 -> Inspector DbgFormatter -dbgI128 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgF32 : F32 -> Inspector DbgFormatter -dbgF32 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgF64 : F64 -> Inspector DbgFormatter -dbgF64 = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgDec : Dec -> Inspector DbgFormatter -dbgDec = \num -> - custom \f0 -> - dbgWrite f0 (num |> Num.toStr) - -dbgWrite : DbgFormatter, Str -> DbgFormatter -dbgWrite = \@DbgFormatter { data }, added -> - @DbgFormatter { data: Str.concat data added } - -toDbgStr : DbgFormatter -> Str -toDbgStr = \@DbgFormatter { data } -> data + |> dbg_write("\"") + |> dbg_write(s) # TODO: Should we be escaping strings for dbg/logging? + |> dbg_write("\"") + ) + +dbg_opaque : * -> Inspector DbgFormatter +dbg_opaque = \_ -> + custom(\f0 -> dbg_write(f0, "")) + +dbg_function : * -> Inspector DbgFormatter +dbg_function = \_ -> + custom(\f0 -> dbg_write(f0, "")) + +dbg_u8 : U8 -> Inspector DbgFormatter +dbg_u8 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_i8 : I8 -> Inspector DbgFormatter +dbg_i8 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_u16 : U16 -> Inspector DbgFormatter +dbg_u16 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_i16 : I16 -> Inspector DbgFormatter +dbg_i16 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_u32 : U32 -> Inspector DbgFormatter +dbg_u32 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_i32 : I32 -> Inspector DbgFormatter +dbg_i32 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_u64 : U64 -> Inspector DbgFormatter +dbg_u64 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_i64 : I64 -> Inspector DbgFormatter +dbg_i64 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_u128 : U128 -> Inspector DbgFormatter +dbg_u128 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_i128 : I128 -> Inspector DbgFormatter +dbg_i128 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_f32 : F32 -> Inspector DbgFormatter +dbg_f32 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_f64 : F64 -> Inspector DbgFormatter +dbg_f64 = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_dec : Dec -> Inspector DbgFormatter +dbg_dec = \num -> + custom(\f0 -> dbg_write(f0, Num.to_str(num))) + +dbg_write : DbgFormatter, Str -> DbgFormatter +dbg_write = \@DbgFormatter({ data }), added -> + @DbgFormatter({ data: Str.concat(data, added) }) + +to_dbg_str : DbgFormatter -> Str +to_dbg_str = \@DbgFormatter({ data }) -> data diff --git a/crates/compiler/builtins/roc/List.roc b/crates/compiler/builtins/roc/List.roc index 29e4d1e7a10..f74e39ceabc 100644 --- a/crates/compiler/builtins/roc/List.roc +++ b/crates/compiler/builtins/roc/List.roc @@ -1,79 +1,79 @@ module [ - isEmpty, + is_empty, get, set, replace, update, append, - appendIfOk, + append_if_ok, prepend, - prependIfOk, + prepend_if_ok, map, len, - withCapacity, - walkBackwards, + with_capacity, + walk_backwards, concat, first, single, repeat, reverse, join, - keepIf, + keep_if, contains, sum, walk, last, - keepOks, - keepErrs, - mapWithIndex, + keep_oks, + keep_errs, + map_with_index, map2, map3, product, - walkWithIndex, - walkUntil, - walkWithIndexUntil, - walkFrom, - walkFromUntil, + walk_with_index, + walk_until, + walk_with_index_until, + walk_from, + walk_from_until, range, - sortWith, + sort_with, swap, - dropAt, + drop_at, min, max, map4, - mapTry, - walkTry, - joinMap, + map_try, + walk_try, + join_map, any, - takeFirst, - takeLast, - dropFirst, - dropLast, - findFirst, - findLast, - findFirstIndex, - findLastIndex, + take_first, + take_last, + drop_first, + drop_last, + find_first, + find_last, + find_first_index, + find_last_index, sublist, intersperse, - splitAt, - splitOn, - splitOnList, - splitFirst, - splitLast, - startsWith, - endsWith, + split_at, + split_on, + split_on_list, + split_first, + split_last, + starts_with, + ends_with, all, - dropIf, - sortAsc, - sortDesc, + drop_if, + sort_asc, + sort_desc, reserve, - releaseExcessCapacity, - walkBackwardsUntil, - countIf, - chunksOf, - concatUtf8, - forEach!, - forEachTry!, + release_excess_capacity, + walk_backwards_until, + count_if, + chunks_of, + concat_utf8, + for_each!, + for_each_try!, walk!, ] @@ -95,8 +95,8 @@ import Num exposing [U64, Num, U8] ## is normally enabled, not having enough memory could result in the list appearing ## to be created just fine, but then crashing later.) ## -## > The theoretical maximum length for a list created in Roc is `Num.maxI32` on 32-bit systems -## > and `Num.maxI64` on 64-bit systems. Attempting to create a list bigger than that +## > The theoretical maximum length for a list created in Roc is `Num.max_i32` on 32-bit systems +## > and `Num.max_i64` on 64-bit systems. Attempting to create a list bigger than that ## > in Roc code will always fail, although in practice it is likely to fail ## > at much smaller lengths due to insufficient memory being available. ## @@ -130,34 +130,34 @@ import Num exposing [U64, Num, U8] ## ## Let's turn this example into a function. ## ```roc -## getRatings = \first -> +## get_ratings = \first -> ## ratings = [first, 4, 3] ## ## { foo: ratings, bar: ratings } ## -## getRatings 5 +## get_ratings(5) ## ``` -## At the end of the `getRatings` function, when the record gets returned, +## At the end of the `get_ratings` function, when the record gets returned, ## the original `ratings =` binding has gone out of scope and is no longer ## accessible. (Trying to reference `ratings` outside the scope of the -## `getRatings` function would be an error!) +## `get_ratings` function would be an error!) ## ## Since `ratings` represented a way to reference the list, and that way is no ## longer accessible, the list's refcount gets decremented when `ratings` goes ## out of scope. It will decrease from 3 back down to 2. ## -## Putting these together, when we call `getRatings 5`, what we get back is +## Putting these together, when we call `get_ratings(5)`, what we get back is ## a record with two fields, `foo`, and `bar`, each of which refers to the same ## list, and that list has a refcount of 2. ## -## Let's change the last line to be `(getRatings 5).bar` instead of `getRatings 5`: +## Let's change the last line to be `get_ratings(5).bar` instead of `get_ratings(5)`: ## ```roc -## getRatings = \first -> +## get_ratings = \first -> ## ratings = [first, 4, 3] ## ## { foo: ratings, bar: ratings } ## -## (getRatings 5).bar +## get_ratings(5).bar ## ``` ## Now, when this expression returns, only the `bar` field of the record will ## be returned. This will mean that the `foo` field becomes inaccessible, causing @@ -166,7 +166,7 @@ import Num exposing [U64, Num, U8] ## ## Finally let's suppose the final line were changed to this: ## ```roc -## List.first (getRatings 5).bar +## List.first(get_ratings(5).bar) ## ``` ## This call to [List.first] means that even the list in the `bar` field has become ## inaccessible. As such, this line will cause the list's refcount to get @@ -181,8 +181,8 @@ import Num exposing [U64, Num, U8] ## ```roc ## nums = [1, 2, 3, 4, 5, 6, 7] ## -## first = List.first nums -## last = List.last nums +## first = List.first(nums) +## last = List.last(nums) ## ## first ## ``` @@ -192,8 +192,8 @@ import Num exposing [U64, Num, U8] ## ```roc ## lists = [[1], [2, 3], [], [4, 5, 6, 7]] ## -## first = List.first lists -## last = List.last lists +## first = List.first(lists) +## last = List.last(lists) ## ## first ## ``` @@ -213,66 +213,66 @@ import Num exposing [U64, Num, U8] ## At the end, we once again call [List.first] on the list, but this time ## ## * Copying small lists (64 elements or fewer) is typically slightly faster than copying small persistent data structures. This is because, at small sizes, persistent data structures tend to be thin wrappers around flat arrays anyway. They don't have any copying advantage until crossing a certain minimum size threshold. -## * Even when copying is faster, other list operations may still be slightly slower with persistent data structures. For example, even if it were a persistent data structure, [List.map], [List.walk], and [List.keepIf] would all need to traverse every element in the list and build up the result from scratch. These operations are all -## * Roc's compiler optimizes many list operations into in-place mutations behind the scenes, depending on how the list is being used. For example, [List.map], [List.keepIf], and [List.set] can all be optimized to perform in-place mutations. +## * Even when copying is faster, other list operations may still be slightly slower with persistent data structures. For example, even if it were a persistent data structure, [List.map], [List.walk], and [List.keep_if] would all need to traverse every element in the list and build up the result from scratch. These operations are all +## * Roc's compiler optimizes many list operations into in-place mutations behind the scenes, depending on how the list is being used. For example, [List.map], [List.keep_if], and [List.set] can all be optimized to perform in-place mutations. ## * If possible, it is usually best for performance to use large lists in a way where the optimizer can turn them into in-place mutations. If this is not possible, a persistent data structure might be faster - but this is a rare enough scenario that it would not be good for the average Roc program's performance if this were the way [List] worked by default. Instead, you can look outside Roc's standard modules for an implementation of a persistent data structure - likely built using [List] under the hood! -# separator so List.isEmpty doesn't absorb the above into its doc comment +# separator so List.is_empty doesn't absorb the above into its doc comment ## Check if the list is empty. ## ```roc -## List.isEmpty [1, 2, 3] +## List.is_empty([1, 2, 3]) ## -## List.isEmpty [] +## List.is_empty([]) ## ``` -isEmpty : List * -> Bool -isEmpty = \list -> - List.len list == 0 +is_empty : List * -> Bool +is_empty = \list -> + List.len(list) == 0 # unsafe primitive that does not perform a bounds check # but will cause a reference count increment on the value it got out of the list -getUnsafe : List a, U64 -> a +get_unsafe : List a, U64 -> a ## Returns an element from a list at the given index. ## ## Returns `Err OutOfBounds` if the given index exceeds the List's length ## ```roc -## expect List.get [100, 200, 300] 1 == Ok 200 -## expect List.get [100, 200, 300] 5 == Err OutOfBounds +## expect List.get([100, 200, 300], 1) == Ok(200) +## expect List.get([100, 200, 300], 5) == Err(OutOfBounds) ## ``` get : List a, U64 -> Result a [OutOfBounds] get = \list, index -> - if index < List.len list then - Ok (List.getUnsafe list index) + if index < List.len(list) then + Ok(List.get_unsafe(list, index)) else - Err OutOfBounds + Err(OutOfBounds) # unsafe primitive that does not perform a bounds check # but will cause a reference count increment on the value it got out of the list -replaceUnsafe : List a, U64, a -> { list : List a, value : a } +replace_unsafe : List a, U64, a -> { list : List a, value : a } replace : List a, U64, a -> { list : List a, value : a } -replace = \list, index, newValue -> - if index < List.len list then - List.replaceUnsafe list index newValue +replace = \list, index, new_value -> + if index < List.len(list) then + List.replace_unsafe(list, index, new_value) else - { list, value: newValue } + { list, value: new_value } ## Replaces the element at the given index with a replacement. ## ```roc -## List.set ["a", "b", "c"] 1 "B" +## List.set(["a", "b", "c"], 1, "B") ## ``` ## If the given index is outside the bounds of the list, returns the original ## list unmodified. ## -## To drop the element at a given index, instead of replacing it, see [List.dropAt]. +## To drop the element at a given index, instead of replacing it, see [List.drop_at]. set : List a, U64, a -> List a set = \list, index, value -> - (List.replace list index value).list + (List.replace(list, index, value)).list ## Updates the element at the given index with the given function. ## ```roc -## List.update [1, 2, 3] 1 (\x -> x + 1) +## List.update([1, 2, 3], 1, (\x -> x + 1)) ## ``` ## If the given index is outside the bounds of the list, returns the original ## list unmodified. @@ -281,17 +281,17 @@ set = \list, index, value -> ## see [List.set] and [List.replace] update : List a, U64, (a -> a) -> List a update = \list, index, func -> - when List.get list index is - Err OutOfBounds -> list - Ok value -> - newValue = func value - (replaceUnsafe list index newValue).list + when List.get(list, index) is + Err(OutOfBounds) -> list + Ok(value) -> + new_value = func(value) + (replace_unsafe(list, index, new_value)).list # Update one element in bounds expect list : List U64 list = [1, 2, 3] - got = update list 1 (\x -> x + 42) + got = update(list, 1, \x -> x + 42) want = [1, 44, 3] got == want @@ -299,7 +299,7 @@ expect expect list : List U64 list = [1, 2, 3] - got = update list 5 (\x -> x + 42) + got = update(list, 5, \x -> x + 42) got == list # Update chain @@ -308,53 +308,53 @@ expect list = [1, 2, 3] got = list - |> update 0 (\x -> x + 10) - |> update 1 (\x -> x + 20) - |> update 2 (\x -> x + 30) + |> update(0, \x -> x + 10) + |> update(1, \x -> x + 20) + |> update(2, \x -> x + 30) want = [11, 22, 33] got == want ## Add a single element to the end of a list. ## ```roc -## List.append [1, 2, 3] 4 +## List.append([1, 2, 3], 4) ## ## [0, 1, 2] -## |> List.append 3 +## |> List.append(3) ## ``` append : List a, a -> List a append = \list, element -> list - |> List.reserve 1 - |> List.appendUnsafe element + |> List.reserve(1) + |> List.append_unsafe(element) ## If the given [Result] is `Ok`, add it to the end of a list. ## Otherwise, return the list unmodified. ## ## ```roc -## List.appendIfOk [1, 2, 3] (Ok 4) +## List.append_if_ok([1, 2, 3], Ok(4)) ## ## [0, 1, 2] -## |> List.appendIfOk (Err 3) +## |> List.append_if_ok(Err(3)) ## ``` -appendIfOk : List a, Result a * -> List a -appendIfOk = \list, result -> +append_if_ok : List a, Result a * -> List a +append_if_ok = \list, result -> when result is - Ok elem -> append list elem - Err _ -> list + Ok(elem) -> append(list, elem) + Err(_) -> list ## Writes the element after the current last element unconditionally. ## In other words, it is assumed that ## -## - the list is owned (i.e. can be updated in-place +## - the list is owned (i.e. can be updated in-place) ## - the list has at least one element of spare capacity -appendUnsafe : List a, a -> List a +append_unsafe : List a, a -> List a ## Add a single element to the beginning of a list. ## ```roc -## List.prepend [1, 2, 3] 0 +## List.prepend([1, 2, 3], 0) ## ## [2, 3, 4] -## |> List.prepend 1 +## |> List.prepend(1) ## ``` prepend : List a, a -> List a @@ -362,59 +362,59 @@ prepend : List a, a -> List a ## Otherwise, return the list unmodified. ## ## ```roc -## List.prepend [1, 2, 3] (Ok 0) +## List.prepend([1, 2, 3], Ok(0)) ## ## [2, 3, 4] -## |> List.prepend (Err 1) +## |> List.prepend(Err(1)) ## ``` -prependIfOk : List a, Result a * -> List a -prependIfOk = \list, result -> +prepend_if_ok : List a, Result a * -> List a +prepend_if_ok = \list, result -> when result is - Ok elem -> prepend list elem - Err _ -> list + Ok(elem) -> prepend(list, elem) + Err(_) -> list ## Returns the length of the list - the number of elements it contains. ## -## One [List] can store up to `Num.maxI64` elements on 64-bit targets and `Num.maxI32` on 32-bit targets like wasm. +## One [List] can store up to `Num.max_i64` elements on 64-bit targets and `Num.max_i32` on 32-bit targets like wasm. ## This means the #U64 this function returns can always be safely converted to #I64 or #I32, depending on the target. len : List * -> U64 ## Create a list with space for at least capacity elements -withCapacity : U64 -> List * +with_capacity : U64 -> List * ## Enlarge the list for at least capacity additional elements reserve : List a, U64 -> List a ## Shrink the memory footprint of a list such that it's capacity and length are equal. ## Note: This will also convert seamless slices to regular lists. -releaseExcessCapacity : List a -> List a +release_excess_capacity : List a -> List a ## Put two lists together. ## ```roc -## List.concat [1, 2, 3] [4, 5] +## List.concat([1, 2, 3], [4, 5]) ## ## [0, 1, 2] -## |> List.concat [3, 4] +## |> List.concat([3, 4]) ## ``` concat : List a, List a -> List a ## Returns the last element in the list, or `ListWasEmpty` if it was empty. ## ```roc -## expect List.last [1, 2, 3] == Ok 3 -## expect List.last [] == Err ListWasEmpty +## expect List.last([1, 2, 3]) == Ok(3) +## expect List.last([]) == Err(ListWasEmpty) ## ``` last : List a -> Result a [ListWasEmpty] last = \list -> - when List.get list (Num.subSaturated (List.len list) 1) is - Ok v -> Ok v - Err _ -> Err ListWasEmpty + when List.get(list, Num.sub_saturated(List.len(list), 1)) is + Ok(v) -> Ok(v) + Err(_) -> Err(ListWasEmpty) ## A list with a single element in it. ## ## This is useful in pipelines, like so: ## ```roc ## websites = -## Str.concat domain ".com" +## Str.concat(domain, ".com") ## |> List.single ## ``` single : a -> List a @@ -423,27 +423,27 @@ single = \x -> [x] ## Returns a list with the given length, where every element is the given value. repeat : a, U64 -> List a repeat = \value, count -> - repeatHelp value count (List.withCapacity count) + repeat_help(value, count, List.with_capacity(count)) -repeatHelp : a, U64, List a -> List a -repeatHelp = \value, count, accum -> +repeat_help : a, U64, List a -> List a +repeat_help = \value, count, accum -> if count > 0 then - repeatHelp value (Num.subWrap count 1) (List.appendUnsafe accum value) + repeat_help(value, Num.sub_wrap(count, 1), List.append_unsafe(accum, value)) else accum ## Returns the list with its elements reversed. ## ```roc -## expect List.reverse [1, 2, 3] == [3, 2, 1] +## expect List.reverse([1, 2, 3]) == [3, 2, 1] ## ``` reverse : List a -> List a reverse = \list -> - end = List.len list |> Num.subSaturated 1 - reverseHelp (List.clone list) 0 end + end = List.len(list) |> Num.sub_saturated(1) + reverse_help(List.clone(list), 0, end) -reverseHelp = \list, left, right -> +reverse_help = \list, left, right -> if left < right then - reverseHelp (List.swap list left right) (Num.addWrap left 1) (Num.subWrap right 1) + reverse_help(List.swap(list, left, right), Num.add_wrap(left, 1), Num.sub_wrap(right, 1)) else list @@ -452,20 +452,20 @@ clone : List a -> List a ## Join the given lists together into one list. ## ```roc -## expect List.join [[1], [2, 3], [], [4, 5]] == [1, 2, 3, 4, 5] -## expect List.join [[], []] == [] -## expect List.join [] == [] +## expect List.join([[1], [2, 3], [], [4, 5]]) == [1, 2, 3, 4, 5] +## expect List.join([[], []]) == [] +## expect List.join([]) == [] ## ``` join : List (List a) -> List a join = \lists -> - totalLength = - List.walk lists 0 (\state, list -> Num.addWrap state (List.len list)) + total_length = + List.walk(lists, 0, \state, list -> Num.add_wrap(state, List.len(list))) - List.walk lists (List.withCapacity totalLength) \state, list -> List.concat state list + List.walk(lists, List.with_capacity(total_length), \state, list -> List.concat(state, list)) contains : List a, a -> Bool where a implements Eq contains = \list, needle -> - List.any list (\x -> x == needle) + List.any(list, \x -> x == needle) ## Build a value using each element in the list. ## @@ -476,11 +476,11 @@ contains = \list, needle -> ## You can use it in a pipeline: ## ```roc ## [2, 4, 8] -## |> List.walk 0 Num.add +## |> List.walk(0, Num.add) ## ``` ## This returns 14 because: ## * `state` starts at 0 -## * Each `step` runs `Num.add state elem`, and the return value becomes the new `state`. +## * Each `step` runs `Num.add(state, elem)`, and the return value becomes the new `state`. ## ## Here is a table of how `state` changes as [List.walk] walks over the elements ## `[2, 4, 8]` using [Num.add] as its `step` function to determine the next `state`. @@ -495,74 +495,74 @@ contains = \list, needle -> ## The following returns -6: ## ```roc ## [1, 2, 3] -## |> List.walk 0 Num.sub +## |> List.walk(0, Num.sub) ## ``` ## Note that in other languages, `walk` is sometimes called `reduce`, -## `fold`, `foldLeft`, or `foldl`. +## `fold`, `fold_left`, or `foldl`. walk : List elem, state, (state, elem -> state) -> state walk = \list, init, func -> - walkHelp list init func 0 (List.len list) + walk_help(list, init, func, 0, List.len(list)) ## internal helper -walkHelp : List elem, s, (s, elem -> s), U64, U64 -> s -walkHelp = \list, state, f, index, length -> +walk_help : List elem, s, (s, elem -> s), U64, U64 -> s +walk_help = \list, state, f, index, length -> if index < length then - nextState = f state (List.getUnsafe list index) + next_state = f(state, List.get_unsafe(list, index)) - walkHelp list nextState f (Num.addWrap index 1) length + walk_help(list, next_state, f, Num.add_wrap(index, 1), length) else state ## Like [walk], but at each step the function also receives the index of the current element. -walkWithIndex : List elem, state, (state, elem, U64 -> state) -> state -walkWithIndex = \list, init, func -> - walkWithIndexHelp list init func 0 (List.len list) +walk_with_index : List elem, state, (state, elem, U64 -> state) -> state +walk_with_index = \list, init, func -> + walk_with_index_help(list, init, func, 0, List.len(list)) ## internal helper -walkWithIndexHelp : List elem, s, (s, elem, U64 -> s), U64, U64 -> s -walkWithIndexHelp = \list, state, f, index, length -> +walk_with_index_help : List elem, s, (s, elem, U64 -> s), U64, U64 -> s +walk_with_index_help = \list, state, f, index, length -> if index < length then - nextState = f state (List.getUnsafe list index) index + next_state = f(state, List.get_unsafe(list, index), index) - walkWithIndexHelp list nextState f (Num.addWrap index 1) length + walk_with_index_help(list, next_state, f, Num.add_wrap(index, 1), length) else state -## Like [walkUntil], but at each step the function also receives the index of the current element. -walkWithIndexUntil : List elem, state, (state, elem, U64 -> [Continue state, Break state]) -> state -walkWithIndexUntil = \list, state, f -> - when walkWithIndexUntilHelp list state f 0 (List.len list) is - Continue new -> new - Break new -> new +## Like [walk_until], but at each step the function also receives the index of the current element. +walk_with_index_until : List elem, state, (state, elem, U64 -> [Continue state, Break state]) -> state +walk_with_index_until = \list, state, f -> + when walk_with_index_until_help(list, state, f, 0, List.len(list)) is + Continue(new) -> new + Break(new) -> new ## internal helper -walkWithIndexUntilHelp : List elem, s, (s, elem, U64 -> [Continue s, Break b]), U64, U64 -> [Continue s, Break b] -walkWithIndexUntilHelp = \list, state, f, index, length -> +walk_with_index_until_help : List elem, s, (s, elem, U64 -> [Continue s, Break b]), U64, U64 -> [Continue s, Break b] +walk_with_index_until_help = \list, state, f, index, length -> if index < length then - when f state (List.getUnsafe list index) index is - Continue nextState -> - walkWithIndexUntilHelp list nextState f (Num.addWrap index 1) length + when f(state, List.get_unsafe(list, index), index) is + Continue(next_state) -> + walk_with_index_until_help(list, next_state, f, Num.add_wrap(index, 1), length) - Break b -> Break b + Break(b) -> Break(b) else - Continue state + Continue(state) -## Note that in other languages, `walkBackwards` is sometimes called `reduceRight`, -## `fold`, `foldRight`, or `foldr`. -walkBackwards : List elem, state, (state, elem -> state) -> state -walkBackwards = \list, state, func -> - walkBackwardsHelp list state func (len list) +## Note that in other languages, `walk_backwards` is sometimes called `reduce_right`, +## `fold`, `fold_right`, or `foldr`. +walk_backwards : List elem, state, (state, elem -> state) -> state +walk_backwards = \list, state, func -> + walk_backwards_help(list, state, func, len(list)) ## internal helper -walkBackwardsHelp : List elem, state, (state, elem -> state), U64 -> state -walkBackwardsHelp = \list, state, f, indexPlusOne -> - if indexPlusOne == 0 then +walk_backwards_help : List elem, state, (state, elem -> state), U64 -> state +walk_backwards_help = \list, state, f, index_plus_one -> + if index_plus_one == 0 then state else - index = Num.subWrap indexPlusOne 1 - nextState = f state (getUnsafe list index) + index = Num.sub_wrap(index_plus_one, 1) + next_state = f(state, get_unsafe(list, index)) - walkBackwardsHelp list nextState f index + walk_backwards_help(list, next_state, f, index) ## Same as [List.walk], except you can stop walking early. ## @@ -575,79 +575,79 @@ walkBackwardsHelp = \list, state, f, indexPlusOne -> ## ## As such, it is typically better for performance to use this over [List.walk] ## if returning `Break` earlier than the last element is expected to be common. -walkUntil : List elem, state, (state, elem -> [Continue state, Break state]) -> state -walkUntil = \list, initial, step -> - when List.iterate list initial step is - Continue new -> new - Break new -> new - -## Same as [List.walkUntil], but does it from the end of the list instead. -walkBackwardsUntil : List elem, state, (state, elem -> [Continue state, Break state]) -> state -walkBackwardsUntil = \list, initial, func -> - when List.iterateBackwards list initial func is - Continue new -> new - Break new -> new +walk_until : List elem, state, (state, elem -> [Continue state, Break state]) -> state +walk_until = \list, initial, step -> + when List.iterate(list, initial, step) is + Continue(new) -> new + Break(new) -> new + +## Same as [List.walk_until], but does it from the end of the list instead. +walk_backwards_until : List elem, state, (state, elem -> [Continue state, Break state]) -> state +walk_backwards_until = \list, initial, func -> + when List.iterate_backwards(list, initial, func) is + Continue(new) -> new + Break(new) -> new ## Walks to the end of the list from a specified starting index -walkFrom : List elem, U64, state, (state, elem -> state) -> state -walkFrom = \list, index, state, func -> +walk_from : List elem, U64, state, (state, elem -> state) -> state +walk_from = \list, index, state, func -> step : _, _ -> [Continue _, Break []] - step = \currentState, element -> Continue (func currentState element) + step = \current_state, element -> Continue(func(current_state, element)) - when List.iterHelp list state step index (List.len list) is - Continue new -> new + when List.iter_help(list, state, step, index, List.len(list)) is + Continue(new) -> new -## A combination of [List.walkFrom] and [List.walkUntil] -walkFromUntil : List elem, U64, state, (state, elem -> [Continue state, Break state]) -> state -walkFromUntil = \list, index, state, func -> - when List.iterHelp list state func index (List.len list) is - Continue new -> new - Break new -> new +## A combination of [List.walk_from] and [List.walk_until] +walk_from_until : List elem, U64, state, (state, elem -> [Continue state, Break state]) -> state +walk_from_until = \list, index, state, func -> + when List.iter_help(list, state, func, index, List.len(list)) is + Continue(new) -> new + Break(new) -> new sum : List (Num a) -> Num a sum = \list -> - List.walk list 0 Num.add + List.walk(list, 0, Num.add) product : List (Num a) -> Num a product = \list -> - List.walk list 1 Num.mul + List.walk(list, 1, Num.mul) ## Run the given predicate on each element of the list, returning `Bool.true` if ## any of the elements satisfy it. any : List a, (a -> Bool) -> Bool any = \list, predicate -> looper = \{}, element -> - if predicate element then - Break {} + if predicate(element) then + Break({}) else - Continue {} + Continue({}) - when List.iterate list {} looper is - Continue {} -> Bool.false - Break {} -> Bool.true + when List.iterate(list, {}, looper) is + Continue({}) -> Bool.false + Break({}) -> Bool.true ## Run the given predicate on each element of the list, returning `Bool.true` if ## all of the elements satisfy it. all : List a, (a -> Bool) -> Bool all = \list, predicate -> looper = \{}, element -> - if predicate element then - Continue {} + if predicate(element) then + Continue({}) else - Break {} + Break({}) - when List.iterate list {} looper is - Continue {} -> Bool.true - Break {} -> Bool.false + when List.iterate(list, {}, looper) is + Continue({}) -> Bool.true + Break({}) -> Bool.false ## Run the given function on each element of a list, and return all the ## elements for which the function returned `Bool.true`. ## ```roc -## List.keepIf [1, 2, 3, 4] (\num -> num > 2) +## List.keep_if([1, 2, 3, 4], (\num -> num > 2)) ## ``` ## ## Performance Details ## -## [List.keepIf] always returns a list that takes up exactly the same amount +## [List.keep_if] always returns a list that takes up exactly the same amount ## of memory as the original, even if its length decreases. This is because it ## can't know in advance exactly how much space it will need, and if it guesses a ## length that's too low, it would have to re-allocate. @@ -656,110 +656,111 @@ all = \list, predicate -> ## of the resulting list, you can do two passes over the list with [List.walk] - one ## to calculate the precise new size, and another to populate the new list.) ## -## If given a unique list, [List.keepIf] will mutate it in place to assemble the appropriate list. +## If given a unique list, [List.keep_if] will mutate it in place to assemble the appropriate list. ## If that happens, this function will not allocate any new memory on the heap. ## If all elements in the list end up being kept, Roc will return the original ## list unaltered. ## -keepIf : List a, (a -> Bool) -> List a -keepIf = \list, predicate -> - length = List.len list +keep_if : List a, (a -> Bool) -> List a +keep_if = \list, predicate -> + length = List.len(list) - keepIfHelp list predicate 0 0 length + keep_if_help(list, predicate, 0, 0, length) -keepIfHelp : List a, (a -> Bool), U64, U64, U64 -> List a -keepIfHelp = \list, predicate, kept, index, length -> +keep_if_help : List a, (a -> Bool), U64, U64, U64 -> List a +keep_if_help = \list, predicate, kept, index, length -> if index < length then - if predicate (List.getUnsafe list index) then - keepIfHelp (List.swap list kept index) predicate (Num.addWrap kept 1) (Num.addWrap index 1) length + if predicate(List.get_unsafe(list, index)) then + keep_if_help(List.swap(list, kept, index), predicate, Num.add_wrap(kept, 1), Num.add_wrap(index, 1), length) else - keepIfHelp list predicate kept (Num.addWrap index 1) length + keep_if_help(list, predicate, kept, Num.add_wrap(index, 1), length) else - List.takeFirst list kept + List.take_first(list, kept) ## Run the given function on each element of a list, and return all the ## elements for which the function returned `Bool.false`. ## ```roc -## List.dropIf [1, 2, 3, 4] (\num -> num > 2) +## List.drop_if([1, 2, 3, 4], (\num -> num > 2)) ## ``` ## ## Performance Details ## -## `List.dropIf` has the same performance characteristics as [List.keepIf]. +## `List.drop_if` has the same performance characteristics as [List.keep_if]. ## See its documentation for details on those characteristics! -dropIf : List a, (a -> Bool) -> List a -dropIf = \list, predicate -> - List.keepIf list (\e -> Bool.not (predicate e)) +drop_if : List a, (a -> Bool) -> List a +drop_if = \list, predicate -> + List.keep_if(list, \e -> Bool.not(predicate(e))) ## Run the given function on each element of a list, and return the ## number of elements for which the function returned `Bool.true`. ## ```roc -## expect List.countIf [1, -2, -3] Num.isNegative == 2 -## expect List.countIf [1, 2, 3] (\num -> num > 1 ) == 2 +## expect List.count_if([1, -2, -3], Num.is_negative) == 2 +## expect List.count_if([1, 2, 3], (\num -> num > 1)) == 2 ## ``` -countIf : List a, (a -> Bool) -> U64 -countIf = \list, predicate -> - walkState = \state, elem -> - if predicate elem then - Num.addWrap state 1 +count_if : List a, (a -> Bool) -> U64 +count_if = \list, predicate -> + walk_state = \state, elem -> + if predicate(elem) then + Num.add_wrap(state, 1) else state - List.walk list 0 walkState + List.walk(list, 0, walk_state) ## This works like [List.map], except only the transformed values that are ## wrapped in `Ok` are kept. Any that are wrapped in `Err` are dropped. ## ```roc -## expect List.keepOks ["1", "Two", "23", "Bird"] Str.toI32 == [1, 23] +## expect List.keep_oks(["1", "Two", "23", "Bird"], Str.to_i32) == [1, 23] ## -## expect List.keepOks [["a", "b"], [], ["c", "d", "e"], [] ] List.first == ["a", "c"] +## expect List.keep_oks([["a", "b"], [], ["c", "d", "e"], [] ], List.first) == ["a", "c"] ## -## fn = \str -> if Str.isEmpty str then Err StrWasEmpty else Ok str -## expect List.keepOks ["", "a", "bc", "", "d", "ef", ""] fn == ["a", "bc", "d", "ef"] +## fn = \str -> if Str.is_empty(str) then Err(StrWasEmpty) else Ok(str) +## expect List.keep_oks(["", "a", "bc", "", "d", "ef", ""], fn) == ["a", "bc", "d", "ef"] ## ``` -keepOks : List before, (before -> Result after *) -> List after -keepOks = \list, toResult -> +keep_oks : List before, (before -> Result after *) -> List after +keep_oks = \list, to_result -> walker = \accum, element -> - when toResult element is - Ok keep -> List.append accum keep - Err _drop -> accum + when to_result(element) is + Ok(keep) -> List.append(accum, keep) + Err(_drop) -> accum - List.walk list (List.withCapacity (List.len list)) walker + List.walk(list, List.with_capacity(List.len(list)), walker) ## This works like [List.map], except only the transformed values that are ## wrapped in `Err` are kept. Any that are wrapped in `Ok` are dropped. ## ```roc -## List.keepErrs [["a", "b"], [], [], ["c", "d", "e"]] List.last +## List.keep_errs([["a", "b"], [], [], ["c", "d", "e"]], List.last) ## -## fn = \str -> if Str.isEmpty str then Err StrWasEmpty else Ok (Str.len str) +## fn = \str -> if Str.is_empty(str) then Err(StrWasEmpty) else Okd(Str.len(str)) ## -## List.keepErrs ["", "a", "bc", "", "d", "ef", ""] +## List.keep_errs(["", "a", "bc", "", "d", "ef", ""], fn) ## ``` -keepErrs : List before, (before -> Result * after) -> List after -keepErrs = \list, toResult -> +keep_errs : List before, (before -> Result * after) -> List after +keep_errs = \list, to_result -> walker = \accum, element -> - when toResult element is - Ok _drop -> accum - Err keep -> List.append accum keep + when to_result(element) is + Ok(_drop) -> accum + Err(keep) -> List.append(accum, keep) - List.walk list (List.withCapacity (List.len list)) walker + List.walk(list, List.with_capacity(List.len(list)), walker) ## Convert each element in the list to something new, by calling a conversion ## function on each of them. Then return a new list of the converted values. ## ```roc -## expect List.map [1, 2, 3] (\num -> num + 1) == [2, 3, 4] +## expect List.map([1, 2, 3], (\num -> num + 1)) == [2, 3, 4] ## -## expect List.map ["", "a", "bc"] Str.isEmpty == [Bool.true, Bool.false, Bool.false] +## expect List.map(["", "a", "bc"], Str.is_empty) == [Bool.true, Bool.false, Bool.false] ## ``` map : List a, (a -> b) -> List b map = \list, mapper -> # TODO: allow checking the refcounting and running the map inplace. # Preferably allow it even if the types are different (must be same size with padding though). - length = List.len list - List.walk - list - (List.withCapacity length) + length = List.len(list) + List.walk( + list, + List.with_capacity(length), \state, elem -> - List.appendUnsafe state (mapper elem) + List.append_unsafe(state, mapper(elem)), + ) ## Run a transformation function on the first element of each list, ## and use that as the first element in the returned list. @@ -768,19 +769,19 @@ map = \list, mapper -> ## Some languages have a function named `zip`, which does something similar to ## calling [List.map2] passing two lists and `Pair`: ## ```roc -## zipped = List.map2 ["a", "b", "c"] [1, 2, 3] Pair +## zipped = List.map2(["a", "b", "c"], [1, 2, 3], Pair) ## ``` map2 : List a, List b, (a, b -> c) -> List c -map2 = \listA, listB, mapper -> - length = Num.min (List.len listA) (List.len listB) - map2Help listA listB (List.withCapacity length) mapper 0 length +map2 = \list_a, list_b, mapper -> + length = Num.min(List.len(list_a), List.len(list_b)) + map2_help(list_a, list_b, List.with_capacity(length), mapper, 0, length) -map2Help : List a, List b, List c, (a, b -> c), U64, U64 -> List c -map2Help = \listA, listB, out, mapper, index, length -> +map2_help : List a, List b, List c, (a, b -> c), U64, U64 -> List c +map2_help = \list_a, list_b, out, mapper, index, length -> if index < length then - mapped = mapper (List.getUnsafe listA index) (List.getUnsafe listB index) + mapped = mapper(List.get_unsafe(list_a, index), List.get_unsafe(list_b, index)) - map2Help listA listB (List.appendUnsafe out mapped) mapper (Num.addWrap index 1) length + map2_help(list_a, list_b, List.append_unsafe(out, mapped), mapper, Num.add_wrap(index, 1), length) else out @@ -788,18 +789,19 @@ map2Help = \listA, listB, out, mapper, index, length -> ## and use that as the first element in the returned list. ## Repeat until a list runs out of elements. map3 : List a, List b, List c, (a, b, c -> d) -> List d -map3 = \listA, listB, listC, mapper -> - length = Num.min - (Num.min (List.len listA) (List.len listB)) - (List.len listC) - map3Help listA listB listC (List.withCapacity length) mapper 0 length - -map3Help : List a, List b, List c, List d, (a, b, c -> d), U64, U64 -> List d -map3Help = \listA, listB, listC, out, mapper, index, length -> +map3 = \list_a, list_b, list_c, mapper -> + length = Num.min( + Num.min(List.len(list_a), List.len(list_b)), + List.len(list_c), + ) + map3_help(list_a, list_b, list_c, List.with_capacity(length), mapper, 0, length) + +map3_help : List a, List b, List c, List d, (a, b, c -> d), U64, U64 -> List d +map3_help = \list_a, list_b, list_c, out, mapper, index, length -> if index < length then - mapped = mapper (List.getUnsafe listA index) (List.getUnsafe listB index) (List.getUnsafe listC index) + mapped = mapper(List.get_unsafe(list_a, index), List.get_unsafe(list_b, index), List.get_unsafe(list_c, index)) - map3Help listA listB listC (List.appendUnsafe out mapped) mapper (Num.addWrap index 1) length + map3_help(list_a, list_b, list_c, List.append_unsafe(out, mapped), mapper, Num.add_wrap(index, 1), length) else out @@ -807,42 +809,43 @@ map3Help = \listA, listB, listC, out, mapper, index, length -> ## and use that as the first element in the returned list. ## Repeat until a list runs out of elements. map4 : List a, List b, List c, List d, (a, b, c, d -> e) -> List e -map4 = \listA, listB, listC, listD, mapper -> - length = Num.min - (Num.min (List.len listA) (List.len listB)) - (Num.min (List.len listC) (List.len listD)) - map4Help listA listB listC listD (List.withCapacity length) mapper 0 length - -map4Help : List a, List b, List c, List d, List e, (a, b, c, d -> e), U64, U64 -> List e -map4Help = \listA, listB, listC, listD, out, mapper, index, length -> +map4 = \list_a, list_b, list_c, list_d, mapper -> + length = Num.min( + Num.min(List.len(list_a), List.len(list_b)), + Num.min(List.len(list_c), List.len(list_d)), + ) + map4_help(list_a, list_b, list_c, list_d, List.with_capacity(length), mapper, 0, length) + +map4_help : List a, List b, List c, List d, List e, (a, b, c, d -> e), U64, U64 -> List e +map4_help = \list_a, list_b, list_c, list_d, out, mapper, index, length -> if index < length then - mapped = mapper (List.getUnsafe listA index) (List.getUnsafe listB index) (List.getUnsafe listC index) (List.getUnsafe listD index) + mapped = mapper(List.get_unsafe(list_a, index), List.get_unsafe(list_b, index), List.get_unsafe(list_c, index), List.get_unsafe(list_d, index)) - map4Help listA listB listC listD (List.append out mapped) mapper (Num.addWrap index 1) length + map4_help(list_a, list_b, list_c, list_d, List.append(out, mapped), mapper, Num.add_wrap(index, 1), length) else out ## This works like [List.map], except it also passes the index ## of the element to the conversion function. ## ```roc -## expect List.mapWithIndex [10, 20, 30] (\num, index -> num + index) == [10, 21, 32] +## expect List.map_with_index([10, 20, 30], (\num, index -> num + index)) == [10, 21, 32] ## ``` -mapWithIndex : List a, (a, U64 -> b) -> List b -mapWithIndex = \src, func -> - length = len src - dest = withCapacity length +map_with_index : List a, (a, U64 -> b) -> List b +map_with_index = \src, func -> + length = len(src) + dest = with_capacity(length) - mapWithIndexHelp src dest func 0 length + map_with_index_help(src, dest, func, 0, length) # Internal helper -mapWithIndexHelp : List a, List b, (a, U64 -> b), U64, U64 -> List b -mapWithIndexHelp = \src, dest, func, index, length -> +map_with_index_help : List a, List b, (a, U64 -> b), U64, U64 -> List b +map_with_index_help = \src, dest, func, index, length -> if index < length then - elem = getUnsafe src index - mappedElem = func elem index - newDest = List.appendUnsafe dest mappedElem + elem = get_unsafe(src, index) + mapped_elem = func(elem, index) + new_dest = List.append_unsafe(dest, mapped_elem) - mapWithIndexHelp src newDest func (Num.addWrap index 1) length + map_with_index_help(src, new_dest, func, Num.add_wrap(index, 1), length) else dest @@ -850,373 +853,373 @@ mapWithIndexHelp = \src, dest, func, index, length -> ## ## To include the `start` and `end` integers themselves, use `At` like so: ## ```roc -## List.range { start: At 2, end: At 5 } # returns [2, 3, 4, 5] +## List.range({ start: At 2, end: At 5 }) == [2, 3, 4, 5] ## ``` ## To exclude them, use `After` and `Before`, like so: ## ```roc -## List.range { start: After 2, end: Before 5 } # returns [3, 4] +## List.range({ start: After 2, end: Before 5 }) == [3, 4] ## ``` ## You can have the list end at a certain length rather than a certain integer: ## ```roc -## List.range { start: At 6, end: Length 4 } # returns [6, 7, 8, 9] +## List.range({ start: At 6, end: Length 4 }) == [6, 7, 8, 9] ## ``` ## If `step` is specified, each integer increases by that much. (`step: 1` is the default.) ## ```roc -## List.range { start: After 0, end: Before 9, step: 3 } # returns [3, 6] +## List.range({ start: After 0, end: Before 9, step: 3 }) == [3, 6] ## ``` ## List.range will also generate a reversed list if step is negative or end comes before start: ## ```roc -## List.range { start: At 5, end: At 2 } # returns [5, 4, 3, 2] +## List.range({ start: At 5, end: At 2 }) == [5, 4, 3, 2] ## ``` ## All of these options are compatible with the others. For example, you can use `At` or `After` ## with `start` regardless of what `end` and `step` are set to. range : _ range = \{ start, end, step ? 0 } -> - { calcNext, stepIsPositive } = + { calc_next, step_is_positive } = if step == 0 then - when T start end is - T (At x) (At y) | T (At x) (Before y) | T (After x) (At y) | T (After x) (Before y) -> + when T(start, end) is + T(At(x), At(y)) | T(At(x), Before(y)) | T(After(x), At(y)) | T(After(x), Before(y)) -> if x < y then { - calcNext: \i -> Num.addChecked i 1, - stepIsPositive: Bool.true, + calc_next: \i -> Num.add_checked(i, 1), + step_is_positive: Bool.true, } else { - calcNext: \i -> Num.subChecked i 1, - stepIsPositive: Bool.false, + calc_next: \i -> Num.sub_checked(i, 1), + step_is_positive: Bool.false, } - T (At _) (Length _) | T (After _) (Length _) -> + T(At(_), Length(_)) | T(After(_), Length(_)) -> { - calcNext: \i -> Num.addChecked i 1, - stepIsPositive: Bool.true, + calc_next: \i -> Num.add_checked(i, 1), + step_is_positive: Bool.true, } else { - calcNext: \i -> Num.addChecked i step, - stepIsPositive: step > 0, + calc_next: \i -> Num.add_checked(i, step), + step_is_positive: step > 0, } - inclusiveStart = + inclusive_start = when start is - At x -> Ok x - After x -> calcNext x + At(x) -> Ok(x) + After(x) -> calc_next(x) when end is - At at -> - isValid = - if stepIsPositive then + At(at) -> + is_valid = + if step_is_positive then \i -> i <= at else \i -> i >= at - # TODO: switch to List.withCapacity - rangeHelp [] inclusiveStart calcNext isValid + # TODO: switch to List.with_capacity + range_help([], inclusive_start, calc_next, is_valid) - Before before -> - isValid = - if stepIsPositive then + Before(before) -> + is_valid = + if step_is_positive then \i -> i < before else \i -> i > before - # TODO: switch to List.withCapacity - rangeHelp [] inclusiveStart calcNext isValid + # TODO: switch to List.with_capacity + range_help([], inclusive_start, calc_next, is_valid) - Length l -> - rangeLengthHelp (List.withCapacity l) inclusiveStart l calcNext + Length(l) -> + range_length_help(List.with_capacity(l), inclusive_start, l, calc_next) -rangeHelp = \accum, i, calcNext, isValid -> +range_help = \accum, i, calc_next, is_valid -> when i is - Ok val -> - if isValid val then - # TODO: change this to List.appendUnsafe once capacity is set correctly - rangeHelp (List.append accum val) (calcNext val) calcNext isValid + Ok(val) -> + if is_valid(val) then + # TODO: change this to List.append_unsafe once capacity is set correctly + range_help(List.append(accum, val), calc_next(val), calc_next, is_valid) else accum - Err _ -> + Err(_) -> # We went past the end of the numeric range and there is no next. # return the generated list. accum -rangeLengthHelp = \accum, i, remaining, calcNext -> +range_length_help = \accum, i, remaining, calc_next -> if remaining == 0 then accum else when i is - Ok val -> - rangeLengthHelp (List.appendUnsafe accum val) (calcNext val) (Num.subWrap remaining 1) calcNext + Ok(val) -> + range_length_help(List.append_unsafe(accum, val), calc_next(val), Num.sub_wrap(remaining, 1), calc_next) - Err _ -> + Err(_) -> # We went past the end of the numeric range and there is no next. # The list is not the correct length yet, so we must crash. - crash "List.range: failed to generate enough elements to fill the range before overflowing the numeric type" + crash("List.range: failed to generate enough elements to fill the range before overflowing the numeric type") expect - List.range { start: At 0, end: At 4 } == [0, 1, 2, 3, 4] + List.range({ start: At(0), end: At(4) }) == [0, 1, 2, 3, 4] expect - List.range { start: After 0, end: At 4 } == [1, 2, 3, 4] + List.range({ start: After(0), end: At(4) }) == [1, 2, 3, 4] expect - List.range { start: At 0, end: At 4, step: 2 } == [0, 2, 4] + List.range({ start: At(0), end: At(4), step: 2 }) == [0, 2, 4] expect - List.range { start: At 0, end: Before 4 } == [0, 1, 2, 3] + List.range({ start: At(0), end: Before(4) }) == [0, 1, 2, 3] expect - List.range { start: After 0, end: Before 4 } == [1, 2, 3] + List.range({ start: After(0), end: Before(4) }) == [1, 2, 3] expect - List.range { start: At 0, end: Before 4, step: 2 } == [0, 2] + List.range({ start: At(0), end: Before(4), step: 2 }) == [0, 2] expect - List.range { start: At 4, end: Length 5 } == [4, 5, 6, 7, 8] + List.range({ start: At(4), end: Length(5) }) == [4, 5, 6, 7, 8] expect - List.range { start: At 4, end: Length 5, step: 10 } == [4, 14, 24, 34, 44] + List.range({ start: At(4), end: Length(5), step: 10 }) == [4, 14, 24, 34, 44] expect - List.range { start: At 4, end: Length 5, step: -3 } == [4, 1, -2, -5, -8] + List.range({ start: At(4), end: Length(5), step: -3 }) == [4, 1, -2, -5, -8] expect - List.range { start: After 250u8, end: At 255 } == [251, 252, 253, 254, 255] + List.range({ start: After(250u8), end: At(255) }) == [251, 252, 253, 254, 255] expect - List.range { start: After 250u8, end: At 255, step: 10 } == [] + List.range({ start: After(250u8), end: At(255), step: 10 }) == [] expect - List.range { start: After 250u8, end: At 245, step: 10 } == [] + List.range({ start: After(250u8), end: At(245), step: 10 }) == [] expect - List.range { start: At 4, end: At 0 } == [4, 3, 2, 1, 0] + List.range({ start: At(4), end: At(0) }) == [4, 3, 2, 1, 0] ## Sort with a custom comparison function -sortWith : List a, (a, a -> [LT, EQ, GT]) -> List a +sort_with : List a, (a, a -> [LT, EQ, GT]) -> List a ## Sorts a list of numbers in ascending order (lowest to highest). ## -## To sort in descending order (highest to lowest), use [List.sortDesc] instead. -sortAsc : List (Num a) -> List (Num a) -sortAsc = \list -> List.sortWith list Num.compare +## To sort in descending order (highest to lowest), use [List.sort_desc] instead. +sort_asc : List (Num a) -> List (Num a) +sort_asc = \list -> List.sort_with(list, Num.compare) ## Sorts a list of numbers in descending order (highest to lowest). ## -## To sort in ascending order (lowest to highest), use [List.sortAsc] instead. -sortDesc : List (Num a) -> List (Num a) -sortDesc = \list -> List.sortWith list (\a, b -> Num.compare b a) +## To sort in ascending order (lowest to highest), use [List.sort_asc] instead. +sort_desc : List (Num a) -> List (Num a) +sort_desc = \list -> List.sort_with(list, \a, b -> Num.compare(b, a)) swap : List a, U64, U64 -> List a ## Returns the first element in the list, or `ListWasEmpty` if it was empty. first : List a -> Result a [ListWasEmpty] first = \list -> - when List.get list 0 is - Ok v -> Ok v - Err _ -> Err ListWasEmpty + when List.get(list, 0) is + Ok(v) -> Ok(v) + Err(_) -> Err(ListWasEmpty) ## Returns the given number of elements from the beginning of the list. ## ```roc -## List.takeFirst [1, 2, 3, 4, 5, 6, 7, 8] 4 +## List.take_first([1, 2, 3, 4, 5, 6, 7, 8], 4) == [1, 2, 3, 4] ## ``` ## If there are fewer elements in the list than the requested number, ## returns the entire list. ## ```roc -## List.takeFirst [1, 2] 5 +## List.take_first([1, 2], 5) == [1, 2] ## ``` -## To *remove* elements from the beginning of the list, use `List.takeLast`. +## To *remove* elements from the beginning of the list, use `List.take_last`. ## ## To remove elements from both the beginning and end of the list, ## use `List.sublist`. ## -## To split the list into two lists, use `List.splitAt`. +## To split the list into two lists, use `List.split_at`. ## -takeFirst : List elem, U64 -> List elem -takeFirst = \list, outputLength -> - List.sublist list { start: 0, len: outputLength } +take_first : List elem, U64 -> List elem +take_first = \list, output_length -> + List.sublist(list, { start: 0, len: output_length }) ## Returns the given number of elements from the end of the list. ## ```roc -## List.takeLast [1, 2, 3, 4, 5, 6, 7, 8] 4 +## List.take_last([1, 2, 3, 4, 5, 6, 7, 8], 4) == [5, 6, 7, 8] ## ``` ## If there are fewer elements in the list than the requested number, ## returns the entire list. ## ```roc -## List.takeLast [1, 2] 5 +## List.take_last([1, 2], 5) == [1, 2] ## ``` -## To *remove* elements from the end of the list, use `List.takeFirst`. +## To *remove* elements from the end of the list, use `List.take_first`. ## ## To remove elements from both the beginning and end of the list, ## use `List.sublist`. ## -## To split the list into two lists, use `List.splitAt`. +## To split the list into two lists, use `List.split_at`. ## -takeLast : List elem, U64 -> List elem -takeLast = \list, outputLength -> - List.sublist list { start: Num.subSaturated (List.len list) outputLength, len: outputLength } +take_last : List elem, U64 -> List elem +take_last = \list, output_length -> + List.sublist(list, { start: Num.sub_saturated(List.len(list), output_length), len: output_length }) ## Drops n elements from the beginning of the list. -dropFirst : List elem, U64 -> List elem -dropFirst = \list, n -> - remaining = Num.subSaturated (List.len list) n +drop_first : List elem, U64 -> List elem +drop_first = \list, n -> + remaining = Num.sub_saturated(List.len(list), n) - List.takeLast list remaining + List.take_last(list, remaining) ## Drops n elements from the end of the list. -dropLast : List elem, U64 -> List elem -dropLast = \list, n -> - remaining = Num.subSaturated (List.len list) n +drop_last : List elem, U64 -> List elem +drop_last = \list, n -> + remaining = Num.sub_saturated(List.len(list), n) - List.takeFirst list remaining + List.take_first(list, remaining) ## Drops the element at the given index from the list. ## ## This has no effect if the given index is outside the bounds of the list. ## ## To replace the element at a given index, instead of dropping it, see [List.set]. -dropAt : List elem, U64 -> List elem +drop_at : List elem, U64 -> List elem min : List (Num a) -> Result (Num a) [ListWasEmpty] min = \list -> - when List.first list is - Ok initial -> - Ok (minHelp list initial) + when List.first(list) is + Ok(initial) -> + Ok(min_help(list, initial)) - Err ListWasEmpty -> - Err ListWasEmpty + Err(ListWasEmpty) -> + Err(ListWasEmpty) -minHelp : List (Num a), Num a -> Num a -minHelp = \list, initial -> - List.walk list initial \bestSoFar, current -> - if current < bestSoFar then +min_help : List (Num a), Num a -> Num a +min_help = \list, initial -> + List.walk(list, initial, \best_so_far, current -> + if current < best_so_far then current else - bestSoFar + best_so_far) max : List (Num a) -> Result (Num a) [ListWasEmpty] max = \list -> - when List.first list is - Ok initial -> - Ok (maxHelp list initial) + when List.first(list) is + Ok(initial) -> + Ok(max_help(list, initial)) - Err ListWasEmpty -> - Err ListWasEmpty + Err(ListWasEmpty) -> + Err(ListWasEmpty) -maxHelp : List (Num a), Num a -> Num a -maxHelp = \list, initial -> - List.walk list initial \bestSoFar, current -> - if current > bestSoFar then +max_help : List (Num a), Num a -> Num a +max_help = \list, initial -> + List.walk(list, initial, \best_so_far, current -> + if current > best_so_far then current else - bestSoFar + best_so_far) ## Like [List.map], except the transformation function wraps the return value ## in a list. At the end, all the lists get joined together into one list. ## -## You may know a similar function named `concatMap` in other languages. -joinMap : List a, (a -> List b) -> List b -joinMap = \list, mapper -> - List.walk list [] \state, elem -> List.concat state (mapper elem) +## You may know a similar function named `concat_map` in other languages. +join_map : List a, (a -> List b) -> List b +join_map = \list, mapper -> + List.walk(list, [], \state, elem -> List.concat(state, mapper(elem))) ## Returns the first element of the list satisfying a predicate function. ## If no satisfying element is found, an `Err NotFound` is returned. -findFirst : List elem, (elem -> Bool) -> Result elem [NotFound] -findFirst = \list, pred -> +find_first : List elem, (elem -> Bool) -> Result elem [NotFound] +find_first = \list, pred -> callback = \_, elem -> - if pred elem then - Break elem + if pred(elem) then + Break(elem) else - Continue {} + Continue({}) - when List.iterate list {} callback is - Continue {} -> Err NotFound - Break found -> Ok found + when List.iterate(list, {}, callback) is + Continue({}) -> Err(NotFound) + Break(found) -> Ok(found) ## Returns the last element of the list satisfying a predicate function. ## If no satisfying element is found, an `Err NotFound` is returned. -findLast : List elem, (elem -> Bool) -> Result elem [NotFound] -findLast = \list, pred -> +find_last : List elem, (elem -> Bool) -> Result elem [NotFound] +find_last = \list, pred -> callback = \_, elem -> - if pred elem then - Break elem + if pred(elem) then + Break(elem) else - Continue {} + Continue({}) - when List.iterateBackwards list {} callback is - Continue {} -> Err NotFound - Break found -> Ok found + when List.iterate_backwards(list, {}, callback) is + Continue({}) -> Err(NotFound) + Break(found) -> Ok(found) ## Returns the index at which the first element in the list ## satisfying a predicate function can be found. ## If no satisfying element is found, an `Err NotFound` is returned. -findFirstIndex : List elem, (elem -> Bool) -> Result U64 [NotFound] -findFirstIndex = \list, matcher -> - foundIndex = List.iterate list 0 \index, elem -> - if matcher elem then - Break index +find_first_index : List elem, (elem -> Bool) -> Result U64 [NotFound] +find_first_index = \list, matcher -> + found_index = List.iterate(list, 0, \index, elem -> + if matcher(elem) then + Break(index) else - Continue (Num.addWrap index 1) + Continue(Num.add_wrap(index, 1))) - when foundIndex is - Break index -> Ok index - Continue _ -> Err NotFound + when found_index is + Break(index) -> Ok(index) + Continue(_) -> Err(NotFound) ## Returns the last index at which the first element in the list ## satisfying a predicate function can be found. ## If no satisfying element is found, an `Err NotFound` is returned. -findLastIndex : List elem, (elem -> Bool) -> Result U64 [NotFound] -findLastIndex = \list, matches -> - foundIndex = List.iterateBackwards list (List.len list) \prevIndex, elem -> - answer = Num.subWrap prevIndex 1 +find_last_index : List elem, (elem -> Bool) -> Result U64 [NotFound] +find_last_index = \list, matches -> + found_index = List.iterate_backwards(list, List.len(list), \prev_index, elem -> + answer = Num.sub_wrap(prev_index, 1) - if matches elem then - Break answer + if matches(elem) then + Break(answer) else - Continue answer + Continue(answer)) - when foundIndex is - Break index -> Ok index - Continue _ -> Err NotFound + when found_index is + Break(index) -> Ok(index) + Continue(_) -> Err(NotFound) ## Returns a subsection of the given list, beginning at the `start` index and ## including a total of `len` elements. ## ## If `start` is outside the bounds of the given list, returns the empty list. ## ```roc -## List.sublist [1, 2, 3] { start: 4, len: 0 } +## List.sublist([1, 2, 3], { start: 4, len: 0 }) ## ``` ## If more elements are requested than exist in the list, returns as many as it can. ## ```roc -## List.sublist [1, 2, 3, 4, 5] { start: 2, len: 10 } +## List.sublist([1, 2, 3, 4, 5], { start: 2, len: 10 }) ## ``` ## > If you want a sublist which goes all the way to the end of the list, no -## > matter how long the list is, `List.takeLast` can do that more efficiently. +## > matter how long the list is, `List.take_last` can do that more efficiently. ## ## Some languages have a function called **`slice`** which works similarly to this. sublist : List elem, { start : U64, len : U64 } -> List elem sublist = \list, config -> - sublistLowlevel list config.start config.len + sublist_lowlevel(list, config.start, config.len) ## low-level slicing operation that does no bounds checking -sublistLowlevel : List elem, U64, U64 -> List elem +sublist_lowlevel : List elem, U64, U64 -> List elem ## Intersperses `sep` between the elements of `list` ## ```roc -## List.intersperse [1, 2, 3] 9 # [1, 9, 2, 9, 3] +## List.intersperse([1, 2, 3], 9) == [1, 9, 2, 9, 3] ## ``` intersperse : List elem, elem -> List elem intersperse = \list, sep -> - capacity = 2 * List.len list - init = List.withCapacity capacity - newList = - List.walk list init \acc, elem -> + capacity = 2 * List.len(list) + init = List.with_capacity(capacity) + new_list = + List.walk(list, init, \acc, elem -> acc - |> List.appendUnsafe elem - |> List.appendUnsafe sep + |> List.append_unsafe(elem) + |> List.append_unsafe(sep)) - List.dropLast newList 1 + List.drop_last(new_list, 1) ## Returns `Bool.true` if the first list starts with the second list. ## @@ -1224,11 +1227,11 @@ intersperse = \list, sep -> ## is considered to "start with" an empty list. ## ## If the first list is empty, this only returns `Bool.true` if the second list is empty. -startsWith : List elem, List elem -> Bool where elem implements Eq -startsWith = \list, prefix -> +starts_with : List elem, List elem -> Bool where elem implements Eq +starts_with = \list, prefix -> # TODO once we have seamless slices, verify that this wouldn't - # have better performance with a function like List.compareSublists - prefix == List.sublist list { start: 0, len: List.len prefix } + # have better performance with a function like List.compare_sublists + prefix == List.sublist(list, { start: 0, len: List.len(prefix) }) ## Returns `Bool.true` if the first list ends with the second list. ## @@ -1236,14 +1239,14 @@ startsWith = \list, prefix -> ## is considered to "end with" an empty list. ## ## If the first list is empty, this only returns `Bool.true` if the second list is empty. -endsWith : List elem, List elem -> Bool where elem implements Eq -endsWith = \list, suffix -> +ends_with : List elem, List elem -> Bool where elem implements Eq +ends_with = \list, suffix -> # TODO once we have seamless slices, verify that this wouldn't - # have better performance with a function like List.compareSublists - length = List.len suffix - start = Num.subSaturated (List.len list) length + # have better performance with a function like List.compare_sublists + length = List.len(suffix) + start = Num.sub_saturated(List.len(list), length) - suffix == List.sublist list { start, len: length } + suffix == List.sublist(list, { start, len: length }) ## Splits the list into two lists, around the given index. ## @@ -1252,113 +1255,113 @@ endsWith = \list, suffix -> ## than the given index, # and the `others` list will be all the others. (This ## means if you give an index of 0, the `before` list will be empty and the ## `others` list will have the same elements as the original list.) -splitAt : List elem, U64 -> { before : List elem, others : List elem } -splitAt = \elements, userSplitIndex -> - length = List.len elements - splitIndex = if length > userSplitIndex then userSplitIndex else length - before = List.sublist elements { start: 0, len: splitIndex } - others = List.sublist elements { start: splitIndex, len: Num.subWrap length splitIndex } +split_at : List elem, U64 -> { before : List elem, others : List elem } +split_at = \elements, user_split_index -> + length = List.len(elements) + split_index = if length > user_split_index then user_split_index else length + before = List.sublist(elements, { start: 0, len: split_index }) + others = List.sublist(elements, { start: split_index, len: Num.sub_wrap(length, split_index) }) { before, others } ## Splits the input list on the delimiter element. ## ## ```roc -## List.splitOn [1, 2, 3] 2 == [[1], [3]] +## List.split_on([1, 2, 3], 2) == [[1], [3]] ## ``` -splitOn : List a, a -> List (List a) where a implements Eq -splitOn = \elements, delimiter -> - help = \remaining, chunks, currentChunk -> +split_on : List a, a -> List (List a) where a implements Eq +split_on = \elements, delimiter -> + help = \remaining, chunks, current_chunk -> when remaining is - [] -> List.append chunks currentChunk + [] -> List.append(chunks, current_chunk) [x, .. as rest] if x == delimiter -> - help rest (List.append chunks currentChunk) [] + help(rest, List.append(chunks, current_chunk), []) [x, .. as rest] -> - help rest chunks (List.append currentChunk x) - help elements [] [] + help(rest, chunks, List.append(current_chunk, x)) + help(elements, [], []) ## Splits the input list on the delimiter list. ## ## ```roc -## List.splitOnList [1, 2, 3] [1, 2] == [[], [3]] +## List.split_on_list([1, 2, 3], [1, 2]) == [[], [3]] ## ``` -splitOnList : List a, List a -> List (List a) where a implements Eq -splitOnList = \elements, delimiter -> - help = \remaining, chunks, currentChunk -> +split_on_list : List a, List a -> List (List a) where a implements Eq +split_on_list = \elements, delimiter -> + help = \remaining, chunks, current_chunk -> when remaining is - [] -> List.append chunks currentChunk + [] -> List.append(chunks, current_chunk) [x, .. as rest] -> - if List.startsWith remaining delimiter then - help (List.dropFirst remaining (List.len delimiter)) (List.append chunks currentChunk) [] + if List.starts_with(remaining, delimiter) then + help(List.drop_first(remaining, List.len(delimiter)), List.append(chunks, current_chunk), []) else - help rest chunks (List.append currentChunk x) + help(rest, chunks, List.append(current_chunk, x)) if delimiter == [] then [elements] else - help elements [] [] + help(elements, [], []) ## Returns the elements before the first occurrence of a delimiter, as well as the ## remaining elements after that occurrence. If the delimiter is not found, returns `Err`. ## ```roc -## List.splitFirst [Foo, Z, Bar, Z, Baz] Z == Ok { before: [Foo], after: [Bar, Z, Baz] } +## List.split_first([Foo, Z, Bar, Z, Baz], Z) == Ok({ before: [Foo], after: [Bar, Z, Baz] }) ## ``` -splitFirst : List elem, elem -> Result { before : List elem, after : List elem } [NotFound] where elem implements Eq -splitFirst = \list, delimiter -> - when List.findFirstIndex list (\elem -> elem == delimiter) is - Ok index -> - before = List.sublist list { start: 0, len: index } - after = List.sublist list { start: Num.addWrap index 1, len: Num.subWrap (List.len list) index |> Num.subWrap 1 } +split_first : List elem, elem -> Result { before : List elem, after : List elem } [NotFound] where elem implements Eq +split_first = \list, delimiter -> + when List.find_first_index(list, \elem -> elem == delimiter) is + Ok(index) -> + before = List.sublist(list, { start: 0, len: index }) + after = List.sublist(list, { start: Num.add_wrap(index, 1), len: Num.sub_wrap(List.len(list), index) |> Num.sub_wrap(1) }) - Ok { before, after } + Ok({ before, after }) - Err NotFound -> Err NotFound + Err(NotFound) -> Err(NotFound) ## Returns the elements before the last occurrence of a delimiter, as well as the ## remaining elements after that occurrence. If the delimiter is not found, returns `Err`. ## ```roc -## List.splitLast [Foo, Z, Bar, Z, Baz] Z == Ok { before: [Foo, Z, Bar], after: [Baz] } +## List.split_last([Foo, Z, Bar, Z, Baz], Z) == Ok({ before: [Foo, Z, Bar], after: [Baz] }) ## ``` -splitLast : List elem, elem -> Result { before : List elem, after : List elem } [NotFound] where elem implements Eq -splitLast = \list, delimiter -> - when List.findLastIndex list (\elem -> elem == delimiter) is - Ok index -> - before = List.sublist list { start: 0, len: index } - after = List.sublist list { start: Num.addWrap index 1, len: Num.subWrap (List.len list) index |> Num.subWrap 1 } +split_last : List elem, elem -> Result { before : List elem, after : List elem } [NotFound] where elem implements Eq +split_last = \list, delimiter -> + when List.find_last_index(list, \elem -> elem == delimiter) is + Ok(index) -> + before = List.sublist(list, { start: 0, len: index }) + after = List.sublist(list, { start: Num.add_wrap(index, 1), len: Num.sub_wrap(List.len(list), index) |> Num.sub_wrap(1) }) - Ok { before, after } + Ok({ before, after }) - Err NotFound -> Err NotFound + Err(NotFound) -> Err(NotFound) ## Splits the list into many chunks, each of which is length of the given chunk ## size. The last chunk will be shorter if the list does not evenly divide by the ## chunk size. If the provided list is empty or if the chunk size is 0 then the ## result is an empty list. -chunksOf : List a, U64 -> List (List a) -chunksOf = \list, chunkSize -> - if chunkSize == 0 || List.isEmpty list then +chunks_of : List a, U64 -> List (List a) +chunks_of = \list, chunk_size -> + if chunk_size == 0 || List.is_empty(list) then [] else - chunkCapacity = Num.divCeil (List.len list) chunkSize - chunksOfHelp list chunkSize (List.withCapacity chunkCapacity) + chunk_capacity = Num.div_ceil(List.len(list), chunk_size) + chunks_of_help(list, chunk_size, List.with_capacity(chunk_capacity)) -chunksOfHelp : List a, U64, List (List a) -> List (List a) -chunksOfHelp = \listRest, chunkSize, chunks -> - if List.isEmpty listRest then +chunks_of_help : List a, U64, List (List a) -> List (List a) +chunks_of_help = \list_rest, chunk_size, chunks -> + if List.is_empty(list_rest) then chunks else - { before, others } = List.splitAt listRest chunkSize - chunksOfHelp others chunkSize (List.append chunks before) + { before, others } = List.split_at(list_rest, chunk_size) + chunks_of_help(others, chunk_size, List.append(chunks, before)) ## Like [List.map], except the transformation function returns a [Result]. -## If that function ever returns `Err`, [mapTry] immediately returns that `Err`. -## If it returns `Ok` for every element, [mapTry] returns `Ok` with the transformed list. -mapTry : List elem, (elem -> Result ok err) -> Result (List ok) err -mapTry = \list, toResult -> - walkTry list [] \state, elem -> - Result.map (toResult elem) \ok -> - List.append state ok +## If that function ever returns `Err`, [map_try] immediately returns that `Err`. +## If it returns `Ok` for every element, [map_try] returns `Ok` with the transformed list. +map_try : List elem, (elem -> Result ok err) -> Result (List ok) err +map_try = \list, to_result -> + walk_try(list, [], \state, elem -> + Result.map(to_result(elem), \ok -> + List.append(state, ok))) ## Same as [List.walk], except you can stop walking early by returning `Err`. ## @@ -1371,109 +1374,113 @@ mapTry = \list, toResult -> ## ## As such, it is typically better for performance to use this over [List.walk] ## if returning `Break` earlier than the last element is expected to be common. -walkTry : List elem, state, (state, elem -> Result state err) -> Result state err -walkTry = \list, init, func -> - walkTryHelp list init func 0 (List.len list) +walk_try : List elem, state, (state, elem -> Result state err) -> Result state err +walk_try = \list, init, func -> + walk_try_help(list, init, func, 0, List.len(list)) ## internal helper -walkTryHelp : List elem, state, (state, elem -> Result state err), U64, U64 -> Result state err -walkTryHelp = \list, state, f, index, length -> +walk_try_help : List elem, state, (state, elem -> Result state err), U64, U64 -> Result state err +walk_try_help = \list, state, f, index, length -> if index < length then - when f state (List.getUnsafe list index) is - Ok nextState -> walkTryHelp list nextState f (Num.addWrap index 1) length - Err b -> Err b + when f(state, List.get_unsafe(list, index)) is + Ok(next_state) -> walk_try_help(list, next_state, f, Num.add_wrap(index, 1), length) + Err(b) -> Err(b) else - Ok state + Ok(state) ## Primitive for iterating over a List, being able to decide at every element whether to continue iterate : List elem, s, (s, elem -> [Continue s, Break b]) -> [Continue s, Break b] iterate = \list, init, func -> - iterHelp list init func 0 (List.len list) + iter_help(list, init, func, 0, List.len(list)) ## internal helper -iterHelp : List elem, s, (s, elem -> [Continue s, Break b]), U64, U64 -> [Continue s, Break b] -iterHelp = \list, state, f, index, length -> +iter_help : List elem, s, (s, elem -> [Continue s, Break b]), U64, U64 -> [Continue s, Break b] +iter_help = \list, state, f, index, length -> if index < length then - when f state (List.getUnsafe list index) is - Continue nextState -> iterHelp list nextState f (Num.addWrap index 1) length - Break b -> Break b + when f(state, List.get_unsafe(list, index)) is + Continue(next_state) -> iter_help(list, next_state, f, Num.add_wrap(index, 1), length) + Break(b) -> Break(b) else - Continue state + Continue(state) ## Primitive for iterating over a List from back to front, being able to decide at every ## element whether to continue -iterateBackwards : List elem, s, (s, elem -> [Continue s, Break b]) -> [Continue s, Break b] -iterateBackwards = \list, init, func -> - iterBackwardsHelp list init func (List.len list) +iterate_backwards : List elem, s, (s, elem -> [Continue s, Break b]) -> [Continue s, Break b] +iterate_backwards = \list, init, func -> + iter_backwards_help(list, init, func, List.len(list)) ## internal helper -iterBackwardsHelp : List elem, s, (s, elem -> [Continue s, Break b]), U64 -> [Continue s, Break b] -iterBackwardsHelp = \list, state, f, prevIndex -> - if prevIndex > 0 then - index = Num.subWrap prevIndex 1 - - when f state (List.getUnsafe list index) is - Continue nextState -> iterBackwardsHelp list nextState f index - Break b -> Break b +iter_backwards_help : List elem, s, (s, elem -> [Continue s, Break b]), U64 -> [Continue s, Break b] +iter_backwards_help = \list, state, f, prev_index -> + if prev_index > 0 then + index = Num.sub_wrap(prev_index, 1) + + when f(state, List.get_unsafe(list, index)) is + Continue(next_state) -> iter_backwards_help(list, next_state, f, index) + Break(b) -> Break(b) else - Continue state + Continue(state) ## Concatenates the bytes of a string encoded as utf8 to a list of bytes. ## ```roc -## expect (List.concatUtf8 [1, 2, 3, 4] "🐦") == [1, 2, 3, 4, 240, 159, 144, 166] +## expect List.concat_utf8([1, 2, 3, 4], "🐦") == [1, 2, 3, 4, 240, 159, 144, 166] ## ``` -concatUtf8 : List U8, Str -> List U8 +concat_utf8 : List U8, Str -> List U8 -expect (List.concatUtf8 [1, 2, 3, 4] "🐦") == [1, 2, 3, 4, 240, 159, 144, 166] +expect (List.concat_utf8([1, 2, 3, 4], "🐦")) == [1, 2, 3, 4, 240, 159, 144, 166] ## Run an effectful function for each element on the list. ## ## ```roc -## List.forEach! ["Alice", "Bob", "Charlie"] \name -> -## createAccount! name -## log! "Account created" +## List.for_each!(["Alice", "Bob", "Charlie"], \name -> +## create_account!(name) +## log!("Account created") +## ) ## ``` ## -## If the function might fail or you need to return early, use [forEachTry!]. -forEach! : List a, (a => {}) => {} -forEach! = \list, func! -> +## If the function might fail or you need to return early, use [for_each_try!]. +for_each! : List a, (a => {}) => {} +for_each! = \list, func! -> when list is [] -> {} [elem, .. as rest] -> - func! elem - forEach! rest func! + func!(elem) + for_each!(rest, func!) ## Run an effectful function that might fail for each element on the list. ## ## If the function returns `Err`, the iteration stops and the error is returned. ## ## ```roc -## List.forEachTry! filesToDelete \path -> -## try File.delete! path -## Stdout.line! "$(path) deleted" +## List.for_each_try!(files_to_delete, \path -> +## File.delete!(path)? +## +## Stdout.line!("$(path) deleted") +## ) ## ``` -forEachTry! : List a, (a => Result {} err) => Result {} err -forEachTry! = \list, func! -> +for_each_try! : List a, (a => Result {} err) => Result {} err +for_each_try! = \list, func! -> when list is [] -> - Ok {} + Ok({}) [elem, .. as rest] -> - when func! elem is - Ok {} -> - forEachTry! rest func! + when func!(elem) is + Ok({}) -> + for_each_try!(rest, func!) - Err err -> - Err err + Err(err) -> + Err(err) ## Build a value from the contents of a list, using an effectful function. ## ## ```roc -## now_multiples = List.walk! [1, 2, 3] [] \nums, i -> -## now = Utc.now! {} |> Utc.to_millis_since_epoch -## List.append nums (now * i) +## now_multiples = List.walk!([1, 2, 3], [], \nums, i -> +## now = Utc.now!({}) |> Utc.to_millis_since_epoch +## List.append(nums, now * i) +## ) ## ``` ## ## This is the same as [walk], except that the step function can have effects. @@ -1482,5 +1489,5 @@ walk! = \list, state, func! -> when list is [] -> state [elem, .. as rest] -> - nextState = func! state elem - walk! rest nextState func! + next_state = func!(state, elem) + walk!(rest, next_state, func!) diff --git a/crates/compiler/builtins/roc/Num.roc b/crates/compiler/builtins/roc/Num.roc index 110e4581bb8..4b85aef6cf6 100644 --- a/crates/compiler/builtins/roc/Num.roc +++ b/crates/compiler/builtins/roc/Num.roc @@ -34,132 +34,132 @@ module [ pi, tau, abs, - absDiff, + abs_diff, neg, add, sub, mul, min, max, - isLt, - isLte, - isGt, - isGte, - isApproxEq, + is_lt, + is_lte, + is_gt, + is_gte, + is_approx_eq, sin, cos, tan, atan, acos, asin, - isZero, - isEven, - isOdd, - toFrac, - isPositive, - isNegative, - isNaN, - isInfinite, - isFinite, + is_zero, + is_even, + is_odd, + to_frac, + is_positive, + is_negative, + is_nan, + is_infinite, + is_finite, rem, - remChecked, + rem_checked, div, - divChecked, + div_checked, sqrt, - sqrtChecked, + sqrt_checked, log, - logChecked, + log_checked, round, ceiling, floor, compare, pow, - powInt, - countLeadingZeroBits, - countTrailingZeroBits, - countOneBits, - addWrap, - addChecked, - addSaturated, - bitwiseAnd, - bitwiseXor, - bitwiseOr, - bitwiseNot, - shiftLeftBy, - shiftRightBy, - shiftRightZfBy, - subWrap, - subChecked, - subSaturated, - mulWrap, - mulSaturated, - mulChecked, - intCast, - divCeil, - divCeilChecked, - divTrunc, - divTruncChecked, - toStr, - isMultipleOf, - minI8, - maxI8, - minU8, - maxU8, - minI16, - maxI16, - minU16, - maxU16, - minI32, - maxI32, - minU32, - maxU32, - minI64, - maxI64, - minU64, - maxU64, - minI128, - maxI128, - minU128, - maxU128, - minF32, - maxF32, - minF64, - maxF64, - toI8, - toI8Checked, - toI16, - toI16Checked, - toI32, - toI32Checked, - toI64, - toI64Checked, - toI128, - toI128Checked, - toU8, - toU8Checked, - toU16, - toU16Checked, - toU32, - toU32Checked, - toU64, - toU64Checked, - toU128, - toU128Checked, - toF32, - toF32Checked, - toF64, - toF64Checked, - withoutDecimalPoint, - withDecimalPoint, - f32ToParts, - f64ToParts, - f32FromParts, - f64FromParts, - fromBool, - nanF32, - nanF64, - infinityF32, - infinityF64, + pow_int, + count_leading_zero_bits, + count_trailing_zero_bits, + count_one_bits, + add_wrap, + add_checked, + add_saturated, + bitwise_and, + bitwise_xor, + bitwise_or, + bitwise_not, + shift_left_by, + shift_right_by, + shift_right_zf_by, + sub_wrap, + sub_checked, + sub_saturated, + mul_wrap, + mul_saturated, + mul_checked, + int_cast, + div_ceil, + div_ceil_checked, + div_trunc, + div_trunc_checked, + to_str, + is_multiple_of, + min_i8, + max_i8, + min_u8, + max_u8, + min_i16, + max_i16, + min_u16, + max_u16, + min_i32, + max_i32, + min_u32, + max_u32, + min_i64, + max_i64, + min_u64, + max_u64, + min_i128, + max_i128, + min_u128, + max_u128, + min_f32, + max_f32, + min_f64, + max_f64, + to_i8, + to_i8_checked, + to_i16, + to_i16_checked, + to_i32, + to_i32_checked, + to_i64, + to_i64_checked, + to_i128, + to_i128_checked, + to_u8, + to_u8_checked, + to_u16, + to_u16_checked, + to_u32, + to_u32_checked, + to_u64, + to_u64_checked, + to_u128, + to_u128_checked, + to_f32, + to_f32_checked, + to_f64, + to_f64_checked, + without_decimal_point, + with_decimal_point, + f32_to_parts, + f64_to_parts, + f32_from_parts, + f64_from_parts, + from_bool, + nan_f32, + nan_f64, + infinity_f32, + infinity_f64, ] import Bool exposing [Bool] @@ -193,14 +193,14 @@ import Result exposing [Result] ## have the type `Num *` at first, but usually end up taking on ## a more specific type based on how they're used. ## -## For example, in `(1 + List.len myList)`, the `1` has the type `Num *` at first, +## For example, in `1 + List.len(myList)`, the `1` has the type `Num *` at first, ## but because `List.len` returns a `U64`, the `1` ends up changing from ## `Num *` to the more specific `U64`, and the expression as a whole ## ends up having the type `U64`. ## ## Sometimes number literals don't become more specific. For example, ## the `Num.toStr` function has the type `Num * -> Str`. This means that -## when calling `Num.toStr (5 + 6)`, the expression `(5 + 6)` +## when calling `Num.toStr(5 + 6)`, the expression `5 + 6` ## still has the type `Num *`. When this happens, `Num *` defaults to ## being an [I64] - so this addition expression would overflow ## if either 5 or 6 were replaced with a number big enough to cause @@ -209,7 +209,7 @@ import Result exposing [Result] ## If this default of [I64] is not big enough for your purposes, ## you can add an `i128` to the end of the number literal, like so: ## ```roc -## Num.toStr 5_000_000_000i128 +## Num.toStr(5_000_000_000i128) ## ``` ## This `i128` suffix specifies that you want this number literal to be ## an [I128] instead of a `Num *`. All the other numeric types have @@ -369,7 +369,7 @@ Int range : Num (Integer range) ## when a floating-point calculation encounters an error. For example: ## * Dividing a positive [F64] by `0.0` returns ∞. ## * Dividing a negative [F64] by `0.0` returns -∞. -## * Dividing a [F64] of `0.0` by `0.0` returns [*NaN*](Num.isNaN). +## * Dividing a [F64] of `0.0` by `0.0` returns [*NaN*](Num.is_nan). ## ## These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) ## floating point standard. Because almost all modern processors are built to @@ -378,7 +378,7 @@ Int range : Num (Integer range) ## access to hardware-accelerated performance, Roc follows these rules exactly. ## ## There's no literal syntax for these error values, but you can check to see if -## you ended up with one of them by using #isNaN, #isFinite, and #isInfinite. +## you ended up with one of them by using #is_nan, #is_finite, and #is_infinite. ## Whenever a function in this module could return one of these values, that ## possibility is noted in the function's documentation. ## @@ -538,24 +538,24 @@ tau = 2 * pi ## Convert a number to a [Str]. ## ## ```roc -## Num.toStr 42 +## Num.to_str(42) ## ``` ## Only [Frac] values will include a decimal point, and they will always include one. ## ```roc -## Num.toStr 4.2 -## Num.toStr 4.0 +## Num.to_str(4.2) +## Num.to_str(4.0) ## ``` -## When this function is given a non-[finite](Num.isFinite) +## When this function is given a non-[finite](Num.is_finite) ## [F64] or [F32] value, the returned string will be `"NaN"`, `"∞"`, or `"-∞"`. ## -toStr : Num * -> Str +to_str : Num * -> Str ## Convert an [Int] to a new [Int] of the expected type: ## ## ```roc ## # Casts a U8 to a U16 ## x : U16 -## x = Num.intCast 255u8 +## x = Num.int_cast(255u8) ## ``` ## ## In the case of downsizing, information is lost: @@ -563,114 +563,113 @@ toStr : Num * -> Str ## ```roc ## # returns 0, as the bits were truncated. ## x : U8 -## x = Num.intCast 256u16 +## x = Num.int_cast(256u16) ## ``` ## -intCast : Int a -> Int b +int_cast : Int a -> Int b compare : Num a, Num a -> [LT, EQ, GT] ## Returns `Bool.true` if the first number is less than the second. ## -## `a < b` is shorthand for `Num.isLt a b`. +## `a < b` is shorthand for `Num.is_lt(a, b)`. ## -## If either argument is [*NaN*](Num.isNaN), returns `Bool.false` no matter what. (*NaN* +## If either argument is [*NaN*](Num.is_nan), returns `Bool.false` no matter what. (*NaN* ## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).) ## ```roc ## 5 -## |> Num.isLt 6 +## |> Num.is_lt 6 ## ``` -isLt : Num a, Num a -> Bool +is_lt : Num a, Num a -> Bool ## Returns `Bool.true` if the first number is greater than the second. ## -## `a > b` is shorthand for `Num.isGt a b`. +## `a > b` is shorthand for `Num.is_gt a b`. ## -## If either argument is [*NaN*](Num.isNaN), returns `Bool.false` no matter what. (*NaN* +## If either argument is [*NaN*](Num.is_nan), returns `Bool.false` no matter what. (*NaN* ## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).) ## ```roc -## 6 -## |> Num.isGt 5 +## Num.is_gt(6, 5) ## ``` -isGt : Num a, Num a -> Bool +is_gt : Num a, Num a -> Bool ## Returns `Bool.true` if the first number is less than or equal to the second. ## -## `a <= b` is shorthand for `Num.isLte a b`. +## `a <= b` is shorthand for `Num.is_lte(a, b)`. ## -## If either argument is [*NaN*](Num.isNaN), returns `Bool.false` no matter what. (*NaN* +## If either argument is [*NaN*](Num.is_nan), returns `Bool.false` no matter what. (*NaN* ## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).) -isLte : Num a, Num a -> Bool +is_lte : Num a, Num a -> Bool ## Returns `Bool.true` if the first number is greater than or equal to the second. ## -## `a >= b` is shorthand for `Num.isGte a b`. +## `a >= b` is shorthand for `Num.is_gte(a, b)`. ## -## If either argument is [*NaN*](Num.isNaN), returns `Bool.false` no matter what. (*NaN* +## If either argument is [*NaN*](Num.is_nan), returns `Bool.false` no matter what. (*NaN* ## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).) -isGte : Num a, Num a -> Bool +is_gte : Num a, Num a -> Bool ## Returns `Bool.true` if the first number and second number are within a specific threshold ## ## A specific relative and absolute tolerance can be provided to change the threshold ## -## This function is symmetric: `Num.isApproxEq a b == Num.isApproxEq b a` +## This function is symmetric: `Num.is_approx_eq(a, b) == Num.is_approx_eq(b, a)` ## -## If either argument is [*NaN*](Num.isNaN), returns `Bool.false` no matter what. (*NaN* +## If either argument is [*NaN*](Num.is_nan), returns `Bool.false` no matter what. (*NaN* ## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).) -isApproxEq : Frac a, Frac a, { rtol ? Frac a, atol ? Frac a } -> Bool -isApproxEq = \x, y, { rtol ? 0.00001, atol ? 0.00000001 } -> +is_approx_eq : Frac a, Frac a, { rtol ? Frac a, atol ? Frac a } -> Bool +is_approx_eq = \x, y, { rtol ? 0.00001, atol ? 0.00000001 } -> eq = x <= y && x >= y - meetsTolerance = Num.absDiff x y <= Num.max atol (rtol * Num.max (Num.abs x) (Num.abs y)) - eq || meetsTolerance + meets_tolerance = Num.abs_diff(x, y) <= Num.max(atol, (rtol * Num.max(Num.abs(x), Num.abs(y)))) + eq || meets_tolerance ## Returns `Bool.true` if the number is `0`, and `Bool.false` otherwise. -isZero : Num a -> Bool +is_zero : Num a -> Bool ## A number is even if dividing it by 2 gives a remainder of 0. ## ## Examples of even numbers: 0, 2, 4, 6, 8, -2, -4, -6, -8 -isEven : Int a -> Bool -isEven = \x -> Num.isMultipleOf x 2 +is_even : Int a -> Bool +is_even = \x -> Num.is_multiple_of(x, 2) ## A number is odd if dividing it by 2 gives a remainder of 1. ## ## Examples of odd numbers: 1, 3, 5, 7, -1, -3, -5, -7 -isOdd : Int a -> Bool -isOdd = \x -> Bool.not (Num.isMultipleOf x 2) +is_odd : Int a -> Bool +is_odd = \x -> Bool.not(Num.is_multiple_of(x, 2)) ## Positive numbers are greater than `0`. -isPositive : Num a -> Bool -isPositive = \x -> x > 0 +is_positive : Num a -> Bool +is_positive = \x -> x > 0 ## Negative numbers are less than `0`. -isNegative : Num a -> Bool -isNegative = \x -> x < 0 +is_negative : Num a -> Bool +is_negative = \x -> x < 0 -toFrac : Num * -> Frac * +to_frac : Num * -> Frac * ## Returns `Bool.true` if the [Frac] is not a number as defined by [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) ## ## ```roc -## Num.isNaN (0 / 0) +## Num.is_nan(0 / 0) ## ``` -isNaN : Frac * -> Bool +is_nan : Frac * -> Bool ## Returns `Bool.true` if the [Frac] is positive or negative infinity as defined by [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) ## ## ```roc -## Num.isInfinite (1 / 0) +## Num.is_infinite(1 / 0) ## -## Num.isInfinite (-1 / 0) +## Num.is_infinite(-1 / 0) ## ``` -isInfinite : Frac * -> Bool +is_infinite : Frac * -> Bool ## Returns `Bool.true` if the [Frac] is not an infinity as defined by [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) ## ## ```roc -## Num.isFinite 42 +## Num.is_finite(42) ## ``` -isFinite : Frac * -> Bool +is_finite : Frac * -> Bool ## Returns the absolute value of the number. ## @@ -678,17 +677,17 @@ isFinite : Frac * -> Bool ## * For a negative number, returns the same number except positive. ## * For zero, returns zero. ## ```roc -## Num.abs 4 +## Num.abs(4) ## -## Num.abs -2.5 +## Num.abs(-2.5) ## -## Num.abs 0 +## Num.abs(0) ## -## Num.abs 0.0 +## Num.abs(0.0) ## ``` ## This is safe to use with any [Frac], but it can cause overflow when used with certain [Int] values. ## -## For example, calling #Num.abs on the lowest value of a signed integer (such as [Num.minI64] or [Num.minI32]) will cause overflow. +## For example, calling #Num.abs on the lowest value of a signed integer (such as [Num.min_i64] or [Num.min_i32]) will cause overflow. ## This is because, for any given size of signed integer (32-bit, 64-bit, etc.) its negated lowest value turns out to be 1 higher than ## the highest value it can represent. (For this reason, calling [Num.neg] on the lowest signed value will also cause overflow.) ## @@ -698,19 +697,19 @@ abs : Num a -> Num a ## Returns the absolute difference between two numbers. ## ## ```roc -## Num.absDiff 5 3 +## Num.abs_diff(5, 3) ## -## Num.absDiff -3 5 +## Num.abs_diff(-3, 5) ## -## Num.absDiff 3.0 5.0 +## Num.abs_diff(3.0, 5.0) ## ``` ## ## If the answer to this operation can't fit in the return value (e.g. an ## [I8] answer that's higher than 127 or lower than -128), the result is an ## *overflow*. For [F64] and [F32], overflow results in an answer of either ## ∞ or -∞. For all other number types, overflow results in a panic. -absDiff : Num a, Num a -> Num a -absDiff = \a, b -> +abs_diff : Num a, Num a -> Num a +abs_diff = \a, b -> if a > b then a - b else @@ -718,20 +717,20 @@ absDiff = \a, b -> ## Returns a negative number when given a positive one, and vice versa. ## ```roc -## Num.neg 5 +## Num.neg(5) ## -## Num.neg -2.5 +## Num.neg(-2.5) ## -## Num.neg 0 +## Num.neg(0) ## -## Num.neg 0.0 +## Num.neg(0.0) ## ``` ## !! Num.neg is not completely implemented for all types in all contexts, see github.com/roc-lang/roc/issues/6959 ## You can use `\someNum -> 0 - someNum` as a workaround. ## ## This is safe to use with any [Frac], but it can cause overflow when used with certain [Int] values. ## -## For example, calling #Num.neg on the lowest value of a signed integer (such as [Num.minI64] or [Num.minI32]) will cause overflow. +## For example, calling #Num.neg on the lowest value of a signed integer (such as [Num.min_i64] or [Num.min_i32]) will cause overflow. ## This is because, for any given size of signed integer (32-bit, 64-bit, etc.) its negated lowest value turns out to be 1 higher than ## the highest value it can represent. (For this reason, calling #Num.abs on the lowest signed value will also cause overflow.) ## @@ -744,16 +743,16 @@ neg : Num a -> Num a ## ## (To add an [Int] and a [Frac], first convert one so that they both have the same type. There are functions in this module that can convert both [Int] to [Frac] and the other way around.) ## -## `a + b` is shorthand for `Num.add a b`. +## `a + b` is shorthand for `Num.add(a, b)`. ## ```roc ## 5 + 7 ## -## Num.add 5 7 +## Num.add(5, 7) ## ``` ## `Num.add` can be convenient in pipelines. ## ```roc ## Frac.pi -## |> Num.add 1.0 +## |> Num.add(1.0) ## ``` ## If the answer to this operation can't fit in the return value (e.g. an ## [I8] answer that's higher than 127 or lower than -128), the result is an @@ -765,16 +764,16 @@ add : Num a, Num a -> Num a ## ## (To subtract an [Int] and a [Frac], first convert one so that they both have the same type. There are functions in this module that can convert both [Int] to [Frac] and the other way around.) ## -## `a - b` is shorthand for `Num.sub a b`. +## `a - b` is shorthand for `Num.sub(a, b)`. ## ```roc ## 7 - 5 ## -## Num.sub 7 5 +## Num.sub(7, 5) ## ``` ## `Num.sub` can be convenient in pipelines. ## ```roc ## Frac.pi -## |> Num.sub 2.0 +## |> Num.sub(2.0) ## ``` ## If the answer to this operation can't fit in the return value (e.g. an ## [I8] answer that's higher than 127 or lower than -128), the result is an @@ -786,18 +785,18 @@ sub : Num a, Num a -> Num a ## ## (To multiply an [Int] and a [Frac], first convert one so that they both have the same type. There are functions in this module that can convert both [Int] to [Frac] and the other way around.) ## -## `a * b` is shorthand for `Num.mul a b`. +## `a * b` is shorthand for `Num.mul(a, b)`. ## ```roc ## 5 * 7 ## -## Num.mul 5 7 +## Num.mul(5, 7) ## ``` ## ## `Num.mul` can be convenient in pipelines. ## ## ```roc ## Frac.pi -## |> Num.mul 2.0 +## |> Num.mul(2.0) ## ``` ## If the answer to this operation can't fit in the return value (e.g. an ## [I8] answer that's higher than 127 or lower than -128), the result is an @@ -808,9 +807,9 @@ mul : Num a, Num a -> Num a ## Obtains the smaller between two numbers of the same type. ## ## ```roc -## Num.min 100 0 +## Num.min(100, 0) ## -## Num.min 3.0 -3.0 +## Num.min(3.0, -3.0) ## ``` min : Num a, Num a -> Num a min = \a, b -> @@ -822,9 +821,9 @@ min = \a, b -> ## Obtains the greater between two numbers of the same type. ## ## ```roc -## Num.max 100 0 +## Num.max(100, 0) ## -## Num.max 3.0 -3.0 +## Num.max(3.0, -3.0) ## ``` max : Num a, Num a -> Num a max = \a, b -> @@ -848,8 +847,8 @@ atan : Frac a -> Frac a ## function a negative number! Calling [sqrt] on a negative [Dec] will cause a panic. ## ## Calling [sqrt] on [F32] and [F64] values follows these rules: -## * Passing a negative [F64] or [F32] returns [*NaN*](Num.isNaN). -## * Passing [*NaN*](Num.isNaN) or -∞ also returns [*NaN*](Num.isNaN). +## * Passing a negative [F64] or [F32] returns [*NaN*](Num.is_nan). +## * Passing [*NaN*](Num.is_nan) or -∞ also returns [*NaN*](Num.is_nan). ## * Passing ∞ returns ∞. ## ## > These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) @@ -858,36 +857,36 @@ atan : Frac a -> Frac a ## > cost! Since the most common reason to choose [F64] or [F32] over [Dec] is ## > access to hardware-accelerated performance, Roc follows these rules exactly. ## ```roc -## Num.sqrt 4.0 +## Num.sqrt(4.0) ## -## Num.sqrt 1.5 +## Num.sqrt(1.5) ## -## Num.sqrt 0.0 +## Num.sqrt(0.0) ## -## Num.sqrt -4.0f64 +## Num.sqrt(-4.0f64) ## ``` sqrt : Frac a -> Frac a -sqrtChecked : Frac a -> Result (Frac a) [SqrtOfNegative] -sqrtChecked = \x -> +sqrt_checked : Frac a -> Result (Frac a) [SqrtOfNegative] +sqrt_checked = \x -> if x < 0.0 then - Err SqrtOfNegative + Err(SqrtOfNegative) else - Ok (Num.sqrt x) + Ok(Num.sqrt(x)) ## Natural logarithm log : Frac a -> Frac a -logChecked : Frac a -> Result (Frac a) [LogNeedsPositive] -logChecked = \x -> +log_checked : Frac a -> Result (Frac a) [LogNeedsPositive] +log_checked = \x -> if x <= 0.0 then - Err LogNeedsPositive + Err(LogNeedsPositive) else - Ok (Num.log x) + Ok(Num.log(x)) ## Divides one [Frac] by another. ## -## `a / b` is shorthand for `Num.div a b`. +## `a / b` is shorthand for `Num.div(a, b)`. ## ## [Division by zero is undefined in mathematics](https://en.wikipedia.org/wiki/Division_by_zero). ## As such, you should make sure never to pass zero as the denominator to this function! @@ -896,7 +895,7 @@ logChecked = \x -> ## Calling [div] on [F32] and [F64] values follows these rules: ## * Dividing a positive [F64] or [F32] by zero returns ∞. ## * Dividing a negative [F64] or [F32] by zero returns -∞. -## * Dividing a zero [F64] or [F32] by zero returns [*NaN*](Num.isNaN). +## * Dividing a zero [F64] or [F32] by zero returns [*NaN*](Num.is_nan). ## ## > These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) ## > floating point standard. Because almost all modern processors are built to @@ -909,34 +908,34 @@ logChecked = \x -> ## ```roc ## 5.0 / 7.0 ## -## Num.div 5 7 +## Num.div(5, 7) ## ``` ## `Num.div` can be convenient in pipelines. ## ```roc ## Num.pi -## |> Num.div 2.0 +## |> Num.div (2.0) ## ``` div : Frac a, Frac a -> Frac a -divChecked : Frac a, Frac a -> Result (Frac a) [DivByZero] -divChecked = \a, b -> - if Num.isZero b then - Err DivByZero +div_checked : Frac a, Frac a -> Result (Frac a) [DivByZero] +div_checked = \a, b -> + if Num.is_zero(b) then + Err(DivByZero) else - Ok (Num.div a b) + Ok(Num.div(a, b)) -divCeil : Int a, Int a -> Int a +div_ceil : Int a, Int a -> Int a -divCeilChecked : Int a, Int a -> Result (Int a) [DivByZero] -divCeilChecked = \a, b -> - if Num.isZero b then - Err DivByZero +div_ceil_checked : Int a, Int a -> Result (Int a) [DivByZero] +div_ceil_checked = \a, b -> + if Num.is_zero(b) then + Err(DivByZero) else - Ok (Num.divCeil a b) + Ok(Num.div_ceil(a, b)) ## Divides two integers, truncating the result towards zero. ## -## `a // b` is shorthand for `Num.divTrunc a b`. +## `a // b` is shorthand for `Num.div_trunc(a, b)`. ## ## Division by zero is undefined in mathematics. As such, you should make ## sure never to pass zero as the denominator to this function! If you do, @@ -944,117 +943,117 @@ divCeilChecked = \a, b -> ## ```roc ## 5 // 7 ## -## Num.divTrunc 5 7 +## Num.div_trunc(5, 7) ## ## 8 // -3 ## -## Num.divTrunc 8 -3 +## Num.div_trunc(8, -3) ## ``` -divTrunc : Int a, Int a -> Int a -divTrunc = \a, b -> - if Num.isZero b then - crash "Integer division by 0!" +div_trunc : Int a, Int a -> Int a +div_trunc = \a, b -> + if Num.is_zero(b) then + crash("Integer division by 0!") else - Num.divTruncUnchecked a b + Num.div_trunc_unchecked(a, b) -divTruncChecked : Int a, Int a -> Result (Int a) [DivByZero] -divTruncChecked = \a, b -> - if Num.isZero b then - Err DivByZero +div_trunc_checked : Int a, Int a -> Result (Int a) [DivByZero] +div_trunc_checked = \a, b -> + if Num.is_zero(b) then + Err(DivByZero) else - Ok (Num.divTruncUnchecked a b) + Ok(Num.div_trunc_unchecked(a, b)) ## traps (hardware fault) when given zero as the second argument. -divTruncUnchecked : Int a, Int a -> Int a +div_trunc_unchecked : Int a, Int a -> Int a ## Obtains the remainder (truncating modulo) from the division of two integers. ## -## `a % b` is shorthand for `Num.rem a b`. +## `a % b` is shorthand for `Num.rem(a, b)`. ## ```roc ## 5 % 7 ## -## Num.rem 5 7 +## Num.rem(5, 7) ## ## -8 % -3 ## -## Num.rem -8 -3 +## Num.rem(-8, -3) ## ``` rem : Int a, Int a -> Int a rem = \a, b -> - if Num.isZero b then - crash "Integer division by 0!" + if Num.is_zero(b) then + crash("Integer division by 0!") else - Num.remUnchecked a b + Num.rem_unchecked(a, b) -remChecked : Int a, Int a -> Result (Int a) [DivByZero] -remChecked = \a, b -> - if Num.isZero b then - Err DivByZero +rem_checked : Int a, Int a -> Result (Int a) [DivByZero] +rem_checked = \a, b -> + if Num.is_zero(b) then + Err(DivByZero) else - Ok (Num.remUnchecked a b) + Ok(Num.rem_unchecked(a, b)) ## traps (hardware fault) when given zero as the second argument. -remUnchecked : Int a, Int a -> Int a +rem_unchecked : Int a, Int a -> Int a -isMultipleOf : Int a, Int a -> Bool +is_multiple_of : Int a, Int a -> Bool ## Does a "bitwise and". Each bit of the output is 1 if the corresponding bit ## of x AND of y is 1, otherwise it's 0. -bitwiseAnd : Int a, Int a -> Int a +bitwise_and : Int a, Int a -> Int a ## Does a "bitwise exclusive or". Each bit of the output is the same as the ## corresponding bit in x if that bit in y is 0, and it's the complement of ## the bit in x if that bit in y is 1. -bitwiseXor : Int a, Int a -> Int a +bitwise_xor : Int a, Int a -> Int a ## Does a "bitwise or". Each bit of the output is 0 if the corresponding bit ## of x OR of y is 0, otherwise it's 1. -bitwiseOr : Int a, Int a -> Int a +bitwise_or : Int a, Int a -> Int a ## Returns the complement of x - the number you get by switching each 1 for a ## 0 and each 0 for a 1. This is the same as -x - 1. -bitwiseNot : Int a -> Int a -bitwiseNot = \n -> - bitwiseXor n (subWrap 0 1) +bitwise_not : Int a -> Int a +bitwise_not = \n -> + bitwise_xor(n, sub_wrap(0, 1)) ## Bitwise left shift of a number by another ## ## The least significant bits always become 0. This means that shifting left is ## like multiplying by factors of two for unsigned integers. ## ```roc -## shiftLeftBy 0b0000_0011 2 == 0b0000_1100 +## shift_left_by(0b0000_0011, 2) == 0b0000_1100 ## -## 0b0000_0101 |> shiftLeftBy 2 == 0b0001_0100 +## 0b0000_0101 |> shift_left_by(2) == 0b0001_0100 ## ``` -## In some languages `shiftLeftBy` is implemented as a binary operator `<<`. -shiftLeftBy : Int a, U8 -> Int a +## In some languages `shift_left_by` is implemented as a binary operator `<<`. +shift_left_by : Int a, U8 -> Int a ## Bitwise arithmetic shift of a number by another ## ## The most significant bits are copied from the current. ## ```roc -## shiftRightBy 0b0000_1100 2 == 0b0000_0011 +## shift_right_by(0b0000_1100, 2) == 0b0000_0011 ## -## 0b0001_0100 |> shiftRightBy 2 == 0b0000_0101 +## 0b0001_0100 |> shift_right_by(2) == 0b0000_0101 ## -## 0b1001_0000 |> shiftRightBy 2 == 0b1110_0100 +## 0b1001_0000 |> shift_right_by(2) == 0b1110_0100 ## ``` -## In some languages `shiftRightBy` is implemented as a binary operator `>>>`. -shiftRightBy : Int a, U8 -> Int a +## In some languages `shift_right_by` is implemented as a binary operator `>>>`. +shift_right_by : Int a, U8 -> Int a ## Bitwise logical right shift of a number by another ## ## The most significant bits always become 0. This means that shifting right is ## like dividing by factors of two for unsigned integers. ## ```roc -## shiftRightZfBy 0b0010_1000 2 == 0b0000_1010 +## shift_right_zf_by(0b0010_1000, 2) == 0b0000_1010 ## -## 0b0010_1000 |> shiftRightZfBy 2 == 0b0000_1010 +## 0b0010_1000 |> shift_right_zf_by(2) == 0b0000_1010 ## -## 0b1001_0000 |> shiftRightZfBy 2 == 0b0010_0100 +## 0b1001_0000 |> shift_right_zf_by(2) == 0b0010_0100 ## ``` -## In some languages `shiftRightZfBy` is implemented as a binary operator `>>`. -shiftRightZfBy : Int a, U8 -> Int a +## In some languages `shift_right_zf_by` is implemented as a binary operator `>>`. +shift_right_zf_by : Int a, U8 -> Int a ## Round off the given fraction to the nearest integer. round : Frac * -> Int * @@ -1078,48 +1077,48 @@ pow : Frac a, Frac a -> Frac a ## ## It is very easy for this function to produce an answer ## so large it causes an overflow. -powInt : Int a, Int a -> Int a +pow_int : Int a, Int a -> Int a ## Counts the number of most-significant (leading in a big-Endian sense) zeroes in an integer. ## ## ```roc -## Num.countLeadingZeroBits 0b0001_1100u8 +## Num.count_leading_zero_bits(0b0001_1100u8) ## ## 3 ## -## Num.countLeadingZeroBits 0b0000_0000u8 +## Num.count_leading_zero_bits(0b0000_0000u8) ## ## 8 ## ``` -countLeadingZeroBits : Int a -> U8 +count_leading_zero_bits : Int a -> U8 ## Counts the number of least-significant (trailing in a big-Endian sense) zeroes in an integer. ## ## ```roc -## Num.countTrailingZeroBits 0b0001_1100u8 +## Num.count_trailing_zero_bits(0b0001_1100u8) ## ## 2 ## -## Num.countTrailingZeroBits 0b0000_0000u8 +## Num.count_trailing_zero_bits(0b0000_0000u8) ## ## 8 ## ``` -countTrailingZeroBits : Int a -> U8 +count_trailing_zero_bits : Int a -> U8 ## Counts the number of set bits in an integer. ## ## ```roc -## Num.countOneBits 0b0001_1100u8 +## Num.count_one_bits(0b0001_1100u8) ## ## 3 ## -## Num.countOneBits 0b0000_0000u8 +## Num.count_one_bits(0b0000_0000u8) ## ## 0 ## ``` -countOneBits : Int a -> U8 +count_one_bits : Int a -> U8 -addWrap : Int range, Int range -> Int range +add_wrap : Int range, Int range -> Int range ## Adds two numbers, clamping on the maximum representable number rather than ## overflowing. @@ -1128,72 +1127,72 @@ addWrap : Int range, Int range -> Int range ## addition is to overflow. ## For example, if `x : U8` is 200 and `y : U8` is 100, `addSaturated x y` will ## yield 255, the maximum value of a `U8`. -addSaturated : Num a, Num a -> Num a +add_saturated : Num a, Num a -> Num a ## Adds two numbers and checks for overflow. ## ## This is the same as [Num.add] except if the operation overflows, instead of ## panicking or returning ∞ or -∞, it will return `Err Overflow`. -addChecked : Num a, Num a -> Result (Num a) [Overflow] -addChecked = \a, b -> - result = addCheckedLowlevel a b +add_checked : Num a, Num a -> Result (Num a) [Overflow] +add_checked = \a, b -> + result = add_checked_lowlevel(a, b) if result.b then - Err Overflow + Err(Overflow) else - Ok result.a + Ok(result.a) -addCheckedLowlevel : Num a, Num a -> { b : Bool, a : Num a } +add_checked_lowlevel : Num a, Num a -> { b : Bool, a : Num a } -subWrap : Int range, Int range -> Int range +sub_wrap : Int range, Int range -> Int range ## Subtracts two numbers, clamping on the minimum representable number rather ## than overflowing. ## ## This is the same as [Num.sub] except for the saturating behavior if the ## subtraction is to overflow. -## For example, if `x : U8` is 10 and `y : U8` is 20, `subSaturated x y` will +## For example, if `x : U8` is 10 and `y : U8` is 20, `sub_saturated x y` will ## yield 0, the minimum value of a `U8`. -subSaturated : Num a, Num a -> Num a +sub_saturated : Num a, Num a -> Num a ## Subtracts two numbers and checks for overflow. ## ## This is the same as [Num.sub] except if the operation overflows, instead of ## panicking or returning ∞ or -∞, it will return `Err Overflow`. -subChecked : Num a, Num a -> Result (Num a) [Overflow] -subChecked = \a, b -> - result = subCheckedLowlevel a b +sub_checked : Num a, Num a -> Result (Num a) [Overflow] +sub_checked = \a, b -> + result = sub_checked_lowlevel(a, b) if result.b then - Err Overflow + Err(Overflow) else - Ok result.a + Ok(result.a) -subCheckedLowlevel : Num a, Num a -> { b : Bool, a : Num a } +sub_checked_lowlevel : Num a, Num a -> { b : Bool, a : Num a } -mulWrap : Int range, Int range -> Int range +mul_wrap : Int range, Int range -> Int range ## Multiplies two numbers, clamping on the maximum representable number rather than ## overflowing. ## ## This is the same as [Num.mul] except for the saturating behavior if the ## addition is to overflow. -mulSaturated : Num a, Num a -> Num a +mul_saturated : Num a, Num a -> Num a ## Multiplies two numbers and checks for overflow. ## ## This is the same as [Num.mul] except if the operation overflows, instead of ## panicking or returning ∞ or -∞, it will return `Err Overflow`. -mulChecked : Num a, Num a -> Result (Num a) [Overflow] -mulChecked = \a, b -> - result = mulCheckedLowlevel a b +mul_checked : Num a, Num a -> Result (Num a) [Overflow] +mul_checked = \a, b -> + result = mul_checked_lowlevel(a, b) if result.b then - Err Overflow + Err(Overflow) else - Ok result.a + Ok(result.a) -mulCheckedLowlevel : Num a, Num a -> { b : Bool, a : Num a } +mul_checked_lowlevel : Num a, Num a -> { b : Bool, a : Num a } ## Returns the lowest number that can be stored in an [I8] without underflowing ## its available memory and crashing. @@ -1201,19 +1200,19 @@ mulCheckedLowlevel : Num a, Num a -> { b : Bool, a : Num a } ## For reference, this number is `-128`. ## ## Note that the positive version of this number is larger than [Num.maxI8], -## which means if you call [Num.abs] on [Num.minI8], it will overflow and crash! -minI8 : I8 -minI8 = -128i8 +## which means if you call [Num.abs] on [Num.min_i8], it will overflow and crash! +min_i8 : I8 +min_i8 = -128i8 ## Returns the highest number that can be stored in an [I8] without overflowing ## its available memory and crashing. ## ## For reference, this number is `127`. ## -## Note that this is smaller than the positive version of [Num.minI8], -## which means if you call [Num.abs] on [Num.minI8], it will overflow and crash! -maxI8 : I8 -maxI8 = 127i8 +## Note that this is smaller than the positive version of [Num.min_i8], +## which means if you call [Num.abs] on [Num.min_i8], it will overflow and crash! +max_i8 : I8 +max_i8 = 127i8 ## Returns the lowest number that can be stored in a [U8] without underflowing ## its available memory and crashing. @@ -1222,15 +1221,15 @@ maxI8 = 127i8 ## [unsigned](https://en.wikipedia.org/wiki/Signed_number_representations), ## and zero is the lowest unsigned number. ## Unsigned numbers cannot be negative. -minU8 : U8 -minU8 = 0u8 +min_u8 : U8 +min_u8 = 0u8 ## Returns the highest number that can be stored in a [U8] without overflowing ## its available memory and crashing. ## ## For reference, this number is `255`. -maxU8 : U8 -maxU8 = 255u8 +max_u8 : U8 +max_u8 = 255u8 ## Returns the lowest number that can be stored in an [I16] without underflowing ## its available memory and crashing. @@ -1238,19 +1237,19 @@ maxU8 = 255u8 ## For reference, this number is `-32_768`. ## ## Note that the positive version of this number is larger than [Num.maxI16], -## which means if you call [Num.abs] on [Num.minI16], it will overflow and crash! -minI16 : I16 -minI16 = -32768i16 +## which means if you call [Num.abs] on [Num.min_i16], it will overflow and crash! +min_i16 : I16 +min_i16 = -32768i16 ## Returns the highest number that can be stored in an [I16] without overflowing ## its available memory and crashing. ## ## For reference, this number is `32_767`. ## -## Note that this is smaller than the positive version of [Num.minI16], -## which means if you call [Num.abs] on [Num.minI16], it will overflow and crash! -maxI16 : I16 -maxI16 = 32767i16 +## Note that this is smaller than the positive version of [Num.min_i16], +## which means if you call [Num.abs] on [Num.min_i16], it will overflow and crash! +max_i16 : I16 +max_i16 = 32767i16 ## Returns the lowest number that can be stored in a [U16] without underflowing ## its available memory and crashing. @@ -1259,15 +1258,15 @@ maxI16 = 32767i16 ## [unsigned](https://en.wikipedia.org/wiki/Signed_number_representations), ## and zero is the lowest unsigned number. ## Unsigned numbers cannot be negative. -minU16 : U16 -minU16 = 0u16 +min_u16 : U16 +min_u16 = 0u16 ## Returns the highest number that can be stored in a [U16] without overflowing ## its available memory and crashing. ## ## For reference, this number is `65_535`. -maxU16 : U16 -maxU16 = 65535u16 +max_u16 : U16 +max_u16 = 65535u16 ## Returns the lowest number that can be stored in an [I32] without underflowing ## its available memory and crashing. @@ -1275,9 +1274,9 @@ maxU16 = 65535u16 ## For reference, this number is `-2_147_483_648`. ## ## Note that the positive version of this number is larger than [Num.maxI32], -## which means if you call [Num.abs] on [Num.minI32], it will overflow and crash! -minI32 : I32 -minI32 = -2147483648 +## which means if you call [Num.abs] on [Num.min_i32], it will overflow and crash! +min_i32 : I32 +min_i32 = -2147483648 ## Returns the highest number that can be stored in an [I32] without overflowing ## its available memory and crashing. @@ -1285,10 +1284,10 @@ minI32 = -2147483648 ## For reference, this number is `2_147_483_647`, ## which is over 2 million. ## -## Note that this is smaller than the positive version of [Num.minI32], -## which means if you call [Num.abs] on [Num.minI32], it will overflow and crash! -maxI32 : I32 -maxI32 = 2147483647 +## Note that this is smaller than the positive version of [Num.min_i32], +## which means if you call [Num.abs] on [Num.min_i32], it will overflow and crash! +max_i32 : I32 +max_i32 = 2147483647 ## Returns the lowest number that can be stored in a [U32] without underflowing ## its available memory and crashing. @@ -1297,15 +1296,15 @@ maxI32 = 2147483647 ## [unsigned](https://en.wikipedia.org/wiki/Signed_number_representations), ## and zero is the lowest unsigned number. ## Unsigned numbers cannot be negative. -minU32 : U32 -minU32 = 0 +min_u32 : U32 +min_u32 = 0 ## Returns the highest number that can be stored in a [U32] without overflowing ## its available memory and crashing. ## ## For reference, this number is `4_294_967_295`. -maxU32 : U32 -maxU32 = 4294967295 +max_u32 : U32 +max_u32 = 4294967295 ## Returns the lowest number that can be stored in an [I64] without underflowing ## its available memory and crashing. @@ -1314,9 +1313,9 @@ maxU32 = 4294967295 ## which is under 9 quintillion. ## ## Note that the positive version of this number is larger than [Num.maxI64], -## which means if you call [Num.abs] on [Num.minI64], it will overflow and crash! -minI64 : I64 -minI64 = -9223372036854775808 +## which means if you call [Num.abs] on [Num.min_i64], it will overflow and crash! +min_i64 : I64 +min_i64 = -9223372036854775808 ## Returns the highest number that can be stored in an [I64] without overflowing ## its available memory and crashing. @@ -1324,10 +1323,10 @@ minI64 = -9223372036854775808 ## For reference, this number is `9_223_372_036_854_775_807`, ## which is over 9 quintillion. ## -## Note that this is smaller than the positive version of [Num.minI64], -## which means if you call [Num.abs] on [Num.minI64], it will overflow and crash! -maxI64 : I64 -maxI64 = 9223372036854775807 +## Note that this is smaller than the positive version of [Num.min_i64], +## which means if you call [Num.abs] on [Num.min_i64], it will overflow and crash! +max_i64 : I64 +max_i64 = 9223372036854775807 ## Returns the lowest number that can be stored in a [U64] without underflowing ## its available memory and crashing. @@ -1336,16 +1335,16 @@ maxI64 = 9223372036854775807 ## [unsigned](https://en.wikipedia.org/wiki/Signed_number_representations), ## and zero is the lowest unsigned number. ## Unsigned numbers cannot be negative. -minU64 : U64 -minU64 = 0 +min_u64 : U64 +min_u64 = 0 ## Returns the highest number that can be stored in a [U64] without overflowing ## its available memory and crashing. ## ## For reference, this number is `18_446_744_073_709_551_615`, ## which is over 18 quintillion. -maxU64 : U64 -maxU64 = 18446744073709551615 +max_u64 : U64 +max_u64 = 18446744073709551615 ## Returns the lowest number that can be stored in an [I128] without underflowing ## its available memory and crashing. @@ -1354,9 +1353,9 @@ maxU64 = 18446744073709551615 ## which is under 170 undecillion. ## ## Note that the positive version of this number is larger than [Num.maxI128], -## which means if you call [Num.abs] on [Num.minI128], it will overflow and crash! -minI128 : I128 -minI128 = -170141183460469231731687303715884105728 +## which means if you call [Num.abs] on [Num.min_i128], it will overflow and crash! +min_i128 : I128 +min_i128 = -170141183460469231731687303715884105728 ## Returns the highest number that can be stored in an [I128] without overflowing ## its available memory and crashing. @@ -1364,10 +1363,10 @@ minI128 = -170141183460469231731687303715884105728 ## For reference, this number is `170_141_183_460_469_231_731_687_303_715_884_105_727`, ## which is over 170 undecillion. ## -## Note that this is smaller than the positive version of [Num.minI128], -## which means if you call [Num.abs] on [Num.minI128], it will overflow and crash! -maxI128 : I128 -maxI128 = 170141183460469231731687303715884105727 +## Note that this is smaller than the positive version of [Num.min_i128], +## which means if you call [Num.abs] on [Num.min_i128], it will overflow and crash! +max_i128 : I128 +max_i128 = 170141183460469231731687303715884105727 ## Returns the lowest number that can be stored in a [U128] without underflowing ## its available memory and crashing. @@ -1376,114 +1375,114 @@ maxI128 = 170141183460469231731687303715884105727 ## [unsigned](https://en.wikipedia.org/wiki/Signed_number_representations), ## and zero is the lowest unsigned number. ## Unsigned numbers cannot be negative. -minU128 : U128 -minU128 = 0 +min_u128 : U128 +min_u128 = 0 ## Returns the highest number that can be stored in a [U128] without overflowing ## its available memory and crashing. ## ## For reference, this number is `340_282_366_920_938_463_463_374_607_431_768_211_455`, ## which is over 340 undecillion. -maxU128 : U128 -maxU128 = 340282366920938463463374607431768211455 +max_u128 : U128 +max_u128 = 340282366920938463463374607431768211455 -minF32 : F32 -minF32 = -3.40282347e38 +min_f32 : F32 +min_f32 = -3.40282347e38 -maxF32 : F32 -maxF32 = 3.40282347e38 +max_f32 : F32 +max_f32 = 3.40282347e38 -minF64 : F64 -minF64 = -1.7976931348623157e308 +min_f64 : F64 +min_f64 = -1.7976931348623157e308 -maxF64 : F64 -maxF64 = 1.7976931348623157e308 +max_f64 : F64 +max_f64 = 1.7976931348623157e308 ## Converts an [Int] to an [I8]. If the given number can't be precisely represented in an [I8], ## the returned number may be different from the given number. -toI8 : Int * -> I8 -toI16 : Int * -> I16 -toI32 : Int * -> I32 -toI64 : Int * -> I64 -toI128 : Int * -> I128 -toU8 : Int * -> U8 -toU16 : Int * -> U16 -toU32 : Int * -> U32 -toU64 : Int * -> U64 -toU128 : Int * -> U128 +to_i8 : Int * -> I8 +to_i16 : Int * -> I16 +to_i32 : Int * -> I32 +to_i64 : Int * -> I64 +to_i128 : Int * -> I128 +to_u8 : Int * -> U8 +to_u16 : Int * -> U16 +to_u32 : Int * -> U32 +to_u64 : Int * -> U64 +to_u128 : Int * -> U128 ## Converts a [Num] to an [F32]. If the given number can't be precisely represented in an [F32], ## the returned number may be different from the given number. -toF32 : Num * -> F32 +to_f32 : Num * -> F32 ## Converts a [Num] to an [F64]. If the given number can't be precisely represented in an [F64], ## the returned number may be different from the given number. -toF64 : Num * -> F64 +to_f64 : Num * -> F64 ## Converts a [Int] to an [I8]. ## If the given integer can't be precisely represented in an [I8], returns ## `Err OutOfBounds`. -toI8Checked : Int * -> Result I8 [OutOfBounds] -toI16Checked : Int * -> Result I16 [OutOfBounds] -toI32Checked : Int * -> Result I32 [OutOfBounds] -toI64Checked : Int * -> Result I64 [OutOfBounds] -toI128Checked : Int * -> Result I128 [OutOfBounds] -toU8Checked : Int * -> Result U8 [OutOfBounds] -toU16Checked : Int * -> Result U16 [OutOfBounds] -toU32Checked : Int * -> Result U32 [OutOfBounds] -toU64Checked : Int * -> Result U64 [OutOfBounds] -toU128Checked : Int * -> Result U128 [OutOfBounds] -toF32Checked : Num * -> Result F32 [OutOfBounds] -toF64Checked : Num * -> Result F64 [OutOfBounds] +to_i8_checked : Int * -> Result I8 [OutOfBounds] +to_i16_checked : Int * -> Result I16 [OutOfBounds] +to_i32_checked : Int * -> Result I32 [OutOfBounds] +to_i64_checked : Int * -> Result I64 [OutOfBounds] +to_i128_checked : Int * -> Result I128 [OutOfBounds] +to_u8_checked : Int * -> Result U8 [OutOfBounds] +to_u16_checked : Int * -> Result U16 [OutOfBounds] +to_u32_checked : Int * -> Result U32 [OutOfBounds] +to_u64_checked : Int * -> Result U64 [OutOfBounds] +to_u128_checked : Int * -> Result U128 [OutOfBounds] +to_f32_checked : Num * -> Result F32 [OutOfBounds] +to_f64_checked : Num * -> Result F64 [OutOfBounds] ## Turns a [Dec] into its [I128] representation by removing the decimal point. ## This is equivalent to multiplying the [Dec] by 10^18. -withoutDecimalPoint : Dec -> I128 +without_decimal_point : Dec -> I128 ## Turns a [I128] into the coresponding [Dec] by adding the decimal point. ## This is equivalent to dividing the [I128] by 10^18. -withDecimalPoint : I128 -> Dec +with_decimal_point : I128 -> Dec ## Splits a [F32] into its components according to IEEE 754 standard. -f32ToParts : F32 -> { sign : Bool, exponent : U8, fraction : U32 } +f32_to_parts : F32 -> { sign : Bool, exponent : U8, fraction : U32 } ## Splits a [F64] into its components according to IEEE 754 standard. -f64ToParts : F64 -> { sign : Bool, exponent : U16, fraction : U64 } +f64_to_parts : F64 -> { sign : Bool, exponent : U16, fraction : U64 } ## Combine parts of a [F32] according to IEEE 754 standard. ## The fraction should not be bigger than 0x007F_FFFF, any bigger value will be truncated. -f32FromParts : { sign : Bool, exponent : U8, fraction : U32 } -> F32 +f32_from_parts : { sign : Bool, exponent : U8, fraction : U32 } -> F32 ## Combine parts of a [F64] according to IEEE 754 standard. ## The fraction should not be bigger than 0x000F_FFFF_FFFF_FFFF, any bigger value will be truncated. ## The exponent should not be bigger than 0x07FF, any bigger value will be truncated. -f64FromParts : { sign : Bool, exponent : U16, fraction : U64 } -> F64 +f64_from_parts : { sign : Bool, exponent : U16, fraction : U64 } -> F64 ## Convert a `Bool` to a `Num` ## ```roc -## expect (Num.fromBool Bool.true) == 1 -## expect (Num.fromBool Bool.false) == 0 +## expect Num.from_bool(Bool.true) == 1 +## expect Num.from_bool(Bool.false) == 0 ## ``` -fromBool : Bool -> Num * -fromBool = \bool -> +from_bool : Bool -> Num * +from_bool = \bool -> if bool then 1 else 0 ## The value for not-a-number for a [F32] according to the IEEE 754 standard. -nanF32 : F32 -nanF32 = 0.0f32 / 0.0 +nan_f32 : F32 +nan_f32 = 0.0f32 / 0.0 ## The value for not-a-number for a [F64] according to the IEEE 754 standard. -nanF64 : F64 -nanF64 = 0.0f64 / 0.0 +nan_f64 : F64 +nan_f64 = 0.0f64 / 0.0 ## The value for infinity for a [F32] according to the IEEE 754 standard. -infinityF32 : F32 -infinityF32 = 1.0f32 / 0.0 +infinity_f32 : F32 +infinity_f32 = 1.0f32 / 0.0 ## The value for infinity for a [F64] according to the IEEE 754 standard. -infinityF64 : F64 -infinityF64 = 1.0f64 / 0.0 +infinity_f64 : F64 +infinity_f64 = 1.0f64 / 0.0 diff --git a/crates/compiler/builtins/roc/Result.roc b/crates/compiler/builtins/roc/Result.roc index 7905215f598..eedec3b6936 100644 --- a/crates/compiler/builtins/roc/Result.roc +++ b/crates/compiler/builtins/roc/Result.roc @@ -1,15 +1,15 @@ module [ Result, - isOk, - isErr, + is_ok, + is_err, map, - mapErr, - mapBoth, + map_err, + map_both, map2, try, - onErr, - onErr!, - withDefault, + on_err, + on_err!, + with_default, ] import Bool exposing [Bool] @@ -20,42 +20,42 @@ Result ok err : [Ok ok, Err err] ## Returns `Bool.true` if the result indicates a success, else returns `Bool.false` ## ```roc -## Result.isOk (Ok 5) +## Result.is_ok(Ok(5)) ## ``` -isOk : Result ok err -> Bool -isOk = \result -> +is_ok : Result ok err -> Bool +is_ok = \result -> when result is - Ok _ -> Bool.true - Err _ -> Bool.false + Ok(_) -> Bool.true + Err(_) -> Bool.false ## Returns `Bool.true` if the result indicates a failure, else returns `Bool.false` ## ```roc -## Result.isErr (Err "uh oh") +## Result.is_err(Err("uh oh")) ## ``` -isErr : Result ok err -> Bool -isErr = \result -> +is_err : Result ok err -> Bool +is_err = \result -> when result is - Ok _ -> Bool.false - Err _ -> Bool.true + Ok(_) -> Bool.false + Err(_) -> Bool.true ## If the result is `Ok`, returns the value it holds. Otherwise, returns ## the given default value. ## ```roc -## Result.withDefault (Ok 7) 42 -## Result.withDefault (Err "uh oh") 42 +## Result.with_default(Ok(7), 42) +## Result.with_default(Err("uh oh"), 42) ## ``` -withDefault : Result ok err, ok -> ok -withDefault = \result, default -> +with_default : Result ok err, ok -> ok +with_default = \result, default -> when result is - Ok value -> value - Err _ -> default + Ok(value) -> value + Err(_) -> default ## If the result is `Ok`, transforms the value it holds by running a conversion ## function on it. Then returns a new `Ok` holding the transformed value. If the -## result is `Err`, this has no effect. Use [mapErr] to transform an `Err`. +## result is `Err`, this has no effect. Use [map_err] to transform an `Err`. ## ```roc -## Result.map (Ok 12) Num.neg -## Result.map (Err "yipes!") Num.neg +## Result.map(Ok(12), Num.neg) +## Result.map(Err("yipes!"), Num.neg) ## ``` ## ## Functions like `map` are common in Roc; see for example [List.map], @@ -63,73 +63,75 @@ withDefault = \result, default -> map : Result a err, (a -> b) -> Result b err map = \result, transform -> when result is - Ok v -> Ok (transform v) - Err e -> Err e + Ok(v) -> Ok(transform(v)) + Err(e) -> Err(e) ## If the result is `Err`, transforms the value it holds by running a conversion ## function on it. Then returns a new `Err` holding the transformed value. If ## the result is `Ok`, this has no effect. Use [map] to transform an `Ok`. ## ```roc -## Result.mapErr (Err "yipes!") Str.isEmpty -## Result.mapErr (Ok 12) Str.isEmpty +## Result.map_err(Err("yipes!"), Str.is_empty) +## Result.map_err(Ok(12), Str.is_empty) ## ``` -mapErr : Result ok a, (a -> b) -> Result ok b -mapErr = \result, transform -> +map_err : Result ok a, (a -> b) -> Result ok b +map_err = \result, transform -> when result is - Ok v -> Ok v - Err e -> Err (transform e) + Ok(v) -> Ok(v) + Err(e) -> Err(transform(e)) ## Maps both the `Ok` and `Err` values of a `Result` to new values. -mapBoth : Result ok1 err1, (ok1 -> ok2), (err1 -> err2) -> Result ok2 err2 -mapBoth = \result, okTransform, errTransform -> +map_both : Result ok1 err1, (ok1 -> ok2), (err1 -> err2) -> Result ok2 err2 +map_both = \result, ok_transform, err_transform -> when result is - Ok val -> Ok (okTransform val) - Err err -> Err (errTransform err) + Ok(val) -> Ok(ok_transform(val)) + Err(err) -> Err(err_transform(err)) ## Maps the `Ok` values of two `Result`s to a new value using a given transformation, ## or returns the first `Err` value encountered. map2 : Result a err, Result b err, (a, b -> c) -> Result c err -map2 = \firstResult, secondResult, transform -> - when (firstResult, secondResult) is - (Ok first, Ok second) -> Ok (transform first second) - (Err err, _) -> Err err - (_, Err err) -> Err err +map2 = \first_result, second_result, transform -> + when (first_result, second_result) is + (Ok(first), Ok(second)) -> Ok(transform(first, second)) + (Err(err), _) -> Err(err) + (_, Err(err)) -> Err(err) ## If the result is `Ok`, transforms the entire result by running a conversion ## function on the value the `Ok` holds. Then returns that new result. If the -## result is `Err`, this has no effect. Use `onErr` to transform an `Err`. +## result is `Err`, this has no effect. Use `on_err` to transform an `Err`. ## ```roc -## Result.try (Ok -1) \num -> if num < 0 then Err "negative!" else Ok -num -## Result.try (Err "yipes!") \num -> if num < 0 then Err "negative!" else Ok -num +## Result.try(Ok(-1), (\num -> if num < 0 then Err("negative!") else Ok(-num))) +## Result.try(Err("yipes!"), (\num -> if num < 0 then Err("negative!") else Ok(-num))) ## ``` try : Result a err, (a -> Result b err) -> Result b err try = \result, transform -> when result is - Ok v -> transform v - Err e -> Err e + Ok(v) -> transform(v) + Err(e) -> Err(e) ## If the result is `Err`, transforms the entire result by running a conversion ## function on the value the `Err` holds. Then returns that new result. If the ## result is `Ok`, this has no effect. Use `try` to transform an `Ok`. ## ```roc -## Result.onErr (Ok 10) \errorNum -> Str.toU64 errorNum -## Result.onErr (Err "42") \errorNum -> Str.toU64 errorNum +## Result.on_err(Ok(10), (\error_num -> Str.to_u64(error_num))) +## Result.on_err(Err("42"), (\error_num -> Str.to_u64(error_num))) ## ``` -onErr : Result a err, (err -> Result a otherErr) -> Result a otherErr -onErr = \result, transform -> +on_err : Result a err, (err -> Result a other_err) -> Result a other_err +on_err = \result, transform -> when result is - Ok v -> Ok v - Err e -> transform e + Ok(v) -> Ok(v) + Err(e) -> transform(e) -## Like [onErr], but it allows the transformation function to produce effects. +## Like [on_err], but it allows the transformation function to produce effects. ## ## ```roc -## Result.onErr (Err "missing user") \msg -> -## try Stdout.line! "ERROR: $(msg)" -## Err msg +## Result.on_err(Err("missing user"), (\msg -> +## Stdout.line!("ERROR: $(msg)")? +## +## Err(msg) +## )) ## ``` -onErr! : Result a err, (err => Result a otherErr) => Result a otherErr -onErr! = \result, transform! -> +on_err! : Result a err, (err => Result a other_err) => Result a other_err +on_err! = \result, transform! -> when result is - Ok v -> Ok v - Err e -> transform! e + Ok(v) -> Ok(v) + Err(e) -> transform!(e) diff --git a/crates/compiler/builtins/roc/Set.roc b/crates/compiler/builtins/roc/Set.roc index 4d0c4a7332d..d7dc778f043 100644 --- a/crates/compiler/builtins/roc/Set.roc +++ b/crates/compiler/builtins/roc/Set.roc @@ -1,27 +1,27 @@ module [ Set, empty, - withCapacity, + with_capacity, reserve, - releaseExcessCapacity, + release_excess_capacity, single, walk, - walkUntil, - keepIf, - dropIf, + walk_until, + keep_if, + drop_if, insert, len, - isEmpty, + is_empty, capacity, remove, contains, - toList, - fromList, + to_list, + from_list, union, intersection, difference, map, - joinMap, + join_map, ] import List @@ -36,154 +36,154 @@ import Inspect exposing [Inspect, Inspector, InspectFormatter] Set k := Dict.Dict k {} where k implements Hash & Eq implements [ Eq { - isEq, + is_eq, }, Hash { - hash: hashSet, + hash: hash_set, }, Inspect { - toInspector: toInspectorSet, + to_inspector: to_inspector_set, }, ] -isEq : Set k, Set k -> Bool -isEq = \xs, ys -> - if len xs != len ys then +is_eq : Set k, Set k -> Bool +is_eq = \xs, ys -> + if len(xs) != len(ys) then Bool.false else - walkUntil xs Bool.true \_, elem -> - if contains ys elem then - Continue Bool.true + walk_until(xs, Bool.true, \_, elem -> + if contains(ys, elem) then + Continue(Bool.true) else - Break Bool.false + Break(Bool.false)) -hashSet : hasher, Set k -> hasher where hasher implements Hasher -hashSet = \hasher, @Set inner -> Hash.hash hasher inner +hash_set : hasher, Set k -> hasher where hasher implements Hasher +hash_set = \hasher, @Set(inner) -> Hash.hash(hasher, inner) -toInspectorSet : Set k -> Inspector f where k implements Inspect & Hash & Eq, f implements InspectFormatter -toInspectorSet = \set -> - Inspect.custom \fmt -> - Inspect.apply (Inspect.set set walk Inspect.toInspector) fmt +to_inspector_set : Set k -> Inspector f where k implements Inspect & Hash & Eq, f implements InspectFormatter +to_inspector_set = \set -> + Inspect.custom(\fmt -> + Inspect.apply(Inspect.set(set, walk, Inspect.to_inspector), fmt)) ## Creates a new empty `Set`. ## ```roc -## emptySet = Set.empty {} -## countValues = Set.len emptySet +## empty_set = Set.empty({}) +## count_values = Set.len(empty_set) ## -## expect countValues == 0 +## expect count_values == 0 ## ``` empty : {} -> Set * -empty = \{} -> @Set (Dict.empty {}) +empty = \{} -> @Set(Dict.empty({})) ## Return a set with space allocated for a number of entries. This ## may provide a performance optimization if you know how many entries will be ## inserted. -withCapacity : U64 -> Set * -withCapacity = \cap -> - @Set (Dict.withCapacity cap) +with_capacity : U64 -> Set * +with_capacity = \cap -> + @Set(Dict.with_capacity(cap)) ## Enlarge the set for at least capacity additional elements reserve : Set k, U64 -> Set k -reserve = \@Set dict, requested -> - @Set (Dict.reserve dict requested) +reserve = \@Set(dict), requested -> + @Set(Dict.reserve(dict, requested)) ## Shrink the memory footprint of a set such that capacity is as small as possible. ## This function will require regenerating the metadata if the size changes. ## There will still be some overhead due to dictionary metadata always being a power of 2. -releaseExcessCapacity : Set k -> Set k -releaseExcessCapacity = \@Set dict -> - @Set (Dict.releaseExcessCapacity dict) +release_excess_capacity : Set k -> Set k +release_excess_capacity = \@Set(dict) -> + @Set(Dict.release_excess_capacity(dict)) ## Creates a new `Set` with a single value. ## ```roc -## singleItemSet = Set.single "Apple" -## countValues = Set.len singleItemSet +## single_item_set = Set.single("Apple") +## count_values = Set.len(single_item_set) ## -## expect countValues == 1 +## expect count_values == 1 ## ``` single : k -> Set k single = \key -> - Dict.single key {} |> @Set + Dict.single(key, {}) |> @Set ## Insert a value into a `Set`. ## ```roc -## fewItemSet = -## Set.empty {} -## |> Set.insert "Apple" -## |> Set.insert "Pear" -## |> Set.insert "Banana" +## few_item_set = +## Set.empty({}) +## |> Set.insert("Apple") +## |> Set.insert("Pear") +## |> Set.insert("Banana") ## -## countValues = Set.len fewItemSet +## count_values = Set.len(few_item_set) ## -## expect countValues == 3 +## expect count_values == 3 ## ``` insert : Set k, k -> Set k -insert = \@Set dict, key -> - Dict.insert dict key {} |> @Set +insert = \@Set(dict), key -> + Dict.insert(dict, key, {}) |> @Set # Inserting a duplicate key has no effect. expect actual = - empty {} - |> insert "foo" - |> insert "bar" - |> insert "foo" - |> insert "baz" + empty({}) + |> insert("foo") + |> insert("bar") + |> insert("foo") + |> insert("baz") expected = - empty {} - |> insert "foo" - |> insert "bar" - |> insert "baz" + empty({}) + |> insert("foo") + |> insert("bar") + |> insert("baz") expected == actual ## Counts the number of values in a given `Set`. ## ```roc -## fewItemSet = -## Set.empty {} -## |> Set.insert "Apple" -## |> Set.insert "Pear" -## |> Set.insert "Banana" +## few_item_set = +## Set.empty({}) +## |> Set.insert("Apple") +## |> Set.insert("Pear") +## |> Set.insert("Banana") ## -## countValues = Set.len fewItemSet +## count_values = Set.len(few_item_set) ## -## expect countValues == 3 +## expect count_values == 3 ## ``` len : Set * -> U64 -len = \@Set dict -> - Dict.len dict +len = \@Set(dict) -> + Dict.len(dict) ## Returns the max number of elements the set can hold before requiring a rehash. ## ```roc -## foodSet = -## Set.empty {} -## |> Set.insert "apple" +## food_set = +## Set.empty({}) +## |> Set.insert("apple") ## -## capacityOfSet = Set.capacity foodSet +## capacity_of_set = Set.capacity(food_set) ## ``` capacity : Set * -> U64 -capacity = \@Set dict -> - Dict.capacity dict +capacity = \@Set(dict) -> + Dict.capacity(dict) ## Check if the set is empty. ## ```roc -## Set.isEmpty (Set.empty {} |> Set.insert 42) +## Set.is_empty(Set.empty({}) |> Set.insert(42)) ## -## Set.isEmpty (Set.empty {}) +## Set.is_empty(Set.empty({})) ## ``` -isEmpty : Set * -> Bool -isEmpty = \@Set dict -> - Dict.isEmpty dict +is_empty : Set * -> Bool +is_empty = \@Set(dict) -> + Dict.is_empty(dict) # Inserting a duplicate key has no effect on length. expect actual = - empty {} - |> insert "foo" - |> insert "bar" - |> insert "foo" - |> insert "baz" + empty({}) + |> insert("foo") + |> insert("bar") + |> insert("foo") + |> insert("baz") |> len actual == 3 @@ -191,20 +191,20 @@ expect ## Removes the value from the given `Set`. ## ```roc ## numbers = -## Set.empty {} -## |> Set.insert 10 -## |> Set.insert 20 -## |> Set.remove 10 +## Set.empty({}) +## |> Set.insert(10) +## |> Set.insert(20) +## |> Set.remove(10) ## -## has10 = Set.contains numbers 10 -## has20 = Set.contains numbers 20 +## has10 = Set.contains(numbers, 10) +## has20 = Set.contains(numbers, 20) ## ## expect has10 == Bool.false ## expect has20 == Bool.true ## ``` remove : Set k, k -> Set k -remove = \@Set dict, key -> - Dict.remove dict key |> @Set +remove = \@Set(dict), key -> + Dict.remove(dict, key) |> @Set ## Test if a value is in the `Set`. ## ```roc @@ -212,47 +212,47 @@ remove = \@Set dict, key -> ## ## fruit : Set Fruit ## fruit = -## Set.single Apple -## |> Set.insert Pear +## Set.single(Apple) +## |> Set.insert(Pear) ## -## hasApple = Set.contains fruit Apple -## hasBanana = Set.contains fruit Banana +## has_apple = Set.contains(fruit, Apple) +## has_banana = Set.contains(fruit, Banana) ## -## expect hasApple == Bool.true -## expect hasBanana == Bool.false +## expect has_apple == Bool.true +## expect has_banana == Bool.false ## ``` contains : Set k, k -> Bool -contains = \@Set dict, key -> - Dict.contains dict key +contains = \@Set(dict), key -> + Dict.contains(dict, key) ## Retrieve the values in a `Set` as a `List`. ## ```roc ## numbers : Set U64 -## numbers = Set.fromList [1,2,3,4,5] +## numbers = Set.from_list([1,2,3,4,5]) ## ## values = [1,2,3,4,5] ## -## expect Set.toList numbers == values +## expect Set.to_list(numbers) == values ## ``` -toList : Set k -> List k -toList = \@Set dict -> - Dict.keys dict +to_list : Set k -> List k +to_list = \@Set(dict) -> + Dict.keys(dict) ## Create a `Set` from a `List` of values. ## ```roc ## values = -## Set.empty {} -## |> Set.insert Banana -## |> Set.insert Apple -## |> Set.insert Pear +## Set.empty({}) +## |> Set.insert(Banana) +## |> Set.insert(Apple) +## |> Set.insert(Pear) ## -## expect Set.fromList [Pear, Apple, Banana] == values +## expect Set.from_list([Pear, Apple, Banana]) == values ## ``` -fromList : List k -> Set k -fromList = \list -> +from_list : List k -> Set k +from_list = \list -> list - |> List.map \k -> (k, {}) - |> Dict.fromList + |> List.map(\k -> (k, {})) + |> Dict.from_list |> @Set ## Combine two `Set` collection by keeping the @@ -260,234 +260,234 @@ fromList = \list -> ## of all the values pairs. This means that all of the values in both `Set`s ## will be combined. ## ```roc -## set1 = Set.single Left -## set2 = Set.single Right +## set1 = Set.single(Left) +## set2 = Set.single(Right) ## -## expect Set.union set1 set2 == Set.fromList [Left, Right] +## expect Set.union(set1, set2) == Set.from_list([Left, Right]) ## ``` union : Set k, Set k -> Set k -union = \@Set dict1, @Set dict2 -> - Dict.insertAll dict1 dict2 |> @Set +union = \@Set(dict1), @Set(dict2) -> + Dict.insert_all(dict1, dict2) |> @Set ## Combine two `Set`s by keeping the [intersection](https://en.wikipedia.org/wiki/Intersection_(set_theory)) ## of all the values pairs. This means that we keep only those values that are ## in both `Set`s. ## ```roc -## set1 = Set.fromList [Left, Other] -## set2 = Set.fromList [Left, Right] +## set1 = Set.from_list([Left, Other]) +## set2 = Set.from_list([Left, Right]) ## -## expect Set.intersection set1 set2 == Set.single Left +## expect Set.intersection(set1, set2) == Set.single(Left) ## ``` intersection : Set k, Set k -> Set k -intersection = \@Set dict1, @Set dict2 -> - Dict.keepShared dict1 dict2 |> @Set +intersection = \@Set(dict1), @Set(dict2) -> + Dict.keep_shared(dict1, dict2) |> @Set ## Remove the values in the first `Set` that are also in the second `Set` ## using the [set difference](https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement) ## of the values. This means that we will be left with only those values that ## are in the first and not in the second. ## ```roc -## first = Set.fromList [Left, Right, Up, Down] -## second = Set.fromList [Left, Right] +## first = Set.from_list([Left, Right, Up, Down]) +## second = Set.from_list([Left, Right]) ## -## expect Set.difference first second == Set.fromList [Up, Down] +## expect Set.difference(first, second) == Set.from_list([Up, Down]) ## ``` difference : Set k, Set k -> Set k -difference = \@Set dict1, @Set dict2 -> - Dict.removeAll dict1 dict2 |> @Set +difference = \@Set(dict1), @Set(dict2) -> + Dict.remove_all(dict1, dict2) |> @Set ## Iterate through the values of a given `Set` and build a value. ## ```roc -## values = Set.fromList ["March", "April", "May"] +## values = Set.from_list(["March", "April", "May"]) ## -## startsWithLetterM = \month -> -## when Str.toUtf8 month is +## starts_with_letter_m = \month -> +## when Str.to_utf8(month) is ## ['M', ..] -> Bool.true ## _ -> Bool.false ## ## reduce = \state, k -> -## if startsWithLetterM k then +## if starts_with_letter_m(k) then ## state + 1 ## else ## state ## -## result = Set.walk values 0 reduce +## result = Set.walk(values, 0, reduce) ## ## expect result == 2 ## ``` walk : Set k, state, (state, k -> state) -> state -walk = \@Set dict, state, step -> - Dict.walk dict state (\s, k, _ -> step s k) +walk = \@Set(dict), state, step -> + Dict.walk(dict, state, \s, k, _ -> step(s, k)) ## Convert each value in the set to something new, by calling a conversion ## function on each of them which receives the old value. Then return a ## new set containing the converted values. map : Set a, (a -> b) -> Set b map = \set, transform -> - init = withCapacity (capacity set) + init = with_capacity(capacity(set)) - walk set init \answer, k -> - insert answer (transform k) + walk(set, init, \answer, k -> + insert(answer, transform(k))) ## Like [Set.map], except the transformation function wraps the return value ## in a set. At the end, all the sets get joined together ## (using [Set.union]) into one set. ## -## You may know a similar function named `concatMap` in other languages. -joinMap : Set a, (a -> Set b) -> Set b -joinMap = \set, transform -> - init = withCapacity (capacity set) # Might be a pessimization +## You may know a similar function named `concat_map` in other languages. +join_map : Set a, (a -> Set b) -> Set b +join_map = \set, transform -> + init = with_capacity(capacity(set)) # Might be a pessimization - walk set init \answer, k -> - union answer (transform k) + walk(set, init, \answer, k -> + union(answer, transform(k))) ## Iterate through the values of a given `Set` and build a value, can stop ## iterating part way through the collection. ## ```roc -## numbers = Set.fromList [1,2,3,4,5,6,42,7,8,9,10] +## numbers = Set.from_list([1,2,3,4,5,6,42,7,8,9,10]) ## ## find42 = \state, k -> ## if k == 42 then -## Break FoundTheAnswer +## Break(FoundTheAnswer) ## else -## Continue state +## Continue(state) ## -## result = Set.walkUntil numbers NotFound find42 +## result = Set.walk_until(numbers, NotFound, find42) ## ## expect result == FoundTheAnswer ## ``` -walkUntil : Set k, state, (state, k -> [Continue state, Break state]) -> state -walkUntil = \@Set dict, state, step -> - Dict.walkUntil dict state (\s, k, _ -> step s k) +walk_until : Set k, state, (state, k -> [Continue state, Break state]) -> state +walk_until = \@Set(dict), state, step -> + Dict.walk_until(dict, state, \s, k, _ -> step(s, k)) ## Run the given function on each element in the `Set`, and return ## a `Set` with just the elements for which the function returned `Bool.true`. ## ```roc -## expect Set.fromList [1,2,3,4,5] -## |> Set.keepIf \k -> k >= 3 -## |> Bool.isEq (Set.fromList [3,4,5]) +## expect Set.from_list([1,2,3,4,5]) +## |> Set.keep_if(\k -> k >= 3) +## |> Bool.is_eq(Set.from_list([3,4,5])) ## ``` -keepIf : Set k, (k -> Bool) -> Set k -keepIf = \@Set dict, predicate -> - @Set (Dict.keepIf dict (\(k, _v) -> predicate k)) +keep_if : Set k, (k -> Bool) -> Set k +keep_if = \@Set(dict), predicate -> + @Set(Dict.keep_if(dict, \(k, _v) -> predicate(k))) ## Run the given function on each element in the `Set`, and return ## a `Set` with just the elements for which the function returned `Bool.false`. ## ```roc -## expect Set.fromList [1,2,3,4,5] -## |> Set.dropIf \k -> k >= 3 -## |> Bool.isEq (Set.fromList [1,2]) +## expect Set.from_list [1,2,3,4,5] +## |> Set.drop_if(\k -> k >= 3) +## |> Bool.is_eq(Set.from_list([1,2])) ## ``` -dropIf : Set k, (k -> Bool) -> Set k -dropIf = \@Set dict, predicate -> - @Set (Dict.dropIf dict (\(k, _v) -> predicate k)) +drop_if : Set k, (k -> Bool) -> Set k +drop_if = \@Set(dict), predicate -> + @Set(Dict.drop_if(dict, \(k, _v) -> predicate(k))) expect first = - single "Keep Me" - |> insert "And Me" - |> insert "Remove Me" + single("Keep Me") + |> insert("And Me") + |> insert("Remove Me") second = - single "Remove Me" - |> insert "I do nothing..." + single("Remove Me") + |> insert("I do nothing...") expected = - single "Keep Me" - |> insert "And Me" + single("Keep Me") + |> insert("And Me") - difference first second == expected + difference(first, second) == expected expect first = - single "Keep Me" - |> insert "And Me" - |> insert "Remove Me" + single("Keep Me") + |> insert("And Me") + |> insert("Remove Me") second = - single "Remove Me" - |> insert "I do nothing..." + single("Remove Me") + |> insert("I do nothing...") expected = - single "Keep Me" - |> insert "And Me" + single("Keep Me") + |> insert("And Me") - difference first second == expected + difference(first, second) == expected expect first = - single 1 - |> insert 2 + single(1) + |> insert(2) second = - single 1 - |> insert 3 - |> insert 4 + single(1) + |> insert(3) + |> insert(4) expected = - single 1 - |> insert 2 - |> insert 3 - |> insert 4 + single(1) + |> insert(2) + |> insert(3) + |> insert(4) - union first second == expected + union(first, second) == expected expect base = - single "Remove Me" - |> insert "Keep Me" - |> insert "And Me" + single("Remove Me") + |> insert("Keep Me") + |> insert("And Me") expected = - single "Keep Me" - |> insert "And Me" + single("Keep Me") + |> insert("And Me") - remove base "Remove Me" == expected + remove(base, "Remove Me") == expected expect x = - single 0 - |> insert 1 - |> insert 2 - |> insert 3 - |> insert 4 - |> insert 5 - |> insert 6 - |> insert 7 - |> insert 8 - |> insert 9 - - x == fromList (toList x) + single(0) + |> insert(1) + |> insert(2) + |> insert(3) + |> insert(4) + |> insert(5) + |> insert(6) + |> insert(7) + |> insert(8) + |> insert(9) + + x == from_list(to_list(x)) expect - orderOne : Set U64 - orderOne = - single 1 - |> insert 2 + order_one : Set U64 + order_one = + single(1) + |> insert(2) - orderTwo : Set U64 - orderTwo = - single 2 - |> insert 1 + order_two : Set U64 + order_two = + single(2) + |> insert(1) - wrapperOne : Set (Set U64) - wrapperOne = - single orderOne - |> insert orderTwo + wrapper_one : Set (Set U64) + wrapper_one = + single(order_one) + |> insert(order_two) - wrapperTwo : Set (Set U64) - wrapperTwo = - single orderTwo - |> insert orderOne + wrapper_two : Set (Set U64) + wrapper_two = + single(order_two) + |> insert(order_one) - wrapperOne == wrapperTwo + wrapper_one == wrapper_two expect - Set.fromList [1, 2, 3, 4, 5] - |> Set.keepIf \k -> k >= 3 - |> Bool.isEq (Set.fromList [3, 4, 5]) + Set.from_list([1, 2, 3, 4, 5]) + |> Set.keep_if(\k -> k >= 3) + |> Bool.is_eq(Set.from_list([3, 4, 5])) expect - Set.fromList [1, 2, 3, 4, 5] - |> Set.dropIf \k -> k >= 3 - |> Bool.isEq (Set.fromList [1, 2]) + Set.from_list([1, 2, 3, 4, 5]) + |> Set.drop_if(\k -> k >= 3) + |> Bool.is_eq(Set.from_list([1, 2])) diff --git a/crates/compiler/builtins/roc/Str.roc b/crates/compiler/builtins/roc/Str.roc index 3e2569ef19a..ff66fdea7c3 100644 --- a/crates/compiler/builtins/roc/Str.roc +++ b/crates/compiler/builtins/roc/Str.roc @@ -44,7 +44,7 @@ ## ``` ## colors = ["red", "green", "blue"] ## -## "The colors are $(colors |> Str.joinWith ", ")!" +## "The colors are $(colors |> Str.join_with(", "))!" ## ``` ## ## Interpolation can be used in multiline strings, but the part inside the parentheses must still be on one line. @@ -245,7 +245,7 @@ ## ## A valuable feature of UTF-8 is that it is backwards-compatible with the [ASCII](https://en.wikipedia.org/wiki/ASCII) encoding that was widely used for many years. ASCII existed before Unicode did, and only used the integers 0 to 127 to represent its equivalent of code points. The Unicode code points 0 to 127 represent the same semantic information as ASCII, (e.g. the number 64 represents the letter "A" in both ASCII and in Unicode), and since UTF-8 represents code points 0 to 127 using one byte, all valid ASCII strings can be successfully parsed as UTF-8 without any need for conversion. ## -## Since many textual computer encodings—including [CSV](https://en.wikipedia.org/wiki/CSV), [XML](https://en.wikipedia.org/wiki/XML), and [JSON](https://en.wikipedia.org/wiki/JSON)—do not use any code points above 127 for their delimiters, it is often possible to write parsers for these formats using only `Str` functions which present UTF-8 as raw `U8` sequences, such as [`Str.walkUtf8`](https://www.roc-lang.org/builtins/Str#walkUtf8) and [`Str.toUtf8`](https://www.roc-lang.org/builtins/Str#toUtf8). In the typical case where they do not to need to parse out individual Unicode code points, they can get everything they need from `Str` UTF-8 functions without needing to depend on other packages. +## Since many textual computer encodings—including [CSV](https://en.wikipedia.org/wiki/CSV), [XML](https://en.wikipedia.org/wiki/XML), and [JSON](https://en.wikipedia.org/wiki/JSON)—do not use any code points above 127 for their delimiters, it is often possible to write parsers for these formats using only `Str` functions which present UTF-8 as raw `U8` sequences, such as [`Str.walk_utf8`](https://www.roc-lang.org/builtins/Str#walk_utf8) and [`Str.to_utf8`](https://www.roc-lang.org/builtins/Str#to_utf8). In the typical case where they do not to need to parse out individual Unicode code points, they can get everything they need from `Str` UTF-8 functions without needing to depend on other packages. ## ## ### When to use code points, graphemes, and UTF-8 ## @@ -253,8 +253,8 @@ ## ## The way Roc organizes the `Str` module and supporting packages is designed to help answer this question. Every situation is different, but the following rules of thumb are typical: ## -## * Most often, using `Str` values along with helper functions like [`splitOn`](https://www.roc-lang.org/builtins/Str#splitOn), [`joinWith`](https://www.roc-lang.org/builtins/Str#joinWith), and so on, is the best option. -## * If you are specifically implementing a parser, working in UTF-8 bytes is usually the best option. So functions like [`walkUtf8`](https://www.roc-lang.org/builtins/Str#walkUtf8), [toUtf8](https://www.roc-lang.org/builtins/Str#toUtf8), and so on. (Note that single-quote literals produce number literals, so ASCII-range literals like `'a'` gives an integer literal that works with a UTF-8 `U8`.) +## * Most often, using `Str` values along with helper functions like [`split_on`](https://www.roc-lang.org/builtins/Str#split_on), [`join_with`](https://www.roc-lang.org/builtins/Str#join_with), and so on, is the best option. +## * If you are specifically implementing a parser, working in UTF-8 bytes is usually the best option. So functions like [`walk_utf8`](https://www.roc-lang.org/builtins/Str#walk_utf8), [to_utf8](https://www.roc-lang.org/builtins/Str#to_utf8), and so on. (Note that single-quote literals produce number literals, so ASCII-range literals like `'a'` gives an integer literal that works with a UTF-8 `U8`.) ## * If you are implementing a Unicode library like [roc-lang/unicode](https://github.com/roc-lang/unicode), working in terms of code points will be unavoidable. Aside from basic readability considerations like `\u(...)` in string literals, if you have the option to avoid working in terms of code points, it is almost always correct to avoid them. ## * If it seems like a good idea to split a string into "characters" (graphemes), you should definitely stop and reconsider whether this is really the best design. Almost always, doing this is some combination of more error-prone or slower (usually both) than doing something else that does not require taking graphemes into consideration. ## @@ -275,7 +275,7 @@ ## ## Like lists, dictionaries, and sets, Roc strings are automatically reference-counted and can benefit from opportunistic in-place mutation. The reference count is stored on the heap immediately before the first byte of the string's contents, and it has the same size as a memory address. This means it can count so high that it's impossible to write a Roc program which overflows a reference count, because having that many simultaneous references (each of which is a memory address) would have exhausted the operating system's address space first. ## -## When the string's reference count is 1, functions like [`Str.concat`](https://www.roc-lang.org/builtins/Str#concat) and [`Str.replaceEach`](https://www.roc-lang.org/builtins/Str#replaceEach) mutate the string in-place rather than allocating a new string. This preserves semantic immutability because it is unobservable in terms of the operation's output; if the reference count is 1, it means that memory would have otherwise been deallocated immediately anyway, and it's more efficient to reuse it instead of deallocating it and then immediately making a new allocation. +## When the string's reference count is 1, functions like [`Str.concat`](https://www.roc-lang.org/builtins/Str#concat) and [`Str.replace_each`](https://www.roc-lang.org/builtins/Str#replace_each) mutate the string in-place rather than allocating a new string. This preserves semantic immutability because it is unobservable in terms of the operation's output; if the reference count is 1, it means that memory would have otherwise been deallocated immediately anyway, and it's more efficient to reuse it instead of deallocating it and then immediately making a new allocation. ## ## The contents of statically-known strings (today that means string literals) are stored in the readonly section of the binary, so they do not need heap allocations or reference counts. They are not eligible for in-place mutation, since mutating the readonly section of the binary would cause an operating system [access violation](https://en.wikipedia.org/wiki/Segmentation_fault). ## @@ -294,7 +294,7 @@ ## Try putting this into `roc repl`: ## ## ``` -## » "foo/bar/baz" |> Str.splitOn "/" +## » "foo/bar/baz" |> Str.split_on("/") ## ## ["foo", "bar", "baz"] : List Str ## ``` @@ -304,7 +304,7 @@ ## Now let's suppose they were long enough that this optimization no longer applied: ## ## ``` -## » "a much, much, much, much/longer/string compared to the last one!" |> Str.splitOn "/" +## » "a much, much, much, much/longer/string compared to the last one!" |> Str.split_on "/" ## ## ["a much, much, much, much", "longer", "string compared to the last one!"] : List Str ## ``` @@ -323,52 +323,52 @@ ## 2. The smaller slice is used for a long time in the program, whereas the much larger original string stops being used. ## 3. In this situation, it might have been better for total program memory usage (although not necessarily overall performance) if the original large string could have been deallocated sooner, even at the expense of having to copy the smaller string into a new allocation instead of reusing the bytes with a seamless slice. ## -## If a situation like this comes up, a slice can be turned into a separate string by using [`Str.concat`](https://www.roc-lang.org/builtins/Str#concat) to concatenate the slice onto an empty string (or one created with [`Str.withCapacity`](https://www.roc-lang.org/builtins/Str#withCapacity)). +## If a situation like this comes up, a slice can be turned into a separate string by using [`Str.concat`](https://www.roc-lang.org/builtins/Str#concat) to concatenate the slice onto an empty string (or one created with [`Str.with_capacity`](https://www.roc-lang.org/builtins/Str#with_capacity)). ## ## Currently, the only way to get seamless slices of strings is by calling certain `Str` functions which return them. In general, `Str` functions which accept a string and return a subset of that string tend to do this. [`Str.trim`](https://www.roc-lang.org/builtins/Str#trim) is another example of a function which returns a seamless slice. module [ Utf8Problem, Utf8ByteProblem, concat, - isEmpty, - joinWith, - splitOn, + is_empty, + join_with, + split_on, repeat, - countUtf8Bytes, - toUtf8, - fromUtf8, - startsWith, - endsWith, + count_utf8_bytes, + to_utf8, + from_utf8, + starts_with, + ends_with, trim, - trimStart, - trimEnd, - toDec, - toF64, - toF32, - toU128, - toI128, - toU64, - toI64, - toU32, - toI32, - toU16, - toI16, - toU8, - toI8, - replaceEach, - replaceFirst, - replaceLast, - splitFirst, - splitLast, - walkUtf8, - walkUtf8WithIndex, + trim_start, + trim_end, + to_dec, + to_f64, + to_f32, + to_u128, + to_i128, + to_u64, + to_i64, + to_u32, + to_i32, + to_u16, + to_i16, + to_u8, + to_i8, + replace_each, + replace_first, + replace_last, + split_first, + split_last, + walk_utf8, + walk_utf8_with_index, reserve, - releaseExcessCapacity, - withCapacity, - withPrefix, + release_excess_capacity, + with_capacity, + with_prefix, contains, - dropPrefix, - dropSuffix, + drop_prefix, + drop_suffix, ] import Bool exposing [Bool] @@ -385,20 +385,20 @@ Utf8ByteProblem : [ EncodesSurrogateHalf, ] -Utf8Problem : { byteIndex : U64, problem : Utf8ByteProblem } +Utf8Problem : { byte_index : U64, problem : Utf8ByteProblem } ## Returns [Bool.true] if the string is empty, and [Bool.false] otherwise. ## ```roc -## expect Str.isEmpty "hi!" == Bool.false -## expect Str.isEmpty "" == Bool.true +## expect Str.is_empty("hi!") == Bool.false +## expect Str.is_empty("") == Bool.true ## ``` -isEmpty : Str -> Bool +is_empty : Str -> Bool ## Concatenates two strings together. ## ```roc -## expect Str.concat "ab" "cd" == "abcd" -## expect Str.concat "hello" "" == "hello" -## expect Str.concat "" "" == "" +## expect Str.concat("ab", "cd") == "abcd" +## expect Str.concat("hello", "") == "hello" +## expect Str.concat("", "") == "" ## ``` concat : Str, Str -> Str @@ -412,21 +412,21 @@ concat : Str, Str -> Str ## subject = "Awesome Programmer" ## ## # Evaluates to "Hello and welcome to Roc, Awesome Programmer!" -## helloWorld = -## Str.withCapacity 45 -## |> Str.concat greeting -## |> Str.concat ", " -## |> Str.concat subject -## |> Str.concat "!" +## hello_world = +## Str.with_capacity(45) +## |> Str.concat(greeting) +## |> Str.concat(", ") +## |> Str.concat(subject) +## |> Str.concat("!") ## ``` ## ## In general, if you plan to use [Str.concat] on an empty string, it will be faster to start with -## [Str.withCapacity] than with `""`. Even if you don't know the exact capacity of the string, giving [withCapacity] +## [Str.with_capacity] than with `""`. Even if you don't know the exact capacity of the string, giving [with_capacity] ## a higher value than ends up being necessary can help prevent reallocation and copying—at ## the cost of using more memory than is necessary. ## ## For more details on how the performance optimization works, see [Str.reserve]. -withCapacity : U64 -> Str +with_capacity : U64 -> Str ## Increase a string's capacity by at least the given number of additional bytes. ## @@ -439,11 +439,11 @@ withCapacity : U64 -> Str ## subject = "Awesome Programmer" ## ## # Evaluates to "Hello and welcome to Roc, Awesome Programmer!" -## helloWorld = +## hello_world = ## greeting -## |> Str.concat ", " -## |> Str.concat subject -## |> Str.concat "!" +## |> Str.concat(", ") +## |> Str.concat(subject) +## |> Str.concat("!") ## ``` ## ## In this example: @@ -457,19 +457,19 @@ withCapacity : U64 -> Str ## Here's a modified example which uses [Str.reserve] to eliminate the need for all that reallocation, copying, and deallocation. ## ## ```roc -## helloWorld = +## hello_world = ## greeting -## |> Str.reserve 21 -## |> Str.concat ", " -## |> Str.concat subject -## |> Str.concat "!" +## |> Str.reserve(21) +## |> Str.concat(", ") +## |> Str.concat(subject) +## |> Str.concat("!") ## ``` ## ## In this example: ## 1. We again start with `greeting`, which has both a length and capacity of 24 bytes. -## 2. `|> Str.reserve 21` will ensure that there is enough capacity in the string for an additional 21 bytes (to make room for `", "`, `"Awesome Programmer"`, and `"!"`). Since the current capacity is only 24, it will create a new 45-byte (24 + 21) heap allocation and copy the contents of the existing allocation (`greeting`) into it. -## 3. `|> Str.concat ", "` will concatenate `, ` to the string. No reallocation, copying, or deallocation will be necessary, because the string already has a capacity of 45 btytes, and `greeting` will only use 24 of them. -## 4. `|> Str.concat subject` will concatenate `subject` (`"Awesome Programmer"`) to the string. Again, no reallocation, copying, or deallocation will be necessary. +## 2. `|> Str.reserve(21)` will ensure that there is enough capacity in the string for an additional 21 bytes (to make room for `", "`, `"Awesome Programmer"`, and `"!"`). Since the current capacity is only 24, it will create a new 45-byte (24 + 21) heap allocation and copy the contents of the existing allocation (`greeting`) into it. +## 3. `|> Str.concat(", ")` will concatenate `, ` to the string. No reallocation, copying, or deallocation will be necessary, because the string already has a capacity of 45 btytes, and `greeting` will only use 24 of them. +## 4. `|> Str.concat(subject)` will concatenate `subject` (`"Awesome Programmer"`) to the string. Again, no reallocation, copying, or deallocation will be necessary. ## 5. `|> Str.concat "!\n"` will concatenate `"!\n"` to the string, still without any reallocation, copying, or deallocation. ## ## Here, [Str.reserve] prevented multiple reallocations, copies, and deallocations during the @@ -483,399 +483,399 @@ withCapacity : U64 -> Str ## this, of course; if you always give it ten times what it turns out to need, that could prevent ## reallocations but will also waste a lot of memory! ## -## If you plan to use [Str.reserve] on an empty string, it's generally better to use [Str.withCapacity] instead. +## If you plan to use [Str.reserve] on an empty string, it's generally better to use [Str.with_capacity] instead. reserve : Str, U64 -> Str ## Combines a [List] of strings into a single string, with a separator ## string in between each. ## ```roc -## expect Str.joinWith ["one", "two", "three"] ", " == "one, two, three" -## expect Str.joinWith ["1", "2", "3", "4"] "." == "1.2.3.4" +## expect Str.join_with(["one", "two", "three"], ", ") == "one, two, three" +## expect Str.join_with(["1", "2", "3", "4"], ".") == "1.2.3.4" ## ``` -joinWith : List Str, Str -> Str +join_with : List Str, Str -> Str ## Split a string around a separator. ## ## Passing `""` for the separator is not useful; ## it returns the original string wrapped in a [List]. ## ```roc -## expect Str.splitOn "1,2,3" "," == ["1","2","3"] -## expect Str.splitOn "1,2,3" "" == ["1,2,3"] +## expect Str.split_on("1,2,3", ",") == ["1","2","3"] +## expect Str.split_on("1,2,3", "") == ["1,2,3"] ## ``` -splitOn : Str, Str -> List Str +split_on : Str, Str -> List Str ## Repeats a string the given number of times. ## ```roc -## expect Str.repeat "z" 3 == "zzz" -## expect Str.repeat "na" 8 == "nananananananana" +## expect Str.repeat("z", 3) == "zzz" +## expect Str.repeat("na", 8) == "nananananananana" ## ``` ## Returns `""` when given `""` for the string or `0` for the count. ## ```roc -## expect Str.repeat "" 10 == "" -## expect Str.repeat "anything" 0 == "" +## expect Str.repeat("", 10) == "" +## expect Str.repeat("anything", 0) == "" ## ``` repeat : Str, U64 -> Str ## Returns a [List] of the string's [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit). ## (To split the string into a [List] of smaller [Str] values instead of [U8] values, -## see [Str.splitOn].) +## see [Str.split_on].) ## ```roc -## expect Str.toUtf8 "Roc" == [82, 111, 99] -## expect Str.toUtf8 "鹏" == [233, 185, 143] -## expect Str.toUtf8 "சி" == [224, 174, 154, 224, 174, 191] -## expect Str.toUtf8 "🐦" == [240, 159, 144, 166] +## expect Str.to_utf8("Roc") == [82, 111, 99] +## expect Str.to_utf8("鹏") == [233, 185, 143] +## expect Str.to_utf8("சி") == [224, 174, 154, 224, 174, 191] +## expect Str.to_utf8("🐦") == [240, 159, 144, 166] ## ``` -toUtf8 : Str -> List U8 +to_utf8 : Str -> List U8 ## Converts a [List] of [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit) to a string. ## ## Returns `Err` if the given bytes are invalid UTF-8, and returns `Ok ""` when given `[]`. ## ```roc -## expect Str.fromUtf8 [82, 111, 99] == Ok "Roc" -## expect Str.fromUtf8 [233, 185, 143] == Ok "鹏" -## expect Str.fromUtf8 [224, 174, 154, 224, 174, 191] == Ok "சி" -## expect Str.fromUtf8 [240, 159, 144, 166] == Ok "🐦" -## expect Str.fromUtf8 [] == Ok "" -## expect Str.fromUtf8 [255] |> Result.isErr -## ``` -fromUtf8 : List U8 -> Result Str [BadUtf8 Utf8ByteProblem U64] -fromUtf8 = \bytes -> - result = fromUtf8Lowlevel bytes - - if result.cIsOk then - Ok result.bString +## expect Str.from_utf8([82, 111, 99]) == Ok("Roc") +## expect Str.from_utf8([233, 185, 143]) == Ok("鹏") +## expect Str.from_utf8([224, 174, 154, 224, 174, 191]) == Ok("சி") +## expect Str.from_utf8([240, 159, 144, 166]) == Ok("🐦") +## expect Str.from_utf8([]) == Ok("") +## expect Str.from_utf8([255]) |> Result.is_err +## ``` +from_utf8 : List U8 -> Result Str [BadUtf8 Utf8ByteProblem U64] +from_utf8 = \bytes -> + result = from_utf8_lowlevel(bytes) + + if result.c_is_ok then + Ok(result.b_string) else - Err (BadUtf8 result.dProblemCode result.aByteIndex) + Err(BadUtf8(result.d_problem_code, result.a_byte_index)) -expect (Str.fromUtf8 [82, 111, 99]) == Ok "Roc" -expect (Str.fromUtf8 [224, 174, 154, 224, 174, 191]) == Ok "சி" -expect (Str.fromUtf8 [240, 159, 144, 166]) == Ok "🐦" -expect (Str.fromUtf8 []) == Ok "" -expect (Str.fromUtf8 [255]) |> Result.isErr +expect (Str.from_utf8([82, 111, 99])) == Ok("Roc") +expect (Str.from_utf8([224, 174, 154, 224, 174, 191])) == Ok("சி") +expect (Str.from_utf8([240, 159, 144, 166])) == Ok("🐦") +expect (Str.from_utf8([])) == Ok("") +expect (Str.from_utf8([255])) |> Result.is_err FromUtf8Result : { - aByteIndex : U64, - bString : Str, - cIsOk : Bool, - dProblemCode : Utf8ByteProblem, + a_byte_index : U64, + b_string : Str, + c_is_ok : Bool, + d_problem_code : Utf8ByteProblem, } -fromUtf8Lowlevel : List U8 -> FromUtf8Result +from_utf8_lowlevel : List U8 -> FromUtf8Result ## Check if the given [Str] starts with a value. ## ```roc -## expect Str.startsWith "ABC" "A" == Bool.true -## expect Str.startsWith "ABC" "X" == Bool.false +## expect Str.starts_with("ABC", "A") == Bool.true +## expect Str.starts_with("ABC", "X") == Bool.false ## ``` -startsWith : Str, Str -> Bool +starts_with : Str, Str -> Bool ## Check if the given [Str] ends with a value. ## ```roc -## expect Str.endsWith "ABC" "C" == Bool.true -## expect Str.endsWith "ABC" "X" == Bool.false +## expect Str.ends_with("ABC", "C") == Bool.true +## expect Str.ends_with("ABC", "X") == Bool.false ## ``` -endsWith : Str, Str -> Bool +ends_with : Str, Str -> Bool ## Return the [Str] with all whitespace removed from both the beginning ## as well as the end. ## ```roc -## expect Str.trim " Hello \n\n" == "Hello" +## expect Str.trim(" Hello \n\n") == "Hello" ## ``` trim : Str -> Str ## Return the [Str] with all whitespace removed from the beginning. ## ```roc -## expect Str.trimStart " Hello \n\n" == "Hello \n\n" +## expect Str.trim_start(" Hello \n\n") == "Hello \n\n" ## ``` -trimStart : Str -> Str +trim_start : Str -> Str ## Return the [Str] with all whitespace removed from the end. ## ```roc -## expect Str.trimEnd " Hello \n\n" == " Hello" +## expect Str.trim_end(" Hello \n\n") == " Hello" ## ``` -trimEnd : Str -> Str +trim_end : Str -> Str ## Encode a [Str] to a [Dec]. A [Dec] value is a 128-bit decimal ## [fixed-point number](https://en.wikipedia.org/wiki/Fixed-point_arithmetic). ## ```roc -## expect Str.toDec "10" == Ok 10dec -## expect Str.toDec "-0.25" == Ok -0.25dec -## expect Str.toDec "not a number" == Err InvalidNumStr +## expect Str.to_dec("10") == Ok(10dec) +## expect Str.to_dec("-0.25") == Ok(-0.25dec) +## expect Str.to_dec("not a number") == Err(InvalidNumStr) ## ``` -toDec : Str -> Result Dec [InvalidNumStr] -toDec = \string -> strToNumHelp string +to_dec : Str -> Result Dec [InvalidNumStr] +to_dec = \string -> str_to_num_help(string) ## Encode a [Str] to a [F64]. A [F64] value is a 64-bit ## [floating-point number](https://en.wikipedia.org/wiki/IEEE_754) and can be ## specified with a `f64` suffix. ## ```roc -## expect Str.toF64 "0.10" == Ok 0.10f64 -## expect Str.toF64 "not a number" == Err InvalidNumStr +## expect Str.to_f64("0.10") == Ok(0.10f64) +## expect Str.to_f64("not a number") == Err(InvalidNumStr) ## ``` -toF64 : Str -> Result F64 [InvalidNumStr] -toF64 = \string -> strToNumHelp string +to_f64 : Str -> Result F64 [InvalidNumStr] +to_f64 = \string -> str_to_num_help(string) ## Encode a [Str] to a [F32].A [F32] value is a 32-bit ## [floating-point number](https://en.wikipedia.org/wiki/IEEE_754) and can be ## specified with a `f32` suffix. ## ```roc -## expect Str.toF32 "0.10" == Ok 0.10f32 -## expect Str.toF32 "not a number" == Err InvalidNumStr +## expect Str.to_f32("0.10") == Ok(0.10f32) +## expect Str.to_f32("not a number") == Err(InvalidNumStr) ## ``` -toF32 : Str -> Result F32 [InvalidNumStr] -toF32 = \string -> strToNumHelp string +to_f32 : Str -> Result F32 [InvalidNumStr] +to_f32 = \string -> str_to_num_help(string) ## Encode a [Str] to an unsigned [U128] integer. A [U128] value can hold numbers ## from `0` to `340_282_366_920_938_463_463_374_607_431_768_211_455` (over ## 340 undecillion). It can be specified with a u128 suffix. ## ```roc -## expect Str.toU128 "1500" == Ok 1500u128 -## expect Str.toU128 "0.1" == Err InvalidNumStr -## expect Str.toU128 "-1" == Err InvalidNumStr -## expect Str.toU128 "not a number" == Err InvalidNumStr +## expect Str.to_u128("1500") == Ok(1500u128) +## expect Str.to_u128("0.1") == Err(InvalidNumStr) +## expect Str.to_u128("-1") == Err(InvalidNumStr) +## expect Str.to_u128("not a number") == Err(InvalidNumStr) ## ``` -toU128 : Str -> Result U128 [InvalidNumStr] -toU128 = \string -> strToNumHelp string +to_u128 : Str -> Result U128 [InvalidNumStr] +to_u128 = \string -> str_to_num_help(string) ## Encode a [Str] to a signed [I128] integer. A [I128] value can hold numbers ## from `-170_141_183_460_469_231_731_687_303_715_884_105_728` to ## `170_141_183_460_469_231_731_687_303_715_884_105_727`. It can be specified ## with a i128 suffix. ## ```roc -## expect Str.toI128 "1500" == Ok 1500i128 -## expect Str.toI128 "-1" == Ok -1i128 -## expect Str.toI128 "0.1" == Err InvalidNumStr -## expect Str.toI128 "not a number" == Err InvalidNumStr +## expect Str.to_u128("1500") == Ok(1500i128) +## expect Str.to_i128("-1") == Ok(-1i128) +## expect Str.to_i128("0.1") == Err(InvalidNumStr) +## expect Str.to_i128("not a number") == Err(InvalidNumStr) ## ``` -toI128 : Str -> Result I128 [InvalidNumStr] -toI128 = \string -> strToNumHelp string +to_i128 : Str -> Result I128 [InvalidNumStr] +to_i128 = \string -> str_to_num_help(string) ## Encode a [Str] to an unsigned [U64] integer. A [U64] value can hold numbers ## from `0` to `18_446_744_073_709_551_615` (over 18 quintillion). It ## can be specified with a u64 suffix. ## ```roc -## expect Str.toU64 "1500" == Ok 1500u64 -## expect Str.toU64 "0.1" == Err InvalidNumStr -## expect Str.toU64 "-1" == Err InvalidNumStr -## expect Str.toU64 "not a number" == Err InvalidNumStr +## expect Str.to_u64("1500") == Ok(1500u64) +## expect Str.to_u64("0.1") == Err(InvalidNumStr) +## expect Str.to_u64("-1") == Err(InvalidNumStr) +## expect Str.to_u64("not a number") == Err(InvalidNumStr) ## ``` -toU64 : Str -> Result U64 [InvalidNumStr] -toU64 = \string -> strToNumHelp string +to_u64 : Str -> Result U64 [InvalidNumStr] +to_u64 = \string -> str_to_num_help(string) ## Encode a [Str] to a signed [I64] integer. A [I64] value can hold numbers ## from `-9_223_372_036_854_775_808` to `9_223_372_036_854_775_807`. It can be ## specified with a i64 suffix. ## ```roc -## expect Str.toI64 "1500" == Ok 1500i64 -## expect Str.toI64 "-1" == Ok -1i64 -## expect Str.toI64 "0.1" == Err InvalidNumStr -## expect Str.toI64 "not a number" == Err InvalidNumStr +## expect Str.to_i64("1500") == Ok(1500i64) +## expect Str.to_i64("-1") == Ok(-1i64) +## expect Str.to_i64("0.1") == Err(InvalidNumStr) +## expect Str.to_i64("not a number") == Err(InvalidNumStr) ## ``` -toI64 : Str -> Result I64 [InvalidNumStr] -toI64 = \string -> strToNumHelp string +to_i64 : Str -> Result I64 [InvalidNumStr] +to_i64 = \string -> str_to_num_help(string) ## Encode a [Str] to an unsigned [U32] integer. A [U32] value can hold numbers ## from `0` to `4_294_967_295` (over 4 billion). It can be specified with ## a u32 suffix. ## ```roc -## expect Str.toU32 "1500" == Ok 1500u32 -## expect Str.toU32 "0.1" == Err InvalidNumStr -## expect Str.toU32 "-1" == Err InvalidNumStr -## expect Str.toU32 "not a number" == Err InvalidNumStr +## expect Str.to_u32("1500") == Ok(1500u32) +## expect Str.to_u32("0.1") == Err(InvalidNumStr) +## expect Str.to_u32("-1") == Err(InvalidNumStr) +## expect Str.to_u32("not a number") == Err(InvalidNumStr) ## ``` -toU32 : Str -> Result U32 [InvalidNumStr] -toU32 = \string -> strToNumHelp string +to_u32 : Str -> Result U32 [InvalidNumStr] +to_u32 = \string -> str_to_num_help(string) ## Encode a [Str] to a signed [I32] integer. A [I32] value can hold numbers ## from `-2_147_483_648` to `2_147_483_647`. It can be ## specified with a i32 suffix. ## ```roc -## expect Str.toI32 "1500" == Ok 1500i32 -## expect Str.toI32 "-1" == Ok -1i32 -## expect Str.toI32 "0.1" == Err InvalidNumStr -## expect Str.toI32 "not a number" == Err InvalidNumStr +## expect Str.to_i32("1500") == Ok(1500i32) +## expect Str.to_i32("-1") == Ok(-1i32) +## expect Str.to_i32("0.1") == Err(InvalidNumStr) +## expect Str.to_i32("not a number") == Err(InvalidNumStr) ## ``` -toI32 : Str -> Result I32 [InvalidNumStr] -toI32 = \string -> strToNumHelp string +to_i32 : Str -> Result I32 [InvalidNumStr] +to_i32 = \string -> str_to_num_help(string) ## Encode a [Str] to an unsigned [U16] integer. A [U16] value can hold numbers ## from `0` to `65_535`. It can be specified with a u16 suffix. ## ```roc -## expect Str.toU16 "1500" == Ok 1500u16 -## expect Str.toU16 "0.1" == Err InvalidNumStr -## expect Str.toU16 "-1" == Err InvalidNumStr -## expect Str.toU16 "not a number" == Err InvalidNumStr +## expect Str.to_u16("1500") == Ok(1500u16) +## expect Str.to_u16("0.1") == Err(InvalidNumStr) +## expect Str.to_u16("-1") == Err(InvalidNumStr) +## expect Str.to_u16("not a number") == Err(InvalidNumStr) ## ``` -toU16 : Str -> Result U16 [InvalidNumStr] -toU16 = \string -> strToNumHelp string +to_u16 : Str -> Result U16 [InvalidNumStr] +to_u16 = \string -> str_to_num_help(string) ## Encode a [Str] to a signed [I16] integer. A [I16] value can hold numbers ## from `-32_768` to `32_767`. It can be ## specified with a i16 suffix. ## ```roc -## expect Str.toI16 "1500" == Ok 1500i16 -## expect Str.toI16 "-1" == Ok -1i16 -## expect Str.toI16 "0.1" == Err InvalidNumStr -## expect Str.toI16 "not a number" == Err InvalidNumStr +## expect Str.to_i16("1500") == Ok(1500i16) +## expect Str.to_i16("-1") == Ok(-1i16) +## expect Str.to_i16("0.1") == Err(InvalidNumStr) +## expect Str.to_i16("not a number") == Err(InvalidNumStr) ## ``` -toI16 : Str -> Result I16 [InvalidNumStr] -toI16 = \string -> strToNumHelp string +to_i16 : Str -> Result I16 [InvalidNumStr] +to_i16 = \string -> str_to_num_help(string) ## Encode a [Str] to an unsigned [U8] integer. A [U8] value can hold numbers ## from `0` to `255`. It can be specified with a u8 suffix. ## ```roc -## expect Str.toU8 "250" == Ok 250u8 -## expect Str.toU8 "-0.1" == Err InvalidNumStr -## expect Str.toU8 "not a number" == Err InvalidNumStr -## expect Str.toU8 "1500" == Err InvalidNumStr +## expect Str.to_u8("250") == Ok(250u8) +## expect Str.to_u8("-0.1") == Err(InvalidNumStr) +## expect Str.to_u8("not a number") == Err(InvalidNumStr) +## expect Str.to_u8("1500") == Err(InvalidNumStr) ## ``` -toU8 : Str -> Result U8 [InvalidNumStr] -toU8 = \string -> strToNumHelp string +to_u8 : Str -> Result U8 [InvalidNumStr] +to_u8 = \string -> str_to_num_help(string) ## Encode a [Str] to a signed [I8] integer. A [I8] value can hold numbers ## from `-128` to `127`. It can be ## specified with a i8 suffix. ## ```roc -## expect Str.toI8 "-15" == Ok -15i8 -## expect Str.toI8 "150.00" == Err InvalidNumStr -## expect Str.toI8 "not a number" == Err InvalidNumStr +## expect Str.to_i8("-15") == Ok(-15i8) +## expect Str.to_i8("150.00") == Err(InvalidNumStr) +## expect Str.to_i8("not a number") == Err(InvalidNumStr) ## ``` -toI8 : Str -> Result I8 [InvalidNumStr] -toI8 = \string -> strToNumHelp string +to_i8 : Str -> Result I8 [InvalidNumStr] +to_i8 = \string -> str_to_num_help(string) ## Get the byte at the given index, without performing a bounds check. -getUnsafe : Str, U64 -> U8 +get_unsafe : Str, U64 -> U8 ## Gives the number of bytes in a [Str] value. ## ```roc -## expect Str.countUtf8Bytes "Hello World" == 11 +## expect Str.count_utf8_bytes("Hello World") == 11 ## ``` -countUtf8Bytes : Str -> U64 +count_utf8_bytes : Str -> U64 -## string slice that does not do bounds checking or utf-8 verification -substringUnsafe : Str, U64, U64 -> Str +## string slice that does not do bounds checking or UTF-8 verification +substring_unsafe : Str, U64, U64 -> Str ## Returns the given [Str] with each occurrence of a substring replaced. ## If the substring is not found, returns the original string. ## ## ```roc -## expect Str.replaceEach "foo/bar/baz" "/" "_" == "foo_bar_baz" -## expect Str.replaceEach "not here" "/" "_" == "not here" +## expect Str.replace_each("foo/bar/baz", "/", "_") == "foo_bar_baz" +## expect Str.replace_each("not here", "/", "_") == "not here" ## ``` -replaceEach : Str, Str, Str -> Str -replaceEach = \haystack, needle, flower -> - when splitFirst haystack needle is - Ok { before, after } -> +replace_each : Str, Str, Str -> Str +replace_each = \haystack, needle, flower -> + when split_first(haystack, needle) is + Ok({ before, after }) -> # We found at least one needle, so start the buffer off with # `before` followed by the first replacement flower. - Str.withCapacity (Str.countUtf8Bytes haystack) - |> Str.concat before - |> Str.concat flower - |> replaceEachHelp after needle flower + Str.with_capacity(Str.count_utf8_bytes(haystack)) + |> Str.concat(before) + |> Str.concat(flower) + |> replace_each_help(after, needle, flower) - Err NotFound -> haystack + Err(NotFound) -> haystack -replaceEachHelp : Str, Str, Str, Str -> Str -replaceEachHelp = \buf, haystack, needle, flower -> - when splitFirst haystack needle is - Ok { before, after } -> +replace_each_help : Str, Str, Str, Str -> Str +replace_each_help = \buf, haystack, needle, flower -> + when split_first(haystack, needle) is + Ok({ before, after }) -> buf - |> Str.concat before - |> Str.concat flower - |> replaceEachHelp after needle flower + |> Str.concat(before) + |> Str.concat(flower) + |> replace_each_help(after, needle, flower) - Err NotFound -> Str.concat buf haystack + Err(NotFound) -> Str.concat(buf, haystack) -expect Str.replaceEach "abXdeXghi" "X" "_" == "ab_de_ghi" -expect Str.replaceEach "abcdefg" "nothing" "_" == "abcdefg" +expect Str.replace_each("abXdeXghi", "X", "_") == "ab_de_ghi" +expect Str.replace_each("abcdefg", "nothing", "_") == "abcdefg" ## Returns the given [Str] with the first occurrence of a substring replaced. ## If the substring is not found, returns the original string. ## ## ```roc -## expect Str.replaceFirst "foo/bar/baz" "/" "_" == "foo_bar/baz" -## expect Str.replaceFirst "no slashes here" "/" "_" == "no slashes here" +## expect Str.replace_first("foo/bar/baz", "/", "_") == "foo_bar/baz" +## expect Str.replace_first("no slashes here", "/", "_") == "no slashes here" ## ``` -replaceFirst : Str, Str, Str -> Str -replaceFirst = \haystack, needle, flower -> - when splitFirst haystack needle is - Ok { before, after } -> +replace_first : Str, Str, Str -> Str +replace_first = \haystack, needle, flower -> + when split_first(haystack, needle) is + Ok({ before, after }) -> "$(before)$(flower)$(after)" - Err NotFound -> haystack + Err(NotFound) -> haystack -expect Str.replaceFirst "abXdeXghi" "X" "_" == "ab_deXghi" -expect Str.replaceFirst "abcdefg" "nothing" "_" == "abcdefg" +expect Str.replace_first("abXdeXghi", "X", "_") == "ab_deXghi" +expect Str.replace_first("abcdefg", "nothing", "_") == "abcdefg" ## Returns the given [Str] with the last occurrence of a substring replaced. ## If the substring is not found, returns the original string. ## ## ```roc -## expect Str.replaceLast "foo/bar/baz" "/" "_" == "foo/bar_baz" -## expect Str.replaceLast "no slashes here" "/" "_" == "no slashes here" +## expect Str.replace_last("foo/bar/baz", "/", "_") == "foo/bar_baz" +## expect Str.replace_last("no slashes here", "/", "_") == "no slashes here" ## ``` -replaceLast : Str, Str, Str -> Str -replaceLast = \haystack, needle, flower -> - when splitLast haystack needle is - Ok { before, after } -> +replace_last : Str, Str, Str -> Str +replace_last = \haystack, needle, flower -> + when split_last(haystack, needle) is + Ok({ before, after }) -> "$(before)$(flower)$(after)" - Err NotFound -> haystack + Err(NotFound) -> haystack -expect Str.replaceLast "abXdeXghi" "X" "_" == "abXde_ghi" -expect Str.replaceLast "abcdefg" "nothing" "_" == "abcdefg" +expect Str.replace_last("abXdeXghi", "X", "_") == "abXde_ghi" +expect Str.replace_last("abcdefg", "nothing", "_") == "abcdefg" ## Returns the given [Str] before the first occurrence of a [delimiter](https://www.computerhope.com/jargon/d/delimite.htm), as well ## as the rest of the string after that occurrence. ## Returns [Err NotFound] if the delimiter is not found. ## ```roc -## expect Str.splitFirst "foo/bar/baz" "/" == Ok { before: "foo", after: "bar/baz" } -## expect Str.splitFirst "no slashes here" "/" == Err NotFound +## expect Str.split_first("foo/bar/baz", "/") == Ok({ before: "foo", after: "bar/baz" }) +## expect Str.split_first("no slashes here", "/") == Err(NotFound) ## ``` -splitFirst : Str, Str -> Result { before : Str, after : Str } [NotFound] -splitFirst = \haystack, needle -> - when firstMatch haystack needle is - Some index -> - remaining = Str.countUtf8Bytes haystack - Str.countUtf8Bytes needle - index +split_first : Str, Str -> Result { before : Str, after : Str } [NotFound] +split_first = \haystack, needle -> + when first_match(haystack, needle) is + Some(index) -> + remaining = Str.count_utf8_bytes(haystack) - Str.count_utf8_bytes(needle) - index - before = Str.substringUnsafe haystack 0 index - after = Str.substringUnsafe haystack (Num.addWrap index (Str.countUtf8Bytes needle)) remaining + before = Str.substring_unsafe(haystack, 0, index) + after = Str.substring_unsafe(haystack, Num.add_wrap(index, Str.count_utf8_bytes(needle)), remaining) - Ok { before, after } + Ok({ before, after }) None -> - Err NotFound + Err(NotFound) -# splitFirst when needle isn't in haystack -expect splitFirst "foo" "z" == Err NotFound +# split_first when needle isn't in haystack +expect split_first("foo", "z") == Err(NotFound) -# splitFirst when needle isn't in haystack, and haystack is empty -expect splitFirst "" "z" == Err NotFound +# split_first when needle isn't in haystack, and haystack is empty +expect split_first("", "z") == Err(NotFound) -# splitFirst when haystack ends with needle repeated -expect splitFirst "foo" "o" == Ok { before: "f", after: "o" } +# split_first when haystack ends with needle repeated +expect split_first("foo", "o") == Ok({ before: "f", after: "o" }) -# splitFirst with multi-byte needle -expect splitFirst "hullabaloo" "ab" == Ok { before: "hull", after: "aloo" } +# split_first with multi-byte needle +expect split_first("hullabaloo", "ab") == Ok({ before: "hull", after: "aloo" }) -# splitFirst when needle is haystack -expect splitFirst "foo" "foo" == Ok { before: "", after: "" } +# split_first when needle is haystack +expect split_first("foo", "foo") == Ok({ before: "", after: "" }) -firstMatch : Str, Str -> [Some U64, None] -firstMatch = \haystack, needle -> - haystackLength = Str.countUtf8Bytes haystack - needleLength = Str.countUtf8Bytes needle - lastPossible = Num.subSaturated haystackLength needleLength +first_match : Str, Str -> [Some U64, None] +first_match = \haystack, needle -> + haystack_length = Str.count_utf8_bytes(haystack) + needle_length = Str.count_utf8_bytes(needle) + last_possible = Num.sub_saturated(haystack_length, needle_length) - firstMatchHelp haystack needle 0 lastPossible + first_match_help(haystack, needle, 0, last_possible) -firstMatchHelp : Str, Str, U64, U64 -> [Some U64, None] -firstMatchHelp = \haystack, needle, index, lastPossible -> - if index <= lastPossible then - if matchesAt haystack index needle then - Some index +first_match_help : Str, Str, U64, U64 -> [Some U64, None] +first_match_help = \haystack, needle, index, last_possible -> + if index <= last_possible then + if matches_at(haystack, index, needle) then + Some(index) else - firstMatchHelp haystack needle (Num.addWrap index 1) lastPossible + first_match_help(haystack, needle, Num.add_wrap(index, 1), last_possible) else None @@ -883,113 +883,114 @@ firstMatchHelp = \haystack, needle, index, lastPossible -> ## the rest of the string after that occurrence. ## Returns [Err NotFound] if the delimiter is not found. ## ```roc -## expect Str.splitLast "foo/bar/baz" "/" == Ok { before: "foo/bar", after: "baz" } -## expect Str.splitLast "no slashes here" "/" == Err NotFound +## expect Str.split_last("foo/bar/baz", "/") == Ok({ before: "foo/bar", after: "baz" }) +## expect Str.split_last("no slashes here", "/") == Err(NotFound) ## ``` -splitLast : Str, Str -> Result { before : Str, after : Str } [NotFound] -splitLast = \haystack, needle -> - when lastMatch haystack needle is - Some index -> - remaining = Str.countUtf8Bytes haystack - Str.countUtf8Bytes needle - index +split_last : Str, Str -> Result { before : Str, after : Str } [NotFound] +split_last = \haystack, needle -> + when last_match(haystack, needle) is + Some(index) -> + remaining = Str.count_utf8_bytes(haystack) - Str.count_utf8_bytes(needle) - index - before = Str.substringUnsafe haystack 0 index - after = Str.substringUnsafe haystack (Num.addWrap index (Str.countUtf8Bytes needle)) remaining + before = Str.substring_unsafe(haystack, 0, index) + after = Str.substring_unsafe(haystack, Num.add_wrap(index, Str.count_utf8_bytes(needle)), remaining) - Ok { before, after } + Ok({ before, after }) None -> - Err NotFound + Err(NotFound) -# splitLast when needle isn't in haystack -expect Str.splitLast "foo" "z" == Err NotFound +# split_last when needle isn't in haystack +expect Str.split_last("foo", "z") == Err(NotFound) -# splitLast when haystack ends with needle repeated -expect Str.splitLast "foo" "o" == Ok { before: "fo", after: "" } +# split_last when haystack ends with needle repeated +expect Str.split_last("foo", "o") == Ok({ before: "fo", after: "" }) -# splitLast with multi-byte needle -expect Str.splitLast "hullabaloo" "ab" == Ok { before: "hull", after: "aloo" } +# split_last with multi-byte needle +expect Str.split_last("hullabaloo", "ab") == Ok({ before: "hull", after: "aloo" }) -# splitLast when needle is haystack -expect Str.splitLast "foo" "foo" == Ok { before: "", after: "" } +# split_last when needle is haystack +expect Str.split_last("foo", "foo") == Ok({ before: "", after: "" }) -lastMatch : Str, Str -> [Some U64, None] -lastMatch = \haystack, needle -> - haystackLength = Str.countUtf8Bytes haystack - needleLength = Str.countUtf8Bytes needle - lastPossibleIndex = Num.subSaturated haystackLength needleLength +last_match : Str, Str -> [Some U64, None] +last_match = \haystack, needle -> + haystack_length = Str.count_utf8_bytes(haystack) + needle_length = Str.count_utf8_bytes(needle) + last_possible_index = Num.sub_saturated(haystack_length, needle_length) - lastMatchHelp haystack needle lastPossibleIndex + last_match_help(haystack, needle, last_possible_index) -lastMatchHelp : Str, Str, U64 -> [Some U64, None] -lastMatchHelp = \haystack, needle, index -> - if matchesAt haystack index needle then - Some index +last_match_help : Str, Str, U64 -> [Some U64, None] +last_match_help = \haystack, needle, index -> + if matches_at(haystack, index, needle) then + Some(index) else - when Num.subChecked index 1 is - Ok nextIndex -> - lastMatchHelp haystack needle nextIndex + when Num.sub_checked(index, 1) is + Ok(next_index) -> + last_match_help(haystack, needle, next_index) - Err _ -> + Err(_) -> None min = \x, y -> if x < y then x else y -matchesAt : Str, U64, Str -> Bool -matchesAt = \haystack, haystackIndex, needle -> - haystackLength = Str.countUtf8Bytes haystack - needleLength = Str.countUtf8Bytes needle - endIndex = min (Num.addSaturated haystackIndex needleLength) haystackLength +matches_at : Str, U64, Str -> Bool +matches_at = \haystack, haystack_index, needle -> + haystack_length = Str.count_utf8_bytes(haystack) + needle_length = Str.count_utf8_bytes(needle) + end_index = min(Num.add_saturated(haystack_index, needle_length), haystack_length) - matchesAtHelp { + matches_at_help({ haystack, - haystackIndex, + haystack_index, needle, - needleIndex: 0, - needleLength, - endIndex, - } + needle_index: 0, + needle_length, + end_index, + }) -matchesAtHelp = \state -> - { haystack, haystackIndex, needle, needleIndex, needleLength, endIndex } = state - isAtEndOfHaystack = haystackIndex >= endIndex +matches_at_help = \state -> + { haystack, haystack_index, needle, needle_index, needle_length, end_index } = state + is_at_end_of_haystack = haystack_index >= end_index - if isAtEndOfHaystack then - didWalkEntireNeedle = needleIndex == needleLength + if is_at_end_of_haystack then + did_walk_entire_needle = needle_index == needle_length - didWalkEntireNeedle + did_walk_entire_needle else - doesThisMatch = - Str.getUnsafe haystack haystackIndex + does_this_match = + Str.get_unsafe(haystack, haystack_index) == - Str.getUnsafe needle needleIndex - doesRestMatch = - matchesAtHelp + Str.get_unsafe(needle, needle_index) + does_rest_match = + matches_at_help( { state & - haystackIndex: Num.addWrap haystackIndex 1, - needleIndex: Num.addWrap needleIndex 1, - } + haystack_index: Num.add_wrap(haystack_index, 1), + needle_index: Num.add_wrap(needle_index, 1), + }, + ) - doesThisMatch && doesRestMatch + does_this_match && does_rest_match ## Walks over the `UTF-8` bytes of the given [Str] and calls a function to update ## state for each byte. The index for that byte in the string is provided ## to the update function. ## ```roc ## f : List U8, U8, U64 -> List U8 -## f = \state, byte, _ -> List.append state byte -## expect Str.walkUtf8WithIndex "ABC" [] f == [65, 66, 67] +## f = \state, byte, _ -> List.append(state, byte) +## expect Str.walk_utf8_with_index("ABC", [], f) == [65, 66, 67] ## ``` -walkUtf8WithIndex : Str, state, (state, U8, U64 -> state) -> state -walkUtf8WithIndex = \string, state, step -> - walkUtf8WithIndexHelp string state step 0 (Str.countUtf8Bytes string) +walk_utf8_with_index : Str, state, (state, U8, U64 -> state) -> state +walk_utf8_with_index = \string, state, step -> + walk_utf8_with_index_help(string, state, step, 0, Str.count_utf8_bytes(string)) -walkUtf8WithIndexHelp : Str, state, (state, U8, U64 -> state), U64, U64 -> state -walkUtf8WithIndexHelp = \string, state, step, index, length -> +walk_utf8_with_index_help : Str, state, (state, U8, U64 -> state), U64, U64 -> state +walk_utf8_with_index_help = \string, state, step, index, length -> if index < length then - byte = Str.getUnsafe string index - newState = step state byte index + byte = Str.get_unsafe(string, index) + new_state = step(state, byte, index) - walkUtf8WithIndexHelp string newState step (Num.addWrap index 1) length + walk_utf8_with_index_help(string, new_state, step, Num.add_wrap(index, 1), length) else state @@ -997,78 +998,79 @@ walkUtf8WithIndexHelp = \string, state, step, index, length -> ## state for each byte. ## ## ```roc -## sumOfUtf8Bytes = -## Str.walkUtf8 "Hello, World!" 0 \total, byte -> +## sum_of_utf8_bytes = +## Str.walk_utf8("Hello, World!", 0, (\total, byte -> ## total + byte +## )) ## -## expect sumOfUtf8Bytes == 105 +## expect sum_of_utf8_bytes == 105 ## ``` -walkUtf8 : Str, state, (state, U8 -> state) -> state -walkUtf8 = \str, initial, step -> - walkUtf8Help str initial step 0 (Str.countUtf8Bytes str) +walk_utf8 : Str, state, (state, U8 -> state) -> state +walk_utf8 = \str, initial, step -> + walk_utf8_help(str, initial, step, 0, Str.count_utf8_bytes(str)) -walkUtf8Help : Str, state, (state, U8 -> state), U64, U64 -> state -walkUtf8Help = \str, state, step, index, length -> +walk_utf8_help : Str, state, (state, U8 -> state), U64, U64 -> state +walk_utf8_help = \str, state, step, index, length -> if index < length then - byte = Str.getUnsafe str index - newState = step state byte + byte = Str.get_unsafe(str, index) + new_state = step(state, byte) - walkUtf8Help str newState step (Num.addWrap index 1) length + walk_utf8_help(str, new_state, step, Num.add_wrap(index, 1), length) else state -expect (walkUtf8 "ABC" [] List.append) == [65, 66, 67] -expect (walkUtf8 "鹏" [] List.append) == [233, 185, 143] +expect (walk_utf8("ABC", [], List.append)) == [65, 66, 67] +expect (walk_utf8("鹏", [], List.append)) == [233, 185, 143] ## Shrink the memory footprint of a str such that its capacity and length are equal. ## Note: This will also convert seamless slices to regular lists. -releaseExcessCapacity : Str -> Str +release_excess_capacity : Str -> Str -strToNum : Str -> { berrorcode : U8, aresult : Num * } +str_to_num : Str -> { berrorcode : U8, aresult : Num * } -strToNumHelp : Str -> Result (Num a) [InvalidNumStr] -strToNumHelp = \string -> +str_to_num_help : Str -> Result (Num a) [InvalidNumStr] +str_to_num_help = \string -> result : { berrorcode : U8, aresult : Num a } - result = strToNum string + result = str_to_num(string) if result.berrorcode == 0 then - Ok result.aresult + Ok(result.aresult) else - Err InvalidNumStr + Err(InvalidNumStr) ## Adds a prefix to the given [Str]. ## ```roc -## expect Str.withPrefix "Awesome" "Roc" == "RocAwesome" +## expect Str.with_prefix("Awesome", "Roc") == "RocAwesome" ## ``` -withPrefix : Str, Str -> Str -withPrefix = \str, prefix -> Str.concat prefix str +with_prefix : Str, Str -> Str +with_prefix = \str, prefix -> Str.concat(prefix, str) ## Determines whether or not the first Str contains the second. ## ```roc -## expect Str.contains "foobarbaz" "bar" -## expect !(Str.contains "apple" "orange") -## expect Str.contains "anything" "" +## expect Str.contains("foobarbaz", "bar") +## expect !Str.contains("apple", "orange") +## expect Str.contains("anything", "") ## ``` contains : Str, Str -> Bool contains = \haystack, needle -> - when firstMatch haystack needle is - Some _index -> Bool.true + when first_match(haystack, needle) is + Some(_index) -> Bool.true None -> Bool.false ## Drops the given prefix [Str] from the start of a [Str] ## If the prefix is not found, returns the original string. ## ## ```roc -## expect Str.dropPrefix "bar" "foo" == "bar" -## expect Str.dropPrefix "foobar" "foo" == "bar" +## expect Str.drop_prefix("bar", "foo") == "bar" +## expect Str.drop_prefix("foobar", "foo") == "bar" ## ``` -dropPrefix : Str, Str -> Str -dropPrefix = \haystack, prefix -> - if Str.startsWith haystack prefix then - start = Str.countUtf8Bytes prefix - len = Num.subWrap (Str.countUtf8Bytes haystack) start +drop_prefix : Str, Str -> Str +drop_prefix = \haystack, prefix -> + if Str.starts_with(haystack, prefix) then + start = Str.count_utf8_bytes(prefix) + len = Num.sub_wrap(Str.count_utf8_bytes(haystack), start) - substringUnsafe haystack start len + substring_unsafe(haystack, start, len) else haystack @@ -1076,15 +1078,15 @@ dropPrefix = \haystack, prefix -> ## If the suffix is not found, returns the original string. ## ## ```roc -## expect Str.dropSuffix "bar" "foo" == "bar" -## expect Str.dropSuffix "barfoo" "foo" == "bar" +## expect Str.drop_suffix("bar", "foo") == "bar" +## expect Str.drop_suffix("barfoo", "foo") == "bar" ## ``` -dropSuffix : Str, Str -> Str -dropSuffix = \haystack, suffix -> - if Str.endsWith haystack suffix then +drop_suffix : Str, Str -> Str +drop_suffix = \haystack, suffix -> + if Str.ends_with(haystack, suffix) then start = 0 - len = Num.subWrap (Str.countUtf8Bytes haystack) (Str.countUtf8Bytes suffix) + len = Num.sub_wrap(Str.count_utf8_bytes(haystack), Str.count_utf8_bytes(suffix)) - substringUnsafe haystack start len + substring_unsafe(haystack, start, len) else haystack diff --git a/crates/compiler/builtins/roc/Task.roc b/crates/compiler/builtins/roc/Task.roc index 3f03f23d69e..63dbf2bbc35 100644 --- a/crates/compiler/builtins/roc/Task.roc +++ b/crates/compiler/builtins/roc/Task.roc @@ -4,16 +4,16 @@ module [ err, await, map, - mapErr, - onErr, + map_err, + on_err, attempt, forever, loop, - fromResult, + from_result, batch, combine, sequence, - forEach, + for_each, result, ] @@ -26,61 +26,62 @@ Task ok err := {} -> Result ok err ## Run a task repeatedly, until it fails with `err`. Note that this task does not return a success value. forever : Task a err -> Task * err -forever = \@Task task -> +forever = \@Task(task) -> looper = \{} -> - when task {} is - Err e -> Err e - Ok _ -> looper {} + when task({}) is + Err(e) -> Err(e) + Ok(_) -> looper({}) - @Task \{} -> looper {} + @Task(\{} -> looper({})) ## Run a task repeatedly, until it fails with `err` or completes with `done`. ## ## ``` ## sum = -## Task.loop! 0 \total -> -## numResult = +## Task.loop!(0, \total -> +## num_result = ## Stdin.line ## |> Task.result! -## |> Result.try Str.toU64 +## |> Result.try(Str.toU64) ## -## when numResult is -## Ok num -> Task.ok (Step (total + num)) -## Err (StdinErr EndOfFile) -> Task.ok (Done total) -## Err InvalidNumStr -> Task.err NonNumberGiven +## when num_result is +## Ok num -> Task.ok(Step(total + num)) +## Err(StdinErr(EndOfFile)) -> Task.ok(Done(total)) +## Err(InvalidNumStr) -> Task.err(NonNumberGiven) +## ) ## ``` loop : state, (state -> Task [Step state, Done done] err) -> Task done err loop = \state, step -> looper = \current -> - (@Task next) = step current - when next {} is - Err e -> Err e - Ok (Done newResult) -> Ok newResult - Ok (Step newState) -> looper (newState) + @Task(next) = step(current) + when next({}) is + Err(e) -> Err(e) + Ok(Done(new_result)) -> Ok(new_result) + Ok(Step(new_state)) -> looper(new_state) - @Task \{} -> looper state + @Task(\{} -> looper(state)) ## Create a task that always succeeds with the value provided. ## ## ``` ## # Always succeeds with "Louis" -## getName : Task.Task Str * -## getName = Task.ok "Louis" +## get_name : Task.Task Str * +## get_name = Task.ok("Louis") ## ``` ## ok : a -> Task a * -ok = \a -> @Task \{} -> Ok a +ok = \a -> @Task(\{} -> Ok(a)) ## Create a task that always fails with the error provided. ## ## ``` ## # Always fails with the tag `CustomError Str` ## customError : Str -> Task.Task {} [CustomError Str] -## customError = \err -> Task.err (CustomError err) +## customError = \err -> Task.err(CustomError(err)) ## ``` ## err : a -> Task * a -err = \a -> @Task \{} -> Err a +err = \a -> @Task(\{} -> Err(a)) ## Transform a given Task with a function that handles the success or error case ## and returns another task based on that. This is useful for chaining tasks @@ -88,105 +89,107 @@ err = \a -> @Task \{} -> Err a ## ## Consider the following task: ## -## `canFail : Task {} [Failure, AnotherFail, YetAnotherFail]` +## `can_fail : Task {} [Failure, AnotherFail, YetAnotherFail]` ## ## We can use [attempt] to handle the failure cases using the following: ## ## ``` -## Task.attempt canFail \result -> +## Task.attempt(can_fail, \result -> ## when result is -## Ok Success -> Stdout.line "Success!" -## Err Failure -> Stdout.line "Oops, failed!" -## Err AnotherFail -> Stdout.line "Ooooops, another failure!" -## Err YetAnotherFail -> Stdout.line "Really big oooooops, yet again!" +## Ok(Success) -> Stdout.line("Success!") +## Err(Failure) -> Stdout.line("Oops, failed!") +## Err(AnotherFail) -> Stdout.line("Ooooops, another failure!") +## Err(YetAnotherFail) -> Stdout.line("Really big oooooops, yet again!") +## ) ## ``` ## -## Here we know that the `canFail` task may fail, and so we use +## Here we know that the `can_fail` task may fail, and so we use ## `Task.attempt` to convert the task to a `Result` and then use pattern ## matching to handle the success and possible failure cases. attempt : Task a b, (Result a b -> Task c d) -> Task c d -attempt = \@Task task, transform -> - @Task \{} -> - (@Task transformed) = transform (task {}) +attempt = \@Task(task), transform -> + @Task(\{} -> + @Task(transformed) = transform(task({})) - transformed {} + transformed({})) ## Take the success value from a given [Task] and use that to generate a new [Task]. ## ## We can [await] Task results with callbacks: ## ## ``` -## Task.await (Stdin.line "What's your name?") \name -> -## Stdout.line "Your name is: $(name)" +## Task.await(Stdin.line("What's your name?")), \name -> +## Stdout.line("Your name is: $(name)") +## ) ## ``` ## ## Or we can more succinctly use the `!` bang operator, which desugars to [await]: ## ## ``` -## name = Stdin.line! "What's your name?" -## Stdout.line "Your name is: $(name)" +## name = Stdin.line!("What's your name?") +## Stdout.line("Your name is: $(name)") ## ``` await : Task a b, (a -> Task c b) -> Task c b -await = \@Task task, transform -> - @Task \{} -> - when task {} is - Ok a -> - (@Task transformed) = transform a - transformed {} +await = \@Task(task), transform -> + @Task(\{} -> + when task({}) is + Ok(a) -> + @Task(transformed) = transform(a) + transformed({}) - Err b -> - Err b + Err(b) -> + Err(b)) ## Take the error value from a given [Task] and use that to generate a new [Task]. ## ## ``` -## # Prints "Something went wrong!" to standard error if `canFail` fails. -## canFail -## |> Task.onErr \_ -> Stderr.line "Something went wrong!" +## # Prints "Something went wrong!" to standard error if `can_fail` fails. +## can_fail +## |> Task.on_err(\_ -> Stderr.line("Something went wrong!")) ## ``` -onErr : Task a b, (b -> Task a c) -> Task a c -onErr = \@Task task, transform -> - @Task \{} -> - when task {} is - Ok a -> - Ok a +on_err : Task a b, (b -> Task a c) -> Task a c +on_err = \@Task(task), transform -> + @Task(\{} -> + when task({}) is + Ok(a) -> + Ok(a) - Err b -> - (@Task transformed) = transform b - transformed {} + Err(b) -> + @Task(transformed) = transform(b) + transformed({})) ## Transform the success value of a given [Task] with a given function. ## ## ``` ## # Succeeds with a value of "Bonjour Louis!" -## Task.ok "Louis" -## |> Task.map (\name -> "Bonjour $(name)!") +## Task.ok("Louis") +## |> Task.map(\name -> "Bonjour $(name)!") ## ``` map : Task a c, (a -> b) -> Task b c -map = \@Task task, transform -> - @Task \{} -> - when task {} is - Ok a -> Ok (transform a) - Err b -> Err b +map = \@Task(task), transform -> + @Task(\{} -> + when task({}) is + Ok(a) -> Ok(transform(a)) + Err(b) -> Err(b)) ## Transform the error value of a given [Task] with a given function. ## ## ``` ## # Ignore the fail value, and map it to the tag `CustomError` -## canFail -## |> Task.mapErr \_ -> CustomError +## can_fail +## |> Task.map_err(\_ -> CustomError) ## ``` -mapErr : Task c a, (a -> b) -> Task c b -mapErr = \@Task task, transform -> - @Task \{} -> - when task {} is - Ok a -> Ok a - Err b -> Err (transform b) +map_err : Task c a, (a -> b) -> Task c b +map_err = \@Task(task), transform -> + @Task(\{} -> + when task({}) is + Ok(a) -> Ok(a) + Err(b) -> Err(transform(b))) ## Use a Result among other Tasks by converting it into a [Task]. -fromResult : Result a b -> Task a b -fromResult = \res -> - @Task \{} -> res +from_result : Result a b -> Task a b +from_result = \res -> + @Task(\{} -> res) ## Apply a task to another task applicatively. ## @@ -194,8 +197,8 @@ fromResult = \res -> batch : Task a c -> (Task (a -> b) c -> Task b c) batch = \current -> \next -> - await next \f -> - map current f + await(next, \f -> + map(current, f)) ## Combine the values of two tasks with a custom combining function. ## @@ -204,54 +207,54 @@ batch = \current -> ## ``` ## { a, b, c } = ## { Task.combine <- -## a: Task.ok 123, -## b: File.read "file.txt", -## c: Http.get "http://api.com/", +## a: Task.ok(123), +## b: File.read("file.txt"), +## c: Http.get("http://api.com/"), ## }! ## ``` combine : Task a err, Task b err, (a, b -> c) -> Task c err -combine = \@Task leftTask, @Task rightTask, combiner -> - @Task \{} -> - left = try leftTask {} - right = try rightTask {} +combine = \@Task(left_task), @Task(right_task), combiner -> + @Task(\{} -> + left = try(left_task, {}) + right = try(right_task, {}) - Ok (combiner left right) + Ok(combiner(left, right))) ## Apply each task in a list sequentially, and return a list of the resulting values. ## Each task will be awaited before beginning the next task. ## ## ``` -## fetchAuthorTasks : List (Task Author [DbError]) +## fetch_author_tasks : List (Task Author [DbError]) ## -## getAuthors : Task (List Author) [DbError] -## getAuthors = Task.sequence fetchAuthorTasks +## get_authors : Task (List Author) [DbError] +## get_authors = Task.sequence(fetch_author_tasks) ## ``` ## sequence : List (Task ok err) -> Task (List ok) err -sequence = \taskList -> - Task.loop (taskList, List.withCapacity (List.len taskList)) \(tasks, values) -> +sequence = \task_list -> + Task.loop((task_list, List.with_capacity(List.len(task_list))), \(tasks, values) -> when tasks is [task, .. as rest] -> - Task.map task \value -> - Step (rest, List.append values value) + Task.map(task, \value -> + Step((rest, List.append(values, value)))) [] -> - Task.ok (Done values) + Task.ok(Done(values))) ## Apply a task repeatedly for each item in a list ## ## ``` ## authors : List Author -## saveAuthor : Author -> Task {} [DbError] +## save_author : Author -> Task {} [DbError] ## -## saveAuthors : Task (List Author) [DbError] -## saveAuthors = Task.forEach authors saveAuthor +## save_authors : Task (List Author) [DbError] +## save_authors = Task.for_each(authors, save_author) ## ``` ## -forEach : List a, (a -> Task {} b) -> Task {} b -forEach = \items, fn -> - List.walk items (ok {}) \state, item -> - state |> await \_ -> fn item +for_each : List a, (a -> Task {} b) -> Task {} b +for_each = \items, fn -> + List.walk(items, ok({}), \state, item -> + state |> await(\_ -> fn(item))) ## Transform a task that can either succeed with `ok`, or fail with `err`, into ## a task that succeeds with `Result ok err`. @@ -260,16 +263,16 @@ forEach = \items, fn -> ## ## ``` ## # Path.roc -## checkFile : Str -> Task [Good, Bad] [IOError] +## check_file : Str -> Task [Good, Bad] [IOError] ## ## # main.roc -## when checkFile "/usr/local/bin/roc" |> Task.result! is -## Ok Good -> "..." -## Ok Bad -> "..." -## Err IOError -> "..." +## when check_file("/usr/local/bin/roc") |> Task.result! is +## Ok(Good) -> "..." +## Ok(Bad) -> "..." +## Err(IOError) -> "..." ## ``` ## result : Task ok err -> Task (Result ok err) * -result = \@Task task -> - @Task \{} -> - Ok (task {}) +result = \@Task(task) -> + @Task(\{} -> + Ok(task({}))) diff --git a/crates/compiler/collections/src/small_string_interner.rs b/crates/compiler/collections/src/small_string_interner.rs index f9f009266c8..930b28d25e9 100644 --- a/crates/compiler/collections/src/small_string_interner.rs +++ b/crates/compiler/collections/src/small_string_interner.rs @@ -1,4 +1,5 @@ use std::{fmt::Debug, mem::ManuallyDrop}; +use std::borrow::Cow; /// Collection of small (length < u16::MAX) strings, stored compactly. #[derive(Clone, Default, PartialEq, Eq)] @@ -113,6 +114,7 @@ impl SmallStringInterner { /// Insert without deduplicating pub fn insert(&mut self, string: &str) -> usize { + let string = Self::snakify_ident(string); let bytes = string.as_bytes(); assert!(bytes.len() < (1 << 15)); @@ -175,6 +177,7 @@ impl SmallStringInterner { pub fn find_indices<'a>(&'a self, string: &'a str) -> impl Iterator + 'a { use std::slice::from_raw_parts; + let string = Self::snakify_ident(string); let target_length = string.len(); let lengths: &[i16] = @@ -226,6 +229,7 @@ impl SmallStringInterner { } pub fn update(&mut self, index: usize, new_string: &str) { + let new_string = Self::snakify_ident(new_string); let length = new_string.len(); let offset = self.buffer.len(); @@ -240,7 +244,8 @@ impl SmallStringInterner { pub fn find_and_update(&mut self, old_string: &str, new_string: &str) -> Option { match self.find_index(old_string) { Some(index) => { - self.update(index, new_string); + let new_string = Self::snakify_ident(new_string); + self.update(index, &new_string); Some(index) } @@ -255,6 +260,52 @@ impl SmallStringInterner { pub fn is_empty(&self) -> bool { self.lengths.is_empty() } + + fn snakify_ident(s: &str) -> Cow<'_, str> { + if s.chars() + .next() + .is_some_and(|first_char| first_char.is_ascii_uppercase()) + || (s.contains('_') && !s.ends_with('_')) + { + return s.into(); + } + + let chars: Vec = s.chars().collect(); + let mut index = 0; + let len = chars.len(); + let mut out = String::new(); + + while index < len { + let prev = if index == 0 { + None + } else { + Some(chars[index - 1]) + }; + let c = chars[index]; + let next = chars.get(index + 1); + let boundary = match (prev, c, next) { + // LUU, LUN, and LUL (simplified to LU_) + (Some(p), curr, _) if !p.is_ascii_uppercase() && curr.is_ascii_uppercase() => true, + // UUL + (Some(p), curr, Some(n)) + if p.is_ascii_uppercase() + && curr.is_ascii_uppercase() + && n.is_ascii_lowercase() => + { + true + } + _ => false, + }; + // those are boundary transitions - should push _ and curr + if boundary { + out.push('_'); + } + out.push(c.to_ascii_lowercase()); + index += 1; + } + + out.into() + } } #[allow(dead_code)] diff --git a/crates/compiler/load/build.rs b/crates/compiler/load/build.rs index 9a515109271..058ca79bb21 100644 --- a/crates/compiler/load/build.rs +++ b/crates/compiler/load/build.rs @@ -29,6 +29,8 @@ const MODULES: &[(ModuleId, &str)] = &[ ]; fn main() { + panic!("Fail now to avoid infinite loading."); + for (module_id, filename) in MODULES { write_subs_for_module(*module_id, filename); } diff --git a/crates/compiler/module/src/symbol.rs b/crates/compiler/module/src/symbol.rs index 8be0f15cdd4..4965eaf75e6 100644 --- a/crates/compiler/module/src/symbol.rs +++ b/crates/compiler/module/src/symbol.rs @@ -1195,45 +1195,45 @@ define_builtins! { 12 NUM_F64: "F64" exposed_type=true // the Num.F64 type alias 13 NUM_F32: "F32" exposed_type=true // the Num.F32 type alias 14 NUM_FLOATINGPOINT: "FloatingPoint" exposed_type=true // Float : Num FloatingPoint - 15 NUM_MAX_F32: "maxF32" - 16 NUM_MIN_F32: "minF32" + 15 NUM_MAX_F32: "max_f32" + 16 NUM_MIN_F32: "min_f32" 17 NUM_ABS: "abs" 18 NUM_NEG: "neg" 19 NUM_ADD: "add" 20 NUM_SUB: "sub" 21 NUM_MUL: "mul" - 22 NUM_LT: "isLt" - 23 NUM_LTE: "isLte" - 24 NUM_GT: "isGt" - 25 NUM_GTE: "isGte" - 26 NUM_TO_FRAC: "toFrac" + 22 NUM_LT: "is_lt" + 23 NUM_LTE: "is_lte" + 24 NUM_GT: "is_gt" + 25 NUM_GTE: "is_gte" + 26 NUM_TO_FRAC: "to_frac" 27 NUM_SIN: "sin" 28 NUM_COS: "cos" 29 NUM_TAN: "tan" - 30 NUM_IS_ZERO: "isZero" - 31 NUM_IS_EVEN: "isEven" - 32 NUM_IS_ODD: "isOdd" - 33 NUM_IS_POSITIVE: "isPositive" - 34 NUM_IS_NEGATIVE: "isNegative" + 30 NUM_IS_ZERO: "is_zero" + 31 NUM_IS_EVEN: "is_even" + 32 NUM_IS_ODD: "is_odd" + 33 NUM_IS_POSITIVE: "is_positive" + 34 NUM_IS_NEGATIVE: "is_negative" 35 NUM_REM: "rem" - 36 NUM_REM_CHECKED: "remChecked" + 36 NUM_REM_CHECKED: "rem_checked" 37 NUM_DIV_FRAC: "div" - 38 NUM_DIV_FRAC_CHECKED: "divChecked" - 39 NUM_DIV_TRUNC: "divTrunc" - 40 NUM_DIV_TRUNC_CHECKED: "divTruncChecked" + 38 NUM_DIV_FRAC_CHECKED: "div_checked" + 39 NUM_DIV_TRUNC: "div_trunc" + 40 NUM_DIV_TRUNC_CHECKED: "div_trunc_checked" 41 NUM_SQRT: "sqrt" - 42 NUM_SQRT_CHECKED: "sqrtChecked" + 42 NUM_SQRT_CHECKED: "sqrt_checked" 43 NUM_LOG: "log" - 44 NUM_LOG_CHECKED: "logChecked" + 44 NUM_LOG_CHECKED: "log_checked" 45 NUM_ROUND: "round" 46 NUM_COMPARE: "compare" 47 NUM_POW: "pow" 48 NUM_CEILING: "ceiling" - 49 NUM_POW_INT: "powInt" + 49 NUM_POW_INT: "pow_int" 50 NUM_FLOOR: "floor" - 51 NUM_ADD_WRAP: "addWrap" - 52 NUM_ADD_CHECKED: "addChecked" - 53 NUM_ADD_SATURATED: "addSaturated" + 51 NUM_ADD_WRAP: "add_wrap" + 52 NUM_ADD_CHECKED: "add_checked" + 53 NUM_ADD_SATURATED: "add_saturated" 54 NUM_ATAN: "atan" 55 NUM_ACOS: "acos" 56 NUM_ASIN: "asin" @@ -1249,107 +1249,107 @@ define_builtins! { 66 NUM_UNSIGNED8: "Unsigned8" exposed_type=true 67 NUM_BINARY64: "Binary64" exposed_type=true 68 NUM_BINARY32: "Binary32" exposed_type=true - 69 NUM_BITWISE_AND: "bitwiseAnd" - 70 NUM_BITWISE_XOR: "bitwiseXor" - 71 NUM_BITWISE_OR: "bitwiseOr" - 72 NUM_SHIFT_LEFT: "shiftLeftBy" - 73 NUM_SHIFT_RIGHT: "shiftRightBy" - 74 NUM_SHIFT_RIGHT_ZERO_FILL: "shiftRightZfBy" - 75 NUM_SUB_WRAP: "subWrap" - 76 NUM_SUB_CHECKED: "subChecked" - 77 NUM_SUB_SATURATED: "subSaturated" - 78 NUM_MUL_WRAP: "mulWrap" - 79 NUM_MUL_CHECKED: "mulChecked" - 80 NUM_MUL_SATURATED: "mulSaturated" + 69 NUM_BITWISE_AND: "bitwise_and" + 70 NUM_BITWISE_XOR: "bitwise_xor" + 71 NUM_BITWISE_OR: "bitwise_or" + 72 NUM_SHIFT_LEFT: "shift_left_by" + 73 NUM_SHIFT_RIGHT: "shift_right_by" + 74 NUM_SHIFT_RIGHT_ZERO_FILL: "shift_right_zf_by" + 75 NUM_SUB_WRAP: "sub_wrap" + 76 NUM_SUB_CHECKED: "sub_checked" + 77 NUM_SUB_SATURATED: "sub_saturated" + 78 NUM_MUL_WRAP: "mul_wrap" + 79 NUM_MUL_CHECKED: "mul_checked" + 80 NUM_MUL_SATURATED: "mul_saturated" 81 NUM_INT: "Int" exposed_type=true 82 NUM_FRAC: "Frac" exposed_type=true 83 NUM_E: "e" 84 NUM_PI: "pi" 85 NUM_TAU: "tau" - 86 NUM_IS_MULTIPLE_OF: "isMultipleOf" + 86 NUM_IS_MULTIPLE_OF: "is_multiple_of" 87 NUM_DECIMAL: "Decimal" exposed_type=true 88 NUM_DEC: "Dec" exposed_type=true // the Num.Dectype alias - 89 NUM_COUNT_ONE_BITS: "countOneBits" - 90 NUM_ABS_DIFF: "absDiff" - 91 NUM_IS_NAN: "isNaN" - 92 NUM_IS_INFINITE: "isInfinite" - 93 NUM_IS_FINITE: "isFinite" - 94 NUM_COUNT_LEADING_ZERO_BITS: "countLeadingZeroBits" - 95 NUM_COUNT_TRAILING_ZERO_BITS: "countTrailingZeroBits" - 96 NUM_TO_STR: "toStr" - 97 NUM_MIN_I8: "minI8" - 98 NUM_MAX_I8: "maxI8" - 99 NUM_MIN_U8: "minU8" - 100 NUM_MAX_U8: "maxU8" - 101 NUM_MIN_I16: "minI16" - 102 NUM_MAX_I16: "maxI16" - 103 NUM_MIN_U16: "minU16" - 104 NUM_MAX_U16: "maxU16" - 105 NUM_MIN_I32: "minI32" - 106 NUM_MAX_I32: "maxI32" - 107 NUM_MIN_U32: "minU32" - 108 NUM_MAX_U32: "maxU32" - 109 NUM_MIN_I64: "minI64" - 110 NUM_MAX_I64: "maxI64" - 111 NUM_MIN_U64: "minU64" - 112 NUM_MAX_U64: "maxU64" - 113 NUM_MIN_I128: "minI128" - 114 NUM_MAX_I128: "maxI128" - 115 NUM_MIN_U128: "minU128" - 116 NUM_MAX_U128: "maxU128" - 117 NUM_TO_I8: "toI8" - 118 NUM_TO_I8_CHECKED: "toI8Checked" - 119 NUM_TO_I16: "toI16" - 120 NUM_TO_I16_CHECKED: "toI16Checked" - 121 NUM_TO_I32: "toI32" - 122 NUM_TO_I32_CHECKED: "toI32Checked" - 123 NUM_TO_I64: "toI64" - 124 NUM_TO_I64_CHECKED: "toI64Checked" - 125 NUM_TO_I128: "toI128" - 126 NUM_TO_I128_CHECKED: "toI128Checked" - 127 NUM_TO_U8: "toU8" - 128 NUM_TO_U8_CHECKED: "toU8Checked" - 129 NUM_TO_U16: "toU16" - 130 NUM_TO_U16_CHECKED: "toU16Checked" - 131 NUM_TO_U32: "toU32" - 132 NUM_TO_U32_CHECKED: "toU32Checked" - 133 NUM_TO_U64: "toU64" - 134 NUM_TO_U64_CHECKED: "toU64Checked" - 135 NUM_TO_U128: "toU128" - 136 NUM_TO_U128_CHECKED: "toU128Checked" - 137 NUM_DIV_CEIL: "divCeil" - 138 NUM_DIV_CEIL_CHECKED: "divCeilChecked" - 139 NUM_TO_F32: "toF32" - 140 NUM_TO_F32_CHECKED: "toF32Checked" - 141 NUM_TO_F64: "toF64" - 142 NUM_TO_F64_CHECKED: "toF64Checked" - 143 NUM_MAX_F64: "maxF64" - 144 NUM_MIN_F64: "minF64" - 145 NUM_ADD_CHECKED_LOWLEVEL: "addCheckedLowlevel" - 146 NUM_SUB_CHECKED_LOWLEVEL: "subCheckedLowlevel" - 147 NUM_MUL_CHECKED_LOWLEVEL: "mulCheckedLowlevel" + 89 NUM_COUNT_ONE_BITS: "count_one_bits" + 90 NUM_ABS_DIFF: "abs_diff" + 91 NUM_IS_NAN: "is_nan" + 92 NUM_IS_INFINITE: "is_infinite" + 93 NUM_IS_FINITE: "is_finite" + 94 NUM_COUNT_LEADING_ZERO_BITS: "count_leading_zero_bits" + 95 NUM_COUNT_TRAILING_ZERO_BITS: "count_trailing_zero_bits" + 96 NUM_TO_STR: "to_str" + 97 NUM_MIN_I8: "min_i8" + 98 NUM_MAX_I8: "max_i8" + 99 NUM_MIN_U8: "min_u8" + 100 NUM_MAX_U8: "max_u8" + 101 NUM_MIN_I16: "min_i16" + 102 NUM_MAX_I16: "max_i16" + 103 NUM_MIN_U16: "min_u16" + 104 NUM_MAX_U16: "max_u16" + 105 NUM_MIN_I32: "min_i32" + 106 NUM_MAX_I32: "max_i32" + 107 NUM_MIN_U32: "min_u32" + 108 NUM_MAX_U32: "max_u32" + 109 NUM_MIN_I64: "min_i64" + 110 NUM_MAX_I64: "max_i64" + 111 NUM_MIN_U64: "min_u64" + 112 NUM_MAX_U64: "max_u64" + 113 NUM_MIN_I128: "min_i128" + 114 NUM_MAX_I128: "max_i128" + 115 NUM_MIN_U128: "min_u128" + 116 NUM_MAX_U128: "max_u128" + 117 NUM_TO_I8: "to_i8" + 118 NUM_TO_I8_CHECKED: "to_i8_checked" + 119 NUM_TO_I16: "to_i16" + 120 NUM_TO_I16_CHECKED: "to_i16_checked" + 121 NUM_TO_I32: "to_i32" + 122 NUM_TO_I32_CHECKED: "to_i32_checked" + 123 NUM_TO_I64: "to_i64" + 124 NUM_TO_I64_CHECKED: "to_i64_checked" + 125 NUM_TO_I128: "to_i128" + 126 NUM_TO_I128_CHECKED: "to_i128_checked" + 127 NUM_TO_U8: "to_u8" + 128 NUM_TO_U8_CHECKED: "to_u8_checked" + 129 NUM_TO_U16: "to_u16" + 130 NUM_TO_U16_CHECKED: "to_u16_checked" + 131 NUM_TO_U32: "to_u32" + 132 NUM_TO_U32_CHECKED: "to_u32_checked" + 133 NUM_TO_U64: "to_u64" + 134 NUM_TO_U64_CHECKED: "to_u64_checked" + 135 NUM_TO_U128: "to_u128" + 136 NUM_TO_U128_CHECKED: "to_u128_checked" + 137 NUM_DIV_CEIL: "div_ceil" + 138 NUM_DIV_CEIL_CHECKED: "div_ceil_checked" + 139 NUM_TO_F32: "to_f32" + 140 NUM_TO_F32_CHECKED: "to_f32_checked" + 141 NUM_TO_F64: "to_f64" + 142 NUM_TO_F64_CHECKED: "to_f64_checked" + 143 NUM_MAX_F64: "max_f64" + 144 NUM_MIN_F64: "min_f64" + 145 NUM_ADD_CHECKED_LOWLEVEL: "add_checked_lowlevel" + 146 NUM_SUB_CHECKED_LOWLEVEL: "sub_checked_lowlevel" + 147 NUM_MUL_CHECKED_LOWLEVEL: "mul_checked_lowlevel" 148 NUM_MIN: "min" 149 NUM_MAX: "max" - 150 NUM_BITWISE_NOT: "bitwiseNot" - 151 NUM_INT_CAST: "intCast" - 152 NUM_IS_APPROX_EQ: "isApproxEq" - 153 NUM_BYTES_TO_U16_LOWLEVEL: "bytesToU16Lowlevel" - 154 NUM_BYTES_TO_U32_LOWLEVEL: "bytesToU32Lowlevel" - 155 NUM_BYTES_TO_U64_LOWLEVEL: "bytesToU64Lowlevel" - 156 NUM_BYTES_TO_U128_LOWLEVEL: "bytesToU128Lowlevel" - 157 NUM_DIV_TRUNC_UNCHECKED: "divTruncUnchecked" // traps on division by zero - 158 NUM_REM_UNCHECKED: "remUnchecked" // traps on division by zero - 159 NUM_WITHOUT_DECIMAL_POINT: "withoutDecimalPoint" - 160 NUM_WITH_DECIMAL_POINT: "withDecimalPoint" - 161 NUM_F32_TO_PARTS: "f32ToParts" - 162 NUM_F64_TO_PARTS: "f64ToParts" - 163 NUM_F32_FROM_PARTS: "f32FromParts" - 164 NUM_F64_FROM_PARTS: "f64FromParts" - 165 NUM_NAN_F32: "nanF32" - 166 NUM_NAN_F64: "nanF64" - 167 NUM_INFINITY_F32: "infinityF32" - 168 NUM_INFINITY_F64: "infinityF64" - 169 NUM_FROM_BOOL: "fromBool" + 150 NUM_BITWISE_NOT: "bitwise_not" + 151 NUM_INT_CAST: "int_cast" + 152 NUM_IS_APPROX_EQ: "is_approx_eq" + 153 NUM_BYTES_TO_U16_LOWLEVEL: "bytes_to_u16_owlevel" + 154 NUM_BYTES_TO_U32_LOWLEVEL: "bytes_to_u32_lowlevel" + 155 NUM_BYTES_TO_U64_LOWLEVEL: "bytes_to_u64_lowlevel" + 156 NUM_BYTES_TO_U128_LOWLEVEL: "bytes_to_u128_lowlevel" + 157 NUM_DIV_TRUNC_UNCHECKED: "div_trunc_unchecked" // traps on division by zero + 158 NUM_REM_UNCHECKED: "rem_unchecked" // traps on division by zero + 159 NUM_WITHOUT_DECIMAL_POINT: "without_decimal_point" + 160 NUM_WITH_DECIMAL_POINT: "with_decimal_point" + 161 NUM_F32_TO_PARTS: "f32_to_parts" + 162 NUM_F64_TO_PARTS: "f64_to_parts" + 163 NUM_F32_FROM_PARTS: "f32_from_parts" + 164 NUM_F64_FROM_PARTS: "f64_from_parts" + 165 NUM_NAN_F32: "nan_f32" + 166 NUM_NAN_F64: "nan_f64" + 167 NUM_INFINITY_F32: "infinity_f32" + 168 NUM_INFINITY_F64: "infinity_f64" + 169 NUM_FROM_BOOL: "from_bool" } 4 BOOL: "Bool" => { 0 BOOL_BOOL: "Bool" exposed_type=true // the Bool.Bool type alias @@ -1359,75 +1359,75 @@ define_builtins! { 4 BOOL_OR: "or" 5 BOOL_NOT: "not" 6 BOOL_XOR: "xor" - 7 BOOL_NEQ: "isNotEq" + 7 BOOL_NEQ: "is_not_eq" 8 BOOL_EQ: "Eq" exposed_type=true - 9 BOOL_IS_EQ: "isEq" - 10 BOOL_IS_EQ_IMPL: "boolIsEq" - unexposed 11 BOOL_STRUCTURAL_EQ: "structuralEq" - unexposed 12 BOOL_STRUCTURAL_NOT_EQ: "structuralNotEq" + 9 BOOL_IS_EQ: "is_eq" + 10 BOOL_IS_EQ_IMPL: "bool_is_eq" + unexposed 11 BOOL_STRUCTURAL_EQ: "structural_eq" + unexposed 12 BOOL_STRUCTURAL_NOT_EQ: "structural_not_eq" } 5 STR: "Str" => { 0 STR_STR: "Str" exposed_apply_type=true // the Str.Str type alias - 1 STR_IS_EMPTY: "isEmpty" + 1 STR_IS_EMPTY: "is_empty" 2 STR_APPEND: "#append" // unused 3 STR_CONCAT: "concat" - 4 STR_JOIN_WITH: "joinWith" - 5 STR_SPLIT_ON: "splitOn" - 6 STR_WITH_PREFIX: "withPrefix" - 7 STR_STARTS_WITH: "startsWith" - 8 STR_ENDS_WITH: "endsWith" - 9 STR_FROM_UTF8: "fromUtf8" + 4 STR_JOIN_WITH: "join_with" + 5 STR_SPLIT_ON: "split_on" + 6 STR_WITH_PREFIX: "with_prefix" + 7 STR_STARTS_WITH: "starts_with" + 8 STR_ENDS_WITH: "ends_with" + 9 STR_FROM_UTF8: "from_utf8" 10 STR_UT8_PROBLEM: "Utf8Problem" // the Utf8Problem type alias 11 STR_UT8_BYTE_PROBLEM: "Utf8ByteProblem" // the Utf8ByteProblem type alias - 12 STR_TO_UTF8: "toUtf8" - 13 STR_WALK_UTF8: "walkUtf8" + 12 STR_TO_UTF8: "to_utf8" + 13 STR_WALK_UTF8: "walk_utf8" 14 STR_ALIAS_ANALYSIS_STATIC: "#aliasAnalysisStatic" // string with the static lifetime - 15 STR_FROM_UTF8_RANGE: "fromUtf8Range" + 15 STR_FROM_UTF8_RANGE: "from_utf8_range" 16 STR_REPEAT: "repeat" 17 STR_TRIM: "trim" - 18 STR_TRIM_START: "trimStart" - 19 STR_TRIM_END: "trimEnd" - 20 STR_WITH_CAPACITY: "withCapacity" - 21 STR_TO_F64: "toF64" - 22 STR_TO_F32: "toF32" - 23 STR_TO_DEC: "toDec" - 24 STR_TO_U128: "toU128" - 25 STR_TO_I128: "toI128" - 26 STR_TO_U64: "toU64" - 27 STR_TO_I64: "toI64" - 28 STR_TO_U32: "toU32" - 29 STR_TO_I32: "toI32" - 30 STR_TO_U16: "toU16" - 31 STR_TO_I16: "toI16" - 32 STR_TO_U8: "toU8" - 33 STR_TO_I8: "toI8" + 18 STR_TRIM_START: "trim_start" + 19 STR_TRIM_END: "trim_end" + 20 STR_WITH_CAPACITY: "with_capacity" + 21 STR_TO_F64: "to_f64" + 22 STR_TO_F32: "to_f32" + 23 STR_TO_DEC: "to_dec" + 24 STR_TO_U128: "to_u128" + 25 STR_TO_I128: "to_i128" + 26 STR_TO_U64: "to_u64" + 27 STR_TO_I64: "to_i64" + 28 STR_TO_U32: "to_u32" + 29 STR_TO_I32: "to_i32" + 30 STR_TO_U16: "to_u16" + 31 STR_TO_I16: "to_i16" + 32 STR_TO_U8: "to_u8" + 33 STR_TO_I8: "to_i8" 34 STR_CONTAINS: "contains" - 35 STR_GET_UNSAFE: "getUnsafe" - 36 STR_COUNT_UTF8_BYTES: "countUtf8Bytes" - 37 STR_SUBSTRING_UNSAFE: "substringUnsafe" - 38 STR_SPLIT_FIRST: "splitFirst" - 39 STR_SPLIT_LAST: "splitLast" - 40 STR_WALK_UTF8_WITH_INDEX: "walkUtf8WithIndex" + 35 STR_GET_UNSAFE: "get_unsafe" + 36 STR_COUNT_UTF8_BYTES: "count_utf8_bytes" + 37 STR_SUBSTRING_UNSAFE: "substring_unsafe" + 38 STR_SPLIT_FIRST: "split_first" + 39 STR_SPLIT_LAST: "split_last" + 40 STR_WALK_UTF8_WITH_INDEX: "walk_utf8_with_index" 41 STR_RESERVE: "reserve" - 42 STR_TO_NUM: "strToNum" - 43 STR_FROM_UTF8_LOWLEVEL: "fromUtf8Lowlevel" + 42 STR_TO_NUM: "str_to_num" + 43 STR_FROM_UTF8_LOWLEVEL: "from_utf8_lowlevel" 44 STR_CAPACITY: "capacity" - 45 STR_REPLACE_EACH: "replaceEach" - 46 STR_REPLACE_FIRST: "replaceFirst" - 47 STR_REPLACE_LAST: "replaceLast" - 48 STR_RELEASE_EXCESS_CAPACITY: "releaseExcessCapacity" - 49 STR_DROP_PREFIX: "dropPrefix" - 50 STR_DROP_SUFFIX: "dropSuffix" + 45 STR_REPLACE_EACH: "replace_each" + 46 STR_REPLACE_FIRST: "replace_first" + 47 STR_REPLACE_LAST: "replace_last" + 48 STR_RELEASE_EXCESS_CAPACITY: "release_excess_capacity" + 49 STR_DROP_PREFIX: "drop_prefix" + 50 STR_DROP_SUFFIX: "drop_suffix" } 6 LIST: "List" => { 0 LIST_LIST: "List" exposed_apply_type=true // the List.List type alias - 1 LIST_IS_EMPTY: "isEmpty" + 1 LIST_IS_EMPTY: "is_empty" 2 LIST_GET: "get" 3 LIST_SET: "set" 4 LIST_APPEND: "append" 5 LIST_MAP: "map" 6 LIST_LEN_U64: "len" - 7 LIST_WALK_BACKWARDS: "walkBackwards" + 7 LIST_WALK_BACKWARDS: "walk_backwards" 8 LIST_CONCAT: "concat" 9 LIST_FIRST: "first" 10 LIST_SINGLE: "single" @@ -1435,99 +1435,99 @@ define_builtins! { 12 LIST_REVERSE: "reverse" 13 LIST_PREPEND: "prepend" 14 LIST_JOIN: "join" - 15 LIST_KEEP_IF: "keepIf" + 15 LIST_KEEP_IF: "keep_if" 16 LIST_CONTAINS: "contains" 17 LIST_SUM: "sum" 18 LIST_WALK: "walk" 19 LIST_LAST: "last" - 20 LIST_KEEP_OKS: "keepOks" - 21 LIST_KEEP_ERRS: "keepErrs" - 22 LIST_MAP_WITH_INDEX: "mapWithIndex" + 20 LIST_KEEP_OKS: "keep_oks" + 21 LIST_KEEP_ERRS: "keep_errs" + 22 LIST_MAP_WITH_INDEX: "map_with_index" 23 LIST_MAP2: "map2" 24 LIST_MAP3: "map3" 25 LIST_PRODUCT: "product" - 26 LIST_WALK_UNTIL: "walkUntil" + 26 LIST_WALK_UNTIL: "walk_until" 27 LIST_RANGE: "range" - 28 LIST_SORT_WITH: "sortWith" - 29 LIST_CHUNKS_OF: "chunksOf" + 28 LIST_SORT_WITH: "sort_with" + 29 LIST_CHUNKS_OF: "chunks_of" 30 LIST_SWAP: "swap" - 31 LIST_DROP_AT: "dropAt" - 32 LIST_DROP_LAST: "dropLast" + 31 LIST_DROP_AT: "drop_at" + 32 LIST_DROP_LAST: "drop_last" 33 LIST_MIN: "min" - 34 LIST_MIN_LT: "#minlt" + 34 LIST_MIN_LT: "#min_lt" 35 LIST_MAX: "max" - 36 LIST_MAX_GT: "#maxGt" + 36 LIST_MAX_GT: "#max_gt" 37 LIST_MAP4: "map4" - 38 LIST_DROP_FIRST: "dropFirst" - 39 LIST_JOIN_MAP: "joinMap" - 40 LIST_JOIN_MAP_CONCAT: "#joinMapConcat" + 38 LIST_DROP_FIRST: "drop_first" + 39 LIST_JOIN_MAP: "join_map" + 40 LIST_JOIN_MAP_CONCAT: "#join_map_concat" 41 LIST_ANY: "any" - 42 LIST_TAKE_FIRST: "takeFirst" - 43 LIST_TAKE_LAST: "takeLast" - 44 LIST_FIND_FIRST: "findFirst" - 45 LIST_FIND_LAST: "findLast" - 46 LIST_FIND_FIRST_INDEX: "findFirstIndex" - 47 LIST_FIND_LAST_INDEX: "findLastIndex" + 42 LIST_TAKE_FIRST: "take_first" + 43 LIST_TAKE_LAST: "take_last" + 44 LIST_FIND_FIRST: "find_first" + 45 LIST_FIND_LAST: "find_last" + 46 LIST_FIND_FIRST_INDEX: "find_first_index" + 47 LIST_FIND_LAST_INDEX: "find_last_index" 48 LIST_FIND_RESULT: "#find_result" // symbol used in the definition of List.findFirst 49 LIST_SUBLIST: "sublist" 50 LIST_INTERSPERSE: "intersperse" - 51 LIST_INTERSPERSE_CLOS: "#intersperseClos" - 52 LIST_SPLIT_AT: "splitAt" - 53 LIST_SPLIT_FIRST: "splitFirst" - 54 LIST_SPLIT_LAST: "splitLast" - 55 LIST_SPLIT_CLOS: "#splitClos" + 51 LIST_INTERSPERSE_CLOS: "#intersperse_clos" + 52 LIST_SPLIT_AT: "split_at" + 53 LIST_SPLIT_FIRST: "split_first" + 54 LIST_SPLIT_LAST: "split_last" + 55 LIST_SPLIT_CLOS: "#split_clos" 56 LIST_ALL: "all" - 57 LIST_DROP_IF: "dropIf" - 58 LIST_DROP_IF_PREDICATE: "#dropIfPred" - 59 LIST_SORT_ASC: "sortAsc" - 60 LIST_SORT_DESC: "sortDesc" - 61 LIST_SORT_DESC_COMPARE: "#sortDescCompare" - 62 LIST_STARTS_WITH: "startsWith" - 63 LIST_ENDS_WITH: "endsWith" + 57 LIST_DROP_IF: "drop_if" + 58 LIST_DROP_IF_PREDICATE: "#drop_if_pred" + 59 LIST_SORT_ASC: "sort_asc" + 60 LIST_SORT_DESC: "sort_desc" + 61 LIST_SORT_DESC_COMPARE: "#sort_desc_compare" + 62 LIST_STARTS_WITH: "starts_with" + 63 LIST_ENDS_WITH: "ends_with" 64 LIST_REPLACE: "replace" - 65 LIST_IS_UNIQUE: "#isUnique" - 66 LIST_GET_UNSAFE: "getUnsafe" - 67 LIST_REPLACE_UNSAFE: "replaceUnsafe" - 68 LIST_WITH_CAPACITY: "withCapacity" + 65 LIST_IS_UNIQUE: "#is_unique" + 66 LIST_GET_UNSAFE: "get_unsafe" + 67 LIST_REPLACE_UNSAFE: "replace_unsafe" + 68 LIST_WITH_CAPACITY: "with_capacity" 69 LIST_UNREACHABLE: "unreachable" 70 LIST_RESERVE: "reserve" - 71 LIST_APPEND_UNSAFE: "appendUnsafe" - 72 LIST_SUBLIST_LOWLEVEL: "sublistLowlevel" + 71 LIST_APPEND_UNSAFE: "append_unsafe" + 72 LIST_SUBLIST_LOWLEVEL: "sublist_lowlevel" 73 LIST_CAPACITY: "capacity" - 74 LIST_MAP_TRY: "mapTry" - 75 LIST_WALK_TRY: "walkTry" - 76 LIST_WALK_BACKWARDS_UNTIL: "walkBackwardsUntil" - 77 LIST_COUNT_IF: "countIf" - 78 LIST_WALK_FROM: "walkFrom" - 79 LIST_WALK_FROM_UNTIL: "walkFromUntil" - 80 LIST_ITER_HELP: "iterHelp" - 81 LIST_RELEASE_EXCESS_CAPACITY: "releaseExcessCapacity" + 74 LIST_MAP_TRY: "map_try" + 75 LIST_WALK_TRY: "walk_try" + 76 LIST_WALK_BACKWARDS_UNTIL: "walk_backwards_until" + 77 LIST_COUNT_IF: "count_if" + 78 LIST_WALK_FROM: "walk_from" + 79 LIST_WALK_FROM_UNTIL: "walk_from_until" + 80 LIST_ITER_HELP: "iter_help" + 81 LIST_RELEASE_EXCESS_CAPACITY: "release_excess_capacity" 82 LIST_UPDATE: "update" - 83 LIST_WALK_WITH_INDEX: "walkWithIndex" - 84 LIST_APPEND_IF_OK: "appendIfOk" - 85 LIST_PREPEND_IF_OK: "prependIfOk" - 86 LIST_WALK_WITH_INDEX_UNTIL: "walkWithIndexUntil" + 83 LIST_WALK_WITH_INDEX: "walk_with_index" + 84 LIST_APPEND_IF_OK: "append_if_ok" + 85 LIST_PREPEND_IF_OK: "prepend_if_ok" + 86 LIST_WALK_WITH_INDEX_UNTIL: "walk_with_index_until" 87 LIST_CLONE: "clone" - 88 LIST_LEN_USIZE: "lenUsize" - 89 LIST_CONCAT_UTF8: "concatUtf8" - 90 LIST_FOR_EACH_FX: "forEach!" - 91 LIST_FOR_EACH_TRY_FX: "forEachTry!" + 88 LIST_LEN_USIZE: "len_usize" + 89 LIST_CONCAT_UTF8: "concat_utf8" + 90 LIST_FOR_EACH_FX: "for_each!" + 91 LIST_FOR_EACH_TRY_FX: "for_each_try!" 92 LIST_WALK_FX: "walk!" - 93 LIST_SPLIT_ON: "splitOn" - 94 LIST_SPLIT_ON_LIST: "splitOnList" + 93 LIST_SPLIT_ON: "split_on" + 94 LIST_SPLIT_ON_LIST: "split_on_list" } 7 RESULT: "Result" => { 0 RESULT_RESULT: "Result" exposed_type=true // the Result.Result type alias - 1 RESULT_IS_ERR: "isErr" - 2 RESULT_ON_ERR: "onErr" + 1 RESULT_IS_ERR: "is_err" + 2 RESULT_ON_ERR: "on_err" 3 RESULT_MAP: "map" - 4 RESULT_MAP_ERR: "mapErr" - 5 RESULT_WITH_DEFAULT: "withDefault" + 4 RESULT_MAP_ERR: "map_err" + 5 RESULT_WITH_DEFAULT: "with_default" 6 RESULT_TRY: "try" - 7 RESULT_IS_OK: "isOk" - 8 RESULT_MAP_BOTH: "mapBoth" + 7 RESULT_IS_OK: "is_ok" + 8 RESULT_MAP_BOTH: "map_both" 9 RESULT_MAP_TWO: "map2" - 10 RESULT_ON_ERR_FX: "onErr!" + 10 RESULT_ON_ERR_FX: "on_err!" } 8 DICT: "Dict" => { 0 DICT_DICT: "Dict" exposed_type=true // the Dict.Dict type alias @@ -1542,29 +1542,29 @@ define_builtins! { 9 DICT_REMOVE: "remove" 10 DICT_WALK: "walk" - 11 DICT_WALK_UNTIL: "walkUntil" - 12 DICT_FROM_LIST: "fromList" - 13 DICT_TO_LIST: "toList" + 11 DICT_WALK_UNTIL: "walk_until" + 12 DICT_FROM_LIST: "from_list" + 13 DICT_TO_LIST: "to_list" 14 DICT_KEYS: "keys" 15 DICT_VALUES: "values" - 16 DICT_INSERT_ALL: "insertAll" // union - 17 DICT_KEEP_SHARED: "keepShared" // intersection - 18 DICT_REMOVE_ALL: "removeAll" // difference + 16 DICT_INSERT_ALL: "insert_all" // union + 17 DICT_KEEP_SHARED: "keep_shared" // intersection + 18 DICT_REMOVE_ALL: "remove_all" // difference - 19 DICT_WITH_CAPACITY: "withCapacity" + 19 DICT_WITH_CAPACITY: "with_capacity" 20 DICT_CAPACITY: "capacity" 21 DICT_UPDATE: "update" - 22 DICT_LIST_GET_UNSAFE: "listGetUnsafe" - 23 DICT_PSEUDO_SEED: "pseudoSeed" - 24 DICT_IS_EMPTY: "isEmpty" + 22 DICT_LIST_GET_UNSAFE: "list_get_unsafe" + 23 DICT_PSEUDO_SEED: "pseudo_seed" + 24 DICT_IS_EMPTY: "is_empty" 25 DICT_MAP: "map" - 26 DICT_JOINMAP: "joinMap" - 27 DICT_KEEP_IF: "keepIf" - 28 DICT_DROP_IF: "dropIf" + 26 DICT_JOINMAP: "join_map" + 27 DICT_KEEP_IF: "keep_if" + 28 DICT_DROP_IF: "drop_if" 29 DICT_RESERVE: "reserve" - 30 DICT_RELEASE_EXCESS_CAPACITY: "releaseExcessCapacity" + 30 DICT_RELEASE_EXCESS_CAPACITY: "release_excess_capacity" } 9 SET: "Set" => { 0 SET_SET: "Set" exposed_type=true // the Set.Set type alias @@ -1576,22 +1576,22 @@ define_builtins! { 6 SET_UNION: "union" 7 SET_DIFFERENCE: "difference" 8 SET_INTERSECTION: "intersection" - 9 SET_TO_LIST: "toList" - 10 SET_FROM_LIST: "fromList" + 9 SET_TO_LIST: "to_list" + 10 SET_FROM_LIST: "from_list" 11 SET_WALK: "walk" - 12 SET_WALK_UNTIL: "walkUntil" + 12 SET_WALK_UNTIL: "walk_until" 13 SET_WALK_USER_FUNCTION: "#walk_user_function" 14 SET_CONTAINS: "contains" - 15 SET_TO_DICT: "toDict" + 15 SET_TO_DICT: "to_dict" 16 SET_CAPACITY: "capacity" - 17 SET_IS_EMPTY: "isEmpty" + 17 SET_IS_EMPTY: "is_empty" 18 SET_MAP: "map" - 19 SET_JOIN_MAP: "joinMap" - 20 SET_KEEP_IF: "keepIf" - 21 SET_DROP_IF: "dropIf" - 22 SET_WITH_CAPACITY: "withCapacity" + 19 SET_JOIN_MAP: "join_map" + 20 SET_KEEP_IF: "keep_if" + 21 SET_DROP_IF: "drop_if" + 22 SET_WITH_CAPACITY: "with_capacity" 23 SET_RESERVE: "reserve" - 24 SET_RELEASE_EXCESS_CAPACITY: "releaseExcessCapacity" + 24 SET_RELEASE_EXCESS_CAPACITY: "release_excess_capacity" } 10 BOX: "Box" => { 0 BOX_BOX_TYPE: "Box" exposed_apply_type=true // the Box.Box opaque type @@ -1601,7 +1601,7 @@ define_builtins! { 11 ENCODE: "Encode" => { 0 ENCODE_ENCODER: "Encoder" exposed_type=true 1 ENCODE_ENCODING: "Encoding" exposed_type=true - 2 ENCODE_TO_ENCODER: "toEncoder" + 2 ENCODE_TO_ENCODER: "to_encoder" 3 ENCODE_ENCODERFORMATTING: "EncoderFormatting" exposed_type=true 4 ENCODE_U8: "u8" 5 ENCODE_U16: "u16" @@ -1623,9 +1623,9 @@ define_builtins! { 21 ENCODE_TUPLE: "tuple" 22 ENCODE_TAG: "tag" 23 ENCODE_CUSTOM: "custom" - 24 ENCODE_APPEND_WITH: "appendWith" + 24 ENCODE_APPEND_WITH: "append_with" 25 ENCODE_APPEND: "append" - 26 ENCODE_TO_BYTES: "toBytes" + 26 ENCODE_TO_BYTES: "to_bytes" } 12 DECODE: "Decode" => { 0 DECODE_DECODE_ERROR: "DecodeError" exposed_type=true @@ -1653,33 +1653,33 @@ define_builtins! { 22 DECODE_RECORD: "record" 23 DECODE_TUPLE: "tuple" 24 DECODE_CUSTOM: "custom" - 25 DECODE_DECODE_WITH: "decodeWith" - 26 DECODE_FROM_BYTES_PARTIAL: "fromBytesPartial" - 27 DECODE_FROM_BYTES: "fromBytes" - 28 DECODE_MAP_RESULT: "mapResult" + 25 DECODE_DECODE_WITH: "decode_with" + 26 DECODE_FROM_BYTES_PARTIAL: "from_bytes_partial" + 27 DECODE_FROM_BYTES: "from_bytes" + 28 DECODE_MAP_RESULT: "map_result" } 13 HASH: "Hash" => { 0 HASH_HASH_ABILITY: "Hash" exposed_type=true 1 HASH_HASH: "hash" 2 HASH_HASHER: "Hasher" exposed_type=true - 3 HASH_ADD_BYTES: "addBytes" - 4 HASH_ADD_U8: "addU8" - 5 HASH_ADD_U16: "addU16" - 6 HASH_ADD_U32: "addU32" - 7 HASH_ADD_U64: "addU64" - 8 HASH_ADD_U128: "addU128" - 9 HASH_HASH_BOOL: "hashBool" - 10 HASH_HASH_I8: "hashI8" - 11 HASH_HASH_I16: "hashI16" - 12 HASH_HASH_I32: "hashI32" - 13 HASH_HASH_I64: "hashI64" - 14 HASH_HASH_I128: "hashI128" - 15 HASH_HASH_UNORDERED: "hashUnordered" - 16 I128_OF_DEC: "i128OfDec" - 17 HASH_HASH_DEC: "hashDec" + 3 HASH_ADD_BYTES: "add_bytes" + 4 HASH_ADD_U8: "add_u8" + 5 HASH_ADD_U16: "add_u16" + 6 HASH_ADD_U32: "add_u32" + 7 HASH_ADD_U64: "add_u64" + 8 HASH_ADD_U128: "add_u128" + 9 HASH_HASH_BOOL: "hash_bool" + 10 HASH_HASH_I8: "hash_i8" + 11 HASH_HASH_I16: "hash_i16" + 12 HASH_HASH_I32: "hash_i32" + 13 HASH_HASH_I64: "hash_i64" + 14 HASH_HASH_I128: "hash_i128" + 15 HASH_HASH_UNORDERED: "hash_unordered" + 16 I128_OF_DEC: "i128_of_dec" + 17 HASH_HASH_DEC: "hash_dec" 18 HASH_COMPLETE: "complete" - 19 HASH_HASH_STR_BYTES: "hashStrBytes" - 20 HASH_HASH_LIST: "hashList" + 19 HASH_HASH_STR_BYTES: "hash_str_bytes" + 20 HASH_HASH_LIST: "hash_list" } 14 INSPECT: "Inspect" => { 0 INSPECT_INSPECT_ABILITY: "Inspect" exposed_type=true @@ -1714,8 +1714,8 @@ define_builtins! { 29 INSPECT_DEC: "dec" 30 INSPECT_CUSTOM: "custom" 31 INSPECT_APPLY: "apply" - 32 INSPECT_TO_INSPECTOR: "toInspector" - 33 INSPECT_TO_STR: "toStr" + 32 INSPECT_TO_INSPECTOR: "to_inspector" + 33 INSPECT_TO_STR: "to_str" } 15 TASK: "Task" => { 0 TASK_TASK: "Task" exposed_type=true // the Task.Task opaque type @@ -1725,14 +1725,14 @@ define_builtins! { 4 TASK_ERR: "err" 5 TASK_ATTEMPT: "attempt" 6 TASK_AWAIT: "await" - 7 TASK_ON_ERR: "onErr" + 7 TASK_ON_ERR: "on_err" 8 TASK_MAP: "map" - 9 TASK_MAP_ERR: "mapErr" - 10 TASK_FROM_RESULT: "fromResult" + 9 TASK_MAP_ERR: "map_err" + 10 TASK_FROM_RESULT: "from_result" 11 TASK_BATCH: "batch" 12 TASK_COMBINE: "combine" 13 TASK_SEQUENCE: "sequence" - 14 TASK_FOR_EACH: "forEach" + 14 TASK_FOR_EACH: "for_each" 15 TASK_RESULT: "result" } From 30b8a1407df6db15fcd18bf6376df02e5f5f07e0 Mon Sep 17 00:00:00 2001 From: Sam Mohr Date: Sat, 4 Jan 2025 05:37:17 -0800 Subject: [PATCH 02/20] Fix broken ability implementation --- crates/compiler/builtins/roc/Dict.roc | 18 ++-- crates/compiler/builtins/roc/Inspect.roc | 2 +- crates/compiler/can/src/def.rs | 4 +- crates/compiler/can/src/derive.rs | 40 ++++----- crates/compiler/can/src/desugar.rs | 14 +-- crates/compiler/derive/src/decoding/record.rs | 90 +++++++++---------- crates/compiler/derive/src/inspect.rs | 82 ++++++++--------- crates/compiler/derive_key/src/lib.rs | 4 +- crates/compiler/load/build.rs | 2 - crates/compiler/solve/src/ability.rs | 2 +- crates/compiler/unify/src/unify.rs | 4 +- 11 files changed, 130 insertions(+), 132 deletions(-) diff --git a/crates/compiler/builtins/roc/Dict.roc b/crates/compiler/builtins/roc/Dict.roc index 5c6964bbd90..6ddccf377c2 100644 --- a/crates/compiler/builtins/roc/Dict.roc +++ b/crates/compiler/builtins/roc/Dict.roc @@ -130,12 +130,12 @@ hash_dict = \hasher, dict -> Hash.hash_unordered(hasher, to_list(dict), List.wal to_inspector_dict : Dict k v -> Inspector f where k implements Inspect & Hash & Eq, v implements Inspect, f implements InspectFormatter to_inspector_dict = \dict -> - Inspect.custom \fmt -> - Inspect.apply(Inspect.dict(dict, walk, Inspect.to_inspector, Inspect.to_inspector) fmt) + Inspect.custom(\fmt -> + Inspect.apply(Inspect.dict(dict, walk, Inspect.to_inspector, Inspect.to_inspector), fmt)) ## Return an empty dictionary. ## ```roc -## emptyDict = Dict.empty({}) +## empty_dict = Dict.empty({}) ## ``` empty : {} -> Dict * * empty = \{} -> @@ -376,7 +376,7 @@ keep_if_help : Dict k v, ((k, v) -> Bool), U64, U64 -> Dict k v keep_if_help = \@Dict(dict), predicate, index, length -> if index < length then (key, value) = list_get_unsafe(dict.data, index) - if predicate(key, value) then + if predicate((key, value)) then keep_if_help(@Dict(dict), predicate, Num.add_wrap(index, 1), length) else keep_if_help(Dict.remove(@Dict(dict), key), predicate, index, Num.sub_wrap(length, 1)) @@ -426,7 +426,7 @@ contains : Dict k v, k -> Bool contains = \dict, key -> find(dict, key) |> .result - |> Result.isOk + |> Result.is_ok ## Insert a value into the dictionary at a specified key. ## ```roc @@ -791,7 +791,7 @@ find_helper = \buckets, bucket_index, dist_and_fingerprint, data, key -> remove_bucket : Dict k v, U64 -> Dict k v remove_bucket = \@Dict({ buckets: buckets0, data: data0, max_bucket_capacity, max_load_factor, shifts }), bucket_index0 -> - data_index_to_remove = list_get_unsafe(buckets0, bucket_index0).data_index + data_index_to_remove = list_get_unsafe(buckets0, bucket_index0) |> .data_index data_index_to_remove_u64 = Num.to_u64(data_index_to_remove) (buckets1, bucket_index1) = remove_bucket_helper(buckets0, bucket_index0) @@ -859,7 +859,7 @@ increase_size = \@Dict({ data, max_bucket_capacity, max_load_factor, shifts }) - shifts: new_shifts, }) else - crash("Dict hit limit of $(Num.toStr(max_bucket_count)) elements. Unable to grow more.") + crash("Dict hit limit of $(Num.to_str(max_bucket_count)) elements. Unable to grow more.") alloc_buckets_from_shift : U8, F32 -> (List Bucket, U64) alloc_buckets_from_shift = \shifts, max_load_factor -> @@ -1418,7 +1418,7 @@ wymix = \a, b -> wymum : U64, U64 -> { lower : U64, upper : U64 } wymum = \a, b -> - r = Num.mul_wrap(Num.toU128(a), Num.toU128(b)) + r = Num.mul_wrap(Num.to_u128(a), Num.to_u128(b)) lower = Num.to_u64(r) upper = Num.shift_right_zf_by(r, 64) |> Num.to_u64 @@ -1691,7 +1691,7 @@ expect |> Dict.insert("Alice", 17) |> Dict.insert("Bob", 18) |> Dict.insert("Charlie", 19) - |> Dict.keep_if(\(k, _v) -> Str.endsWith(k, "e")) + |> Dict.keep_if(\(k, _v) -> Str.ends_with(k, "e")) d2 = Dict.empty({}) diff --git a/crates/compiler/builtins/roc/Inspect.roc b/crates/compiler/builtins/roc/Inspect.roc index 4a5b3fbc3e2..010ded7b223 100644 --- a/crates/compiler/builtins/roc/Inspect.roc +++ b/crates/compiler/builtins/roc/Inspect.roc @@ -220,7 +220,7 @@ dbg_tuple = \fields -> custom(\f0 -> dbg_write(f0, "(") |> \f1 -> - (List.walk, fields, (f1, Bool.false), (\(f2, prepend_sep), inspector -> + List.walk(fields, (f1, Bool.false), (\(f2, prepend_sep), inspector -> f3 = if prepend_sep then dbg_write(f2, ", ") diff --git a/crates/compiler/can/src/def.rs b/crates/compiler/can/src/def.rs index bbe2f5f0ebe..09558ae65f0 100644 --- a/crates/compiler/can/src/def.rs +++ b/crates/compiler/can/src/def.rs @@ -847,8 +847,8 @@ fn canonicalize_opaque<'a>( // Did the user claim this implementation for a specialization of a different // type? e.g. // - // A implements [Hash {hash: myHash}] - // B implements [Hash {hash: myHash}] + // A implements [Hash {hash: my_hash}] + // B implements [Hash {hash: my_hash}] // // If so, that's an error and we drop the impl for this opaque type. let member_impl = match scope.abilities_store.impl_key(impl_symbol) { diff --git a/crates/compiler/can/src/derive.rs b/crates/compiler/can/src/derive.rs index 04fc1e29835..ac21d54af19 100644 --- a/crates/compiler/can/src/derive.rs +++ b/crates/compiler/can/src/derive.rs @@ -30,11 +30,11 @@ fn to_encoder<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { ast::PatternApplyStyle::Whitespace, ); - // Encode.toEncoder payload + // Encode.to_encoder(payload) let call_member = alloc_expr(ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Encode", - ident: "toEncoder", + ident: "to_encoder", }), &*env.arena.alloc([&*alloc_expr(ast::Expr::Var { module_name: "", @@ -43,7 +43,7 @@ fn to_encoder<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { roc_module::called_via::CalledVia::Space, )); - // \@Opaq payload -> Encode.toEncoder payload + // \@Opaq payload -> Encode.to_encoder(payload) ast::Expr::Closure( env.arena .alloc([Loc::at(DERIVED_REGION, opaque_apply_pattern)]), @@ -58,11 +58,11 @@ fn decoder<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { let bytes = "#bytes"; let fmt = "#fmt"; - // Decode.decodeWith bytes Decode.decoder fmt + // Decode.decode_with(bytes, Decode.decoder, fmt) let call_decode_with = ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Decode", - ident: "decodeWith", + ident: "decode_with", }), env.arena.alloc([ &*alloc_expr(ast::Expr::Var { @@ -81,11 +81,11 @@ fn decoder<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { CalledVia::Space, ); - // Decode.mapResult (Decode.decodeWith bytes Decode.decoder fmt) @Opaq + // Decode.map_result(Decode.decode_with(bytes, Decode.decoder, fmt), @Opaq) let call_map_result = ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Decode", - ident: "mapResult", + ident: "map_result", }), env.arena.alloc([ &*alloc_expr(call_decode_with), @@ -95,7 +95,7 @@ fn decoder<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { ); // \bytes, fmt -> - // Decode.mapResult (Decode.decodeWith bytes Decode.decoder fmt) @Opaq + // Decode.map_result(Decode.decode_with(bytes, Decode.decoder, fmt), @Opaq) let custom_closure = ast::Expr::Closure( env.arena.alloc([ Loc::at(DERIVED_REGION, ast::Pattern::Identifier { ident: bytes }), @@ -136,7 +136,7 @@ fn hash<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { PatternApplyStyle::Whitespace, ); - // Hash.hash hasher payload + // Hash.hash(hasher, payload) let call_member = alloc_expr(ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Hash", @@ -155,7 +155,7 @@ fn hash<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { roc_module::called_via::CalledVia::Space, )); - // \hasher, @Opaq payload -> Hash.hash hasher payload + // \hasher, @Opaq payload -> Hash.hash(hasher, payload) ast::Expr::Closure( env.arena.alloc([ Loc::at(DERIVED_REGION, ast::Pattern::Identifier { ident: hasher }), @@ -192,11 +192,11 @@ fn is_eq<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { PatternApplyStyle::Whitespace, ); - // Bool.isEq payload1 payload2 + // Bool.is_eq(payload1, payload2) let call_member = alloc_expr(ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Bool", - ident: "isEq", + ident: "is_eq", }), &*env.arena.alloc([ &*alloc_expr(ast::Expr::Var { @@ -211,7 +211,7 @@ fn is_eq<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { roc_module::called_via::CalledVia::Space, )); - // \@Opaq payload1, @Opaq payload2 -> Bool.isEq payload1 payload2 + // \@Opaq payload1, @Opaq payload2 -> Bool.is_eq(payload1, payload2) ast::Expr::Closure( env.arena.alloc([ Loc::at(DERIVED_REGION, opaque1), @@ -239,11 +239,11 @@ fn to_inspector<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { PatternApplyStyle::Whitespace, ); - // Inspect.toInspector payload + // Inspect.to_inspector(payload) let to_inspector_payload = alloc_expr(ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Inspect", - ident: "toInspector", + ident: "to_inspector", }), &*env.arena.alloc([&*alloc_expr(ast::Expr::Var { module_name: "", @@ -252,7 +252,7 @@ fn to_inspector<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { roc_module::called_via::CalledVia::Space, )); - // Inspect.tag "@opaque" [Inspect.toInspector payload] + // Inspect.tag("@opaque", [Inspect.to_inspector(payload)]) let to_inspector_list = alloc_expr(ast::Expr::List(Collection::with_items( &*env.arena.alloc([&*to_inspector_payload]), ))); @@ -269,7 +269,7 @@ fn to_inspector<'a>(env: &mut Env<'a>, at_opaque: &'a str) -> ast::Expr<'a> { let fmt = "#fmt"; - // \fmt -> Inspect.apply opaqueInspector fmt + // \fmt -> Inspect.apply(opaque_inspector, fmt) let apply_opaque_inspector = alloc_expr(ast::Expr::Apply( alloc_expr(ast::Expr::Var { module_name: "Inspect", @@ -325,14 +325,14 @@ pub(crate) fn synthesize_member_impl<'a>( let (impl_name, def_body): (String, ast::Expr<'a>) = match ability_member { Symbol::ENCODE_TO_ENCODER => ( - format!("#{opaque_name}_toEncoder"), + format!("#{opaque_name}_to_encoder"), to_encoder(env, at_opaque), ), Symbol::DECODE_DECODER => (format!("#{opaque_name}_decoder"), decoder(env, at_opaque)), Symbol::HASH_HASH => (format!("#{opaque_name}_hash"), hash(env, at_opaque)), - Symbol::BOOL_IS_EQ => (format!("#{opaque_name}_isEq"), is_eq(env, at_opaque)), + Symbol::BOOL_IS_EQ => (format!("#{opaque_name}_is_eq"), is_eq(env, at_opaque)), Symbol::INSPECT_TO_INSPECTOR => ( - format!("#{opaque_name}_toInspector"), + format!("#{opaque_name}_to_inspector"), to_inspector(env, at_opaque), ), other => internal_error!("{:?} is not a derivable ability member!", other), diff --git a/crates/compiler/can/src/desugar.rs b/crates/compiler/can/src/desugar.rs index d81630a14c1..fdbd99ccb77 100644 --- a/crates/compiler/can/src/desugar.rs +++ b/crates/compiler/can/src/desugar.rs @@ -1608,16 +1608,16 @@ fn binop_to_function(binop: BinOp) -> (&'static str, &'static str) { Caret => (ModuleName::NUM, "pow"), Star => (ModuleName::NUM, "mul"), Slash => (ModuleName::NUM, "div"), - DoubleSlash => (ModuleName::NUM, "divTrunc"), + DoubleSlash => (ModuleName::NUM, "div_trunc"), Percent => (ModuleName::NUM, "rem"), Plus => (ModuleName::NUM, "add"), Minus => (ModuleName::NUM, "sub"), - Equals => (ModuleName::BOOL, "isEq"), - NotEquals => (ModuleName::BOOL, "isNotEq"), - LessThan => (ModuleName::NUM, "isLt"), - GreaterThan => (ModuleName::NUM, "isGt"), - LessThanOrEq => (ModuleName::NUM, "isLte"), - GreaterThanOrEq => (ModuleName::NUM, "isGte"), + Equals => (ModuleName::BOOL, "is_eq"), + NotEquals => (ModuleName::BOOL, "is_not_eq"), + LessThan => (ModuleName::NUM, "is_lt"), + GreaterThan => (ModuleName::NUM, "is_gt"), + LessThanOrEq => (ModuleName::NUM, "is_lte"), + GreaterThanOrEq => (ModuleName::NUM, "is_gte"), And => (ModuleName::BOOL, "and"), Or => (ModuleName::BOOL, "or"), Pizza => unreachable!("Cannot desugar the |> operator"), diff --git a/crates/compiler/derive/src/decoding/record.rs b/crates/compiler/derive/src/decoding/record.rs index 97974bd5aae..635c42f9049 100644 --- a/crates/compiler/derive/src/decoding/record.rs +++ b/crates/compiler/derive/src/decoding/record.rs @@ -30,19 +30,19 @@ use super::wrap_in_decode_custom_decode_with; /// ```roc /// decoder : Decoder {first: a, second: b} fmt where a implements Decoding, b implements Decoding, fmt implements DecoderFormatting /// decoder = -/// initialState : {f0: Result a [NoField], f1: Result b [NoField]} -/// initialState = {f0: Err NoField, f1: Err NoField} +/// initial_state : {f0: Result a [NoField], f1: Result b [NoField]} +/// initial_state = {f0: Err NoField, f1: Err NoField} /// -/// stepField = \state, field -> +/// step_field = \state, field -> /// when field is /// "first" -> /// Keep (Decode.custom \bytes, fmt -> -/// when Decode.decodeWith bytes Decode.decoder fmt is +/// when Decode.decode_with bytes Decode.decoder fmt is /// {result, rest} -> /// {result: Result.map result \val -> {state & f0: Ok val}, rest}) /// "second" -> /// Keep (Decode.custom \bytes, fmt -> -/// when Decode.decodeWith bytes Decode.decoder fmt is +/// when Decode.decode_with bytes Decode.decoder fmt is /// {result, rest} -> /// {result: Result.map result \val -> {state & f1: Ok val}, rest}) /// _ -> Skip @@ -51,7 +51,7 @@ use super::wrap_in_decode_custom_decode_with; /// when /// when rec.f0 is /// Err NoField -> -/// when Decode.decodeWith [] Decode.decoder fmt is +/// when Decode.decode_with [] Decode.decoder fmt is /// rec2 -> rec2.result /// Ok a -> Ok a /// is @@ -59,7 +59,7 @@ use super::wrap_in_decode_custom_decode_with; /// when /// when rec.f1 is /// Err NoField -> -/// when Decode.decodeWith [] Decode.decoder fmt is +/// when Decode.decode_with [] Decode.decoder fmt is /// rec2 -> rec2.result /// Ok a -> Ok a /// is @@ -67,7 +67,7 @@ use super::wrap_in_decode_custom_decode_with; /// Err _ -> Err TooShort /// Err _ -> Err TooShort /// -/// Decode.custom \bytes, fmt -> Decode.decodeWith bytes (Decode.record initialState stepField finalizer) fmt +/// Decode.custom \bytes, fmt -> Decode.decode_with bytes (Decode.record initial_state step_field finalizer) fmt ///``` pub(crate) fn decoder( env: &mut Env, @@ -79,7 +79,7 @@ pub(crate) fn decoder( // The type of each field in the decoding state, e.g. {first: Result a [NoField], second: Result b [NoField]} let mut result_field_vars = Vec::with_capacity(fields.len()); - // initialState = ... + // initial_state = ... let (initial_state_var, initial_state) = initial_state(env, &fields, &mut field_vars, &mut result_field_vars); @@ -92,7 +92,7 @@ pub(crate) fn decoder( &result_field_vars, ); - // stepField = ... + // step_field = ... let (step_field, step_var) = step_field( env, fields, @@ -120,7 +120,7 @@ pub(crate) fn decoder( env.unify(decode_record_var, this_decode_record_var); - // Decode.record initialState stepField finalizer + // Decode.record initial_state step_field finalizer let call_decode_record = Expr::Call( Box::new(( this_decode_record_var, @@ -161,13 +161,13 @@ pub(crate) fn decoder( } // Example: -// stepField = \state, field -> +// step_field = \state, field -> // when field is // "first" -> // Keep (Decode.custom \bytes, fmt -> // # Uses a single-branch `when` because `let` is more expensive to monomorphize // # due to checks for polymorphic expressions, and `rec` would be polymorphic. -// when Decode.decodeWith bytes Decode.decoder fmt is +// when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -178,7 +178,7 @@ pub(crate) fn decoder( // // "second" -> // Keep (Decode.custom \bytes, fmt -> -// when Decode.decodeWith bytes Decode.decoder fmt is +// when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -196,7 +196,7 @@ pub(super) fn step_field( state_record_var: Variable, decode_err_var: Variable, ) -> (Expr, Variable) { - let state_arg_symbol = env.new_symbol("stateRecord"); + let state_arg_symbol = env.new_symbol("state_record"); let field_arg_symbol = env.new_symbol("field"); // +1 because of the default branch. @@ -228,7 +228,7 @@ pub(super) fn step_field( // Keep (Decode.custom \bytes, fmt -> // # Uses a single-branch `when` because `let` is more expensive to monomorphize // # due to checks for polymorphic expressions, and `rec` would be polymorphic. - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -254,7 +254,7 @@ pub(super) fn step_field( let keep = { // Keep (Decode.custom \bytes, fmt -> - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -274,7 +274,7 @@ pub(super) fn step_field( let branch = { // "first" -> // Keep (Decode.custom \bytes, fmt -> - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -326,7 +326,7 @@ pub(super) fn step_field( exhaustive: ExhaustiveMark::known_exhaustive(), }; - let step_field_closure = env.new_symbol("stepField"); + let step_field_closure = env.new_symbol("step_field"); let function_type = env.subs.fresh_unnamed_flex_var(); let closure_type = { let lambda_set = LambdaSet { @@ -395,7 +395,7 @@ struct DecodingFieldArgs { /// Decode.custom \bytes, fmt -> /// # Uses a single-branch `when` because `let` is more expensive to monomorphize /// # due to checks for polymorphic expressions, and `rec` would be polymorphic. -/// when Decode.decodeWith bytes Decode.decoder fmt is +/// when Decode.decode_with bytes Decode.decoder fmt is /// rec -> /// { /// rest: rec.rest, @@ -444,7 +444,7 @@ fn custom_decoder(env: &mut Env<'_>, args: DecodingFieldArgs) -> (Variable, Expr /// ```roc /// \bytes, fmt -> -/// when Decode.decodeWith bytes Decode.decoder fmt is +/// when Decode.decode_with bytes Decode.decoder fmt is /// rec -> /// { /// rest: rec.rest, @@ -467,7 +467,7 @@ fn custom_decoder_lambda(env: &mut Env<'_>, args: DecodingFieldArgs) -> (Variabl let custom_callback_ret_var; // \bytes, fmt -> - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -507,7 +507,7 @@ fn custom_decoder_lambda(env: &mut Env<'_>, args: DecodingFieldArgs) -> (Variabl synth_var(env.subs, Content::Structure(flat_type)) }; - // Decode.decodeWith bytes Decode.decoder fmt + // Decode.decode_with bytes Decode.decoder fmt let (condition_expr, rec_var, rec_dot_result) = decode_with( env, field_var, @@ -519,7 +519,7 @@ fn custom_decoder_lambda(env: &mut Env<'_>, args: DecodingFieldArgs) -> (Variabl // # Uses a single-branch `when` because `let` is more expensive to monomorphize // # due to checks for polymorphic expressions, and `rec` would be polymorphic. - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // rec -> // { // rest: rec.rest, @@ -556,7 +556,7 @@ fn custom_decoder_lambda(env: &mut Env<'_>, args: DecodingFieldArgs) -> (Variabl redundant: RedundantMark::known_non_redundant(), }; - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is // ... Expr::When { loc_cond: Box::new(Loc::at_zero(condition_expr)), @@ -806,7 +806,7 @@ fn state_record_update( /// when /// when rec.f0 is /// Err NoField -> -/// when Decode.decodeWith [] Decode.decoder fmt is +/// when Decode.decode_with [] Decode.decoder fmt is /// rec2 -> rec2.result /// Ok a -> Ok a /// is @@ -814,7 +814,7 @@ fn state_record_update( /// when /// when rec.f1 is /// Err NoField -> -/// when Decode.decodeWith [] Decode.decoder fmt is +/// when Decode.decode_with [] Decode.decoder fmt is /// rec2 -> rec2.result /// Ok a -> Ok a /// is @@ -828,7 +828,7 @@ pub(super) fn finalizer( field_vars: &[Variable], result_field_vars: &[Variable], ) -> (Expr, Variable, Variable) { - let state_arg_symbol = env.new_symbol("stateRecord"); + let state_arg_symbol = env.new_symbol("state_record"); let mut fields_map = SendMap::default(); let mut pattern_symbols = Vec::with_capacity(fields.len()); @@ -909,7 +909,7 @@ pub(super) fn finalizer( // [Ok field_var, Err DecodeError] // when rec.f0 is // Err _ -> - // when Decode.decodeWith [] Decode.decoder fmt is + // when Decode.decode_with [] Decode.decoder fmt is // rec2 -> rec2.result // Ok a -> Ok a let (attempt_empty_decode_expr, attempt_empty_decode_var) = attempt_empty_decode_if_missing( @@ -968,11 +968,11 @@ pub(super) fn finalizer( }; // when - // when stateRecord.f0 is + // when state_record.f0 is // Ok f0 -> Ok f0 // _ -> - // when Decode.decodeWith [] Decode.decoder fmt is - // decRec -> decRec.result + // when Decode.decode_with [] Decode.decoder fmt is + // dec_rec -> dec_rec.result // is // _-> TooShort // Ok x -> expr @@ -1037,8 +1037,8 @@ pub(super) fn finalizer( /// ```roc /// when rec.f0 is /// Err _ -> -/// when Decode.decodeWith [] Decode.decoder fmt is -/// decRec-> decRec.result +/// when Decode.decode_with [] Decode.decoder fmt is +/// dec_rec-> dec_rec.result /// Ok a -> Ok a /// ``` /// Tries to decode the field with a zero byte input if it missing, @@ -1070,7 +1070,7 @@ fn attempt_empty_decode_if_missing( decode_err_var, ); let decode_when = { - let decoder_rec_symb = env.new_symbol("decRec"); + let decoder_rec_symb = env.new_symbol("dec_rec"); let branch = WhenBranch { patterns: vec![WhenBranchPattern { @@ -1088,7 +1088,7 @@ fn attempt_empty_decode_if_missing( redundant: RedundantMark::known_non_redundant(), }; - // when Decode.decodeWith bytes Decode.decoder fmt is + // when Decode.decode_with bytes Decode.decoder fmt is Expr::When { loc_cond: Box::new(Loc::at_zero(decode_expr)), cond_var: rec_result, @@ -1112,7 +1112,7 @@ fn attempt_empty_decode_if_missing( // Example: `Ok x -> Ok x` let ok_branch = ok_to_ok_branch(result_field_var, rec_dot_result, field_var, symbol, env); - // Example: `Err NoField -> when decodeWith [] decoder #Derived.fmt is` + // Example: `Err NoField -> when decode_with [] decoder #Derived.fmt is` let no_field_label = "NoField"; let union_tags = UnionTags::tag_without_arguments(env.subs, no_field_label.into()); let no_field_var = synth_var( @@ -1159,8 +1159,8 @@ fn attempt_empty_decode_if_missing( } // Example: -// initialState : {first: Result a [NoField], second: Result b [NoField]} -// initialState = {first: Err NoField, second: Err NoField} +// initial_state : {first: Result a [NoField], second: Result b [NoField]} +// initial_state = {first: Err NoField, second: Err NoField} fn initial_state( env: &mut Env<'_>, field_names: &[Lowercase], @@ -1237,16 +1237,16 @@ fn initial_state( } struct DecodeWithVars { - /// Type of the record returned by `Decode.decodeWith` + /// Type of the record returned by `Decode.decode_with` /// `rec : { rest: List U8, result: (typeof rec.result) }` rec_var: Variable, - /// type of the result field of the record returned by `Decode.decodeWith` + /// type of the result field of the record returned by `Decode.decode_with` rec_dot_result: Variable, /// type of `Decode.decoder` decoder_var: Variable, - /// lambda set for `Decode.decodeWith` call + /// lambda set for `Decode.decode_with` call lambda_set_var: Variable, - /// specialised type of this specific call to `Decode.decodeWith` + /// specialised type of this specific call to `Decode.decode_with` this_decode_with_var: Variable, } @@ -1314,9 +1314,9 @@ fn make_decode_with_vars( } } -/// `Decode.decodeWith bytes Decode.decoder fmt` +/// `Decode.decode_with bytes Decode.decoder fmt` /// -/// Generates a call to decodeWith, returns that expression, +/// Generates a call to decode_with, returns that expression, /// the variable of the return value `{ rest: List U8, result: (typeof rec.result) }`, /// and the variable of the result field of the return value `[Ok field_var, Err DecodeError]`. pub(super) fn decode_with( diff --git a/crates/compiler/derive/src/inspect.rs b/crates/compiler/derive/src/inspect.rs index 8a41356ca6c..0720c879ecb 100644 --- a/crates/compiler/derive/src/inspect.rs +++ b/crates/compiler/derive/src/inspect.rs @@ -109,7 +109,7 @@ pub(crate) fn derive_to_inspector( } fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { - // Build \lst -> list, List.walk, (\elem -> Inspect.toInspector elem) + // Build \lst -> list, List.walk, (\elem -> Inspect.to_inspector elem) use Expr::*; @@ -124,7 +124,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { Content::Structure(FlatType::Apply(Symbol::LIST_LIST, elem_var_slice)), ); - // build `toInspector elem` type + // build `to_inspector elem` type // val -[uls]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_TO_INSPECTOR); @@ -145,7 +145,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { // ~ elem -[clos]-> t1 env.unify(to_inspector_fn_var, elem_to_inspector_fn_var); - // toInspector : (typeof rcd.a) -[clos]-> Inspector fmt where fmt implements InspectorFormatter + // to_inspector : (typeof rcd.a) -[clos]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_var = AbilityMember(Symbol::INSPECT_TO_INSPECTOR, None, elem_to_inspector_fn_var); let to_inspector_fn = Box::new(( @@ -156,14 +156,14 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { Variable::PURE, )); - // toInspector elem + // to_inspector elem let to_inspector_call = Call( to_inspector_fn, vec![(elem_var, Loc::at_zero(Var(elem_sym, elem_var)))], CalledVia::Space, ); - // elem -[to_elem_inspector]-> toInspector elem + // elem -[to_elem_inspector]-> to_inspector elem let to_elem_inspector_sym = env.new_symbol("to_elem_inspector"); // Create fn_var for ambient capture; we fix it up below. @@ -181,7 +181,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { ambient_function: to_elem_inspector_fn_var, }), ); - // elem -[to_elem_inspector]-> toInspector elem + // elem -[to_elem_inspector]-> to_inspector elem env.subs.set_content( to_elem_inspector_fn_var, Content::Structure(FlatType::Func( @@ -192,7 +192,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { )), ); - // \elem -> toInspector elem + // \elem -> to_inspector elem let to_elem_inspector = Closure(ClosureData { function_type: to_elem_inspector_fn_var, closure_type: to_elem_inspector_lset, @@ -210,7 +210,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { loc_body: Box::new(Loc::at_zero(to_inspector_call)), }); - // build `Inspect.list lst (\elem -> Inspect.toInspector elem)` type + // build `Inspect.list lst (\elem -> Inspect.to_inspector elem)` type // List e, (e -> Inspector fmt) -[uls]-> Inspector fmt where fmt implements InspectorFormatter let inspect_list_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_LIST); @@ -268,7 +268,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { list_var, ); - // \lst -> Inspect.list lst (\elem -> Inspect.toInspector elem) + // \lst -> Inspect.list lst (\elem -> Inspect.to_inspector elem) // Create fn_var for ambient capture; we fix it up below. let fn_var = synth_var(env.subs, Content::Error); @@ -295,7 +295,7 @@ fn to_inspector_list(env: &mut Env<'_>, fn_name: Symbol) -> (Expr, Variable) { )), ); - // \lst -[fn_name]-> Inspect.list lst (\elem -> Inspect.toInspector elem) + // \lst -[fn_name]-> Inspect.list lst (\elem -> Inspect.to_inspector elem) let clos = Closure(ClosureData { function_type: fn_var, closure_type: fn_clos_var, @@ -325,8 +325,8 @@ fn to_inspector_record( // Suppose rcd = { a: t1, b: t2 }. Build // // \rcd -> Inspect.record [ - // { key: "a", value: Inspect.toInspector rcd.a }, - // { key: "b", value: Inspect.toInspector rcd.b }, + // { key: "a", value: Inspect.to_inspector rcd.a }, + // { key: "b", value: Inspect.to_inspector rcd.b }, // ] let rcd_sym = env.new_symbol("rcd"); @@ -360,7 +360,7 @@ fn to_inspector_record( field: field_name, }; - // build `toInspector rcd.a` type + // build `to_inspector rcd.a` type // val -[uls]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_TO_INSPECTOR); @@ -381,7 +381,7 @@ fn to_inspector_record( // ~ (typeof rcd.a) -[clos]-> t1 env.unify(to_inspector_fn_var, this_to_inspector_fn_var); - // toInspector : (typeof rcd.a) -[clos]-> Inspector fmt where fmt implements InspectorFormatter + // to_inspector : (typeof rcd.a) -[clos]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_var = AbilityMember(Symbol::INSPECT_TO_INSPECTOR, None, to_inspector_fn_var); let to_inspector_fn = Box::new(( @@ -392,21 +392,21 @@ fn to_inspector_record( Variable::PURE, )); - // toInspector rcd.a + // to_inspector rcd.a let to_inspector_call = Call( to_inspector_fn, vec![(field_var, Loc::at_zero(field_access))], CalledVia::Space, ); - // value: toInspector rcd.a + // value: to_inspector rcd.a let value_field = Field { var: inspector_var, region: Region::zero(), loc_expr: Box::new(Loc::at_zero(to_inspector_call)), }; - // { key: "a", value: toInspector rcd.a } + // { key: "a", value: to_inspector rcd.a } let mut kv = SendMap::default(); kv.insert("key".into(), key_field); kv.insert("value".into(), value_field); @@ -542,8 +542,8 @@ fn to_inspector_tuple( // Suppose tup = (t1, t2). Build // // \tup -> Inspect.tuple [ - // Inspect.toInspector tup.0, - // Inspect.toInspector tup.1, + // Inspect.to_inspector tup.0, + // Inspect.to_inspector tup.1, // ] let tup_sym = env.new_symbol("tup"); @@ -570,7 +570,7 @@ fn to_inspector_tuple( index, }; - // build `toInspector tup.0` type + // build `to_inspector tup.0` type // val -[uls]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_TO_INSPECTOR); @@ -591,7 +591,7 @@ fn to_inspector_tuple( // ~ (typeof tup.0) -[clos]-> t1 env.unify(to_inspector_fn_var, this_to_inspector_fn_var); - // toInspector : (typeof tup.0) -[clos]-> Inspector fmt where fmt implements InspectorFormatter + // to_inspector : (typeof tup.0) -[clos]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_var = AbilityMember(Symbol::INSPECT_TO_INSPECTOR, None, to_inspector_fn_var); let to_inspector_fn = Box::new(( @@ -602,7 +602,7 @@ fn to_inspector_tuple( Variable::PURE, )); - // toInspector tup.0 + // to_inspector tup.0 let to_inspector_call = Call( to_inspector_fn, vec![(elem_var, Loc::at_zero(tuple_access))], @@ -616,7 +616,7 @@ fn to_inspector_tuple( }) .collect::>(); - // typeof [ toInspector tup.0, toInspector tup.1 ] + // typeof [ to_inspector tup.0, to_inspector tup.1 ] let whole_inspector_in_list_var_slice = env.subs.insert_into_vars(once(whole_inspector_in_list_var)); let elem_inspectors_list_var = synth_var( @@ -627,13 +627,13 @@ fn to_inspector_tuple( )), ); - // [ toInspector tup.0, toInspector tup.1 ] + // [ to_inspector tup.0, to_inspector tup.1 ] let elem_inspectors_list = List { elem_var: whole_inspector_in_list_var, loc_elems: elem_inspectors_list, }; - // build `Inspect.tuple [ toInspector tup.0, toInspector tup.1 ]` type + // build `Inspect.tuple [ to_inspector tup.0, to_inspector tup.1 ]` type // List (Inspector fmt) -[uls]-> Inspector fmt where fmt implements InspectorFormatter let inspect_tuple_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_TUPLE); @@ -732,8 +732,8 @@ fn to_inspector_tag_union( // Suppose tag = [ A t1 t2, B t3 ]. Build // // \tag -> when tag is - // A v1 v2 -> Inspect.tag "A" [ Inspect.toInspector v1, Inspect.toInspector v2 ] - // B v3 -> Inspect.tag "B" [ Inspect.toInspector v3 ] + // A v1 v2 -> Inspect.tag "A" [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] + // B v3 -> Inspect.tag "B" [ Inspect.to_inspector v3 ] let tag_sym = env.new_symbol("tag"); let whole_tag_inspectors_var = env.subs.fresh_unnamed_flex_var(); // type of the Inspect.tag ... calls in the branch bodies @@ -769,13 +769,13 @@ fn to_inspector_tag_union( degenerate: false, }; - // whole type of the elements in [ Inspect.toInspector v1, Inspect.toInspector v2 ] + // whole type of the elements in [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] let whole_payload_inspectors_var = env.subs.fresh_unnamed_flex_var(); - // [ Inspect.toInspector v1, Inspect.toInspector v2 ] + // [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] let payload_to_inspectors = (payload_syms.iter()) .zip(payload_vars.iter()) .map(|(&sym, &sym_var)| { - // build `toInspector v1` type + // build `to_inspector v1` type // expected: val -[uls]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_fn_var = env.import_builtin_symbol_var(Symbol::INSPECT_TO_INSPECTOR); @@ -798,7 +798,7 @@ fn to_inspector_tag_union( // ~ t1 -[clos]-> t' env.unify(to_inspector_fn_var, this_to_inspector_fn_var); - // toInspector : t1 -[clos]-> Inspector fmt where fmt implements InspectorFormatter + // to_inspector : t1 -[clos]-> Inspector fmt where fmt implements InspectorFormatter let to_inspector_var = AbilityMember(Symbol::INSPECT_TO_INSPECTOR, None, this_to_inspector_fn_var); let to_inspector_fn = Box::new(( @@ -809,7 +809,7 @@ fn to_inspector_tag_union( Variable::PURE, )); - // toInspector rcd.a + // to_inspector rcd.a let to_inspector_call = Call( to_inspector_fn, vec![(sym_var, Loc::at_zero(Var(sym, sym_var)))], @@ -823,7 +823,7 @@ fn to_inspector_tag_union( }) .collect(); - // typeof [ Inspect.toInspector v1, Inspect.toInspector v2 ] + // typeof [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] let whole_inspectors_var_slice = env.subs.insert_into_vars([whole_payload_inspectors_var]); let payload_inspectors_list_var = synth_var( @@ -834,7 +834,7 @@ fn to_inspector_tag_union( )), ); - // [ Inspect.toInspector v1, Inspect.toInspector v2 ] + // [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] let payload_inspectors_list = List { elem_var: whole_payload_inspectors_var, loc_elems: payload_to_inspectors, @@ -874,13 +874,13 @@ fn to_inspector_tag_union( Variable::PURE, )); - // Inspect.tag "A" [ Inspect.toInspector v1, Inspect.toInspector v2 ] + // Inspect.tag "A" [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] let inspect_tag_call = Call( inspect_tag_fn, vec![ // (Str, "A") (Variable::STR, Loc::at_zero(Str(tag_name.0.as_str().into()))), - // (List (Inspector fmt), [ Inspect.toInspector v1, Inspect.toInspector v2 ]) + // (List (Inspector fmt), [ Inspect.to_inspector v1, Inspect.to_inspector v2 ]) ( payload_inspectors_list_var, Loc::at_zero(payload_inspectors_list), @@ -890,7 +890,7 @@ fn to_inspector_tag_union( ); // NOTE: must be done to unify the lambda sets under `inspector_var` - // Inspect.tag "A" [ Inspect.toInspector v1, Inspect.toInspector v2 ] ~ whole_inspectors + // Inspect.tag "A" [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] ~ whole_inspectors env.unify(this_inspector_var, whole_tag_inspectors_var); WhenBranch { @@ -903,8 +903,8 @@ fn to_inspector_tag_union( .collect::>(); // when tag is - // A v1 v2 -> Inspect.tag "A" [ Inspect.toInspector v1, Inspect.toInspector v2 ] - // B v3 -> Inspect.tag "B" [ Inspect.toInspector v3 ] + // A v1 v2 -> Inspect.tag "A" [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] + // B v3 -> Inspect.tag "B" [ Inspect.to_inspector v3 ] let when_branches = When { loc_cond: Box::new(Loc::at_zero(Var(tag_sym, tag_union_var))), cond_var: tag_union_var, @@ -953,8 +953,8 @@ fn to_inspector_tag_union( // \tag -> // Inspect.custom \fmt -> Inspect.apply ( // when tag is - // A v1 v2 -> Inspect.tag "A" [ Inspect.toInspector v1, Inspect.toInspector v2 ] - // B v3 -> Inspect.tag "B" [ Inspect.toInspector v3 ]) + // A v1 v2 -> Inspect.tag "A" [ Inspect.to_inspector v1, Inspect.to_inspector v2 ] + // B v3 -> Inspect.tag "B" [ Inspect.to_inspector v3 ]) // fmt let clos = Closure(ClosureData { function_type: fn_var, diff --git a/crates/compiler/derive_key/src/lib.rs b/crates/compiler/derive_key/src/lib.rs index 7454dcc6aa9..cb1f55818c3 100644 --- a/crates/compiler/derive_key/src/lib.rs +++ b/crates/compiler/derive_key/src/lib.rs @@ -48,10 +48,10 @@ pub enum DeriveKey { impl DeriveKey { pub fn debug_name(&self) -> String { match self { - DeriveKey::ToEncoder(key) => format!("toEncoder_{}", key.debug_name()), + DeriveKey::ToEncoder(key) => format!("to_encoder_{}", key.debug_name()), DeriveKey::Decoder(key) => format!("decoder_{}", key.debug_name()), DeriveKey::Hash(key) => format!("hash_{}", key.debug_name()), - DeriveKey::ToInspector(key) => format!("toInspector_{}", key.debug_name()), + DeriveKey::ToInspector(key) => format!("to_inspector_{}", key.debug_name()), } } } diff --git a/crates/compiler/load/build.rs b/crates/compiler/load/build.rs index 058ca79bb21..9a515109271 100644 --- a/crates/compiler/load/build.rs +++ b/crates/compiler/load/build.rs @@ -29,8 +29,6 @@ const MODULES: &[(ModuleId, &str)] = &[ ]; fn main() { - panic!("Fail now to avoid infinite loading."); - for (module_id, filename) in MODULES { write_subs_for_module(*module_id, filename); } diff --git a/crates/compiler/solve/src/ability.rs b/crates/compiler/solve/src/ability.rs index b9156ee97e3..728e1afca0b 100644 --- a/crates/compiler/solve/src/ability.rs +++ b/crates/compiler/solve/src/ability.rs @@ -1383,7 +1383,7 @@ impl DerivableVisitor for DeriveEq { #[inline(always)] fn visit_ranged_number(_var: Variable, _range: NumericRange) -> Result<(), NotDerivable> { // Ranged numbers are allowed, because they are always possibly ints - floats can not have - // `isEq` derived, but if something were to be a float, we'd see it exactly as a float. + // `is_eq` derived, but if something were to be a float, we'd see it exactly as a float. Ok(()) } } diff --git a/crates/compiler/unify/src/unify.rs b/crates/compiler/unify/src/unify.rs index d5829a41701..2b4e1dea286 100644 --- a/crates/compiler/unify/src/unify.rs +++ b/crates/compiler/unify/src/unify.rs @@ -1282,9 +1282,9 @@ fn extract_specialization_lambda_set( // lambda set does not line up with one required by the ability member prototype. // As an example, consider // - // Q := [ F (Str -> Str) ] implements [Eq {isEq}] + // Q := [ F (Str -> Str) ] implements [Eq {is_eq}] // - // isEq = \@Q _, @Q _ -> Bool.false + // is_eq = \@Q _, @Q _ -> Bool.false // // here the lambda set of `F`'s payload is part of the specialization signature, but it is // irrelevant to the specialization. As such, I believe it is safe to drop the From db1e0a02b4a409dd0f8003badd007da5116ebe9d Mon Sep 17 00:00:00 2001 From: Sam Mohr Date: Sat, 4 Jan 2025 05:54:44 -0800 Subject: [PATCH 03/20] Update tests --- ...xed__suffixed_tests__expect_then_bang.snap | 2 +- ..._suffixed__suffixed_tests__issue_7081.snap | 4 +- crates/compiler/can/tests/test_can.rs | 56 +++++----- crates/repl_eval/src/eval.rs | 12 +-- crates/repl_eval/src/gen.rs | 4 +- crates/repl_test/src/state.rs | 10 +- crates/repl_test/src/tests.rs | 101 +++++++++--------- 7 files changed, 96 insertions(+), 93 deletions(-) diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__expect_then_bang.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__expect_then_bang.snap index 1562686d0a8..c5d6bfe6d9f 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__expect_then_bang.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__expect_then_bang.snap @@ -46,7 +46,7 @@ Defs { condition: @18-24 Apply( @20-22 Var { module_name: "Bool", - ident: "isEq", + ident: "is_eq", }, [ @18-19 Num( diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__issue_7081.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__issue_7081.snap index fef5f14bdf2..9396e9fac35 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__issue_7081.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__issue_7081.snap @@ -49,7 +49,7 @@ Defs { @19-24 Apply( @21-22 Var { module_name: "Num", - ident: "isGt", + ident: "is_gt", }, [ @19-20 Var { @@ -232,7 +232,7 @@ Defs { @213-227 Apply( @220-222 Var { module_name: "Bool", - ident: "isEq", + ident: "is_eq", }, [ @213-219 Var { diff --git a/crates/compiler/can/tests/test_can.rs b/crates/compiler/can/tests/test_can.rs index aa7e818a481..92cbc21be27 100644 --- a/crates/compiler/can/tests/test_can.rs +++ b/crates/compiler/can/tests/test_can.rs @@ -806,7 +806,7 @@ mod test_can { fn question_suffix_simple() { let src = indoc!( r#" - (Str.toU64 "123")? + (Str.to_u64 "123")? "# ); let arena = Bump::new(); @@ -816,10 +816,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Space, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Space, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -829,7 +829,7 @@ mod test_can { fn question_suffix_after_function() { let src = indoc!( r#" - Str.toU64? "123" + Str.to_u64? "123" "# ); let arena = Bump::new(); @@ -839,10 +839,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Try, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Try, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -852,7 +852,7 @@ mod test_can { fn question_suffix_pipe() { let src = indoc!( r#" - "123" |> Str.toU64? + "123" |> Str.to_u64? "# ); let arena = Bump::new(); @@ -862,10 +862,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Try, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Try, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -875,7 +875,7 @@ mod test_can { fn question_suffix_pipe_nested() { let src = indoc!( r#" - "123" |> Str.toU64? (Ok 123)? + "123" |> Str.to_u64? (Ok 123)? "# ); let arena = Bump::new(); @@ -885,10 +885,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123" Try(Ok 123)) + // Try(Str.to_u64 "123" Try(Ok 123)) let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Try, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Try, &out.interns); assert_eq!(cond_args.len(), 2); @@ -906,7 +906,7 @@ mod test_can { fn try_desugar_plain_prefix() { let src = indoc!( r#" - try Str.toU64 "123" + try Str.to_u64 "123" "# ); let arena = Bump::new(); @@ -916,10 +916,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Try, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Try, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -929,7 +929,7 @@ mod test_can { fn try_desugar_pipe_prefix() { let src = indoc!( r#" - "123" |> try Str.toU64 + "123" |> try Str.to_u64 "# ); let arena = Bump::new(); @@ -939,10 +939,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Try, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Try, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -952,7 +952,7 @@ mod test_can { fn try_desugar_pipe_suffix() { let src = indoc!( r#" - Str.toU64 "123" |> try + Str.to_u64 "123" |> try "# ); let arena = Bump::new(); @@ -962,10 +962,10 @@ mod test_can { // Assert that we desugar to: // - // Try(Str.toU64 "123") + // Try(Str.to_u64 "123") let cond_expr = assert_try_expr(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Space, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Space, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -975,7 +975,7 @@ mod test_can { fn try_desugar_double_question_suffix() { let src = indoc!( r#" - Str.toU64 "123" ?? Num.maxU64 + Str.to_u64 "123" ?? Num.max_u64 "# ); let arena = Bump::new(); @@ -985,12 +985,12 @@ mod test_can { // Assert that we desugar to: // - // when Str.toU64 "123" + // when Str.to_u64 "123" // Ok success_BRANCH1_0_9 -> success_BRANCH1_0_9 - // Err _ -> Num.maxU64 + // Err _ -> Num.max_u64 let (cond_expr, branches) = assert_when(&out.loc_expr.value); - let cond_args = assert_func_call(cond_expr, "toU64", CalledVia::Space, &out.interns); + let cond_args = assert_func_call(cond_expr, "to_u64", CalledVia::Space, &out.interns); assert_eq!(cond_args.len(), 1); assert_str_value(&cond_args[0].1.value, "123"); @@ -1000,16 +1000,16 @@ mod test_can { assert_pattern_tag_apply_with_ident( &branches[0].patterns[0].pattern.value, "Ok", - "success_BRANCH1_0_15", + "success_BRANCH1_0_16", &out.interns, ); assert_var_usage( &branches[0].value.value, - "success_BRANCH1_0_15", + "success_BRANCH1_0_16", &out.interns, ); assert_pattern_tag_apply_with_underscore(&branches[1].patterns[0].pattern.value, "Err"); - assert_var_usage(&branches[1].value.value, "maxU64", &out.interns); + assert_var_usage(&branches[1].value.value, "max_u64", &out.interns); } #[test] diff --git a/crates/repl_eval/src/eval.rs b/crates/repl_eval/src/eval.rs index 8343346308d..cc853c7f527 100644 --- a/crates/repl_eval/src/eval.rs +++ b/crates/repl_eval/src/eval.rs @@ -1501,12 +1501,12 @@ fn f64_literal_to_ast(arena: &Bump, num: f64) -> Expr<'_> { use std::fmt::Write; if num.is_nan() { - Expr::Num("Num.nanF64") + Expr::Num("Num.nan_f64") } else if num.is_infinite() { if num.is_sign_positive() { - Expr::Num("Num.infinityF64") + Expr::Num("Num.infinity_f64") } else { - Expr::Num("-Num.infinityF64") + Expr::Num("-Num.infinity_f64") } } else { let mut string = bumpalo::collections::String::with_capacity_in(64, arena); @@ -1519,12 +1519,12 @@ fn f32_literal_to_ast(arena: &Bump, num: f32) -> Expr<'_> { use std::fmt::Write; if num.is_nan() { - Expr::Num("Num.nanF32") + Expr::Num("Num.nan_f32") } else if num.is_infinite() { if num.is_sign_positive() { - Expr::Num("Num.infinityF32") + Expr::Num("Num.infinity_f32") } else { - Expr::Num("-Num.infinityF32") + Expr::Num("-Num.infinity_f32") } } else { let mut string = bumpalo::collections::String::with_capacity_in(64, arena); diff --git a/crates/repl_eval/src/gen.rs b/crates/repl_eval/src/gen.rs index 3d68999eaa1..3fabeb30e10 100644 --- a/crates/repl_eval/src/gen.rs +++ b/crates/repl_eval/src/gen.rs @@ -179,8 +179,8 @@ fn promote_expr_to_module<'a, 'i, I: Iterator>( defs: I, expr: &str, ) -> (usize, &'a str) { - const REPL_MODULE_HEADER: &str = "app \"app\" provides [replOutput] to \"./platform\"\n\n"; - const REPL_MODULE_MAIN_DEF: &str = "replOutput =\n"; + const REPL_MODULE_HEADER: &str = "app \"app\" provides [repl_output] to \"./platform\"\n\n"; + const REPL_MODULE_MAIN_DEF: &str = "repl_output =\n"; const INDENT: &str = " "; let mut buffer = bumpalo::collections::string::String::from_str_in(REPL_MODULE_HEADER, arena); diff --git a/crates/repl_test/src/state.rs b/crates/repl_test/src/state.rs index 96a4af523e0..4705d22618d 100644 --- a/crates/repl_test/src/state.rs +++ b/crates/repl_test/src/state.rs @@ -98,7 +98,7 @@ fn partial_record_definition() { // Partially define a record incompletely { let mut state = ReplState::new(); - let mut input = "failedRecord = {".to_string(); + let mut input = "failed_record = {".to_string(); incomplete(&mut input); input.push_str("field: \"field\","); @@ -111,11 +111,11 @@ fn partial_record_definition() { I am partway through parsing a record, but I got stuck here: - 1│ app "app" provides [replOutput] to "./platform" + 1│ app "app" provides [repl_output] to "./platform" 2│ - 3│ replOutput = - 4│ failedRecord = { - ^ + 3│ repl_output = + 4│ failed_record = { + ^ TODO provide more context."# ); diff --git a/crates/repl_test/src/tests.rs b/crates/repl_test/src/tests.rs index 94536b83caf..c1ff65330b7 100644 --- a/crates/repl_test/src/tests.rs +++ b/crates/repl_test/src/tests.rs @@ -69,14 +69,14 @@ fn num_rem() { #[cfg(not(feature = "wasm"))] #[test] fn num_floor_division() { - expect_success("Num.divTrunc 4 3", "1 : Int *"); + expect_success("Num.div_trunc 4 3", "1 : Int *"); } #[cfg(not(feature = "wasm"))] #[test] fn num_floor_checked_division_success() { expect_success( - "Num.divTruncChecked 4 3", + "Num.div_trunc_checked 4 3", "Ok 1 : Result (Int *) [DivByZero]", ); } @@ -85,7 +85,7 @@ fn num_floor_checked_division_success() { #[test] fn num_floor_checked_division_divby_zero() { expect_success( - "Num.divTruncChecked 4 0", + "Num.div_trunc_checked 4 0", "Err DivByZero : Result (Int *) [DivByZero]", ); } @@ -93,27 +93,27 @@ fn num_floor_checked_division_divby_zero() { #[cfg(not(feature = "wasm"))] #[test] fn num_ceil_division() { - expect_success("Num.divCeil 4 3", "2 : Int *") + expect_success("Num.div_ceil 4 3", "2 : Int *") } #[cfg(not(feature = "wasm"))] #[test] fn num_ceil_checked_division_success() { expect_success( - "Num.divCeilChecked 4 3", + "Num.div_ceil_checked 4 3", "Ok 2 : Result (Int *) [DivByZero]", ) } #[test] fn float_division_by_zero() { - expect_success("1f64 / 0", "Num.infinityF64 : F64"); - expect_success("-1f64 / 0", "-Num.infinityF64 : F64"); - expect_success("0f64 / 0", "Num.nanF64 : F64"); + expect_success("1f64 / 0", "Num.infinity_f64 : F64"); + expect_success("-1f64 / 0", "-Num.infinity_f64 : F64"); + expect_success("0f64 / 0", "Num.nan_f64 : F64"); - expect_success("1f32 / 0", "Num.infinityF32 : F32"); - expect_success("-1f32 / 0", "-Num.infinityF32 : F32"); - expect_success("0f32 / 0", "Num.nanF32 : F32"); + expect_success("1f32 / 0", "Num.infinity_f32 : F32"); + expect_success("-1f32 / 0", "-Num.infinity_f32 : F32"); + expect_success("0f32 / 0", "Num.nan_f32 : F32"); } #[test] @@ -349,50 +349,53 @@ fn nested_float_list() { #[test] fn num_bitwise_and() { - expect_success("Num.bitwiseAnd 20 20", "20 : Int *"); + expect_success("Num.bitwise_and 20 20", "20 : Int *"); - expect_success("Num.bitwiseAnd 25 10", "8 : Int *"); + expect_success("Num.bitwise_and 25 10", "8 : Int *"); - expect_success("Num.bitwiseAnd 200 0", "0 : Int *") + expect_success("Num.bitwise_and 200 0", "0 : Int *") } #[test] fn num_bitwise_xor() { - expect_success("Num.bitwiseXor 20 20", "0 : Int *"); + expect_success("Num.bitwise_xor 20 20", "0 : Int *"); - expect_success("Num.bitwiseXor 15 14", "1 : Int *"); + expect_success("Num.bitwise_xor 15 14", "1 : Int *"); - expect_success("Num.bitwiseXor 7 15", "8 : Int *"); + expect_success("Num.bitwise_xor 7 15", "8 : Int *"); - expect_success("Num.bitwiseXor 200 0", "200 : Int *") + expect_success("Num.bitwise_xor 200 0", "200 : Int *") } #[test] fn num_add_wrap() { - expect_success("Num.addWrap Num.maxI64 1", "-9223372036854775808 : I64"); + expect_success("Num.add_wrap Num.max_i64 1", "-9223372036854775808 : I64"); } #[test] fn num_sub_wrap() { - expect_success("Num.subWrap Num.minI64 1", "9223372036854775807 : I64"); + expect_success("Num.sub_wrap Num.min_i64 1", "9223372036854775807 : I64"); } #[test] fn num_mul_wrap() { - expect_success("Num.mulWrap Num.maxI64 2", "-2 : I64"); + expect_success("Num.mul_wrap Num.max_i64 2", "-2 : I64"); } #[test] fn num_mul_saturated() { - expect_success("Num.mulSaturated Num.maxI64 2", "9223372036854775807 : I64"); + expect_success( + "Num.mul_saturated Num.max_i64 2", + "9223372036854775807 : I64", + ); } #[cfg(not(feature = "wasm"))] #[test] fn num_add_checked() { - expect_success("Num.addChecked 1 1", "Ok 2 : Result (Num *) [Overflow]"); + expect_success("Num.add_checked 1 1", "Ok 2 : Result (Num *) [Overflow]"); expect_success( - "Num.addChecked Num.maxI64 1", + "Num.add_checked Num.max_i64 1", "Err Overflow : Result I64 [Overflow]", ); } @@ -400,9 +403,9 @@ fn num_add_checked() { #[cfg(not(feature = "wasm"))] #[test] fn num_sub_checked() { - expect_success("Num.subChecked 1 1", "Ok 0 : Result (Num *) [Overflow]"); + expect_success("Num.sub_checked 1 1", "Ok 0 : Result (Num *) [Overflow]"); expect_success( - "Num.subChecked Num.minI64 1", + "Num.sub_checked Num.min_i64 1", "Err Overflow : Result I64 [Overflow]", ); } @@ -410,9 +413,9 @@ fn num_sub_checked() { #[cfg(not(feature = "wasm"))] #[test] fn num_mul_checked() { - expect_success("Num.mulChecked 20 2", "Ok 40 : Result (Num *) [Overflow]"); + expect_success("Num.mul_checked 20 2", "Ok 40 : Result (Num *) [Overflow]"); expect_success( - "Num.mulChecked Num.maxI64 2", + "Num.mul_checked Num.max_i64 2", "Err Overflow : Result I64 [Overflow]", ); } @@ -778,21 +781,21 @@ fn type_problem_string_interpolation() { #[test] fn list_drop_at_negative_index() { expect_failure( - "List.dropAt [1, 2, 3] -1", + "List.drop_at [1, 2, 3] -1", indoc!( r#" ── TYPE MISMATCH ─────────────────────────────────────────────────────────────── - This 2nd argument to dropAt has an unexpected type: + This 2nd argument to drop_at has an unexpected type: - 4│ List.dropAt [1, 2, 3] -1 - ^^ + 4│ List.drop_at [1, 2, 3] -1 + ^^ The argument is a number of type: I8, I16, F32, I32, F64, I64, I128, or Dec - But dropAt needs its 2nd argument to be: + But drop_at needs its 2nd argument to be: U64 "# @@ -854,13 +857,13 @@ fn invalid_string_interpolation() { #[test] fn issue_2149_i8_ok() { - expect_success(r#"Str.toI8 "127""#, "Ok 127 : Result I8 [InvalidNumStr]"); + expect_success(r#"Str.to_i8 "127""#, "Ok 127 : Result I8 [InvalidNumStr]"); } #[test] fn issue_2149_i8_err() { expect_success( - r#"Str.toI8 "128""#, + r#"Str.to_i8 "128""#, "Err InvalidNumStr : Result I8 [InvalidNumStr]", ); } @@ -868,7 +871,7 @@ fn issue_2149_i8_err() { #[test] fn issue_2149_i16_ok() { expect_success( - r#"Str.toI16 "32767""#, + r#"Str.to_i16 "32767""#, "Ok 32767 : Result I16 [InvalidNumStr]", ); } @@ -876,7 +879,7 @@ fn issue_2149_i16_ok() { #[test] fn issue_2149_i16_err() { expect_success( - r#"Str.toI16 "32768""#, + r#"Str.to_i16 "32768""#, "Err InvalidNumStr : Result I16 [InvalidNumStr]", ); } @@ -1136,9 +1139,9 @@ fn parse_problem() { I am partway through parsing a definition, but I got stuck here: - 1│ app "app" provides [replOutput] to "./platform" + 1│ app "app" provides [repl_output] to "./platform" 2│ - 3│ replOutput = + 3│ repl_output = 4│ add m n = m + n ^^^ @@ -1330,9 +1333,9 @@ fn box_box_type_alias() { indoc!( r#" HeapStr : Box Str - helloHeap : HeapStr - helloHeap = Box.box "bye stacks" - helloHeap"# + hello_heap : HeapStr + hello_heap = Box.box "bye stacks" + hello_heap"# ), r#"Box.box "bye stacks" : HeapStr"#, ) @@ -1480,7 +1483,7 @@ fn str_to_dec() { expect_success( indoc!( r#" - Str.toDec "1234.1234" + Str.to_dec "1234.1234" "# ), r"Ok 1234.1234 : Result Dec [InvalidNumStr]", @@ -1534,7 +1537,7 @@ fn interpolation_with_nested_strings() { expect_success( indoc!( r#" - "foo $(Str.joinWith ["a", "b", "c"] ", ") bar" + "foo $(Str.join_with ["a", "b", "c"] ", ") bar" "# ), r#""foo a, b, c bar" : Str"#, @@ -1546,7 +1549,7 @@ fn interpolation_with_num_to_str() { expect_success( indoc!( r#" - "foo $(Num.toStr Num.maxI8) bar" + "foo $(Num.to_str Num.max_i8) bar" "# ), r#""foo 127 bar" : Str"#, @@ -1558,7 +1561,7 @@ fn interpolation_with_operator_desugaring() { expect_success( indoc!( r#" - "foo $(Num.toStr (1 + 2)) bar" + "foo $(Num.to_str (1 + 2)) bar" "# ), r#""foo 3 bar" : Str"#, @@ -1573,7 +1576,7 @@ fn interpolation_with_nested_interpolation() { expect_failure( indoc!( r#" - "foo $(Str.joinWith ["a$(Num.toStr 5)", "b"] "c")" + "foo $(Str.join_with ["a$(Num.to_str 5)", "b"] "c")" "# ), indoc!( @@ -1582,8 +1585,8 @@ fn interpolation_with_nested_interpolation() { This string interpolation is invalid: - 4│ "foo $(Str.joinWith ["a$(Num.toStr 5)", "b"] "c")" - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 4│ "foo $(Str.join_with ["a$(Num.to_str 5)", "b"] "c")" + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String interpolations cannot contain newlines or other interpolations. From db6cc5a7b169a6d9a1e3bb8afb044755f1aaf5c1 Mon Sep 17 00:00:00 2001 From: Sam Mohr Date: Sat, 4 Jan 2025 06:16:13 -0800 Subject: [PATCH 04/20] Don't convert any idents with any underscores --- crates/compiler/collections/src/small_string_interner.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/compiler/collections/src/small_string_interner.rs b/crates/compiler/collections/src/small_string_interner.rs index 930b28d25e9..29efa29e541 100644 --- a/crates/compiler/collections/src/small_string_interner.rs +++ b/crates/compiler/collections/src/small_string_interner.rs @@ -1,5 +1,5 @@ -use std::{fmt::Debug, mem::ManuallyDrop}; use std::borrow::Cow; +use std::{fmt::Debug, mem::ManuallyDrop}; /// Collection of small (length < u16::MAX) strings, stored compactly. #[derive(Clone, Default, PartialEq, Eq)] @@ -265,7 +265,7 @@ impl SmallStringInterner { if s.chars() .next() .is_some_and(|first_char| first_char.is_ascii_uppercase()) - || (s.contains('_') && !s.ends_with('_')) + || s.contains('_') { return s.into(); } From b56fbd38e14ba665ef5b618269d4e72b71270ba5 Mon Sep 17 00:00:00 2001 From: Sam Mohr Date: Sun, 5 Jan 2025 03:48:03 -0800 Subject: [PATCH 05/20] Progress on updating entire compiler for snake_case --- crates/cli/tests/benchmarks/AStar.roc | 132 +- crates/cli/tests/benchmarks/Base64.roc | 56 +- crates/cli/tests/benchmarks/Base64/Decode.roc | 96 +- crates/cli/tests/benchmarks/Base64/Encode.roc | 137 +- crates/cli/tests/benchmarks/Bytes/Decode.roc | 136 +- crates/cli/tests/benchmarks/Bytes/Encode.roc | 112 +- crates/cli/tests/benchmarks/Issue2279Help.roc | 4 +- crates/cli/tests/benchmarks/Quicksort.roc | 78 +- crates/cli/tests/benchmarks/cFold.roc | 124 +- crates/cli/tests/benchmarks/closure.roc | 34 +- crates/cli/tests/benchmarks/deriv.roc | 176 +- crates/cli/tests/benchmarks/issue2279.roc | 4 +- crates/cli/tests/benchmarks/nQueens.roc | 56 +- .../benchmarks/platform/PlatformTasks.roc | 8 +- crates/cli/tests/benchmarks/platform/app.roc | 2 +- crates/cli/tests/benchmarks/platform/host.zig | 36 +- crates/cli/tests/benchmarks/platform/main.roc | 6 +- crates/cli/tests/benchmarks/quicksortApp.roc | 26 +- crates/cli/tests/benchmarks/rBTreeCk.roc | 130 +- crates/cli/tests/benchmarks/rBTreeInsert.roc | 94 +- crates/cli/tests/benchmarks/testAStar.roc | 20 +- crates/cli/tests/benchmarks/testBase64.roc | 14 +- crates/cli/tests/cli_tests.rs | 7 +- ...form_simple_zig__expects_test_failure.snap | 3 +- ...ple_zig__module_params_arity_mismatch.snap | 16 +- ...orm_simple_zig__module_params_bad_ann.snap | 21 +- ...mple_zig__module_params_unexpected_fn.snap | 5 +- .../algorithms/fibonacci-platform/host.zig | 6 +- .../algorithms/fibonacci-platform/main.roc | 6 +- .../test-projects/algorithms/fibonacci.roc | 4 +- .../algorithms/quicksort-platform/host.zig | 4 +- .../algorithms/quicksort-platform/main.roc | 6 +- .../test-projects/algorithms/quicksort.roc | 64 +- .../test-projects/effectful/Community.roc | 88 +- .../test-projects/effectful/combine-tasks.roc | 22 +- .../tests/test-projects/effectful/echo.roc | 30 +- .../test-projects/effectful/for_each_try.roc | 19 +- .../tests/test-projects/effectful/form.roc | 26 +- .../tests/test-projects/effectful/hello.roc | 2 +- .../test-projects/effectful/ignore_result.roc | 4 +- .../effectful/inspect-logging.roc | 44 +- .../tests/test-projects/effectful/loops.roc | 10 +- .../tests/test-projects/effectful/on_err.roc | 16 +- .../test-projects/effectful/print-line.roc | 12 +- .../effectful/suffixed_record_field.roc | 14 +- .../effectful/untyped_passed_fx.roc | 8 +- .../tests/test-projects/expects/expects.roc | 18 +- .../expects_transitive/Direct.roc | 10 +- .../expects_transitive/Transitive.roc | 2 +- .../false-interpreter/Context.roc | 126 +- .../false-interpreter/Variable.roc | 28 +- .../test-projects/false-interpreter/main.roc | 464 ++-- .../false-interpreter/platform/File.roc | 28 +- .../false-interpreter/platform/Host.roc | 18 +- .../false-interpreter/platform/Stdin.roc | 4 +- .../false-interpreter/platform/Stdout.roc | 4 +- .../false-interpreter/platform/main.roc | 6 +- .../false-interpreter/platform/src/lib.rs | 2 +- .../fixtures/format/formatted.roc | 2 +- .../format/formatted_directory/Formatted.roc | 2 +- .../fixtures/format/not-formatted.roc | 4 +- .../fixtures/multi-dep-thunk/Dep1.roc | 2 +- .../fixtures/multi-dep-thunk/main.roc | 2 +- .../test-projects/known_bad/UnusedImport.roc | 6 +- ...edImportButWithALongFileNameForTesting.roc | 6 +- .../module_imports_pkg/ImportsUnknownPkg.roc | 6 +- .../module_imports_pkg/Module.roc | 6 +- .../test-projects/module_imports_pkg/app.roc | 2 +- .../tests/test-projects/module_params/Api.roc | 90 +- .../test-projects/module_params/BadAnn.roc | 14 +- .../module_params/ImportInExpect.roc | 8 +- .../test-projects/module_params/Menu.roc | 4 +- .../module_params/MultilineParams.roc | 2 +- .../tests/test-projects/module_params/app.roc | 80 +- .../module_params/arity_mismatch.roc | 8 +- .../test-projects/module_params/bad_ann.roc | 2 +- .../module_params/different_types.roc | 4 +- .../module_params/effect_module.roc | 2 +- .../module_params/issue_7116.roc | 6 +- .../module_params/multiline_params.roc | 4 +- .../test-projects/module_params/pass_task.roc | 4 +- .../module_params/unexpected_fn.roc | 6 +- .../test-projects/multiple_exposed/main.roc | 8 +- .../multiple_exposed/platform/host.zig | 8 +- .../multiple_exposed/platform/main.roc | 10 +- .../platform_requires_pkg/platform/host.zig | 4 +- .../platform_requires_pkg/platform/main.roc | 6 +- .../test-platform-effects-zig/Effect.roc | 6 +- .../test-platform-effects-zig/app-stub.roc | 2 +- .../test-platform-effects-zig/host.zig | 22 +- .../test-platform-effects-zig/main.roc | 6 +- .../test-platform-simple-zig/host.zig | 4 +- .../test-platform-simple-zig/main.roc | 6 +- crates/cli/tests/test-projects/tui/main.roc | 4 +- .../tests/test-projects/tui/platform/host.zig | 50 +- .../tests/test-projects/tui/platform/main.roc | 6 +- crates/compiler/alias_analysis/src/lib.rs | 2 +- crates/compiler/builtins/bitcode/src/dec.zig | 74 +- crates/compiler/builtins/bitcode/src/main.zig | 2 +- crates/compiler/builtins/roc/Num.roc | 6 +- crates/compiler/can/src/desugar.rs | 6 +- ...st_suffixed__suffixed_tests__dbg_expr.snap | 4 +- ..._suffixed__suffixed_tests__dbg_simple.snap | 2 +- ...uffixed__suffixed_tests__dbg_stmt_arg.snap | 2 +- ...t_suffixed__suffixed_tests__pizza_dbg.snap | 4 +- ...uffixed_tests__simple_double_question.snap | 42 +- crates/compiler/can/tests/test_suffixed.rs | 2 +- .../src/components/Graph/VariablesGraph.tsx | 6 +- .../collections/src/small_string_interner.rs | 53 +- crates/compiler/gen_llvm/src/llvm/build.rs | 8 +- .../compiler/gen_llvm/src/llvm/build_str.rs | 2 +- crates/compiler/gen_llvm/src/llvm/lowlevel.rs | 2 +- crates/compiler/gen_wasm/README.md | 6 +- .../gen_wasm/docs/host-to-app-calls.svg | 2 +- crates/compiler/load/tests/platform.roc | 6 +- crates/compiler/load/tests/test_reporting.rs | 18 +- crates/compiler/load_internal/src/module.rs | 2 +- .../compiler/load_internal/tests/test_load.rs | 20 +- crates/compiler/mono/src/ir.rs | 2 +- crates/compiler/mono/src/layout.rs | 2 +- crates/compiler/solve/tests/solve_expr.rs | 6 +- crates/compiler/test_gen/src/gen_abilities.rs | 416 ++-- crates/compiler/test_gen/src/gen_compare.rs | 24 +- crates/compiler/test_gen/src/gen_dict.rs | 96 +- crates/compiler/test_gen/src/gen_erased.rs | 2 +- crates/compiler/test_gen/src/gen_list.rs | 586 ++--- crates/compiler/test_gen/src/gen_num.rs | 1040 ++++---- crates/compiler/test_gen/src/gen_panic.rs | 4 +- .../compiler/test_gen/src/gen_primitives.rs | 428 ++-- crates/compiler/test_gen/src/gen_records.rs | 22 +- crates/compiler/test_gen/src/gen_refcount.rs | 40 +- crates/compiler/test_gen/src/gen_result.rs | 36 +- crates/compiler/test_gen/src/gen_return.rs | 80 +- crates/compiler/test_gen/src/gen_set.rs | 56 +- crates/compiler/test_gen/src/gen_str.rs | 278 +-- crates/compiler/test_gen/src/gen_tags.rs | 86 +- crates/compiler/test_gen/src/gen_tuples.rs | 4 +- .../test_gen/src/helpers/debug-wasm-test.html | 2 +- crates/compiler/test_gen/src/wasm_str.rs | 208 +- .../generated/as_pattern_in_closure_arg.txt | 31 - ...ose_correct_recursion_var_under_record.txt | 162 +- .../compiler/test_mono/generated/dbg_expr.txt | 54 +- .../test_mono/generated/dbg_in_expect.txt | 62 +- .../test_mono/generated/dbg_inside_string.txt | 62 +- .../test_mono/generated/dbg_nested_expr.txt | 54 +- .../generated/dbg_str_followed_by_number.txt | 62 +- crates/compiler/test_mono/generated/dict.txt | 34 +- .../generated/inspect_derived_dict.txt | 1392 +++++------ .../generated/inspect_derived_list.txt | 150 +- .../inspect_derived_nested_record_string.txt | 266 +-- .../generated/inspect_derived_record.txt | 208 +- ...nspect_derived_record_one_field_string.txt | 170 +- ...spect_derived_record_two_field_strings.txt | 170 +- .../generated/inspect_derived_string.txt | 62 +- .../inspect_derived_tag_one_field_string.txt | 150 +- ...nspect_derived_tag_two_payloads_string.txt | 148 +- .../generated/linked_list_filter.txt | 92 +- .../test_mono/generated/pizza_dbg.txt | 54 +- crates/compiler/test_mono/src/tests.rs | 590 ++--- ...function_effect_types.header.formatted.roc | 2 +- .../function_effect_types.header.result-ast | 2 +- .../pass/function_effect_types.header.roc | 2 +- ...empty_platform_header.header.formatted.roc | 2 +- ...nonempty_platform_header.header.result-ast | 2 +- .../pass/nonempty_platform_header.header.roc | 2 +- .../pass/pizza_question.moduledefs.result-ast | 2 +- .../pass/pizza_question.moduledefs.roc | 2 +- .../pass/requires_type.header.formatted.roc | 2 +- .../pass/requires_type.header.result-ast | 2 +- .../snapshots/pass/requires_type.header.roc | 6 +- .../pass/return_in_if.expr.formatted.roc | 2 +- .../pass/return_in_if.expr.result-ast | 2 +- .../snapshots/pass/return_in_if.expr.roc | 2 +- .../pass/return_in_when.expr.formatted.roc | 2 +- .../pass/return_in_when.expr.result-ast | 2 +- .../snapshots/pass/return_in_when.expr.roc | 2 +- .../tag_union_functions_as.expr.formatted.roc | 4 +- .../tag_union_functions_as.expr.result-ast | 4 +- .../pass/tag_union_functions_as.expr.roc | 4 +- crates/compiler/test_syntax/tests/test_fmt.rs | 4 +- crates/glue/README.md | 6 +- crates/glue/platform/Shape.roc | 34 +- crates/glue/platform/Target.roc | 2 +- crates/glue/platform/TypeId.roc | 10 +- crates/glue/platform/Types.roc | 60 +- crates/glue/platform/main.roc | 8 +- crates/glue/src/CGlue.roc | 16 +- crates/glue/src/DescribeGlue.roc | 12 +- crates/glue/src/RustGlue.roc | 2084 +++++++++-------- crates/glue/src/ZigGlue.roc | 32 +- crates/glue/src/glue.rs | 62 +- crates/glue/src/load.rs | 4 +- crates/glue/src/roc_type/mod.rs | 88 +- crates/glue/src/types.rs | 40 +- .../glue/tests/fixtures/c/hello-world/host.c | 6 +- .../tests/fixtures/c/hello-world/platform.roc | 6 +- .../rust/advanced-recursive-union/app.roc | 12 +- .../advanced-recursive-union/platform.roc | 8 +- .../rust/advanced-recursive-union/src/lib.rs | 2 +- .../fixtures/rust/arguments/platform.roc | 6 +- .../tests/fixtures/rust/arguments/src/lib.rs | 2 +- .../fixtures/rust/basic-record/platform.roc | 6 +- .../fixtures/rust/basic-record/src/lib.rs | 2 +- .../rust/basic-recursive-union/app.roc | 2 +- .../rust/basic-recursive-union/platform.roc | 6 +- .../rust/basic-recursive-union/src/lib.rs | 2 +- .../tests/fixtures/rust/closures/platform.roc | 6 +- .../tests/fixtures/rust/closures/src/lib.rs | 2 +- .../fixtures/rust/enumeration/platform.roc | 6 +- .../fixtures/rust/enumeration/src/lib.rs | 2 +- .../rust/list-recursive-union/app.roc | 12 +- .../rust/list-recursive-union/platform.roc | 8 +- .../rust/list-recursive-union/src/lib.rs | 2 +- .../fixtures/rust/multiple-modules/Dep1.roc | 4 +- .../fixtures/rust/multiple-modules/Dep2.roc | 4 +- .../fixtures/rust/multiple-modules/app.roc | 2 +- .../rust/multiple-modules/platform.roc | 6 +- .../fixtures/rust/multiple-modules/src/lib.rs | 2 +- .../fixtures/rust/nested-record/platform.roc | 6 +- .../fixtures/rust/nested-record/src/lib.rs | 2 +- .../rust/nonnullable-unwrapped/app.roc | 2 +- .../rust/nonnullable-unwrapped/platform.roc | 6 +- .../rust/nonnullable-unwrapped/src/lib.rs | 2 +- .../fixtures/rust/nullable-unwrapped/app.roc | 2 +- .../rust/nullable-unwrapped/platform.roc | 6 +- .../rust/nullable-unwrapped/src/lib.rs | 2 +- .../fixtures/rust/nullable-wrapped/app.roc | 2 +- .../rust/nullable-wrapped/platform.roc | 6 +- .../fixtures/rust/nullable-wrapped/src/lib.rs | 4 +- .../glue/tests/fixtures/rust/option/app.roc | 6 +- .../tests/fixtures/rust/option/platform.roc | 8 +- .../tests/fixtures/rust/option/src/lib.rs | 4 +- .../tests/fixtures/rust/rocresult/app.roc | 8 +- .../fixtures/rust/rocresult/platform.roc | 6 +- .../tests/fixtures/rust/rocresult/src/lib.rs | 4 +- .../rust/single-tag-union/platform.roc | 6 +- .../fixtures/rust/single-tag-union/src/lib.rs | 2 +- .../fixtures/rust/union-with-padding/app.roc | 2 +- .../rust/union-with-padding/platform.roc | 6 +- .../rust/union-with-padding/src/lib.rs | 4 +- .../rust/union-without-padding/app.roc | 2 +- .../rust/union-without-padding/platform.roc | 6 +- .../rust/union-without-padding/src/lib.rs | 4 +- crates/glue/tests/test_glue_cli.rs | 5 +- crates/linker/dynhost_benchmarks_elf64 | Bin 780000 -> 780016 bytes crates/linker/dynhost_benchmarks_windows.exe | Bin 757248 -> 757256 bytes crates/linker/src/elf.rs | 8 +- crates/linker/src/macho.rs | 2 +- crates/linker/src/pe.rs | 28 +- crates/test_utils/src/TagLenEncoderFmt.roc | 310 +-- crates/valgrind_tests/src/lib.rs | 2 +- crates/valgrind_tests/zig-platform/host.zig | 4 +- crates/valgrind_tests/zig-platform/main.roc | 6 +- crates/wasm_module/src/lib.rs | 2 +- examples/glue/glue.roc | 6 +- examples/glue/rust-platform/main.roc | 12 +- examples/glue/rust-platform/src/glue.rs | 8 +- examples/glue/rust-platform/src/lib.rs | 2 +- examples/jvm-interop/bridge.c | 12 +- examples/jvm-interop/impl.roc | 16 +- examples/jvm-interop/platform.roc | 10 +- examples/nodejs-interop/native-c-api/demo.c | 4 +- .../native-c-api/platform/main.roc | 8 +- .../nodejs-interop/wasm/platform/host.zig | 4 +- .../nodejs-interop/wasm/platform/main.roc | 6 +- examples/platform-switching/c-platform/host.c | 4 +- .../platform-switching/c-platform/main.roc | 6 +- .../platform-switching/rust-platform/build.rs | 2 +- .../platform-switching/rust-platform/main.roc | 6 +- .../rust-platform/src/lib.rs | 2 +- .../web-assembly-platform/host.zig | 4 +- .../web-assembly-platform/main.roc | 6 +- .../platform-switching/zig-platform/host.zig | 4 +- .../platform-switching/zig-platform/main.roc | 6 +- examples/python-interop/README.md | 2 +- examples/python-interop/demo.c | 4 +- examples/python-interop/libhello.roc | 2 +- examples/python-interop/platform/host.c | 4 +- examples/python-interop/platform/main.roc | 18 +- examples/ruby-interop/demo.c | 4 +- examples/ruby-interop/libhello.roc | 2 +- examples/ruby-interop/platform/host.c | 4 +- examples/ruby-interop/platform/main.roc | 18 +- examples/virtual-dom-wip/ExampleApp.roc | 30 +- examples/virtual-dom-wip/example-client.roc | 4 +- examples/virtual-dom-wip/example-server.roc | 4 +- examples/virtual-dom-wip/platform/Action.roc | 2 +- examples/virtual-dom-wip/platform/Html.roc | 252 +- .../platform/Html/Attributes.roc | 270 +-- .../virtual-dom-wip/platform/Html/Event.roc | 94 +- .../platform/Html/Internal/Client.roc | 860 +++---- .../platform/Html/Internal/Server.roc | 133 +- .../platform/Html/Internal/Shared.roc | 124 +- examples/virtual-dom-wip/platform/Json.roc | 1318 +++++------ .../platform/PlatformTasks.roc | 60 +- .../virtual-dom-wip/platform/client-side.roc | 52 +- .../virtual-dom-wip/platform/server-side.roc | 24 +- 297 files changed, 8546 insertions(+), 8674 deletions(-) delete mode 100644 crates/compiler/test_mono/generated/as_pattern_in_closure_arg.txt diff --git a/crates/cli/tests/benchmarks/AStar.roc b/crates/cli/tests/benchmarks/AStar.roc index 29b8a9d9748..20856b8d7f7 100644 --- a/crates/cli/tests/benchmarks/AStar.roc +++ b/crates/cli/tests/benchmarks/AStar.roc @@ -1,107 +1,107 @@ -module [findPath, Model, initialModel, cheapestOpen, reconstructPath] +module [find_path, Model, initial_model, cheapest_open, reconstruct_path] import Quicksort -findPath = \costFn, moveFn, start, end -> - astar costFn moveFn end (initialModel start) +find_path = \cost_fn, move_fn, start, end -> + astar(cost_fn, move_fn, end, initial_model(start)) Model position : { evaluated : Set position, - openSet : Set position, + open_set : Set position, costs : Dict position F64, - cameFrom : Dict position position, + came_from : Dict position position, } where position implements Hash & Eq -initialModel : position -> Model position where position implements Hash & Eq -initialModel = \start -> { - evaluated: Set.empty {}, - openSet: Set.single start, - costs: Dict.single start 0, - cameFrom: Dict.empty {}, +initial_model : position -> Model position where position implements Hash & Eq +initial_model = \start -> { + evaluated: Set.empty({}), + open_set: Set.single(start), + costs: Dict.single(start, 0), + came_from: Dict.empty({}), } -cheapestOpen : (position -> F64), Model position -> Result position {} where position implements Hash & Eq -cheapestOpen = \costFn, model -> - model.openSet - |> Set.toList - |> List.keepOks - (\position -> - when Dict.get model.costs position is - Err _ -> Err {} - Ok cost -> Ok { cost: cost + costFn position, position } - ) - |> Quicksort.sortBy .cost +cheapest_open : (position -> F64), Model position -> Result position {} where position implements Hash & Eq +cheapest_open = \cost_fn, model -> + model.open_set + |> Set.to_list + |> List.keep_oks( + \position -> + when Dict.get(model.costs, position) is + Err(_) -> Err({}) + Ok(cost) -> Ok({ cost: cost + cost_fn(position), position }), + ) + |> Quicksort.sort_by(.cost) |> List.first - |> Result.map .position - |> Result.mapErr (\_ -> {}) + |> Result.map(.position) + |> Result.map_err(\_ -> {}) -reconstructPath : Dict position position, position -> List position where position implements Hash & Eq -reconstructPath = \cameFrom, goal -> - when Dict.get cameFrom goal is - Err _ -> [] - Ok next -> List.append (reconstructPath cameFrom next) goal +reconstruct_path : Dict position position, position -> List position where position implements Hash & Eq +reconstruct_path = \came_from, goal -> + when Dict.get(came_from, goal) is + Err(_) -> [] + Ok(next) -> List.append(reconstruct_path(came_from, next), goal) -updateCost : position, position, Model position -> Model position where position implements Hash & Eq -updateCost = \current, neighbor, model -> - newCameFrom = - Dict.insert model.cameFrom neighbor current +update_cost : position, position, Model position -> Model position where position implements Hash & Eq +update_cost = \current, neighbor, model -> + new_came_from = + Dict.insert(model.came_from, neighbor, current) - newCosts = - Dict.insert model.costs neighbor distanceTo + new_costs = + Dict.insert(model.costs, neighbor, distance_to) - distanceTo = - reconstructPath newCameFrom neighbor + distance_to = + reconstruct_path(new_came_from, neighbor) |> List.len - |> Num.toFrac + |> Num.to_frac - newModel = + new_model = { model & - costs: newCosts, - cameFrom: newCameFrom, + costs: new_costs, + came_from: new_came_from, } - when Dict.get model.costs neighbor is - Err _ -> - newModel + when Dict.get(model.costs, neighbor) is + Err(_) -> + new_model - Ok previousDistance -> - if distanceTo < previousDistance then - newModel + Ok(previous_distance) -> + if distance_to < previous_distance then + new_model else model astar : (position, position -> F64), (position -> Set position), position, Model position -> Result (List position) {} where position implements Hash & Eq -astar = \costFn, moveFn, goal, model -> - when cheapestOpen (\source -> costFn source goal) model is - Err {} -> Err {} - Ok current -> +astar = \cost_fn, move_fn, goal, model -> + when cheapest_open(\source -> cost_fn(source, goal), model) is + Err({}) -> Err({}) + Ok(current) -> if current == goal then - Ok (reconstructPath model.cameFrom goal) + Ok(reconstruct_path(model.came_from, goal)) else - modelPopped = + model_popped = { model & - openSet: Set.remove model.openSet current, - evaluated: Set.insert model.evaluated current, + open_set: Set.remove(model.open_set, current), + evaluated: Set.insert(model.evaluated, current), } neighbors = - moveFn current + move_fn(current) - newNeighbors = - Set.difference neighbors modelPopped.evaluated + new_neighbors = + Set.difference(neighbors, model_popped.evaluated) - modelWithNeighbors : Model position - modelWithNeighbors = - modelPopped - |> &openSet (Set.union modelPopped.openSet newNeighbors) + model_with_neighbors : Model position + model_with_neighbors = + model_popped + |> &open_set(Set.union(model_popped.open_set, new_neighbors)) walker : Model position, position -> Model position - walker = \amodel, n -> updateCost current n amodel + walker = \amodel, n -> update_cost(current, n, amodel) - modelWithCosts = - Set.walk newNeighbors modelWithNeighbors walker + model_with_costs = + Set.walk(new_neighbors, model_with_neighbors, walker) - astar costFn moveFn goal modelWithCosts + astar(cost_fn, move_fn, goal, model_with_costs) # takeStep = \moveFn, _goal, model, current -> # modelPopped = diff --git a/crates/cli/tests/benchmarks/Base64.roc b/crates/cli/tests/benchmarks/Base64.roc index bdf23ea2ecf..1e0a9623f87 100644 --- a/crates/cli/tests/benchmarks/Base64.roc +++ b/crates/cli/tests/benchmarks/Base64.roc @@ -1,38 +1,38 @@ -module [fromBytes, fromStr, toBytes, toStr] +module [from_bytes, from_str, to_bytes, to_str] import Base64.Decode import Base64.Encode # base 64 encoding from a sequence of bytes -fromBytes : List U8 -> Result Str [InvalidInput] -fromBytes = \bytes -> - when Base64.Decode.fromBytes bytes is - Ok v -> - Ok v +from_bytes : List U8 -> Result Str [InvalidInput] +from_bytes = \bytes -> + when Base64.Decode.from_bytes(bytes) is + Ok(v) -> + Ok(v) - Err _ -> - Err InvalidInput + Err(_) -> + Err(InvalidInput) # base 64 encoding from a string -fromStr : Str -> Result Str [InvalidInput] -fromStr = \str -> - fromBytes (Str.toUtf8 str) +from_str : Str -> Result Str [InvalidInput] +from_str = \str -> + from_bytes(Str.to_utf8(str)) # base64-encode bytes to the original -toBytes : Str -> Result (List U8) [InvalidInput] -toBytes = \str -> - Ok (Base64.Encode.toBytes str) - -toStr : Str -> Result Str [InvalidInput] -toStr = \str -> - when toBytes str is - Ok bytes -> - when Str.fromUtf8 bytes is - Ok v -> - Ok v - - Err _ -> - Err InvalidInput - - Err _ -> - Err InvalidInput +to_bytes : Str -> Result (List U8) [InvalidInput] +to_bytes = \str -> + Ok(Base64.Encode.to_bytes(str)) + +to_str : Str -> Result Str [InvalidInput] +to_str = \str -> + when to_bytes(str) is + Ok(bytes) -> + when Str.from_utf8(bytes) is + Ok(v) -> + Ok(v) + + Err(_) -> + Err(InvalidInput) + + Err(_) -> + Err(InvalidInput) diff --git a/crates/cli/tests/benchmarks/Base64/Decode.roc b/crates/cli/tests/benchmarks/Base64/Decode.roc index 4b32bff95af..e33e7028e05 100644 --- a/crates/cli/tests/benchmarks/Base64/Decode.roc +++ b/crates/cli/tests/benchmarks/Base64/Decode.roc @@ -1,86 +1,86 @@ -module [fromBytes] +module [from_bytes] import Bytes.Decode exposing [ByteDecoder, DecodeProblem] -fromBytes : List U8 -> Result Str DecodeProblem -fromBytes = \bytes -> - Bytes.Decode.decode bytes (decodeBase64 (List.len bytes)) +from_bytes : List U8 -> Result Str DecodeProblem +from_bytes = \bytes -> + Bytes.Decode.decode(bytes, decode_base64(List.len(bytes))) -decodeBase64 : U64 -> ByteDecoder Str -decodeBase64 = \width -> Bytes.Decode.loop loopHelp { remaining: width, string: "" } +decode_base64 : U64 -> ByteDecoder Str +decode_base64 = \width -> Bytes.Decode.loop(loop_help, { remaining: width, string: "" }) -loopHelp : { remaining : U64, string : Str } -> ByteDecoder (Bytes.Decode.Step { remaining : U64, string : Str } Str) -loopHelp = \{ remaining, string } -> +loop_help : { remaining : U64, string : Str } -> ByteDecoder (Bytes.Decode.Step { remaining : U64, string : Str } Str) +loop_help = \{ remaining, string } -> if remaining >= 3 then - Bytes.Decode.map3 Bytes.Decode.u8 Bytes.Decode.u8 Bytes.Decode.u8 \x, y, z -> + Bytes.Decode.map3(Bytes.Decode.u8, Bytes.Decode.u8, Bytes.Decode.u8, \x, y, z -> a : U32 - a = Num.intCast x + a = Num.int_cast(x) b : U32 - b = Num.intCast y + b = Num.int_cast(y) c : U32 - c = Num.intCast z - combined = Num.bitwiseOr (Num.bitwiseOr (Num.shiftLeftBy a 16) (Num.shiftLeftBy b 8)) c + c = Num.int_cast(z) + combined = Num.bitwise_or(Num.bitwise_or(Num.shift_left_by(a, 16), Num.shift_left_by(b, 8)), c) - Loop { + Loop({ remaining: remaining - 3, - string: Str.concat string (bitsToChars combined 0), - } + string: Str.concat(string, bits_to_chars(combined, 0)), + })) else if remaining == 0 then - Bytes.Decode.succeed (Done string) + Bytes.Decode.succeed(Done(string)) else if remaining == 2 then - Bytes.Decode.map2 Bytes.Decode.u8 Bytes.Decode.u8 \x, y -> + Bytes.Decode.map2(Bytes.Decode.u8, Bytes.Decode.u8, \x, y -> a : U32 - a = Num.intCast x + a = Num.int_cast(x) b : U32 - b = Num.intCast y - combined = Num.bitwiseOr (Num.shiftLeftBy a 16) (Num.shiftLeftBy b 8) + b = Num.int_cast(y) + combined = Num.bitwise_or(Num.shift_left_by(a, 16), Num.shift_left_by(b, 8)) - Done (Str.concat string (bitsToChars combined 1)) + Done(Str.concat(string, bits_to_chars(combined, 1)))) else # remaining = 1 - Bytes.Decode.map Bytes.Decode.u8 \x -> + Bytes.Decode.map(Bytes.Decode.u8, \x -> a : U32 - a = Num.intCast x + a = Num.int_cast(x) - Done (Str.concat string (bitsToChars (Num.shiftLeftBy a 16) 2)) + Done(Str.concat(string, bits_to_chars(Num.shift_left_by(a, 16), 2)))) -bitsToChars : U32, Int * -> Str -bitsToChars = \bits, missing -> - when Str.fromUtf8 (bitsToCharsHelp bits missing) is - Ok str -> str - Err _ -> "" +bits_to_chars : U32, Int * -> Str +bits_to_chars = \bits, missing -> + when Str.from_utf8(bits_to_chars_help(bits, missing)) is + Ok(str) -> str + Err(_) -> "" # Mask that can be used to get the lowest 6 bits of a binary number -lowest6BitsMask : Int * -lowest6BitsMask = 63 +lowest6_bits_mask : Int * +lowest6_bits_mask = 63 -bitsToCharsHelp : U32, Int * -> List U8 -bitsToCharsHelp = \bits, missing -> +bits_to_chars_help : U32, Int * -> List U8 +bits_to_chars_help = \bits, missing -> # The input is 24 bits, which we have to partition into 4 6-bit segments. We achieve this by # shifting to the right by (a multiple of) 6 to remove unwanted bits on the right, then `Num.bitwiseAnd` # with `0b111111` (which is 2^6 - 1 or 63) (so, 6 1s) to remove unwanted bits on the left. # any 6-bit number is a valid base64 digit, so this is actually safe p = - Num.shiftRightZfBy bits 18 - |> Num.intCast - |> unsafeToChar + Num.shift_right_zf_by(bits, 18) + |> Num.int_cast + |> unsafe_to_char q = - Num.bitwiseAnd (Num.shiftRightZfBy bits 12) lowest6BitsMask - |> Num.intCast - |> unsafeToChar + Num.bitwise_and(Num.shift_right_zf_by(bits, 12), lowest6_bits_mask) + |> Num.int_cast + |> unsafe_to_char r = - Num.bitwiseAnd (Num.shiftRightZfBy bits 6) lowest6BitsMask - |> Num.intCast - |> unsafeToChar + Num.bitwise_and(Num.shift_right_zf_by(bits, 6), lowest6_bits_mask) + |> Num.int_cast + |> unsafe_to_char s = - Num.bitwiseAnd bits lowest6BitsMask - |> Num.intCast - |> unsafeToChar + Num.bitwise_and(bits, lowest6_bits_mask) + |> Num.int_cast + |> unsafe_to_char equals : U8 equals = 61 @@ -94,8 +94,8 @@ bitsToCharsHelp = \bits, missing -> [] # Base64 index to character/digit -unsafeToChar : U8 -> U8 -unsafeToChar = \n -> +unsafe_to_char : U8 -> U8 +unsafe_to_char = \n -> if n <= 25 then # uppercase characters 65 + n diff --git a/crates/cli/tests/benchmarks/Base64/Encode.roc b/crates/cli/tests/benchmarks/Base64/Encode.roc index 66e195509b4..c29f0680388 100644 --- a/crates/cli/tests/benchmarks/Base64/Encode.roc +++ b/crates/cli/tests/benchmarks/Base64/Encode.roc @@ -1,22 +1,22 @@ -module [toBytes] +module [to_bytes] import Bytes.Encode exposing [ByteEncoder] InvalidChar : U8 # State : [None, One U8, Two U8, Three U8] -toBytes : Str -> List U8 -toBytes = \str -> +to_bytes : Str -> List U8 +to_bytes = \str -> str - |> Str.toUtf8 - |> encodeChunks + |> Str.to_utf8 + |> encode_chunks |> Bytes.Encode.sequence |> Bytes.Encode.encode -encodeChunks : List U8 -> List ByteEncoder -encodeChunks = \bytes -> - List.walk bytes { output: [], accum: None } folder - |> encodeResidual +encode_chunks : List U8 -> List ByteEncoder +encode_chunks = \bytes -> + List.walk(bytes, { output: [], accum: None }, folder) + |> encode_residual coerce : U64, a -> a coerce = \_, x -> x @@ -24,113 +24,114 @@ coerce = \_, x -> x # folder : { output : List ByteEncoder, accum : State }, U8 -> { output : List ByteEncoder, accum : State } folder = \{ output, accum }, char -> when accum is - Unreachable n -> coerce n { output, accum: Unreachable n } - None -> { output, accum: One char } - One a -> { output, accum: Two a char } - Two a b -> { output, accum: Three a b char } - Three a b c -> - when encodeCharacters a b c char is - Ok encoder -> + Unreachable(n) -> coerce(n, { output, accum: Unreachable(n) }) + None -> { output, accum: One(char) } + One(a) -> { output, accum: Two(a, char) } + Two(a, b) -> { output, accum: Three(a, b, char) } + Three(a, b, c) -> + when encode_characters(a, b, c, char) is + Ok(encoder) -> { - output: List.append output encoder, + output: List.append(output, encoder), accum: None, } - Err _ -> + Err(_) -> { output, accum: None } # SGVs bG8g V29y bGQ= # encodeResidual : { output : List ByteEncoder, accum : State } -> List ByteEncoder -encodeResidual = \{ output, accum } -> +encode_residual = \{ output, accum } -> when accum is - Unreachable _ -> output + Unreachable(_) -> output None -> output - One _ -> output - Two a b -> - when encodeCharacters a b equals equals is - Ok encoder -> List.append output encoder - Err _ -> output + One(_) -> output + Two(a, b) -> + when encode_characters(a, b, equals, equals) is + Ok(encoder) -> List.append(output, encoder) + Err(_) -> output - Three a b c -> - when encodeCharacters a b c equals is - Ok encoder -> List.append output encoder - Err _ -> output + Three(a, b, c) -> + when encode_characters(a, b, c, equals) is + Ok(encoder) -> List.append(output, encoder) + Err(_) -> output equals : U8 equals = 61 # Convert 4 characters to 24 bits (as an ByteEncoder) -encodeCharacters : U8, U8, U8, U8 -> Result ByteEncoder InvalidChar -encodeCharacters = \a, b, c, d -> - if !(isValidChar a) then - Err a - else if !(isValidChar b) then - Err b +encode_characters : U8, U8, U8, U8 -> Result ByteEncoder InvalidChar +encode_characters = \a, b, c, d -> + if !(is_valid_char(a)) then + Err(a) + else if !(is_valid_char(b)) then + Err(b) else # `=` is the padding character, and must be special-cased # only the `c` and `d` char are allowed to be padding - n1 = unsafeConvertChar a - n2 = unsafeConvertChar b + n1 = unsafe_convert_char(a) + n2 = unsafe_convert_char(b) x : U32 - x = Num.intCast n1 + x = Num.int_cast(n1) y : U32 - y = Num.intCast n2 + y = Num.int_cast(n2) if d == equals then if c == equals then - n = Num.bitwiseOr (Num.shiftLeftBy x 18) (Num.shiftLeftBy y 12) + n = Num.bitwise_or(Num.shift_left_by(x, 18), Num.shift_left_by(y, 12)) # masking higher bits is not needed, Encode.unsignedInt8 ignores higher bits b1 : U8 - b1 = Num.intCast (Num.shiftRightBy n 16) + b1 = Num.int_cast(Num.shift_right_by(n, 16)) - Ok (Bytes.Encode.u8 b1) - else if !(isValidChar c) then - Err c + Ok(Bytes.Encode.u8(b1)) + else if !(is_valid_char(c)) then + Err(c) else - n3 = unsafeConvertChar c + n3 = unsafe_convert_char(c) z : U32 - z = Num.intCast n3 + z = Num.int_cast(n3) - n = Num.bitwiseOr (Num.bitwiseOr (Num.shiftLeftBy x 18) (Num.shiftLeftBy y 12)) (Num.shiftLeftBy z 6) + n = Num.bitwise_or(Num.bitwise_or(Num.shift_left_by(x, 18), Num.shift_left_by(y, 12)), Num.shift_left_by(z, 6)) combined : U16 - combined = Num.intCast (Num.shiftRightBy n 8) + combined = Num.int_cast(Num.shift_right_by(n, 8)) - Ok (Bytes.Encode.u16 BE combined) - else if !(isValidChar d) then - Err d + Ok(Bytes.Encode.u16(BE, combined)) + else if !(is_valid_char(d)) then + Err(d) else - n3 = unsafeConvertChar c - n4 = unsafeConvertChar d + n3 = unsafe_convert_char(c) + n4 = unsafe_convert_char(d) z : U32 - z = Num.intCast n3 + z = Num.int_cast(n3) w : U32 - w = Num.intCast n4 + w = Num.int_cast(n4) n = - Num.bitwiseOr - (Num.bitwiseOr (Num.shiftLeftBy x 18) (Num.shiftLeftBy y 12)) - (Num.bitwiseOr (Num.shiftLeftBy z 6) w) + Num.bitwise_or( + Num.bitwise_or(Num.shift_left_by(x, 18), Num.shift_left_by(y, 12)), + Num.bitwise_or(Num.shift_left_by(z, 6), w), + ) b3 : U8 - b3 = Num.intCast n + b3 = Num.int_cast(n) combined : U16 - combined = Num.intCast (Num.shiftRightBy n 8) + combined = Num.int_cast(Num.shift_right_by(n, 8)) - Ok (Bytes.Encode.sequence [Bytes.Encode.u16 BE combined, Bytes.Encode.u8 b3]) + Ok(Bytes.Encode.sequence([Bytes.Encode.u16(BE, combined), Bytes.Encode.u8(b3)])) # is the character a base64 digit? # The base16 digits are: A-Z, a-z, 0-1, '+' and '/' -isValidChar : U8 -> Bool -isValidChar = \c -> - if isAlphaNum c then +is_valid_char : U8 -> Bool +is_valid_char = \c -> + if is_alpha_num(c) then Bool.true else when c is @@ -145,14 +146,14 @@ isValidChar = \c -> _ -> Bool.false -isAlphaNum : U8 -> Bool -isAlphaNum = \key -> +is_alpha_num : U8 -> Bool +is_alpha_num = \key -> (key >= 48 && key <= 57) || (key >= 64 && key <= 90) || (key >= 97 && key <= 122) # Convert a base64 character/digit to its index # See also [Wikipedia](https://en.wikipedia.org/wiki/Base64#Base64_table) -unsafeConvertChar : U8 -> U8 -unsafeConvertChar = \key -> +unsafe_convert_char : U8 -> U8 +unsafe_convert_char = \key -> if key >= 65 && key <= 90 then # A-Z key - 65 diff --git a/crates/cli/tests/benchmarks/Bytes/Decode.roc b/crates/cli/tests/benchmarks/Bytes/Decode.roc index 79d96828c6c..75490628d80 100644 --- a/crates/cli/tests/benchmarks/Bytes/Decode.roc +++ b/crates/cli/tests/benchmarks/Bytes/Decode.roc @@ -7,105 +7,111 @@ DecodeProblem : [OutOfBytes] ByteDecoder a := State -> [Good State a, Bad DecodeProblem] decode : List U8, ByteDecoder a -> Result a DecodeProblem -decode = \bytes, @ByteDecoder decoder -> - when decoder { bytes, cursor: 0 } is - Good _ value -> - Ok value +decode = \bytes, @ByteDecoder(decoder) -> + when decoder({ bytes, cursor: 0 }) is + Good(_, value) -> + Ok(value) - Bad e -> - Err e + Bad(e) -> + Err(e) succeed : a -> ByteDecoder a -succeed = \value -> @ByteDecoder \state -> Good state value +succeed = \value -> @ByteDecoder(\state -> Good(state, value)) map : ByteDecoder a, (a -> b) -> ByteDecoder b -map = \@ByteDecoder decoder, transform -> - @ByteDecoder +map = \@ByteDecoder(decoder), transform -> + @ByteDecoder( \state -> - when decoder state is - Good state1 value -> - Good state1 (transform value) + when decoder(state) is + Good(state1, value) -> + Good(state1, transform(value)) - Bad e -> - Bad e + Bad(e) -> + Bad(e), + ) map2 : ByteDecoder a, ByteDecoder b, (a, b -> c) -> ByteDecoder c -map2 = \@ByteDecoder decoder1, @ByteDecoder decoder2, transform -> - @ByteDecoder +map2 = \@ByteDecoder(decoder1), @ByteDecoder(decoder2), transform -> + @ByteDecoder( \state1 -> - when decoder1 state1 is - Good state2 a -> - when decoder2 state2 is - Good state3 b -> - Good state3 (transform a b) + when decoder1(state1) is + Good(state2, a) -> + when decoder2(state2) is + Good(state3, b) -> + Good(state3, transform(a, b)) - Bad e -> - Bad e + Bad(e) -> + Bad(e) - Bad e -> - Bad e + Bad(e) -> + Bad(e), + ) map3 : ByteDecoder a, ByteDecoder b, ByteDecoder c, (a, b, c -> d) -> ByteDecoder d -map3 = \@ByteDecoder decoder1, @ByteDecoder decoder2, @ByteDecoder decoder3, transform -> - @ByteDecoder +map3 = \@ByteDecoder(decoder1), @ByteDecoder(decoder2), @ByteDecoder(decoder3), transform -> + @ByteDecoder( \state1 -> - when decoder1 state1 is - Good state2 a -> - when decoder2 state2 is - Good state3 b -> - when decoder3 state3 is - Good state4 c -> - Good state4 (transform a b c) + when decoder1(state1) is + Good(state2, a) -> + when decoder2(state2) is + Good(state3, b) -> + when decoder3(state3) is + Good(state4, c) -> + Good(state4, transform(a, b, c)) - Bad e -> - Bad e + Bad(e) -> + Bad(e) - Bad e -> - Bad e + Bad(e) -> + Bad(e) - Bad e -> - Bad e + Bad(e) -> + Bad(e), + ) after : ByteDecoder a, (a -> ByteDecoder b) -> ByteDecoder b -after = \@ByteDecoder decoder, transform -> - @ByteDecoder +after = \@ByteDecoder(decoder), transform -> + @ByteDecoder( \state -> - when decoder state is - Good state1 value -> - (@ByteDecoder decoder1) = transform value + when decoder(state) is + Good(state1, value) -> + @ByteDecoder(decoder1) = transform(value) - decoder1 state1 + decoder1(state1) - Bad e -> - Bad e + Bad(e) -> + Bad(e), + ) u8 : ByteDecoder U8 -u8 = @ByteDecoder +u8 = @ByteDecoder( \state -> - when List.get state.bytes state.cursor is - Ok b -> - Good { state & cursor: state.cursor + 1 } b + when List.get(state.bytes, state.cursor) is + Ok(b) -> + Good({ state & cursor: state.cursor + 1 }, b) - Err _ -> - Bad OutOfBytes + Err(_) -> + Bad(OutOfBytes), +) Step state b : [Loop state, Done b] loop : (state -> ByteDecoder (Step state a)), state -> ByteDecoder a loop = \stepper, initial -> - @ByteDecoder + @ByteDecoder( \state -> - loopHelp stepper initial state + loop_help(stepper, initial, state), + ) -loopHelp = \stepper, accum, state -> - (@ByteDecoder stepper1) = stepper accum +loop_help = \stepper, accum, state -> + @ByteDecoder(stepper1) = stepper(accum) - when stepper1 state is - Good newState (Done value) -> - Good newState value + when stepper1(state) is + Good(new_state, Done(value)) -> + Good(new_state, value) - Good newState (Loop newAccum) -> - loopHelp stepper newAccum newState + Good(new_state, Loop(new_accum)) -> + loop_help(stepper, new_accum, new_state) - Bad e -> - Bad e + Bad(e) -> + Bad(e) diff --git a/crates/cli/tests/benchmarks/Bytes/Encode.roc b/crates/cli/tests/benchmarks/Bytes/Encode.roc index 2c70aff7fac..7242638143e 100644 --- a/crates/cli/tests/benchmarks/Bytes/Encode.roc +++ b/crates/cli/tests/benchmarks/Bytes/Encode.roc @@ -5,130 +5,132 @@ Endianness : [BE, LE] ByteEncoder : [Signed8 I8, Unsigned8 U8, Signed16 Endianness I16, Unsigned16 Endianness U16, Sequence U64 (List ByteEncoder), Bytes (List U8)] u8 : U8 -> ByteEncoder -u8 = \value -> Unsigned8 value +u8 = \value -> Unsigned8(value) empty : ByteEncoder empty = foo : List ByteEncoder foo = [] - Sequence 0 foo + Sequence(0, foo) u16 : Endianness, U16 -> ByteEncoder -u16 = \endianness, value -> Unsigned16 endianness value +u16 = \endianness, value -> Unsigned16(endianness, value) bytes : List U8 -> ByteEncoder -bytes = \bs -> Bytes bs +bytes = \bs -> Bytes(bs) sequence : List ByteEncoder -> ByteEncoder sequence = \encoders -> - Sequence (getWidths encoders 0) encoders + Sequence(get_widths(encoders, 0), encoders) -getWidth : ByteEncoder -> U64 -getWidth = \encoder -> +get_width : ByteEncoder -> U64 +get_width = \encoder -> when encoder is - Signed8 _ -> 1 - Unsigned8 _ -> 1 - Signed16 _ _ -> 2 - Unsigned16 _ _ -> 2 + Signed8(_) -> 1 + Unsigned8(_) -> 1 + Signed16(_, _) -> 2 + Unsigned16(_, _) -> 2 # Signed32 _ -> 4 # Unsigned32 _ -> 4 # Signed64 _ -> 8 # Unsigned64 _ -> 8 # Signed128 _ -> 16 # Unsigned128 _ -> 16 - Sequence w _ -> w - Bytes bs -> List.len bs + Sequence(w, _) -> w + Bytes(bs) -> List.len(bs) -getWidths : List ByteEncoder, U64 -> U64 -getWidths = \encoders, initial -> - List.walk encoders initial \accum, encoder -> accum + getWidth encoder +get_widths : List ByteEncoder, U64 -> U64 +get_widths = \encoders, initial -> + List.walk(encoders, initial, \accum, encoder -> accum + get_width(encoder)) encode : ByteEncoder -> List U8 encode = \encoder -> - output = List.repeat 0 (getWidth encoder) + output = List.repeat(0, get_width(encoder)) - encodeHelp encoder 0 output + encode_help(encoder, 0, output) |> .output -encodeHelp : ByteEncoder, U64, List U8 -> { output : List U8, offset : U64 } -encodeHelp = \encoder, offset, output -> +encode_help : ByteEncoder, U64, List U8 -> { output : List U8, offset : U64 } +encode_help = \encoder, offset, output -> when encoder is - Unsigned8 value -> + Unsigned8(value) -> { - output: List.set output offset value, + output: List.set(output, offset, value), offset: offset + 1, } - Signed8 value -> + Signed8(value) -> cast : U8 - cast = Num.intCast value + cast = Num.int_cast(value) { - output: List.set output offset cast, + output: List.set(output, offset, cast), offset: offset + 1, } - Unsigned16 endianness value -> + Unsigned16(endianness, value) -> a : U8 - a = Num.intCast (Num.shiftRightBy value 8) + a = Num.int_cast(Num.shift_right_by(value, 8)) b : U8 - b = Num.intCast value + b = Num.int_cast(value) - newOutput = + new_output = when endianness is BE -> output - |> List.set (offset + 0) a - |> List.set (offset + 1) b + |> List.set((offset + 0), a) + |> List.set((offset + 1), b) LE -> output - |> List.set (offset + 0) b - |> List.set (offset + 1) a + |> List.set((offset + 0), b) + |> List.set((offset + 1), a) { - output: newOutput, + output: new_output, offset: offset + 2, } - Signed16 endianness value -> + Signed16(endianness, value) -> a : U8 - a = Num.intCast (Num.shiftRightBy value 8) + a = Num.int_cast(Num.shift_right_by(value, 8)) b : U8 - b = Num.intCast value + b = Num.int_cast(value) - newOutput = + new_output = when endianness is BE -> output - |> List.set (offset + 0) a - |> List.set (offset + 1) b + |> List.set((offset + 0), a) + |> List.set((offset + 1), b) LE -> output - |> List.set (offset + 0) b - |> List.set (offset + 1) a + |> List.set((offset + 0), b) + |> List.set((offset + 1), a) { - output: newOutput, + output: new_output, offset: offset + 1, } - Bytes bs -> - List.walk - bs - { output, offset } + Bytes(bs) -> + List.walk( + bs, + { output, offset }, \accum, byte -> { offset: accum.offset + 1, - output: List.set accum.output offset byte, - } - - Sequence _ encoders -> - List.walk - encoders - { output, offset } + output: List.set(accum.output, offset, byte), + }, + ) + + Sequence(_, encoders) -> + List.walk( + encoders, + { output, offset }, \accum, single -> - encodeHelp single accum.offset accum.output + encode_help(single, accum.offset, accum.output), + ) diff --git a/crates/cli/tests/benchmarks/Issue2279Help.roc b/crates/cli/tests/benchmarks/Issue2279Help.roc index 3f33b2ac86c..b71a3ceca0a 100644 --- a/crates/cli/tests/benchmarks/Issue2279Help.roc +++ b/crates/cli/tests/benchmarks/Issue2279Help.roc @@ -1,5 +1,5 @@ -module [text, asText] +module [text, as_text] text = "Hello, world!" -asText = Num.toStr +as_text = Num.to_str diff --git a/crates/cli/tests/benchmarks/Quicksort.roc b/crates/cli/tests/benchmarks/Quicksort.roc index 5f36d00f927..3b03df6dfbc 100644 --- a/crates/cli/tests/benchmarks/Quicksort.roc +++ b/crates/cli/tests/benchmarks/Quicksort.roc @@ -1,75 +1,75 @@ -module [sortBy, sortWith, show] +module [sort_by, sort_with, show] show : List I64 -> Str show = \list -> - if List.isEmpty list then + if List.is_empty(list) then "[]" else content = list - |> List.map Num.toStr - |> Str.joinWith ", " + |> List.map(Num.to_str) + |> Str.join_with(", ") "[$(content)]" -sortBy : List a, (a -> Num *) -> List a -sortBy = \list, toComparable -> - sortWith list (\x, y -> Num.compare (toComparable x) (toComparable y)) +sort_by : List a, (a -> Num *) -> List a +sort_by = \list, to_comparable -> + sort_with(list, \x, y -> Num.compare(to_comparable(x), to_comparable(y))) Order a : a, a -> [LT, GT, EQ] -sortWith : List a, (a, a -> [LT, GT, EQ]) -> List a -sortWith = \list, order -> - n = List.len list +sort_with : List a, (a, a -> [LT, GT, EQ]) -> List a +sort_with = \list, order -> + n = List.len(list) - quicksortHelp list order 0 (n - 1) + quicksort_help(list, order, 0, (n - 1)) -quicksortHelp : List a, Order a, U64, U64 -> List a -quicksortHelp = \list, order, low, high -> +quicksort_help : List a, Order a, U64, U64 -> List a +quicksort_help = \list, order, low, high -> if low < high then - when partition low high list order is - Pair partitionIndex partitioned -> + when partition(low, high, list, order) is + Pair(partition_index, partitioned) -> partitioned - |> quicksortHelp order low (Num.subSaturated partitionIndex 1) - |> quicksortHelp order (partitionIndex + 1) high + |> quicksort_help(order, low, Num.sub_saturated(partition_index, 1)) + |> quicksort_help(order, (partition_index + 1), high) else list partition : U64, U64, List a, Order a -> [Pair U64 (List a)] -partition = \low, high, initialList, order -> - when List.get initialList high is - Ok pivot -> - when partitionHelp low low initialList order high pivot is - Pair newI newList -> - Pair newI (swap newI high newList) +partition = \low, high, initial_list, order -> + when List.get(initial_list, high) is + Ok(pivot) -> + when partition_help(low, low, initial_list, order, high, pivot) is + Pair(new_i, new_list) -> + Pair(new_i, swap(new_i, high, new_list)) - Err _ -> - Pair low initialList + Err(_) -> + Pair(low, initial_list) -partitionHelp : U64, U64, List c, Order c, U64, c -> [Pair U64 (List c)] -partitionHelp = \i, j, list, order, high, pivot -> +partition_help : U64, U64, List c, Order c, U64, c -> [Pair U64 (List c)] +partition_help = \i, j, list, order, high, pivot -> if j < high then - when List.get list j is - Ok value -> - when order value pivot is + when List.get(list, j) is + Ok(value) -> + when order(value, pivot) is LT | EQ -> - partitionHelp (i + 1) (j + 1) (swap i j list) order high pivot + partition_help((i + 1), (j + 1), swap(i, j, list), order, high, pivot) GT -> - partitionHelp i (j + 1) list order high pivot + partition_help(i, (j + 1), list, order, high, pivot) - Err _ -> - Pair i list + Err(_) -> + Pair(i, list) else - Pair i list + Pair(i, list) swap : U64, U64, List a -> List a swap = \i, j, list -> - when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + when Pair(List.get(list, i), List.get(list, j)) is + Pair(Ok(at_i), Ok(at_j)) -> list - |> List.set i atJ - |> List.set j atI + |> List.set(i, at_j) + |> List.set(j, at_i) _ -> [] diff --git a/crates/cli/tests/benchmarks/cFold.roc b/crates/cli/tests/benchmarks/cFold.roc index 685827a07c7..0731159aab8 100644 --- a/crates/cli/tests/benchmarks/cFold.roc +++ b/crates/cli/tests/benchmarks/cFold.roc @@ -5,27 +5,27 @@ import pf.PlatformTasks # adapted from https://github.com/koka-lang/koka/blob/master/test/bench/haskell/cfold.hs main : Task {} [] main = - { value, isError } = PlatformTasks.getInt! - inputResult = - if isError then - Err GetIntError + { value, is_error } = PlatformTasks.get_int! + input_result = + if is_error then + Err(GetIntError) else - Ok value + Ok(value) - when inputResult is - Ok n -> - e = mkExpr n 1 # original koka n = 20 (set `ulimit -s unlimited` to avoid stack overflow for n = 20) - unoptimized = eval e - optimized = eval (constFolding (reassoc e)) + when input_result is + Ok(n) -> + e = mk_expr(n, 1) # original koka n = 20 (set `ulimit -s unlimited` to avoid stack overflow for n = 20) + unoptimized = eval(e) + optimized = eval(const_folding(reassoc(e))) unoptimized - |> Num.toStr - |> Str.concat " & " - |> Str.concat (Num.toStr optimized) - |> PlatformTasks.putLine + |> Num.to_str + |> Str.concat(" & ") + |> Str.concat(Num.to_str(optimized)) + |> PlatformTasks.put_line - Err GetIntError -> - PlatformTasks.putLine "Error: Failed to get Integer from stdin." + Err(GetIntError) -> + PlatformTasks.put_line("Error: Failed to get Integer from stdin.") Expr : [ Add Expr Expr, @@ -34,97 +34,97 @@ Expr : [ Var I64, ] -mkExpr : I64, I64 -> Expr -mkExpr = \n, v -> +mk_expr : I64, I64 -> Expr +mk_expr = \n, v -> when n is 0 -> - if v == 0 then Var 1 else Val v + if v == 0 then Var(1) else Val(v) _ -> - Add (mkExpr (n - 1) (v + 1)) (mkExpr (n - 1) (max (v - 1) 0)) + Add(mk_expr((n - 1), (v + 1)), mk_expr((n - 1), max((v - 1), 0))) max : I64, I64 -> I64 max = \a, b -> if a > b then a else b -appendAdd : Expr, Expr -> Expr -appendAdd = \e1, e2 -> +append_add : Expr, Expr -> Expr +append_add = \e1, e2 -> when e1 is - Add a1 a2 -> - Add a1 (appendAdd a2 e2) + Add(a1, a2) -> + Add(a1, append_add(a2, e2)) _ -> - Add e1 e2 + Add(e1, e2) -appendMul : Expr, Expr -> Expr -appendMul = \e1, e2 -> +append_mul : Expr, Expr -> Expr +append_mul = \e1, e2 -> when e1 is - Mul a1 a2 -> - Mul a1 (appendMul a2 e2) + Mul(a1, a2) -> + Mul(a1, append_mul(a2, e2)) _ -> - Mul e1 e2 + Mul(e1, e2) eval : Expr -> I64 eval = \e -> when e is - Var _ -> + Var(_) -> 0 - Val v -> + Val(v) -> v - Add l r -> - eval l + eval r + Add(l, r) -> + eval(l) + eval(r) - Mul l r -> - eval l * eval r + Mul(l, r) -> + eval(l) * eval(r) reassoc : Expr -> Expr reassoc = \e -> when e is - Add e1 e2 -> - x1 = reassoc e1 - x2 = reassoc e2 + Add(e1, e2) -> + x1 = reassoc(e1) + x2 = reassoc(e2) - appendAdd x1 x2 + append_add(x1, x2) - Mul e1 e2 -> - x1 = reassoc e1 - x2 = reassoc e2 + Mul(e1, e2) -> + x1 = reassoc(e1) + x2 = reassoc(e2) - appendMul x1 x2 + append_mul(x1, x2) _ -> e -constFolding : Expr -> Expr -constFolding = \e -> +const_folding : Expr -> Expr +const_folding = \e -> when e is - Add e1 e2 -> - x1 = constFolding e1 - x2 = constFolding e2 + Add(e1, e2) -> + x1 = const_folding(e1) + x2 = const_folding(e2) when x1 is - Val a -> + Val(a) -> when x2 is - Val b -> Val (a + b) - Add (Val b) x | Add x (Val b) -> Add (Val (a + b)) x - _ -> Add x1 x2 + Val(b) -> Val((a + b)) + Add(Val(b), x) | Add(x, Val(b)) -> Add(Val((a + b)), x) + _ -> Add(x1, x2) - _ -> Add x1 x2 + _ -> Add(x1, x2) - Mul e1 e2 -> - x1 = constFolding e1 - x2 = constFolding e2 + Mul(e1, e2) -> + x1 = const_folding(e1) + x2 = const_folding(e2) when x1 is - Val a -> + Val(a) -> when x2 is - Val b -> Val (a * b) - Mul (Val b) x | Mul x (Val b) -> Mul (Val (a * b)) x - _ -> Mul x1 x2 + Val(b) -> Val((a * b)) + Mul(Val(b), x) | Mul(x, Val(b)) -> Mul(Val((a * b)), x) + _ -> Mul(x1, x2) - _ -> Mul x1 x2 + _ -> Mul(x1, x2) _ -> e diff --git a/crates/cli/tests/benchmarks/closure.roc b/crates/cli/tests/benchmarks/closure.roc index d6cda3f73fe..558372af1e2 100644 --- a/crates/cli/tests/benchmarks/closure.roc +++ b/crates/cli/tests/benchmarks/closure.roc @@ -2,19 +2,19 @@ app [main] { pf: platform "platform/main.roc" } main : Task {} [] main = - closure1 {} - |> Task.await (\_ -> closure2 {}) - |> Task.await (\_ -> closure3 {}) - |> Task.await (\_ -> closure4 {}) + closure1({}) + |> Task.await(\_ -> closure2({})) + |> Task.await(\_ -> closure3({})) + |> Task.await(\_ -> closure4({})) # --- closure1 : {} -> Task {} [] closure1 = \_ -> - Task.ok (foo toUnitBorrowed "a long string such that it's malloced") - |> Task.map \_ -> {} + Task.ok(foo(to_unit_borrowed, "a long string such that it's malloced")) + |> Task.map(\_ -> {}) -toUnitBorrowed = \x -> Str.countUtf8Bytes x +to_unit_borrowed = \x -> Str.count_utf8_bytes(x) -foo = \f, x -> f x +foo = \f, x -> f(x) # --- closure2 : {} -> Task {} [] @@ -22,11 +22,11 @@ closure2 = \_ -> x : Str x = "a long string such that it's malloced" - Task.ok {} - |> Task.map (\_ -> x) - |> Task.map toUnit + Task.ok({}) + |> Task.map(\_ -> x) + |> Task.map(to_unit) -toUnit = \_ -> {} +to_unit = \_ -> {} # # --- closure3 : {} -> Task {} [] @@ -34,8 +34,8 @@ closure3 = \_ -> x : Str x = "a long string such that it's malloced" - Task.ok {} - |> Task.await (\_ -> Task.ok x |> Task.map (\_ -> {})) + Task.ok({}) + |> Task.await(\_ -> Task.ok(x) |> Task.map(\_ -> {})) # # --- closure4 : {} -> Task {} [] @@ -43,6 +43,6 @@ closure4 = \_ -> x : Str x = "a long string such that it's malloced" - Task.ok {} - |> Task.await (\_ -> Task.ok x) - |> Task.map (\_ -> {}) + Task.ok({}) + |> Task.await(\_ -> Task.ok(x)) + |> Task.map(\_ -> {}) diff --git a/crates/cli/tests/benchmarks/deriv.roc b/crates/cli/tests/benchmarks/deriv.roc index 25806ac9d67..bb24ef1c275 100644 --- a/crates/cli/tests/benchmarks/deriv.roc +++ b/crates/cli/tests/benchmarks/deriv.roc @@ -7,45 +7,45 @@ IO a : Task a [] main : Task {} [] main = - { value, isError } = PlatformTasks.getInt! - inputResult = - if isError then - Err GetIntError + { value, is_error } = PlatformTasks.get_int! + input_result = + if is_error then + Err(GetIntError) else - Ok value + Ok(value) - when inputResult is - Ok n -> + when input_result is + Ok(n) -> x : Expr - x = Var "x" + x = Var("x") f : Expr - f = pow x x + f = pow(x, x) - nest deriv n f # original koka n = 10 - |> Task.map \_ -> {} + nest(deriv, n, f) # original koka n = 10 + |> Task.map(\_ -> {}) - Err GetIntError -> - PlatformTasks.putLine "Error: Failed to get Integer from stdin." + Err(GetIntError) -> + PlatformTasks.put_line("Error: Failed to get Integer from stdin.") -nestHelp : I64, (I64, Expr -> IO Expr), I64, Expr -> IO Expr -nestHelp = \s, f, m, x -> +nest_help : I64, (I64, Expr -> IO Expr), I64, Expr -> IO Expr +nest_help = \s, f, m, x -> when m is - 0 -> Task.ok x + 0 -> Task.ok(x) _ -> - w = f! (s - m) x - nestHelp s f (m - 1) w + w = f!((s - m), x) + nest_help(s, f, (m - 1), w) nest : (I64, Expr -> IO Expr), I64, Expr -> IO Expr -nest = \f, n, e -> nestHelp n f n e +nest = \f, n, e -> nest_help(n, f, n, e) Expr : [Val I64, Var Str, Add Expr Expr, Mul Expr Expr, Pow Expr Expr, Ln Expr] divmod : I64, I64 -> Result { div : I64, mod : I64 } [DivByZero] divmod = \l, r -> - when Pair (Num.divTruncChecked l r) (Num.remChecked l r) is - Pair (Ok div) (Ok mod) -> Ok { div, mod } - _ -> Err DivByZero + when Pair(Num.div_trunc_checked(l, r), Num.rem_checked(l, r)) is + Pair(Ok(div), Ok(mod)) -> Ok({ div, mod }) + _ -> Err(DivByZero) pown : I64, I64 -> I64 pown = \a, n -> @@ -53,119 +53,119 @@ pown = \a, n -> 0 -> 1 1 -> a _ -> - when divmod n 2 is - Ok { div, mod } -> - b = pown a div + when divmod(n, 2) is + Ok({ div, mod }) -> + b = pown(a, div) b * b * (if mod == 0 then 1 else a) - Err DivByZero -> + Err(DivByZero) -> -1 add : Expr, Expr -> Expr add = \a, b -> - when Pair a b is - Pair (Val n) (Val m) -> - Val (n + m) + when Pair(a, b) is + Pair(Val(n), Val(m)) -> + Val((n + m)) - Pair (Val 0) f -> + Pair(Val(0), f) -> f - Pair f (Val 0) -> + Pair(f, Val(0)) -> f - Pair f (Val n) -> - add (Val n) f + Pair(f, Val(n)) -> + add(Val(n), f) - Pair (Val n) (Add (Val m) f) -> - add (Val (n + m)) f + Pair(Val(n), Add(Val(m), f)) -> + add(Val((n + m)), f) - Pair f (Add (Val n) g) -> - add (Val n) (add f g) + Pair(f, Add(Val(n), g)) -> + add(Val(n), add(f, g)) - Pair (Add f g) h -> - add f (add g h) + Pair(Add(f, g), h) -> + add(f, add(g, h)) - Pair f g -> - Add f g + Pair(f, g) -> + Add(f, g) mul : Expr, Expr -> Expr mul = \a, b -> - when Pair a b is - Pair (Val n) (Val m) -> - Val (n * m) + when Pair(a, b) is + Pair(Val(n), Val(m)) -> + Val((n * m)) - Pair (Val 0) _ -> - Val 0 + Pair(Val(0), _) -> + Val(0) - Pair _ (Val 0) -> - Val 0 + Pair(_, Val(0)) -> + Val(0) - Pair (Val 1) f -> + Pair(Val(1), f) -> f - Pair f (Val 1) -> + Pair(f, Val(1)) -> f - Pair f (Val n) -> - mul (Val n) f + Pair(f, Val(n)) -> + mul(Val(n), f) - Pair (Val n) (Mul (Val m) f) -> - mul (Val (n * m)) f + Pair(Val(n), Mul(Val(m), f)) -> + mul(Val((n * m)), f) - Pair f (Mul (Val n) g) -> - mul (Val n) (mul f g) + Pair(f, Mul(Val(n), g)) -> + mul(Val(n), mul(f, g)) - Pair (Mul f g) h -> - mul f (mul g h) + Pair(Mul(f, g), h) -> + mul(f, mul(g, h)) - Pair f g -> - Mul f g + Pair(f, g) -> + Mul(f, g) pow : Expr, Expr -> Expr pow = \a, b -> - when Pair a b is - Pair (Val m) (Val n) -> Val (pown m n) - Pair _ (Val 0) -> Val 1 - Pair f (Val 1) -> f - Pair (Val 0) _ -> Val 0 - Pair f g -> Pow f g + when Pair(a, b) is + Pair(Val(m), Val(n)) -> Val(pown(m, n)) + Pair(_, Val(0)) -> Val(1) + Pair(f, Val(1)) -> f + Pair(Val(0), _) -> Val(0) + Pair(f, g) -> Pow(f, g) ln : Expr -> Expr ln = \f -> when f is - Val 1 -> Val 0 - _ -> Ln f + Val(1) -> Val(0) + _ -> Ln(f) d : Str, Expr -> Expr d = \x, expr -> when expr is - Val _ -> Val 0 - Var y -> if x == y then Val 1 else Val 0 - Add f g -> add (d x f) (d x g) - Mul f g -> add (mul f (d x g)) (mul g (d x f)) - Pow f g -> - mul (pow f g) (add (mul (mul g (d x f)) (pow f (Val (-1)))) (mul (ln f) (d x g))) + Val(_) -> Val(0) + Var(y) -> if x == y then Val(1) else Val(0) + Add(f, g) -> add(d(x, f), d(x, g)) + Mul(f, g) -> add(mul(f, d(x, g)), mul(g, d(x, f))) + Pow(f, g) -> + mul(pow(f, g), add(mul(mul(g, d(x, f)), pow(f, Val(-1))), mul(ln(f), d(x, g)))) - Ln f -> - mul (d x f) (pow f (Val (-1))) + Ln(f) -> + mul(d(x, f), pow(f, Val(-1))) count : Expr -> I64 count = \expr -> when expr is - Val _ -> 1 - Var _ -> 1 - Add f g -> count f + count g - Mul f g -> count f + count g - Pow f g -> count f + count g - Ln f -> count f + Val(_) -> 1 + Var(_) -> 1 + Add(f, g) -> count(f) + count(g) + Mul(f, g) -> count(f) + count(g) + Pow(f, g) -> count(f) + count(g) + Ln(f) -> count(f) deriv : I64, Expr -> IO Expr deriv = \i, f -> - fprime = d "x" f + fprime = d("x", f) line = - Num.toStr (i + 1) - |> Str.concat " count: " - |> Str.concat (Num.toStr (count fprime)) - PlatformTasks.putLine! line - Task.ok fprime + Num.to_str((i + 1)) + |> Str.concat(" count: ") + |> Str.concat(Num.to_str(count(fprime))) + PlatformTasks.put_line!(line) + Task.ok(fprime) diff --git a/crates/cli/tests/benchmarks/issue2279.roc b/crates/cli/tests/benchmarks/issue2279.roc index 1ec76f507a2..5def55c7b6a 100644 --- a/crates/cli/tests/benchmarks/issue2279.roc +++ b/crates/cli/tests/benchmarks/issue2279.roc @@ -8,6 +8,6 @@ main = if Bool.true then Issue2279Help.text else - Issue2279Help.asText 42 + Issue2279Help.as_text(42) - PlatformTasks.putLine text + PlatformTasks.put_line(text) diff --git a/crates/cli/tests/benchmarks/nQueens.roc b/crates/cli/tests/benchmarks/nQueens.roc index 09eb39fab65..fc9295dfc05 100644 --- a/crates/cli/tests/benchmarks/nQueens.roc +++ b/crates/cli/tests/benchmarks/nQueens.roc @@ -4,63 +4,63 @@ import pf.PlatformTasks main : Task {} [] main = - { value, isError } = PlatformTasks.getInt! - inputResult = - if isError then - Err GetIntError + { value, is_error } = PlatformTasks.get_int! + input_result = + if is_error then + Err(GetIntError) else - Ok value + Ok(value) - when inputResult is - Ok n -> - queens n # original koka 13 - |> Num.toStr - |> PlatformTasks.putLine + when input_result is + Ok(n) -> + queens(n) # original koka 13 + |> Num.to_str + |> PlatformTasks.put_line - Err GetIntError -> - PlatformTasks.putLine "Error: Failed to get Integer from stdin." + Err(GetIntError) -> + PlatformTasks.put_line("Error: Failed to get Integer from stdin.") ConsList a : [Nil, Cons a (ConsList a)] -queens = \n -> length (findSolutions n n) +queens = \n -> length(find_solutions(n, n)) -findSolutions = \n, k -> +find_solutions = \n, k -> if k <= 0 then # should we use U64 as input type here instead? - Cons Nil Nil + Cons(Nil, Nil) else - extend n Nil (findSolutions n (k - 1)) + extend(n, Nil, find_solutions(n, (k - 1))) extend = \n, acc, solutions -> when solutions is Nil -> acc - Cons soln rest -> extend n (appendSafe n soln acc) rest + Cons(soln, rest) -> extend(n, append_safe(n, soln, acc), rest) -appendSafe : I64, ConsList I64, ConsList (ConsList I64) -> ConsList (ConsList I64) -appendSafe = \k, soln, solns -> +append_safe : I64, ConsList I64, ConsList (ConsList I64) -> ConsList (ConsList I64) +append_safe = \k, soln, solns -> if k <= 0 then solns - else if safe k 1 soln then - appendSafe (k - 1) soln (Cons (Cons k soln) solns) + else if safe(k, 1, soln) then + append_safe((k - 1), soln, Cons(Cons(k, soln), solns)) else - appendSafe (k - 1) soln solns + append_safe((k - 1), soln, solns) safe : I64, I64, ConsList I64 -> Bool safe = \queen, diagonal, xs -> when xs is Nil -> Bool.true - Cons q t -> + Cons(q, t) -> if queen != q && queen != q + diagonal && queen != q - diagonal then - safe queen (diagonal + 1) t + safe(queen, (diagonal + 1), t) else Bool.false length : ConsList a -> I64 length = \xs -> - lengthHelp xs 0 + length_help(xs, 0) -lengthHelp : ConsList a, I64 -> I64 -lengthHelp = \foobar, acc -> +length_help : ConsList a, I64 -> I64 +length_help = \foobar, acc -> when foobar is - Cons _ lrest -> lengthHelp lrest (1 + acc) + Cons(_, lrest) -> length_help(lrest, (1 + acc)) Nil -> acc diff --git a/crates/cli/tests/benchmarks/platform/PlatformTasks.roc b/crates/cli/tests/benchmarks/platform/PlatformTasks.roc index 81b7acf111b..5db7e79c88b 100644 --- a/crates/cli/tests/benchmarks/platform/PlatformTasks.roc +++ b/crates/cli/tests/benchmarks/platform/PlatformTasks.roc @@ -1,9 +1,9 @@ hosted PlatformTasks - exposes [putLine, putInt, getInt] + exposes [put_line, put_int, get_int] imports [] -putLine : Str -> Task {} * +put_line : Str -> Task {} * -putInt : I64 -> Task {} * +put_int : I64 -> Task {} * -getInt : Task { value : I64, isError : Bool } * +get_int : Task { value : I64, is_error : Bool } * diff --git a/crates/cli/tests/benchmarks/platform/app.roc b/crates/cli/tests/benchmarks/platform/app.roc index c92d6efd81d..98db3c31724 100644 --- a/crates/cli/tests/benchmarks/platform/app.roc +++ b/crates/cli/tests/benchmarks/platform/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "main.roc" } -main = Task.ok {} +main = Task.ok({}) diff --git a/crates/cli/tests/benchmarks/platform/host.zig b/crates/cli/tests/benchmarks/platform/host.zig index b37056f9039..63ed9f91e3f 100644 --- a/crates/cli/tests/benchmarks/platform/host.zig +++ b/crates/cli/tests/benchmarks/platform/host.zig @@ -10,11 +10,11 @@ const maxInt = std.math.maxInt; const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic([*]u8) void; -extern fn roc__mainForHost_1_exposed_size() i64; -extern fn roc__mainForHost_0_caller(*const u8, [*]u8, [*]u8) void; -extern fn roc__mainForHost_0_size() i64; -extern fn roc__mainForHost_0_result_size() i64; +extern fn roc__main_for_host_1_exposed_generic([*]u8) void; +extern fn roc__main_for_host_1_exposed_size() i64; +extern fn roc__main_for_host_0_caller(*const u8, [*]u8, [*]u8) void; +extern fn roc__main_for_host_0_size() i64; +extern fn roc__main_for_host_0_result_size() i64; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -113,7 +113,7 @@ const Unit = extern struct {}; pub export fn main() u8 { // The size might be zero; if so, make it at least 8 so that we don't have a nullptr - const size = @max(@as(usize, @intCast(roc__mainForHost_1_exposed_size())), 8); + const size = @max(@as(usize, @intCast(roc__main_for_host_1_exposed_size())), 8); const raw_output = roc_alloc(@as(usize, @intCast(size)), @alignOf(u64)) orelse { std.log.err("Memory allocation failed", .{}); return 1; @@ -124,7 +124,7 @@ pub export fn main() u8 { roc_dealloc(raw_output, @alignOf(u64)); } - roc__mainForHost_1_exposed_generic(output); + roc__main_for_host_1_exposed_generic(output); const closure_data_pointer = @as([*]u8, @ptrCast(output)); @@ -137,7 +137,7 @@ fn call_the_closure(closure_data_pointer: [*]u8) void { const allocator = std.heap.page_allocator; // The size might be zero; if so, make it at least 8 so that we don't have a nullptr - const size = @max(roc__mainForHost_0_result_size(), 8); + const size = @max(roc__main_for_host_0_result_size(), 8); const raw_output = allocator.alignedAlloc(u8, @alignOf(u64), @as(usize, @intCast(size))) catch unreachable; const output = @as([*]u8, @ptrCast(raw_output)); @@ -147,13 +147,13 @@ fn call_the_closure(closure_data_pointer: [*]u8) void { const flags: u8 = 0; - roc__mainForHost_0_caller(&flags, closure_data_pointer, output); + roc__main_for_host_0_caller(&flags, closure_data_pointer, output); // The closure returns result, nothing interesting to do with it return; } -pub export fn roc_fx_putInt(int: i64) i64 { +pub export fn roc_fx_put_int(int: i64) i64 { const stdout = std.io.getStdOut().writer(); stdout.print("{d}", .{int}) catch unreachable; @@ -163,7 +163,7 @@ pub export fn roc_fx_putInt(int: i64) i64 { return 0; } -export fn roc_fx_putLine(rocPath: *str.RocStr) callconv(.C) void { +export fn roc_fx_put_line(rocPath: *str.RocStr) callconv(.C) void { const stdout = std.io.getStdOut().writer(); for (rocPath.asSlice()) |char| { @@ -180,14 +180,14 @@ const GetInt = extern struct { comptime { if (@sizeOf(usize) == 8) { - @export(roc_fx_getInt_64bit, .{ .name = "roc_fx_getInt" }); + @export(roc_fx_get_int_64bit, .{ .name = "roc_fx_get_int" }); } else { - @export(roc_fx_getInt_32bit, .{ .name = "roc_fx_getInt" }); + @export(roc_fx_get_int_32bit, .{ .name = "roc_fx_get_int" }); } } -fn roc_fx_getInt_64bit() callconv(.C) GetInt { - if (roc_fx_getInt_help()) |value| { +fn roc_fx_get_int_64bit() callconv(.C) GetInt { + if (roc_fx_get_int_help()) |value| { const get_int = GetInt{ .is_error = false, .value = value }; return get_int; } else |err| switch (err) { @@ -202,8 +202,8 @@ fn roc_fx_getInt_64bit() callconv(.C) GetInt { return 0; } -fn roc_fx_getInt_32bit(output: *GetInt) callconv(.C) void { - if (roc_fx_getInt_help()) |value| { +fn roc_fx_get_int_32bit(output: *GetInt) callconv(.C) void { + if (roc_fx_get_int_help()) |value| { const get_int = GetInt{ .is_error = false, .value = value }; output.* = get_int; } else |err| switch (err) { @@ -218,7 +218,7 @@ fn roc_fx_getInt_32bit(output: *GetInt) callconv(.C) void { return; } -fn roc_fx_getInt_help() !i64 { +fn roc_fx_get_int_help() !i64 { const stdout = std.io.getStdOut().writer(); stdout.print("Please enter an integer\n", .{}) catch unreachable; diff --git a/crates/cli/tests/benchmarks/platform/main.roc b/crates/cli/tests/benchmarks/platform/main.roc index a4ac08d384c..069f4837dcb 100644 --- a/crates/cli/tests/benchmarks/platform/main.roc +++ b/crates/cli/tests/benchmarks/platform/main.roc @@ -3,7 +3,7 @@ platform "benchmarks" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Task {} [] -mainForHost = main +main_for_host : Task {} [] +main_for_host = main diff --git a/crates/cli/tests/benchmarks/quicksortApp.roc b/crates/cli/tests/benchmarks/quicksortApp.roc index b94b73ad108..a6e1280d3ce 100644 --- a/crates/cli/tests/benchmarks/quicksortApp.roc +++ b/crates/cli/tests/benchmarks/quicksortApp.roc @@ -5,16 +5,16 @@ import Quicksort main : Task.Task {} [] main = - { value, isError } = PlatformTasks.getInt! - inputResult = - if isError then - Err GetIntError + { value, is_error } = PlatformTasks.get_int! + input_result = + if is_error then + Err(GetIntError) else - Ok value + Ok(value) - when inputResult is - Ok n -> - unsortedList = + when input_result is + Ok(n) -> + unsorted_list = if n == 0 then # small unsorted list of 20 elements (0-9) [2, 4, 4, 0, 3, 8, 3, 6, 4, 9, 4, 6, 3, 5, 2, 2, 3, 1, 1, 3] @@ -22,13 +22,13 @@ main = # big unsorted list of 10000 elements (0-5000) [4281, 4149, 4579, 3763, 4892, 3305, 740, 1003, 3748, 4353, 1027, 2205, 4096, 4047, 1883, 3757, 3813, 2757, 2241, 1417, 2054, 1819, 680, 3645, 1979, 3897, 2180, 4072, 3688, 3440, 1107, 3511, 133, 4586, 3432, 3279, 2743, 1489, 4058, 2880, 141, 3039, 3270, 1518, 3879, 3241, 577, 981, 233, 2238, 1571, 1056, 721, 2856, 2309, 1274, 969, 1132, 1492, 2659, 106, 1145, 2328, 3854, 998, 2594, 1359, 1172, 3952, 4137, 3539, 3558, 3947, 1705, 1726, 1292, 1669, 2636, 661, 1079, 4190, 4398, 3954, 2016, 4704, 2748, 2273, 261, 321, 1278, 917, 713, 1241, 1827, 1402, 2956, 4481, 3126, 250, 3932, 727, 2689, 2566, 4584, 1718, 1634, 3977, 3045, 3360, 1072, 982, 2277, 4175, 707, 1192, 3124, 2408, 2734, 4173, 4491, 3060, 1095, 845, 4405, 4617, 2762, 1431, 2720, 4510, 1516, 1770, 1010, 499, 2346, 4191, 2684, 3979, 1794, 2796, 1973, 407, 2764, 1975, 3629, 3945, 4635, 2157, 497, 1720, 583, 520, 2036, 3638, 561, 2168, 2301, 4432, 4086, 1465, 1560, 90, 4092, 2882, 3496, 3609, 4961, 507, 106, 242, 1752, 2154, 4410, 4066, 2333, 1570, 621, 1622, 1915, 517, 4424, 2901, 4704, 394, 1066, 4001, 4645, 624, 3833, 165, 2312, 3795, 3707, 557, 4567, 1897, 4894, 4840, 2805, 655, 1514, 2376, 3504, 1029, 4207, 3054, 4802, 4253, 2339, 2278, 3180, 2426, 861, 1582, 1373, 131, 4390, 4168, 4749, 1948, 2489, 586, 614, 2833, 840, 4136, 2443, 4112, 1850, 2207, 4087, 162, 1030, 1983, 2464, 2840, 4644, 2613, 1305, 4340, 3742, 1422, 1703, 1184, 2389, 997, 413, 3787, 199, 1727, 780, 1055, 879, 3400, 4592, 2140, 4564, 3466, 4630, 2127, 197, 4719, 4045, 2818, 2817, 2207, 507, 3047, 3619, 2327, 4196, 1659, 1603, 2104, 1649, 3893, 1615, 2905, 2216, 224, 2140, 4018, 2590, 3647, 3456, 2173, 1573, 4315, 2389, 2787, 137, 4287, 792, 4260, 1363, 3609, 3610, 2550, 2788, 1020, 4347, 2513, 4633, 3633, 3875, 4670, 503, 1698, 4651, 4725, 3394, 1085, 1275, 407, 4394, 132, 2102, 1239, 2186, 588, 1212, 4641, 4371, 4448, 1910, 3735, 4489, 2793, 2422, 2177, 3639, 2284, 3887, 2759, 4667, 2735, 976, 2055, 2791, 2593, 1406, 2439, 1010, 1160, 14, 3388, 3788, 3982, 3907, 3423, 996, 2863, 2370, 2846, 2297, 18, 1961, 1495, 290, 2390, 4248, 3001, 2365, 513, 2494, 1963, 3833, 3284, 375, 4760, 2711, 1436, 195, 1891, 3935, 4384, 1943, 3347, 126, 1582, 3977, 1398, 2483, 528, 230, 1896, 1421, 1843, 4487, 2893, 4240, 3157, 4135, 2887, 113, 1307, 1960, 593, 2435, 4358, 102, 4780, 537, 1394, 1901, 4554, 2099, 2599, 4467, 4145, 192, 1759, 4141, 4102, 3631, 3425, 467, 3017, 1210, 1108, 1243, 3980, 2772, 1525, 2382, 2795, 4731, 2688, 2303, 1511, 3260, 4863, 4792, 3306, 432, 3068, 1586, 3358, 1327, 3136, 3715, 1515, 4144, 4902, 3557, 3891, 1116, 172, 4655, 2079, 1759, 366, 1223, 2066, 155, 1343, 1106, 1016, 3055, 810, 1430, 4618, 1031, 4488, 2571, 240, 4196, 1896, 2887, 4930, 3694, 2395, 1156, 2889, 4749, 4109, 112, 1578, 450, 1422, 1505, 2266, 3756, 3597, 2655, 3748, 3371, 1659, 1867, 139, 879, 469, 1601, 2566, 3471, 1905, 4403, 2714, 1657, 3867, 563, 1820, 4992, 3084, 4559, 2727, 493, 1045, 4884, 1304, 4596, 4843, 978, 3010, 2282, 3267, 1995, 3942, 4235, 2676, 528, 417, 1860, 4944, 2352, 2603, 496, 2395, 4391, 1183, 4271, 3431, 3219, 3728, 873, 4956, 4460, 3638, 1935, 511, 1820, 1753, 2536, 131, 2253, 736, 1438, 2762, 4677, 4836, 8, 4524, 4711, 1575, 334, 3860, 4697, 4237, 3095, 4017, 3574, 2925, 2398, 4938, 2612, 408, 2086, 1938, 1349, 3405, 2827, 4158, 2071, 858, 377, 1043, 776, 4126, 3981, 81, 4471, 916, 52, 427, 8, 4922, 310, 43, 4770, 800, 3928, 1616, 848, 2818, 1300, 4847, 2744, 2528, 3825, 3582, 4781, 2911, 4309, 1188, 2451, 447, 2057, 966, 1159, 2683, 2542, 4010, 367, 252, 1199, 3765, 3974, 1794, 3464, 55, 501, 3389, 745, 763, 3937, 1077, 624, 2896, 3609, 4555, 3830, 3731, 1240, 1844, 4091, 3081, 587, 424, 3000, 1682, 2332, 3235, 3995, 3520, 3567, 2748, 501, 4661, 594, 385, 3271, 3980, 401, 2904, 1184, 1240, 3933, 825, 4068, 1561, 4387, 2776, 2581, 3117, 2219, 3224, 980, 2160, 1941, 2588, 3254, 4410, 261, 414, 802, 1536, 4245, 2935, 1059, 4098, 2750, 4707, 224, 1867, 740, 593, 2448, 408, 2244, 3719, 4149, 1952, 1509, 893, 558, 2409, 409, 4287, 4817, 3790, 2356, 3100, 4204, 416, 2778, 3876, 894, 1115, 4071, 630, 386, 1346, 41, 4039, 2816, 3001, 500, 1557, 15, 775, 42, 3161, 1449, 2916, 2333, 4947, 3883, 4744, 2792, 2434, 1929, 3599, 831, 4511, 813, 927, 4273, 4285, 496, 4068, 2450, 3893, 4982, 173, 667, 3347, 370, 2424, 3855, 538, 2692, 3084, 456, 107, 4433, 4088, 1181, 1755, 4761, 4932, 3014, 221, 1925, 1649, 2944, 1646, 3994, 1389, 4617, 4609, 3952, 2870, 3535, 4859, 4733, 3696, 3549, 1038, 716, 3474, 2122, 4629, 3495, 992, 4594, 4766, 2389, 4901, 4041, 2453, 894, 2077, 874, 188, 2405, 543, 991, 3601, 3121, 329, 402, 2948, 4382, 3203, 3387, 2098, 3473, 3986, 516, 3243, 2341, 490, 4828, 861, 4527, 2197, 3777, 4860, 1031, 1546, 751, 4670, 826, 4832, 2813, 3820, 4927, 3628, 2082, 4043, 3990, 2929, 1545, 4235, 3792, 4680, 131, 4097, 2694, 652, 4785, 4419, 3044, 3127, 470, 3, 1198, 3754, 2969, 503, 3957, 582, 4109, 1982, 4487, 4330, 1452, 2202, 3601, 3797, 4331, 3630, 471, 1655, 1435, 3624, 394, 4306, 207, 1488, 126, 367, 4870, 3969, 3448, 4265, 3475, 1058, 2437, 267, 591, 4352, 4363, 1096, 3807, 2547, 4328, 2811, 4251, 3241, 3518, 1377, 4983, 1353, 1900, 676, 1969, 1213, 190, 1700, 4020, 2219, 4822, 4659, 1324, 4961, 4675, 2317, 467, 835, 179, 1129, 1093, 852, 1360, 3585, 1999, 742, 3284, 3485, 3383, 4864, 4474, 3600, 653, 1333, 767, 4075, 2345, 4888, 1263, 4482, 2638, 4430, 1173, 4543, 2068, 1466, 4302, 3583, 345, 2633, 2515, 2630, 3717, 693, 1906, 2944, 510, 4609, 4064, 3643, 4010, 657, 3435, 2258, 630, 3037, 3199, 3904, 1139, 1446, 1776, 492, 2942, 188, 2935, 1247, 2000, 4413, 1036, 3485, 4691, 606, 1678, 541, 4380, 2673, 3241, 4403, 1896, 1202, 3323, 2433, 2982, 647, 1564, 3543, 1916, 483, 4040, 2974, 4234, 4025, 3208, 2109, 1055, 2989, 4210, 1944, 3504, 465, 1687, 1569, 2783, 97, 65, 4948, 3311, 1885, 2228, 3961, 4695, 4268, 4063, 166, 3998, 2070, 3547, 2148, 2995, 2451, 2833, 4243, 438, 951, 23, 2913, 1301, 2593, 4557, 2278, 4460, 1142, 3740, 2562, 3369, 2601, 3222, 2230, 2475, 4720, 4568, 572, 2737, 4157, 685, 1934, 3377, 4864, 1586, 3916, 2828, 1462, 2539, 4147, 3028, 4734, 3198, 4312, 234, 3578, 1409, 3776, 291, 1168, 1437, 1454, 3965, 4735, 2310, 3865, 4361, 4374, 3684, 1920, 3844, 3982, 1316, 3922, 2116, 641, 4220, 684, 4937, 313, 2456, 65, 4674, 4960, 2432, 4547, 4090, 624, 210, 3766, 3452, 2226, 1189, 605, 4665, 1528, 1553, 1532, 1669, 4051, 2136, 2392, 4053, 2251, 1601, 992, 3924, 2205, 444, 3260, 417, 922, 2362, 3285, 3414, 2350, 4612, 806, 2803, 1990, 2229, 4273, 3311, 379, 2451, 3479, 1900, 4704, 744, 3895, 1795, 817, 3163, 1770, 1677, 4136, 3643, 2368, 2223, 923, 1526, 3917, 2906, 4849, 4457, 4614, 482, 1340, 4931, 1243, 595, 1297, 720, 3060, 2013, 3678, 1163, 2373, 2067, 4725, 2306, 1205, 4180, 4280, 4069, 600, 648, 3515, 762, 778, 1094, 2792, 2495, 1410, 1023, 1627, 3494, 3172, 2991, 2502, 2014, 4077, 3158, 706, 3970, 1436, 4509, 3981, 1207, 1725, 1552, 738, 3873, 4389, 4788, 448, 784, 729, 355, 3491, 308, 328, 4536, 3921, 871, 330, 3655, 4562, 2544, 1274, 3874, 3156, 3979, 1462, 3874, 4016, 4828, 1497, 2818, 4819, 4440, 4833, 2974, 4997, 232, 4843, 4631, 3602, 3109, 1249, 1565, 4556, 3899, 4216, 791, 2908, 2877, 3838, 3102, 3187, 1579, 472, 1916, 3707, 4749, 2701, 2184, 3172, 3743, 4503, 4928, 79, 4743, 1840, 4946, 2584, 1103, 4328, 1819, 4892, 1850, 749, 1717, 3878, 3507, 957, 1469, 57, 3449, 3451, 2988, 4790, 440, 2495, 770, 3417, 4243, 4273, 4189, 757, 2809, 2711, 444, 23, 3318, 3323, 2848, 316, 2036, 44, 2443, 1718, 2042, 1755, 1361, 1049, 2577, 2771, 4908, 3446, 2370, 2802, 3208, 1352, 1932, 2292, 439, 546, 2160, 4736, 4236, 625, 302, 2662, 1115, 3377, 1892, 4705, 1164, 1657, 4675, 2581, 3397, 2128, 744, 4944, 3110, 1673, 672, 4960, 3888, 1621, 3368, 4293, 3066, 3140, 1191, 1965, 2444, 4717, 218, 1385, 1668, 1207, 2764, 588, 2350, 964, 3098, 4045, 764, 3454, 4673, 1115, 3129, 3415, 4340, 1040, 2705, 924, 2776, 1, 3048, 2226, 2977, 3184, 222, 258, 4304, 453, 2176, 4623, 4166, 1949, 3002, 3917, 2304, 4147, 473, 4184, 441, 4788, 4072, 4982, 1434, 1227, 3484, 2237, 2781, 4271, 4578, 1609, 3531, 482, 2884, 1737, 1193, 4598, 2875, 2117, 1684, 2827, 4542, 3435, 908, 4076, 145, 4829, 1008, 445, 3505, 3711, 3246, 3289, 1011, 3018, 2962, 3631, 3019, 120, 4109, 2033, 2615, 4078, 3339, 1183, 3553, 969, 2093, 1306, 1102, 4674, 4567, 3871, 208, 4076, 2969, 2475, 2923, 960, 1618, 1666, 4600, 4468, 290, 4774, 4164, 2037, 2039, 187, 248, 4995, 1048, 1934, 4592, 2120, 3030, 4183, 4832, 1816, 1653, 839, 1832, 16, 2201, 2838, 323, 3270, 2133, 1722, 3816, 3469, 2197, 4336, 3734, 2088, 4666, 2299, 4975, 2704, 3493, 3574, 1152, 853, 1294, 95, 3057, 3010, 1821, 2855, 909, 4879, 620, 4944, 3780, 2516, 4279, 4588, 1714, 2439, 3161, 320, 1382, 1444, 4825, 4228, 3487, 2604, 2232, 1539, 201, 3867, 2869, 411, 46, 3228, 247, 3911, 3511, 351, 2769, 1322, 4826, 2203, 890, 3788, 2824, 3837, 1896, 1967, 3239, 2078, 2617, 3591, 4943, 2532, 2276, 3184, 3456, 312, 2519, 1270, 3996, 2548, 908, 333, 1845, 1167, 369, 1957, 4307, 1501, 1971, 3247, 4857, 3054, 807, 3738, 3072, 4964, 4901, 3514, 2858, 3055, 4569, 3854, 1774, 1876, 770, 2121, 2326, 1937, 2661, 163, 201, 2200, 4013, 3648, 1735, 2438, 3907, 3636, 4299, 3736, 21, 4253, 2514, 186, 466, 2205, 4728, 1035, 1754, 2873, 3581, 3441, 3539, 2999, 4225, 1547, 1689, 2009, 1691, 3751, 3759, 3438, 4774, 867, 1777, 2616, 7, 756, 3411, 1973, 2544, 1132, 2400, 1380, 2520, 2538, 423, 702, 3146, 2029, 3476, 4848, 1003, 3617, 1455, 666, 134, 1296, 813, 1842, 723, 2874, 160, 4041, 1240, 1907, 1634, 725, 1881, 3700, 1238, 1639, 3915, 4499, 2692, 940, 3218, 1931, 3801, 1719, 764, 4816, 1876, 4402, 3599, 890, 198, 940, 1534, 599, 3052, 1232, 910, 3055, 2397, 2772, 1996, 250, 3285, 3573, 2523, 3802, 828, 4554, 4330, 1176, 1222, 4915, 1798, 1580, 4738, 4551, 3322, 1683, 4755, 2995, 4512, 1820, 3685, 224, 4170, 1802, 2824, 2628, 4285, 4236, 4198, 3336, 2651, 10, 2809, 4060, 3718, 831, 2947, 3734, 928, 3624, 849, 2567, 2310, 4474, 4721, 2904, 1491, 4365, 4447, 2052, 4744, 3973, 2650, 3480, 876, 2463, 1084, 3942, 691, 1073, 4757, 229, 1497, 2229, 1669, 674, 256, 2206, 3311, 2800, 592, 2838, 1042, 2123, 602, 434, 552, 2776, 4179, 2976, 4592, 686, 2805, 4840, 484, 4134, 789, 2790, 73, 3113, 4158, 1956, 1377, 1199, 4901, 4755, 1026, 2821, 2649, 3301, 2651, 1398, 330, 1482, 4844, 687, 1116, 4131, 659, 3150, 4282, 475, 2162, 2084, 4439, 3145, 145, 4693, 2926, 3200, 4720, 4341, 4980, 4850, 3961, 3565, 4604, 466, 4441, 832, 2084, 4875, 739, 2790, 523, 3983, 4160, 630, 4038, 1891, 2324, 667, 420, 1361, 2710, 1205, 412, 2410, 2888, 4873, 2372, 612, 1923, 2857, 2725, 4823, 1042, 1721, 2140, 4529, 2801, 3637, 1995, 1503, 4956, 1766, 3910, 1474, 644, 1410, 4705, 3892, 617, 532, 3475, 3111, 646, 4344, 4830, 571, 3380, 862, 4291, 4558, 2115, 861, 1151, 3521, 4244, 2037, 2272, 39, 1371, 1355, 4179, 3072, 442, 4189, 3669, 93, 3968, 3759, 1213, 4340, 1154, 2941, 1192, 3821, 1289, 2307, 559, 424, 3911, 3161, 1996, 4525, 3811, 2902, 3669, 1219, 770, 2820, 1780, 1950, 4995, 345, 3772, 307, 1887, 1452, 3359, 835, 4830, 3846, 2849, 2132, 4070, 1971, 1797, 2890, 3468, 1600, 3872, 937, 4282, 1998, 3550, 908, 4867, 2377, 3462, 2349, 4434, 3216, 1461, 2681, 1775, 4752, 1439, 3203, 4235, 4147, 4750, 4041, 2051, 10, 2780, 2054, 3566, 4111, 2698, 3520, 3816, 2589, 4700, 2338, 1973, 2444, 1465, 1741, 712, 3457, 4272, 4895, 1409, 4963, 2163, 3369, 4570, 1976, 4879, 1459, 2809, 477, 4946, 3800, 3455, 4720, 434, 2919, 4824, 3688, 3555, 2618, 3615, 385, 4330, 4140, 1552, 737, 4288, 4000, 4086, 186, 1673, 2449, 3272, 3262, 1682, 14, 3119, 1206, 2461, 1625, 4644, 2637, 224, 2300, 1708, 2596, 3650, 1312, 775, 4863, 1556, 3868, 1180, 1061, 836, 4295, 2343, 2063, 2186, 3632, 674, 169, 2082, 3316, 2149, 2812, 1032, 2852, 114, 2735, 4646, 58, 744, 3299, 3623, 3607, 3923, 2972, 3414, 3583, 765, 3515, 2965, 295, 4348, 4470, 647, 4716, 2449, 3788, 643, 4188, 3504, 2477, 3341, 1219, 3362, 3267, 3859, 4867, 356, 576, 914, 4799, 2016, 464, 326, 1346, 170, 3880, 4708, 3797, 3992, 2334, 1675, 2084, 481, 421, 1967, 3402, 2183, 766, 2457, 1001, 2993, 3087, 2149, 1252, 3249, 108, 1506, 4488, 2467, 4145, 4475, 3194, 3128, 829, 2059, 3855, 3016, 4874, 1767, 4926, 4170, 119, 3115, 3378, 1256, 1436, 1124, 2819, 592, 522, 3965, 1341, 543, 4912, 2172, 2042, 4834, 4408, 4710, 1863, 4139, 1023, 3996, 2430, 3018, 1574, 2133, 2783, 3716, 1290, 4735, 2425, 4100, 4572, 596, 3189, 2472, 2581, 1409, 2491, 394, 1688, 4597, 2323, 3615, 218, 391, 3287, 2251, 2159, 448, 1178, 925, 228, 3149, 129, 4113, 4031, 2203, 3489, 2631, 268, 2556, 1934, 4581, 712, 4455, 2137, 2474, 3369, 2065, 4924, 3954, 3654, 4730, 3018, 2201, 3975, 1824, 1174, 3195, 1826, 3162, 3273, 1324, 2747, 3767, 619, 714, 3690, 4744, 4198, 597, 604, 1481, 2615, 658, 701, 3166, 4601, 2613, 2864, 3198, 2340, 593, 697, 2345, 4135, 503, 4291, 1559, 3834, 2900, 601, 3722, 613, 313, 896, 1389, 210, 896, 1019, 1174, 1272, 4386, 1672, 2158, 58, 3045, 1933, 2193, 3534, 1660, 2259, 3120, 4678, 1699, 857, 2200, 4399, 2460, 4972, 2731, 166, 3209, 1124, 3143, 249, 2763, 3986, 4186, 1018, 875, 2707, 294, 4042, 1571, 2964, 1407, 780, 4172, 1436, 4576, 543, 2045, 4535, 774, 1744, 4726, 2401, 2392, 1832, 4104, 2271, 4690, 477, 1582, 433, 4457, 2891, 3310, 1586, 4998, 228, 4771, 2426, 3411, 3969, 1677, 610, 4306, 1486, 2107, 341, 2435, 2791, 2670, 4437, 543, 3487, 3252, 3308, 653, 2615, 1414, 247, 2325, 4668, 166, 4087, 4913, 395, 1459, 3842, 4085, 4738, 4150, 4796, 3732, 409, 109, 2460, 3631, 3196, 4989, 4543, 115, 2910, 1277, 3398, 2277, 2748, 3873, 4529, 4035, 2397, 1047, 290, 4040, 2444, 4099, 4129, 344, 3112, 2617, 2039, 1399, 2786, 3335, 258, 1057, 2648, 2521, 4177, 2132, 4976, 2691, 4035, 3683, 1648, 4866, 336, 4792, 2064, 681, 4395, 3937, 1383, 179, 3190, 4743, 3518, 190, 3276, 3536, 4118, 998, 2950, 315, 3981, 1849, 655, 4864, 2239, 667, 1854, 505, 672, 2905, 3005, 2902, 848, 2674, 1363, 2172, 1997, 164, 183, 943, 619, 496, 86, 4457, 1680, 15, 13, 2785, 4164, 2774, 2497, 1415, 1930, 1784, 4144, 2684, 1093, 1712, 959, 3937, 4338, 1185, 4047, 3026, 788, 3554, 856, 2842, 4365, 1365, 3869, 601, 4791, 872, 4103, 2249, 3718, 4285, 2845, 108, 673, 833, 4721, 863, 793, 3078, 4059, 2608, 1448, 4657, 4414, 1090, 1232, 4575, 4572, 4087, 2080, 4579, 301, 4170, 3781, 186, 3661, 3120, 3710, 1090, 4137, 2690, 1002, 1378, 3566, 4420, 1529, 4317, 147, 2660, 4156, 3361, 2691, 4853, 2907, 1066, 1353, 3779, 1257, 3063, 3499, 1749, 719, 3958, 3278, 1047, 646, 2964, 405, 483, 2180, 4509, 2785, 1833, 4437, 3314, 4822, 1122, 1222, 2021, 1598, 4674, 1441, 288, 1657, 2195, 3179, 4479, 3943, 144, 2018, 2633, 4544, 2660, 3875, 3266, 4555, 2934, 3211, 3275, 3769, 1122, 1680, 2140, 2433, 979, 92, 1207, 4971, 583, 964, 3770, 1427, 4636, 1320, 3383, 639, 3218, 438, 1905, 4190, 3919, 1235, 381, 4334, 4223, 4435, 901, 1383, 333, 3596, 2853, 2455, 812, 4043, 2766, 717, 213, 416, 4165, 1130, 1416, 2119, 929, 519, 8, 4904, 4318, 732, 3043, 1728, 3011, 786, 4442, 1085, 2812, 873, 2545, 0, 4085, 4022, 3708, 633, 414, 2440, 1506, 1065, 4450, 4968, 3964, 2380, 3439, 469, 1505, 1001, 1138, 2042, 4548, 826, 298, 2688, 1860, 4108, 3749, 2870, 4513, 1655, 4236, 3919, 4107, 2159, 2809, 4569, 753, 2943, 4429, 4401, 4903, 1727, 28, 4438, 3322, 3042, 4108, 2398, 1697, 2448, 1057, 3503, 1125, 3337, 477, 2051, 986, 4733, 4114, 3420, 48, 1215, 2541, 4511, 1560, 4966, 1588, 2444, 1061, 4625, 4125, 4792, 1184, 4061, 1296, 4415, 3554, 2496, 1860, 267, 916, 3203, 1612, 2416, 4188, 665, 3186, 305, 1590, 4456, 3020, 3224, 3352, 1270, 1526, 3658, 3837, 3119, 2982, 2003, 3052, 1934, 3280, 4316, 1643, 3127, 4071, 493, 3411, 3367, 718, 712, 527, 1844, 4150, 4344, 3559, 4891, 3679, 3341, 1934, 4526, 4279, 2921, 1827, 3431, 2588, 4870, 3826, 2388, 1028, 361, 2999, 2922, 2094, 4244, 139, 4082, 2190, 2652, 1028, 4033, 4299, 280, 178, 4238, 3511, 1381, 1374, 3551, 3766, 4112, 4130, 3104, 2021, 542, 599, 1814, 4610, 2997, 331, 3988, 4890, 2068, 4253, 3929, 2127, 1849, 2185, 4164, 2904, 3439, 4543, 4256, 4934, 4869, 4192, 1043, 799, 4027, 4173, 3357, 4348, 2056, 4101, 2143, 3038, 2384, 1281, 4937, 200, 2489, 1413, 4841, 3930, 3444, 4835, 833, 1938, 4381, 766, 4436, 3167, 2287, 3828, 4270, 2539, 2365, 2508, 3965, 4631, 3099, 2806, 4160, 1234, 1811, 427, 820, 1093, 2433, 4020, 2786, 535, 566, 556, 4616, 4227, 893, 277, 3345, 2043, 3202, 1756, 2757, 2485, 2876, 719, 365, 789, 1865, 1740, 58, 684, 2535, 3405, 3233, 787, 4600, 2421, 1935, 3757, 1462, 4891, 3377, 3338, 4793, 931, 1931, 1105, 1413, 3060, 1602, 531, 1095, 375, 372, 1809, 1276, 2307, 3231, 1493, 344, 3842, 2380, 2042, 3500, 4944, 1290, 1009, 3114, 2857, 937, 4159, 3801, 4189, 4252, 978, 428, 2146, 1386, 182, 558, 2147, 4472, 3930, 3932, 4225, 2803, 4052, 2102, 3013, 267, 901, 1181, 4125, 2851, 4699, 28, 3887, 553, 3347, 2091, 2564, 1176, 3894, 1551, 3435, 1722, 4968, 4875, 3005, 4179, 2207, 2281, 3621, 1336, 2068, 84, 3681, 3086, 4740, 3802, 2458, 4982, 1095, 4132, 4280, 3031, 4305, 1142, 512, 4683, 1554, 3895, 1477, 498, 1242, 4849, 3286, 1396, 3081, 1204, 975, 2235, 2340, 2545, 746, 75, 763, 2986, 1127, 403, 560, 83, 2602, 3947, 485, 4218, 3570, 311, 420, 3835, 2016, 2726, 2372, 1879, 1714, 1202, 3171, 2427, 1227, 3891, 2887, 3736, 2324, 1641, 4637, 4550, 1356, 817, 1207, 789, 4859, 4249, 1438, 4504, 3388, 2365, 3958, 3082, 283, 94, 4211, 2433, 2134, 2256, 1406, 1137, 150, 2519, 2215, 1393, 3664, 4962, 4491, 4873, 282, 4187, 2245, 1296, 3150, 1359, 4711, 4, 4986, 4376, 1933, 549, 3639, 3690, 2302, 4220, 2204, 21, 4578, 1827, 2654, 833, 465, 1340, 303, 4747, 3926, 4667, 69, 4510, 2911, 4950, 3194, 4501, 3167, 923, 2779, 4962, 316, 2158, 1576, 528, 2863, 835, 453, 4153, 3682, 4604, 279, 3484, 797, 1075, 4679, 461, 3688, 3821, 1589, 3247, 589, 1433, 1053, 4798, 2262, 1252, 745, 3621, 814, 997, 1658, 585, 2823, 2677, 3168, 1806, 3065, 3228, 1779, 4536, 4985, 659, 1323, 2465, 4608, 963, 845, 4132, 4142, 2232, 3475, 650, 4563, 1772, 2816, 4082, 4732, 60, 4223, 4211, 4238, 2573, 2569, 737, 178, 3722, 2675, 2632, 4457, 1870, 2275, 1915, 865, 4310, 3789, 1225, 4035, 1217, 4180, 3858, 2130, 1957, 2226, 452, 1307, 917, 713, 4780, 1161, 4473, 393, 829, 1855, 4188, 3483, 4258, 1210, 4033, 3714, 3888, 3897, 4081, 2573, 4360, 960, 4116, 2805, 2854, 4939, 426, 4636, 2845, 4617, 4297, 4341, 1481, 1134, 2437, 2880, 1104, 694, 3780, 4247, 4179, 4870, 2589, 4813, 4651, 1298, 3268, 1018, 657, 2514, 3414, 845, 603, 2546, 1548, 1817, 3770, 844, 2303, 4894, 1581, 4758, 290, 3948, 3456, 2670, 3584, 4368, 706, 1762, 561, 1730, 4119, 4831, 1684, 4001, 1232, 794, 3548, 2316, 765, 1309, 1671, 2616, 1978, 1261, 2111, 570, 23, 210, 2020, 2259, 1078, 1930, 160, 1885, 3150, 511, 144, 4710, 3274, 4083, 4744, 2621, 615, 2967, 1974, 4789, 1044, 672, 283, 3747, 2104, 163, 2959, 1853, 1649, 4748, 1999, 3346, 1339, 2609, 4163, 4669, 4514, 4991, 4621, 1751, 2345, 2265, 3182, 628, 2759, 3863, 2615, 1767, 2935, 1311, 800, 3241, 3998, 3740, 1481, 66, 2898, 4816, 1176, 1462, 2096, 1065, 302, 59, 63, 4819, 2476, 2387, 2607, 3751, 3089, 2947, 4332, 2265, 3890, 2041, 67, 90, 3051, 3009, 4818, 3734, 3008, 1228, 2036, 2741, 3020, 481, 2609, 1641, 4509, 3847, 3822, 1501, 2265, 3800, 2127, 3822, 270, 3206, 927, 90, 3112, 3427, 2096, 1855, 3829, 4611, 1058, 870, 3113, 1028, 798, 4890, 2958, 4104, 2574, 4894, 2454, 4271, 4728, 1253, 1230, 359, 1095, 1297, 2153, 1004, 383, 2781, 2733, 2319, 3984, 3581, 337, 1103, 1911, 1253, 4525, 527, 3394, 1785, 2506, 1539, 1449, 3729, 2402, 1064, 3705, 4892, 4521, 2836, 3505, 3806, 4918, 459, 1495, 3599, 2139, 3809, 1373, 3871, 1919, 3702, 3097, 1211, 1887, 3487, 1286, 3467, 3142, 2636, 1319, 4275, 3138, 756, 4254, 1752, 1608, 4401, 829, 57, 4105, 4566, 135, 4106, 846, 4560, 4673, 4659, 52, 3188, 4244, 4053, 815, 2640, 112, 2280, 3000, 1838, 3639, 2581, 4828, 218, 374, 4038, 1241, 3499, 2158, 3540, 1951, 4771, 131, 3189, 1341, 4741, 4690, 3817, 1552, 2086, 2351, 1451, 1861, 1639, 836, 881, 1385, 14, 1481, 3476, 4453, 3713, 4419, 1995, 4432, 3933, 2167, 734, 1848, 1040, 225, 1488, 1707, 2, 1347, 1341, 2519, 87, 88, 3706, 1880, 2256, 33, 2289, 2942, 3924, 1321, 21, 3769, 3912, 3953, 3425, 4693, 163, 2861, 4181, 1918, 3838, 4871, 2532, 2235, 226, 2219, 4503, 4273, 3782, 4358, 1951, 4361, 2410, 4951, 4377, 2912, 2063, 260, 4937, 1140, 603, 1292, 1330, 3068, 4365, 363, 424, 2708, 291, 3102, 3857, 4466, 3747, 4476, 1544, 293, 1013, 387, 1142, 3991, 2793, 4335, 2122, 289, 3397, 1722, 961, 2172, 4921, 2191, 2301, 3566, 4118, 1498, 1035, 2410, 3879, 2613, 675, 348, 4728, 1150, 1723, 4122, 236, 3486, 3306, 3026, 1049, 2766, 582, 1034, 1514, 840, 2317, 4649, 3800, 4575, 2363, 2059, 2226, 2550, 109, 3517, 2474, 3835, 4790, 4665, 3450, 3113, 2911, 1274, 2086, 4997, 4145, 3349, 1284, 3109, 4474, 2385, 3716, 3594, 3228, 786, 1578, 4239, 2035, 2381, 2447, 4433, 4161, 749, 455, 1320, 343, 1227, 3263, 3308, 1739, 910, 2148, 3094, 4190, 3752, 2966, 3170, 100, 2063, 4427, 3092, 3553, 2156, 4876, 2690, 4148, 4794, 2999, 921, 4758, 3498, 119, 4431, 1373, 2311, 3320, 3801, 2102, 888, 1800, 4792, 4403, 794, 664, 1703, 4190, 1673, 4827, 3331, 4359, 3843, 2091, 4935, 1691, 4164, 3736, 1067, 1412, 2192, 2441, 993, 2410, 3892, 4322, 1768, 2554, 1517, 198, 585, 18, 2312, 3513, 4572, 253, 3077, 4655, 2776, 1869, 719, 4484, 318, 2119, 3315, 1825, 4639, 1419, 3410, 4547, 3713, 2801, 4241, 1079, 2440, 4985, 4035, 285, 1024, 488, 3046, 2216, 1782, 4521, 204, 71, 4435, 4202, 214, 3166, 1885, 3467, 2997, 433, 3705, 230, 2486, 2652, 3802, 2552, 801, 4835, 4055, 1252, 3653, 3586, 1079, 2474, 1473, 3170, 2868, 872, 3832, 4600, 1873, 2454, 1024, 2988, 4640, 3016, 2003, 3122, 434, 3207, 4173, 3078, 4822, 1787, 3109, 4302, 4286, 1542, 4455, 3286, 2360, 3340, 1605, 3196, 2927, 63, 165, 1659, 252, 828, 3844, 3134, 2907, 3043, 4389, 3915, 2876, 1581, 1384, 2097, 3746, 4788, 4533, 1998, 3945, 1152, 449, 4479, 2896, 2604, 330, 3460, 4743, 2939, 3668, 4762, 4924, 3843, 3198, 138, 2740, 4389, 4432, 1226, 4685, 1914, 2818, 3514, 2613, 1389, 4971, 523, 190, 3365, 1581, 2881, 1496, 4997, 530, 243, 4823, 2188, 2995, 3679, 615, 1558, 3394, 3649, 102, 2823, 849, 4905, 4605, 3137, 2944, 3796, 4154, 1945, 1734, 2830, 2496, 2410, 741, 150, 3602, 1605, 3330, 4904, 3214, 4181, 2082, 3408, 3305, 4255, 2608, 2121, 1180, 3495, 42, 2012, 3516, 1143, 4904, 3505, 4714, 3037, 255, 3984, 1279, 2083, 3934, 4372, 2172, 4196, 1207, 339, 2467, 2205, 4089, 3789, 3887, 3402, 3881, 2546, 2132, 4635, 3569, 3082, 1323, 4763, 824, 628, 4253, 1791, 3744, 3302, 3074, 3350, 1994, 3086, 260, 1098, 2633, 799, 4808, 4419, 334, 3884, 2767, 3681, 4939, 465, 1791, 4214, 148, 1674, 3905, 4072, 4337, 717, 726, 3989, 2816, 625, 4911, 1463, 2830, 4210, 4909, 2550, 2155, 1581, 993, 3728, 4693, 370, 4989, 223, 4136, 1160, 4339, 2693, 3075, 1071, 4358, 2647, 3148, 4649, 4513, 1265, 3939, 3646, 4659, 2926, 1088, 4221, 2628, 744, 4574, 4347, 4239, 2228, 2234, 2897, 1140, 3273, 2629, 616, 1422, 1445, 2548, 104, 2711, 2339, 3861, 826, 2622, 3041, 1195, 1602, 4566, 4780, 1304, 2718, 3972, 32, 4140, 3108, 341, 4285, 1365, 2246, 821, 3118, 3870, 1290, 1407, 3457, 1086, 2415, 2634, 4370, 3196, 181, 4192, 6, 1960, 4244, 1957, 595, 1684, 3267, 4396, 1526, 1579, 2437, 1509, 400, 2432, 1074, 2092, 2441, 229, 1606, 1822, 2384, 1510, 4921, 3583, 3862, 4081, 1113, 2367, 105, 4072, 1064, 2072, 2797, 3705, 3351, 1444, 4913, 4757, 4559, 757, 4167, 198, 3736, 4580, 4124, 1111, 4575, 4135, 1857, 3280, 1078, 4269, 423, 3107, 3773, 905, 3074, 2804, 2551, 2572, 3859, 2437, 1328, 1338, 3276, 2349, 4462, 1007, 1819, 3847, 4720, 3077, 2085, 38, 68, 4117, 1411, 2495, 98, 3819, 2619, 1544, 2908, 2811, 1240, 2075, 4228, 518, 806, 3722, 4286, 3039, 3989, 4695, 3899, 4683, 4528, 594, 4761, 752, 800, 4070, 63, 3577, 4086, 1886, 1367, 3256, 99, 1024, 762, 4021, 581, 1744, 2024, 4842, 3200, 3255, 2777, 829, 2524, 2587, 2354, 1506, 224, 1677, 88, 3306, 4582, 470, 2997, 2632, 3862, 2743, 2692, 4571, 2414, 1815, 654, 4387, 2367, 4666, 1640, 3251, 2550, 442, 1440, 1138, 3562, 2363, 3573, 131, 2508, 2276, 991, 1340, 686, 3266, 1538, 491, 2199, 2729, 2843, 249, 4163, 3714, 377, 4539, 4381, 1678, 1871, 1856, 1086, 2347, 1811, 4552, 2802, 3865, 4272, 4960, 2091, 2482, 3890, 1233, 2742, 134, 3301, 2754, 4374, 4176, 2805, 218, 495, 3130, 2889, 1972, 2668, 2436, 839, 2317, 941, 1230, 1309, 4118, 1921, 1556, 3664, 1844, 596, 1791, 3706, 1949, 1658, 4501, 2779, 4255, 2787, 3714, 3309, 3478, 860, 1894, 2324, 660, 3633, 2079, 659, 186, 909, 1000, 317, 392, 3779, 2710, 1609, 4514, 1410, 3321, 1232, 218, 1649, 1314, 324, 2661, 396, 736, 4007, 2544, 3026, 3382, 3923, 4223, 4553, 3045, 945, 1459, 4189, 1608, 1122, 574, 920, 2039, 4058, 2464, 4074, 4093, 310, 1682, 2503, 2960, 566, 4729, 1480, 3270, 357, 58, 3374, 3036, 3333, 821, 3462, 3443, 1415, 3967, 3793, 745, 3359, 894, 4308, 2100, 4701, 2670, 3667, 2736, 2835, 1660, 2755, 368, 2968, 1872, 4315, 2504, 1681, 3688, 878, 415, 3089, 1860, 2191, 4922, 818, 525, 1943, 4214, 1308, 1401, 4893, 2459, 1176, 2365, 2987, 980, 4515, 2718, 4421, 1216, 2459, 1992, 4982, 3582, 1969, 1372, 4283, 4824, 4142, 820, 2895, 2601, 3261, 4060, 2493, 3268, 1184, 1618, 766, 3678, 135, 3016, 3763, 438, 2127, 2270, 1254, 4129, 84, 3175, 298, 2473, 2766, 1040, 244, 242, 2339, 1984, 3900, 4950, 261, 4625, 2174, 4011, 418, 4636, 391, 4405, 2464, 3734, 1385, 2628, 3979, 1463, 19, 1316, 4524, 453, 3443, 93, 1798, 1555, 2133, 2591, 1094, 3512, 331, 1497, 3906, 4080, 3643, 2296, 4069, 3662, 3288, 2495, 1404, 2890, 4265, 1739, 740, 3281, 1477, 2981, 4261, 3177, 447, 2231, 2435, 2379, 42, 1903, 3718, 513, 1444, 779, 708, 3737, 2397, 1841, 4847, 2250, 4312, 4115, 4319, 4457, 1244, 2044, 4594, 1958, 258, 2414, 1308, 31, 4846, 4539, 324, 1167, 4073, 1362, 3209, 4703, 1255, 575, 354, 1951, 3452, 831, 3948, 3464, 4311, 4653, 1987, 4624, 953, 993, 949, 4178, 1296, 3863, 2705, 2066, 2702, 313, 4355, 351, 1407, 2772, 1991, 2640, 968, 3672, 4233, 187, 2687, 73, 406, 513, 1384, 309, 4239, 4542, 2524, 3196, 1950, 4627, 3253, 641, 2394, 842, 2808, 4831, 4647, 381, 3671, 667, 424, 571, 619, 4815, 3068, 2690, 3984, 2479, 1268, 2128, 3331, 3825, 4595, 807, 376, 1757, 1131, 883, 3861, 4361, 4950, 4270, 1602, 3162, 1793, 2187, 2150, 1776, 4769, 2580, 3677, 2980, 1320, 3573, 4496, 4839, 4202, 2313, 2041, 1227, 3071, 4110, 532, 3861, 388, 3687, 2102, 2869, 3600, 1447, 1272, 4372, 3851, 1850, 4928, 3808, 4074, 3003, 1224, 541, 3323, 3370, 4420, 1760, 161, 3133, 4654, 3154, 1179, 2089, 74, 1399, 3331, 3450, 3683, 3254, 1017, 1386, 4010, 81, 4215, 4881, 3132, 4283, 2980, 109, 3784, 2042, 2240, 2868, 124, 3021, 8, 4578, 863, 265, 3412, 3501, 928, 836, 175, 3229, 1366, 1720, 4179, 3854, 2632, 2663, 2900, 3858, 2694, 4116, 2485, 1481, 1779, 2539, 943, 807, 1496, 3670, 4705, 1700, 592, 1933, 180, 4716, 3236, 1332, 1359, 858, 2155, 4587, 4327, 3897, 4718, 3906, 4900, 3178, 2603, 2137, 1478, 4453, 4142, 3359, 2497, 4972, 1854, 1929, 1969, 1325, 3503, 176, 3398, 1740, 2567, 147, 391, 3762, 2557, 4957, 4638, 251, 2897, 3165, 507, 2062, 2904, 4156, 3717, 3223, 3143, 4701, 1789, 3205, 2688, 973, 3495, 2638, 3003, 4371, 4457, 4481, 4546, 505, 1432, 1171, 4641, 1859, 2234, 3384, 1719, 2932, 3087, 4153, 1596, 224, 1568, 4192, 3708, 4949, 2739, 149, 106, 3739, 3182, 3682, 51, 2409, 3891, 1890, 1948, 3705, 784, 354, 456, 1989, 2885, 4830, 2674, 4783, 2717, 335, 3495, 3425, 4217, 444, 790, 1912, 4043, 645, 2713, 4688, 4774, 887, 126, 4560, 4218, 1059, 1674, 4238, 2718, 162, 1814, 892, 4297, 4253, 4500, 996, 1227, 4801, 2862, 1723, 3398, 3443, 54, 1655, 2016, 3079, 3412, 2399, 479, 4144, 36, 3119, 2269, 3960, 1801, 2726, 766, 3105, 3795, 540, 423, 2656, 3552, 1708, 722, 4275, 347, 1232, 1901, 4341, 1360, 1045, 4670, 1906, 4109, 3952, 4078, 865, 3438, 2860, 1607, 186, 514, 3656, 2520, 1680, 4414, 4614, 4117, 1804, 1858, 3613, 4863, 3363, 3576, 1367, 897, 1931, 949, 4701, 4601, 764, 3517, 2338, 1573, 3554, 4393, 4552, 2438, 4181, 551, 2115, 890, 362, 3771, 2195, 1757, 4247, 4787, 557, 4465, 4134, 2704, 2656, 4228, 3758, 1960, 3087, 1970, 4052, 2723, 3321, 2185, 1069, 3802, 3492, 3652, 2566, 2710, 3449, 2227, 308, 1014, 889, 1740, 3667, 1020, 4190, 1359, 658, 3422, 4067, 2280, 659, 4816, 314, 268, 1878, 3742, 1651, 4025, 4844, 1491, 3329, 3340, 2742, 3028, 1760, 4123, 2537, 1878, 3331, 449, 3430, 4031, 1012, 1691, 3324, 2859, 3554, 3745, 1434, 1345, 3053, 1983, 1202, 2791, 4137, 95, 991, 165, 1751, 3568, 2485, 475, 3831, 3175, 4882, 3159, 629, 1965, 1199, 1217, 2538, 916, 1150, 1663, 1094, 690, 3561, 4980, 1555, 997, 563, 4943, 4839, 3615, 4441, 3288, 1634, 4320, 4618, 2952, 1346, 40, 1219, 2474, 2853, 4762, 591, 972, 2563, 3383, 1522, 1051, 3833, 3491, 844, 2622, 4282, 2878, 4411, 3556, 3263, 3429, 1426, 2763, 4631, 4687, 630, 752, 1823, 1016, 4114, 3155, 3524, 1857, 735, 538, 226, 3958, 488, 3794, 730, 1467, 4327, 4494, 200, 622, 3035, 4786, 2592, 2724, 4860, 797, 500, 3508, 1012, 1764, 166, 4178, 3422, 1995, 4290, 3630, 3825, 3454, 3225, 4548, 3445, 2567, 4834, 1215, 3884, 368, 4876, 4356, 2063, 4032, 1, 496, 3074, 4871, 4703, 3560, 954, 932, 82, 3628, 475, 3915, 2700, 2268, 1458, 4327, 3365, 2557, 1170, 3284, 541, 4590, 3276, 326, 1375, 1816, 4114, 3069, 3223, 4634, 476, 1470, 1538, 1626, 1624, 468, 2987, 3251, 3093, 562, 2870, 2010, 2097, 3147, 4738, 3792, 358, 1994, 845, 2554, 425, 3420, 4979, 3131, 1802, 919, 1532, 770, 4811, 4025, 1869, 663, 3909, 2544, 4643, 1998, 64, 4990, 3615, 4085, 2125, 929, 1949, 2028, 4337, 1932, 2690, 666, 1799, 584, 4602, 1444, 4007, 1063, 2459, 2105, 1475, 2220, 4257, 3128, 1276, 990, 659, 385, 1143, 1444, 2553, 673, 3783, 812, 4135, 4291, 3535, 3788, 2736, 3405, 249, 1081, 519, 2699, 4818, 2472, 4746, 1991, 3982, 4715, 2762, 3868, 1793, 3363, 1995, 1746, 3892, 1378, 1755, 3272, 2598, 1958, 295, 3169, 3193, 3302, 1191, 2548, 421, 4620, 3079, 3804, 106, 1722, 1460, 404, 476, 4923, 66, 4327, 1201, 2284, 1167, 4200, 4949, 1302, 3315, 992, 4312, 4835, 4916, 3600, 549, 2133, 55, 4078, 3062, 3633, 58, 839, 1100, 3388, 3694, 3007, 1129, 4679, 3745, 4746, 164, 199, 1528, 1098, 117, 3426, 3895, 3880, 1581, 773, 2260, 2081, 4563, 255, 3112, 1793, 561, 2161, 4728, 4928, 846, 1077, 4671, 4348, 413, 1459, 1781, 3051, 3057, 847, 331, 1660, 123, 2945, 1965, 980, 4853, 294, 1271, 3068, 398, 3272, 1251, 3595, 916, 2532, 2991, 667, 2537, 3977, 2978, 4634, 1645, 3381, 1397, 3087, 3116, 1105, 3427, 4799, 142, 3490, 4602, 349, 1257, 488, 3091, 2258, 223, 1505, 1881, 3444, 3403, 3327, 3586, 1202, 1847, 3116, 1297, 2285, 4287, 185, 756, 4939, 4802, 3685, 4646, 1123, 3666, 177, 886, 1148, 4627, 4200, 4617, 1645, 3818, 4556, 991, 1434, 2577, 3177, 3926, 3110, 2353, 4258, 4261, 3154, 1348, 1450, 1876, 1634, 362, 3839, 3622, 1818, 2566, 4680, 4471, 164, 1339, 3770, 4233, 2296, 1857, 4293, 4710, 1771, 1600, 974, 2342, 1280, 1839, 3068, 1679, 3845, 2653, 3048, 1621, 3282, 1169, 4805, 2175, 3851, 127, 1207, 4414, 1793, 3907, 751, 194, 263, 3127, 3731, 72, 9, 1444, 2884, 3639, 4444, 3021, 4549, 899, 3216, 3344, 2609, 2306, 2164, 3121, 3213, 2375, 2128, 1299, 271, 4975, 2541, 3553, 671, 384, 510, 954, 4247, 2670, 2771, 104, 2552, 1029, 4799, 4048, 559, 4702, 956, 4229, 91, 2149, 3302, 2684, 1920, 523, 1831, 1877, 4523, 2958, 2739, 2160, 1828, 2677, 1586, 2180, 3892, 1595, 4260, 4008, 4264, 3943, 260, 1322, 502, 2729, 4002, 1481, 119, 4338, 3146, 109, 1414, 3901, 369, 1938, 2660, 1172, 1938, 2091, 3088, 4504, 2311, 3943, 2109, 4803, 3092, 2853, 411, 2672, 2485, 1833, 757, 554, 4912, 1642, 948, 1975, 2065, 1620, 4827, 4028, 1823, 3776, 2694, 2293, 395, 1612, 4950, 4952, 4982, 2592, 1489, 3656, 3068, 27, 4957, 2073, 1346, 4753, 2286, 3224, 2146, 370, 292, 1182, 1551, 402, 4870, 1063, 1387, 2063, 4629, 1840, 196, 4332, 2496, 1830, 540, 147, 219, 2457, 923, 755, 102, 4733, 3289, 587, 810, 2088, 3113, 493, 934, 1008, 3836, 2827, 4764, 3095, 1329, 2356, 3619, 784, 135, 2980, 1004, 4722, 4568, 4471, 4187, 418, 492, 4838, 3731, 2442, 3410, 2295, 2516, 2269, 3263, 4575, 3195, 3540, 1482, 1021, 3777, 795, 2002, 889, 742, 3831, 1438, 1073, 3934, 4554, 4865, 4144, 3396, 151, 2695, 4436, 268, 4554, 71, 1438, 1712, 4603, 2831, 4261, 4472, 3234, 1275, 2251, 650, 3407, 640, 3140, 1497, 3230, 4831, 1356, 2183, 4958, 930, 2185, 2578, 935, 3865, 4846, 772, 3225, 3672, 2593, 4589, 1976, 4259, 2439, 2921, 1338, 918, 560, 39, 2312, 2105, 972, 4567, 2384, 3560, 2990, 3194, 1741, 70, 700, 181, 2999, 4095, 1642, 2307, 4035, 3351, 4676, 2809, 734, 1191, 366, 1547, 3419, 167, 1214, 846, 1906, 385, 2202, 1586, 3467, 4389, 3776, 913, 4760, 1132, 3334, 3423, 4948, 2638, 1082, 2689, 2262, 4684, 2967, 292, 2070, 1059, 3508, 1061, 2189, 4530, 852, 26, 230, 2667, 1263, 3651, 1058, 65, 1693, 1243, 2844, 164, 2989, 47, 3180, 2770, 3490, 4822, 3884, 306, 4574, 407, 4669, 1784, 1739, 4751, 2073, 2740, 1275, 309, 2310, 2928, 4132, 2214, 1662, 3128, 3402, 1406, 2927, 2638, 1320, 1043, 4526, 3883, 4345, 4257, 4263, 1941, 2991, 178, 2520, 4227, 4068, 4446, 3634, 4106, 709, 1094, 3058, 2650, 3687, 1007, 4837, 3630, 4999, 4642, 2827, 514, 4300, 4267, 4884, 1737, 3614, 4249, 4112, 3486, 3399, 1395, 434, 934, 4978, 834, 337, 4459, 4410, 4627, 4741, 2955, 525, 4883, 745, 2826, 1815, 4838, 3190, 576, 3952, 4733, 1932, 1552, 1315, 4412, 1262, 720, 3781, 333, 2992, 4261, 2539, 3548, 3285, 4621, 3589, 1792, 1567, 4942, 2038, 3497, 817, 4322, 1091, 669, 478, 2614, 3234, 3338, 4085, 4434, 4249, 2693, 4579, 2833, 3803, 2236, 2225, 2300, 2049, 4447, 3511, 164, 4849, 4528, 1869, 3741, 650, 4041, 1411, 2382, 2527, 980, 4243, 2574, 806, 3111, 596, 2960, 1062, 4292, 3821, 844, 2694, 2771, 2098, 2435, 953, 2770, 2318, 2151, 3816, 3643, 1536, 2839, 1855, 1914, 946, 2291, 1254, 996, 4041, 3904, 1800, 3345, 4649, 1061, 4659, 3117, 820, 702, 4122, 3727, 3869, 644, 2258, 2887, 4471, 4674, 930, 1719, 3349, 3833, 932, 2914, 3198, 1554, 3698, 698, 4175, 4580, 3245, 3055, 506, 672, 1129, 4028, 4448, 259, 1064, 251, 322, 1724, 3707, 1008, 1877, 3575, 4494, 1063, 324, 2663, 3856, 905, 2144, 273, 3906, 2790, 35, 3765, 653, 818, 1217, 2378, 478, 4928, 2288, 3180, 4372, 1209, 4738, 4479, 489, 2036, 1747, 1776, 775, 2309, 4608, 3041, 1572, 2923, 1624, 1904, 1878, 1153, 657, 2232, 1928, 2125, 4822, 3504, 2042, 3558, 1349, 2498, 3717, 4525, 878, 4357, 1777, 1400, 3111, 2179, 4243, 2495, 1070, 1284, 2498, 812, 875, 120, 1573, 4038, 4583, 3193, 990, 2522, 3127, 2089, 2588, 1721, 4945, 1615, 3699, 2088, 1677, 1336, 3719, 3240, 2663, 4439, 316, 3843, 211, 3767, 912, 1474, 1076, 3243, 1738, 2191, 2317, 1416, 3401, 3514, 1486, 3791, 3712, 1107, 553, 1749, 2090, 2271, 3948, 2175, 4712, 1112, 3250, 941, 174, 2299, 4849, 1354, 4217, 861, 1801, 3084, 2189, 2196, 3448, 291, 4205, 988, 20, 1797, 4161, 1446, 2347, 1631, 1869, 2225, 3698, 881, 4104, 3866, 1177, 3083, 3243, 3160, 2665, 301, 863, 3440, 2124, 3151, 831, 1182, 1310, 1925, 2635, 2144, 3511, 1623, 3511, 786, 547, 1236, 473, 3844, 4262, 3349, 4740, 914, 4747, 100, 3617, 2622, 2432, 3499, 878, 3988, 1013, 1274, 1138, 4549, 4706, 471, 1226, 3226, 1382, 2749, 2729, 4438, 4536, 2133, 2659, 1375, 4493, 3596, 3082, 389, 1844, 4697, 4435, 4498, 4205, 4008, 3247, 4822, 1925, 3081, 4331, 1949, 521, 165, 666, 1981, 1980, 2183, 4274, 2398, 4060, 4838, 4394, 1179, 1679, 892, 2016, 2755, 4796, 110, 262, 1784, 4096, 4436, 2345, 3308, 3379, 3340, 3521, 2237, 2716, 4266, 4849, 3304, 4198, 4169, 2162, 1477, 4679, 3473, 4447, 2162, 3269, 112, 3120, 2655, 1283, 1330, 2021, 956, 2805, 1420, 3571, 4038, 4978, 1300, 1382, 1498, 3894, 4421, 3644, 4219, 4360, 4149, 3703, 2979, 1164, 1062, 3182, 2467, 1171, 3386, 4093, 413, 1018, 594, 431, 2187, 1125, 3272, 2160, 2524, 852, 4586, 235, 1869, 3164, 1247, 2657, 3220, 987, 3450, 4669, 2302, 2424, 151, 2865, 4729, 467, 4848, 4615, 358, 3704, 96, 2700, 3132, 3339, 3814, 878, 3951, 438, 4946, 304, 510, 1716, 2395, 1228, 205, 771, 159, 1731, 3135, 337, 4796, 837, 2151, 4102, 2255, 1565, 1569, 3787, 1576, 3981, 2628, 977, 4656, 4462, 4611, 2206, 1161, 2176, 1960, 2826, 4590, 4274, 1810, 2464, 401, 4024, 4718, 3173, 594, 998, 173, 3970, 2133, 3136, 676, 2902, 4838, 2490, 2527, 2959, 2199, 1220, 3090, 4171, 4283, 356, 4457, 3367, 4602, 1701, 742, 3512, 1025, 1595, 3822, 2846, 2748, 3979, 55, 3928, 2625, 1847, 878, 1265, 3248, 2972, 1382, 2627, 501, 3660, 4987, 1422, 2924, 1489, 2617, 332, 2473, 1332, 2125, 1856, 162, 3498, 3358, 901, 4243, 1572, 1127, 3609, 101, 388, 562, 2954, 4718, 1740, 1752, 2855, 233, 4226, 703, 2157, 2189, 2702, 1913, 1796, 3212, 2868, 3, 4135, 6, 3131, 4076, 3000, 3267, 4033, 4283, 4413, 1612, 1598, 814, 4767, 3588, 4134, 812, 75, 274, 2758, 4981, 2129, 166, 316, 3207, 4044, 990, 761, 2557, 4785, 2666, 3211, 1450, 2491, 3354, 2307, 4251, 1666, 1891, 2128, 2908, 2424, 932, 3336, 2358, 2619, 4375, 1566, 3974, 1252, 208, 1113, 1375, 775, 2988, 3462, 1933, 1084, 195, 3280, 3403, 1887, 1201, 3470, 340, 408, 4421, 1349, 1462, 214, 4664, 3537, 999, 3935, 2784, 4605, 4685, 4997, 2768, 3118, 4448, 149, 2098, 4658, 502, 848, 1500, 839, 1724, 1693, 726, 4083, 2417, 729, 4957, 4462, 1526, 1563, 1821, 2752, 2644, 2651, 2221, 3398, 4854, 3489, 3867, 1874, 841, 4196, 2898, 406, 686, 3933, 309, 2411, 4309, 2112, 992, 2599, 4529, 162, 4964, 1844, 4043, 3360, 3152, 955, 1017, 3123, 3215, 2094, 3990, 3928, 1791, 4937, 1441, 1575, 3987, 1097, 1609, 2744, 1788, 1043, 2857, 4790, 4576, 3446, 1875, 3908, 632, 4073, 2373, 121, 1119, 3010, 2231, 3096, 107, 1532, 2660, 4567, 1968, 360, 1513, 1163, 1824, 3306, 647, 4026, 2527, 1229, 3744, 2654, 4739, 1102, 2273, 2030, 678, 807, 1883, 1832, 990, 3932, 3028, 4979, 4394, 1268, 1495, 3185, 2222, 4631, 2697, 3274, 830, 793, 3555, 1413, 1492, 3851, 1866, 160, 1876, 643, 751, 3935, 1541, 4925, 2153, 2199, 1537, 3004, 1673, 67, 4282, 1271, 2518, 2838, 4185, 1997, 3521, 1158, 4580, 992, 1333, 1875, 1095, 3117, 2949, 3977, 3454, 2374, 647, 4472, 2984, 4135, 975, 2823, 1647, 1940, 4738, 4994, 1122, 1555, 4691, 2245, 1866, 559, 2654, 2372, 4669, 4605, 2805, 1619, 710, 493, 1276, 4894, 2097, 1095, 2317, 4049, 880, 3946, 4718, 4297, 4675, 772, 1739, 4487, 887, 4400, 4850, 2525, 3973, 4477, 4386, 1976, 1224, 61, 4361, 2142, 1072, 1509, 3363, 4686, 4980, 1119, 2198, 4649, 2176, 2632, 1511, 2741, 963, 4106, 277, 1392, 4883, 1832, 3582, 1666, 4077, 923, 4194, 3347, 2715, 1040, 1536, 4398, 3671, 1171, 3112, 4614, 4127, 3931, 2154, 1013, 2118, 2905, 3381, 2708, 1824, 4663, 2046, 4050, 4469, 2854, 3189, 2219, 311, 1342, 1016, 3268, 3199, 4290, 2054, 4721, 3731, 1863, 3915, 167, 2858, 1282, 2194, 207, 4876, 2158, 2550, 4346, 1561, 484, 4693, 990, 292, 108, 3642, 4805, 3187, 1735, 2153, 1635, 3389, 1996, 2972, 1346, 1840, 1078, 4579, 2380, 3432, 3520, 3753, 337, 2241, 1855, 3131, 1664, 4101, 2494, 226, 4762, 4693, 3234, 4902, 4568, 1028, 4699, 3843, 1625, 2466, 4104, 3594, 3337, 3385, 1291, 4438, 4423, 1992, 1791, 2821, 3753, 655, 3957, 1968, 526, 3353, 2597, 319, 1526, 4431, 4005, 4483, 3931, 2261, 1482, 4166, 3766, 4781, 3837, 2427, 3191, 3570, 4371, 835, 1140, 3825, 4037, 1887, 2322, 4062, 2241, 2146, 4876, 3243, 2612, 2238, 868, 2068, 491, 318, 1766, 2344, 4593, 4782, 1979, 741, 1806, 2487, 1559, 786, 2490, 2426, 1283, 1273, 4533, 425, 1835, 2637, 3558, 3779, 4042, 3441, 1145, 3464, 3016, 3842, 2694, 2186, 3463, 1338, 2665, 4181, 4470, 3116, 237, 2591, 1410, 2789, 2569, 1932, 3113, 1056, 4001, 4245, 3045, 4149, 3832, 1265, 1778, 3439, 2459, 3689, 4343, 3544, 1697, 1851, 2458, 602, 4854, 4615, 393, 2983, 2317, 4002, 4779, 4811, 1011, 3785, 4316, 3773, 1206, 3143, 369, 1279, 125, 1226, 2734, 3250, 1361, 1861, 4843, 165, 2071, 481, 4000, 2951, 386, 2630, 2756, 4787, 1611, 834, 1403, 1885, 4023, 4858, 1855, 3558, 3518, 954, 1082, 4203, 4471, 4000, 1307, 4117, 4659, 133, 3108, 170, 1828, 309, 1306, 4511, 802, 1989, 2885, 963, 2067, 117, 1722, 42, 991, 3567, 92, 3713, 3642, 1615, 1382, 1671, 3405, 1214, 4327, 711, 4431, 4022, 2412, 2662, 3072, 205, 4801, 1627, 471, 3998, 1206, 4986, 2488, 2592, 796, 1106, 2416, 1381, 3482, 4934, 4815, 2591, 4230, 4864, 2147, 1276, 638, 908, 4099, 3389, 3227, 3225, 2523, 4155, 2561, 1119, 3121, 1107, 3292, 4595, 3722, 4094, 2940, 3275, 2145, 2387, 2970, 4838, 1168, 2872, 1692, 3758, 2106, 177, 4222, 4839, 2646, 3693, 82, 4746, 4165, 4527, 4888, 1796, 1303, 4119, 3320, 4121, 201, 2531, 1083, 473, 703, 1460, 3572, 257, 712, 3842, 240, 1675, 582, 3830, 4888, 1474, 4197, 3479, 4115, 832, 211, 1625, 1575, 2064, 3373, 3614, 39, 939, 2082, 1612, 3535, 4061, 1989, 1259, 352, 4924, 1773, 1664, 2298, 4226, 1870, 677, 2944, 199, 617, 73, 1510, 2363, 3986, 1349, 1098, 4238, 1225, 4968, 1385, 3293, 4877, 857, 3858, 2685, 1190, 2704, 2483, 2762, 1741, 1757, 271, 113, 3828, 1752, 2585, 4261, 4636, 1846, 1451, 2239, 588, 3487, 3247, 4210, 2888, 2568, 3132, 2108, 2508, 4085, 4607, 4250, 4782, 508, 4165, 2377, 3984, 4536, 4926, 4243, 1564, 3399, 3245, 1595, 3302, 553, 2894, 1627, 4951, 2918, 1539, 3392, 459, 1744, 2789, 4006, 802, 2676, 3453, 3567, 1894, 194, 547, 2089, 668, 2960, 4436, 4010, 4914, 3710, 545, 4904, 1751, 4096, 4690, 1681, 2229, 1388, 3669, 4937, 3877, 170, 3122, 1497, 4621, 332, 569, 1715, 731, 3518, 4744, 1193, 1675, 1450, 1518, 188, 1583, 3528, 2902, 2026, 4299, 3239, 1907, 4297, 4358, 2379, 942, 4936, 875, 1513, 4606, 4594, 93, 634, 3094, 2415, 3922, 4782, 4773, 3527, 3401, 4575, 162, 4145, 1205, 1575, 858, 4197, 1253, 2795, 3166, 1173, 2042, 1683, 4203, 1182, 1609, 2657, 831, 2754, 2555, 2318, 35, 4454, 4421, 2513, 2723, 42, 3766, 1407, 3735, 1982, 4364, 1406, 399, 4302, 3794, 3583, 1908, 2162, 4748, 1266, 3419, 1798, 295, 1689, 2889, 3434, 1833, 80, 66, 4148, 4218, 1948, 4487, 1659, 2052, 1944, 2412, 370, 4522, 35, 3828, 908, 4486, 3774, 3744, 3881, 1243, 888, 3988, 3764, 2684, 4748, 4339, 4136, 3617, 168, 4414, 1843, 1174, 2252, 605, 1362, 2529, 2093, 2104, 4318, 1346, 729, 4894, 2509, 3770, 4261, 2537, 1867, 2972, 173, 4284, 2787, 3314, 2938, 823, 1428, 3463, 3945, 4054, 451, 3530, 238, 4863, 1582, 3684, 3695, 1506, 3919, 1105, 2821, 4287, 2495, 1547, 4449, 4616, 3082, 1503, 1573, 4914, 418, 2076, 4059, 2331, 3495, 2047, 4484, 1759, 2065, 339, 3559, 2465, 1131, 4314, 1535, 3902, 4616, 4482, 1663, 1647, 4679, 3806, 874, 835, 2890, 4538, 2554, 3027, 364, 1163, 1520, 498, 39, 2191, 1748, 1444, 2270, 1817, 3534, 412, 1087, 3491, 4339, 2273, 3717, 2996, 345, 1417, 735, 3731, 527, 3741, 3739, 2976, 1511, 4757, 3544, 2792, 4910, 1308, 3028, 3101, 3400, 2336, 4293, 3461, 3243, 986, 2340, 2095, 4531, 2157, 1980, 1578, 3018, 1856, 2886, 3884, 3685, 2584, 3556, 4529, 4872, 183, 2467, 12, 2462, 4658, 906, 1944, 4557, 1184, 2759, 2521, 734, 498, 3038, 957, 3763, 540, 2129, 1039, 1534, 717, 1894, 2119, 1155, 4317, 2448, 2516, 4032, 4393, 3331, 3212, 3713, 2840, 4612, 3776, 4309, 4626, 4082, 1501, 3168, 3213, 205, 1476, 4030, 2432, 2507, 4294, 3473, 3289, 3747, 532, 2950, 3881, 4856, 2458, 2646, 3253, 2718, 1973, 4660, 997, 2223, 1591, 597, 3421, 3584, 2946, 3202, 3192, 3133, 2665, 4747, 2637, 400, 635, 920, 3463, 2909, 1739, 1634, 655, 2284, 4281, 1899, 644, 2738, 1264, 1240, 2217, 2145, 1312, 2114, 4407, 3144, 266, 1935, 3758, 2389, 4865, 3650, 3217, 3837, 1074, 2131, 194, 413, 4626, 4091, 445, 1918, 4161, 1990, 2158, 2689, 4431, 3923, 2806, 4595, 3285, 404, 2971, 1440, 3587, 2620, 2623, 1631, 694, 3604, 3311, 2657, 3605, 4308, 118, 1284, 3820, 89, 3984, 3935, 2376, 633, 1113, 3293, 4858, 3798, 2931, 3859, 693, 4920, 4922, 2075, 1852, 4430, 1567, 3905, 4834, 11, 1951, 3168, 1720, 2367, 131, 1560, 2566, 1022, 2145, 3048, 3305, 1857, 323, 1503, 2677, 2065, 2045, 3638, 4019, 1054, 2359, 1416, 2848, 1579, 4857, 1591, 3278, 4818, 323, 1188, 3150, 804, 2056, 778, 1257, 3886, 2213, 4728, 4908, 2362, 4918, 4525, 2759, 4495, 4218, 458, 2174, 1110, 3421, 2766, 4787, 2677, 3059, 4663, 1867, 4965, 4146, 4981, 3292, 281, 847, 4020, 3009, 1770, 3787, 4981, 4269, 3511, 3871, 3720, 4726, 3534, 3008, 1360, 1516, 305, 2292, 1121, 2822, 4712, 3612, 4700, 2425, 3494, 3841, 2117, 3894, 2728, 4274, 3508, 2361, 8, 286, 2528, 4989, 1434, 388, 1427, 259, 319, 2580, 4506, 2501, 2426, 2527, 2780, 2707, 3999, 608, 920, 247, 1756, 1062, 1227, 2812, 72, 2224, 4719, 151, 488, 4136, 1235, 1688, 4479, 3779, 2252, 3751, 2145, 679, 3486, 4584, 2476, 2337, 4906, 3525, 4648, 2630, 4370, 1363, 4070, 2833, 455, 936, 2677, 3350, 56, 1655, 1113, 956, 1679, 2170, 961, 555, 1332, 3495, 3136, 429, 3776, 3972, 1432, 1612, 1925, 4161, 4817, 999, 2842, 3170, 1979, 4662, 2473, 2190, 3551, 892, 4894, 1989, 3243, 841, 2604, 3506, 3874, 3169, 3269, 907, 3965, 3975, 1568, 149, 1983, 512, 1343, 265, 3290, 1276, 2191, 4768, 3049, 1269, 907, 4981, 1179, 2282, 3472, 3199, 4993, 34, 935, 4432, 866, 2624, 3280, 2972, 2373, 2465, 2729, 3030, 4870, 346, 4683, 4684, 2862, 214, 1867, 2367, 3841, 3805, 2590, 1394, 4983, 3653, 3210, 2787, 4258, 226, 2966, 4553, 2810, 2463, 1655, 135, 4135, 496, 4851, 2147, 1371, 656, 4500, 3348, 4658, 1189, 430, 2047, 4550, 946, 4233, 1789, 1023, 1137, 2788, 686, 1425, 4380, 3652, 616, 4357, 1950, 2032, 3237, 3181, 600, 1742, 3142, 1922, 1174, 4722, 995, 708, 2599, 2411, 1271, 2319, 2183, 2934, 2169, 3938, 4112, 1702, 3579, 2048, 2244, 2433, 2083, 1356, 3535, 3887, 4565, 986, 1128, 1769, 885, 3688, 47, 764, 3549, 2944, 419, 3862, 4456, 780, 3155, 820, 113, 2931, 161, 1053, 4023, 839, 4964, 3644, 2282, 2809, 1500, 3956, 39, 1012, 39, 1115, 3989, 4061, 2230, 88, 142, 558, 2636, 1947, 4496, 1353, 4774, 4410, 1308, 4198, 2513, 1307, 319, 2903, 2263, 1228, 2420, 4303, 2409, 4173, 38, 3673, 4514, 1388, 4751, 3979, 2259, 2762, 1436, 1261, 3772, 1977, 3808, 1138, 2524, 29, 163, 4859, 4811, 4014, 811, 3539, 4707, 4343, 4823, 2346, 808, 4856, 4826, 3150, 3367, 2758, 4405, 3445, 4537, 1178, 1399, 653, 850, 879, 4301, 493, 270, 4962, 2027, 3759, 2352, 1685, 1440, 3800, 4155, 2576, 3444, 3497, 4751, 3798, 4768, 3533, 2852, 1074, 4492, 1106, 3830, 2164, 2818, 2355, 3372, 3948, 2124, 4496, 1158, 1356, 2984, 4503, 4760, 378, 3519, 3352, 2034, 3751, 907, 2375, 371, 2888, 4148, 3848, 4634, 2428, 3861, 51, 3850, 1565, 4764, 4032, 3755, 4494, 437, 2320, 1433, 483, 1814, 40, 4420, 1624, 4983, 840, 3421, 2121, 3348, 2138, 3257, 346, 1151, 1293, 4574, 1528, 4791, 4425, 2534, 3838, 1920, 988, 4391, 4614, 2179, 1064, 258, 1641, 295, 1840, 648, 3297, 3246, 365, 2637, 1973, 2299, 2275, 450, 732, 1978, 1917, 4963, 4983, 1142, 4622, 3520, 3775, 709, 1198, 4471, 1623, 4149, 4097, 1951, 4374, 353, 919, 1560, 1151, 2303, 4775, 4631, 3859, 2405, 1743, 1358, 62, 4245, 3164, 855, 1539, 2789, 3891, 1415, 167, 359, 4220, 967, 4400, 4319, 616, 4810, 498, 905, 2228, 1440, 4435, 3932, 445, 2083, 1446, 3374, 1545, 1172, 208, 3211, 3324, 2807, 1148, 2776, 3348, 4362, 4829, 3358, 1170, 3575, 3143, 1021, 425, 3608, 1696, 348, 3289, 4177, 4265, 3649, 1681, 4944, 15, 2954, 1336, 3720, 1235, 4285, 2919, 2079, 1270, 896, 2266, 4140, 1282, 2752, 1746, 3303, 650, 4929, 4309, 4299, 4038, 3849, 3540, 2521, 1894, 1461, 289, 2547, 2387, 3306, 4451, 2927, 1629, 2122, 3308, 1885, 2058, 4899, 2216, 2282, 4456, 1571, 4408, 1936, 1714, 4794, 1090, 3569, 3628, 3718, 2630, 2194, 3432, 2989, 1653, 4948, 1833, 1485, 3063, 2749, 3572, 2932, 3693, 791, 4106, 1547, 1899, 2078, 4004, 997, 1127, 4039, 3612, 1250, 1603, 554, 3259, 2916, 1666, 886, 1501, 2, 4618, 3790, 4967, 226, 4069, 572, 153, 4984, 1645, 2133, 2527, 4056, 820, 3228, 1453, 4967, 1852, 2491, 473, 4737, 3235, 1736, 544, 4440, 4817, 229, 3678, 2664, 2923, 1745, 2594, 4986, 1316, 3746, 1220, 256, 2820, 4255, 2541, 2957, 3494, 3348, 1562, 3588, 3407, 4961, 1942, 2330, 390, 4414, 1050, 1870, 4987, 4089, 4044, 4936, 668, 867, 163, 1388, 224, 1804, 1634, 4886, 2195, 354, 4088, 638, 1201, 3339, 591, 336, 1712, 3150, 373, 2497, 2301, 2790, 3429, 581, 279, 1252, 3013, 892, 4297, 350, 1007, 718, 754, 83, 4910, 2797, 2695, 4482, 1354, 2908, 3269, 4320, 1434, 4843, 2871, 1004, 2937, 716, 4889, 3723, 2711, 2036, 3178, 4883, 1232, 2831, 2713, 1683, 3679, 4171, 163, 4179, 248, 2311, 3073, 4816, 920, 4321, 428, 772, 2173, 3775, 2058, 4258, 1990, 4001, 113, 2382, 275, 4487, 250, 915, 1956, 2633, 1355, 1335, 2000, 4616, 3293, 1868, 2313, 2819, 1472, 3889, 2068, 2934, 3493, 2496, 426, 4566, 1270, 2525, 4575, 79, 1237, 1345, 3934, 3878, 767, 1758, 92, 2779, 1477, 1946, 4517, 2611, 3170, 3664, 2063, 1621, 2547, 4544, 1785, 1067, 2806, 358, 3330, 1879, 1104, 4455, 2749, 2586, 2044, 1468, 1197, 1462, 1804, 4810, 2392, 4072, 4525, 1714, 2456, 2999, 2637, 3402, 2677, 1472, 28, 4215, 901, 4847, 3361, 957, 422, 2909, 3156, 4340, 4808, 1330, 814, 1865, 4992, 71, 1156, 809, 748, 4408, 2089, 3036, 1519, 4454, 927, 3219, 1040, 3893, 1885, 3149, 3264, 4296, 3112, 679, 3044, 3377, 3751, 937, 2884, 2021, 2260, 2404, 2261, 1956, 767, 688, 29, 541, 4799, 1140, 2154, 3141, 3011, 1629, 3420, 3252, 2898, 3964, 295, 813, 2125, 4404, 2848, 4179, 2038, 3387, 2224, 4298, 3329, 2071, 374, 397, 4497, 2453, 4182, 845, 2364, 3961, 3064, 571, 3397, 0, 1519, 1111, 2265, 4056, 4935, 515, 4177, 3122, 621, 1926, 4031, 3481, 3541, 3503, 3745, 3352, 819, 1914, 1735, 2560, 4055, 2457, 4481, 1594, 187, 4112, 3442, 1982, 3553, 2463, 651, 1372, 429, 957, 1888, 3971, 2717, 4187, 1789, 1502, 482, 4344, 3468, 560, 2461, 1089, 545, 2995, 2131, 2926, 2763, 3386, 1313, 3739, 3192, 2447, 2509, 4256, 1826, 749, 66, 3634, 2750, 1486, 552, 2545, 1190, 1186, 4306, 3405, 557, 2027, 334, 4257, 2336, 2131, 1485, 2871, 1998, 2954, 2520, 3123, 1071, 409, 1393, 3007, 2556, 2943, 2859, 1576, 3214, 986, 3061, 1034, 1402, 2827, 2470, 433, 4428, 3208, 2523, 4429, 1608, 2169, 210, 1259, 4269, 1252, 2234, 2302, 453, 2372, 712, 3341, 4843, 4430, 4678, 460, 1200, 1205, 652, 2789, 2561, 2351, 4917, 4411, 2449, 1840, 3768, 1313, 2248, 3771, 2169, 147, 3447, 307, 2202, 779, 4048, 2711, 4845, 1521, 22, 2198, 4842, 3352, 396, 502, 2650, 249, 4859, 229, 1790, 2019, 1465, 3294, 881, 1856, 4847, 3438, 2794, 2262, 3305, 2930, 2377, 4462, 3267, 2471, 1559, 2817, 4006, 544, 2133, 3678, 4468, 2613, 125, 1688, 802, 2138, 4216, 824, 2087, 2294, 4597, 4898, 3428, 4975, 1611, 230, 1969, 1029, 2469, 180, 2087, 1986, 1006, 3634, 1792, 2875, 3237, 4997, 3243, 3228, 1026, 1986, 2391, 851, 2148, 3528, 3380, 430, 3931, 2980, 538, 4861, 2089, 2918, 1275, 521, 3005, 247, 596, 742, 4939, 4792, 1910, 2692, 4939, 3993, 4600, 1359, 3049, 258, 4340, 134, 4356, 1855, 941, 1991, 816, 2048, 2310, 3591, 565, 3768, 843, 4882, 145, 4554, 3390, 730, 4974, 770, 2214, 4250, 1991, 3719, 2010, 3257, 37, 2859, 207, 2098, 2732, 1526, 1955, 4494, 50, 2596, 4023, 4362, 1432, 4662, 908, 4015, 1186, 2205, 850, 4232, 4398, 4301, 4131, 2079, 70, 2394, 36, 4099, 4862, 416, 333, 2110, 4521, 4375, 1575, 4040, 11, 1921, 1870, 2515, 954, 2861, 1949, 4871, 2673, 1955, 60, 1286, 4746, 652, 1039, 1280, 1953, 4870, 4213, 3476, 3236, 2736, 4708, 3641, 4065, 4166, 4631, 2351, 3225, 1176, 1381, 761, 3130, 829, 172, 1383, 2965, 4141, 2499, 2996, 497, 919, 2427, 2863, 3881, 3415, 78, 3621, 2088, 1158, 3266, 1063, 373, 4707, 3063, 3330, 4471, 3490, 4771, 2405, 4767, 4238, 2347, 1562, 1652, 1398, 585, 4340, 2743, 2106, 4104, 4312, 3647, 4381, 3313, 3412, 3094, 4438, 2922, 1021, 460, 2087, 474, 1785, 1524, 2137, 2609, 3273, 4233, 3665, 3929, 1543, 3541, 1571, 4174, 519, 3437, 567, 365, 914, 2454, 2770, 2351, 3449, 3862, 4216, 4239, 4176, 859, 3093, 2349, 1880, 4325, 571, 2705, 69, 3423, 964, 495, 670, 1636, 683, 2069, 3722, 3663, 3406, 2820, 3060, 2089, 4488, 3537, 3797, 545, 1630, 867, 1431, 1738, 1417, 2298, 1045, 2784, 3567, 4523, 3292, 3447, 1405, 3079, 4700, 4765, 3183, 1554, 3964, 3207, 2531, 4635, 1826, 3022, 2615, 1587, 3588, 580, 4300, 2073, 1130, 441, 4808, 3306, 1271, 1984, 3431, 3340, 4609, 3312, 1152, 126, 4432, 929, 4753, 4415, 1069, 4690, 151, 1570, 4687, 3921, 1088, 4495, 2772, 4136, 364, 1785, 993, 53, 3313, 2254, 3461, 1672, 2404, 750, 2329, 2080, 1246, 4389, 496, 4979, 4857, 1775, 1395, 4240, 1461, 548, 4143, 4838, 3895, 905, 3160, 4999, 3143, 3866, 4893, 1162, 3741, 4494, 3379, 3486, 4976, 186, 2319, 498, 1484, 507, 1115, 457, 522, 2798, 2302, 1840, 2680, 645, 3681, 4372, 763, 1329, 4656, 1053, 3541, 1970, 3015, 1769, 1583, 4294, 2256, 954, 4986, 170, 2396, 1159, 2097, 2879, 691, 3792, 2679, 2337, 4008, 4024, 2040, 674, 1576, 2195, 1869, 1305, 2217, 1920, 138, 678, 389, 2212, 3152, 2915, 910, 2080, 3932, 3131, 3463, 4182, 2464, 4623, 1512, 3670, 1576, 629, 2441, 3551, 2706, 1384, 3257, 3610, 450, 2672, 4573, 491, 1551, 2888, 4370, 1851, 3631, 4041, 2654, 547, 2370, 3045, 1859, 3539, 1678, 447, 3445, 1439, 2830, 52, 1538, 1087, 2482, 3930, 2730, 3721, 568, 2780, 1866, 4338, 3893, 3481, 3785, 2259, 3194, 3049, 757, 1410, 1853, 4921, 724, 933, 1741, 3725, 1014, 4558, 89, 2767, 1976, 7, 1106, 2946, 2611, 2427, 1417, 2633, 672, 3009, 3052, 246, 2770, 1555, 2970, 1219, 4624, 4866, 4050, 1156, 714, 1624, 3336, 106, 1880, 3602, 4814, 2410, 443, 2940, 3424, 1866, 800, 1709, 2111, 8, 4567, 2563, 4921, 1971, 1908, 2382, 1711, 156, 3642, 1647, 731, 1162, 670, 3015, 3797, 2287, 2824, 1810, 4874, 3193, 2147, 4534, 986, 3036, 3361, 718, 3988, 2868, 2546, 824, 3978, 461, 2254, 4122, 1912, 975, 2792, 4521, 2417, 2535, 2887, 3957, 4788, 2786, 1153, 4063, 4730, 4928, 710, 2962, 1655, 4930, 3521, 4446, 502, 2153, 3243, 1790, 1428, 612, 3122, 2221, 2197, 3706, 4323, 683, 3727, 1981, 2015, 1909, 2309, 1989, 2804, 4681, 4623, 4195, 793, 554, 2391, 3740, 4788, 1780, 1323, 4580, 3128, 4572, 3814, 3690, 1731, 3313, 4011, 1808, 3393, 4002, 4597, 4360, 3521, 3948, 3414, 2037, 2810, 2827, 414, 1693, 4452, 607, 1941, 1545, 4395, 2801, 361, 4890, 3384, 416, 1513, 4639, 4473, 408, 2792, 973, 2955, 4419, 2791, 3878, 2366, 3294, 4735, 2267, 2037, 3963, 4018, 3158, 2251, 3131, 3504, 2564, 4003, 1679, 4630, 4559, 4176, 4996, 1132, 4537, 3583, 1253, 3959, 2245, 1240, 2784, 1615, 3763, 1503, 2245, 3850, 2035, 4988, 4438, 331, 1098, 2410, 1825, 628, 2288, 4928, 3246, 2323, 2317, 208, 2919, 1601, 535, 4812, 2513, 237, 3210, 1499, 3687, 3860, 1544, 4041, 1117, 2719, 2566, 2396, 3423, 2634, 2852, 1705, 2397, 47, 3799, 4277, 4163, 2372, 1916, 4412, 1156, 1246, 3699, 274, 4598, 1915, 3560, 2542, 4802, 2711, 288, 2135, 2222, 4492, 1912, 418, 1525, 3298, 4993, 1517, 3873, 1551, 1017, 877, 1033, 4471, 1051, 2454, 2534, 3151, 2857, 3097, 1103, 2999, 301, 1686, 1630, 4862, 1205, 4509, 716, 1849, 4338, 2240, 3436, 4917, 3512, 140, 929, 1837, 895, 2651, 1741, 899, 1251, 2871, 2901, 311, 135, 3715, 2427, 3976, 3413, 4922, 681, 1902, 1165, 2705, 3843, 257, 2506, 3428, 2198, 3593, 3198, 3165, 4914, 1244, 4812, 3753, 4839, 1799, 3321, 2504, 4618, 1570, 3208, 4683, 913, 2327, 4528, 4977, 1198, 1293, 882, 3453, 2564, 868, 2377, 2605, 427, 4532, 690, 420, 351, 762, 1550, 1420, 1888, 781, 1387, 86, 4336, 3461, 2029, 646, 2054, 3051, 624, 2102, 3223, 2826, 4280, 4159, 3647, 1045, 4363, 249, 4335, 984, 3938, 1417, 4787, 322, 3957, 3248, 1716, 1511, 4461, 2471, 29, 2761, 2856, 4090, 1525, 4004, 4057, 3538, 532, 1660, 4643, 4727, 1019, 4004, 687, 2561, 508, 3710, 4317, 4252, 4302, 3978, 2162, 964, 4709, 138, 329, 3695, 4640, 4031, 979, 3000, 3530, 1749, 4177, 2045, 4409, 3337, 1626, 2157, 4432, 3492, 3724, 3454, 223, 3050, 763, 561, 3706, 16, 2696, 1942, 923, 2839, 3625, 4465, 826, 2600, 2185, 874, 705, 397, 1547, 1931, 2375, 3224, 3358, 2990, 281, 645, 3657, 2011, 4842, 613, 2969, 1522, 595, 3562, 1649, 4093, 36, 2965, 941, 982, 818, 1946, 4686, 193, 3532, 2196, 1307, 3647, 3659, 2587, 3753, 1905, 3026, 4681, 1064, 1173, 4899, 54, 1089, 4753, 3587, 2032, 4250, 2825, 2782, 4400, 1069, 1266, 2841, 1165, 1574, 4457, 1335, 4009, 3184, 4577, 4475, 1612, 2796, 4026, 3230, 4443, 4228, 4210, 4307, 2594, 3293, 392, 3372, 3962, 2974, 1685, 1525, 3057, 682, 3347, 227, 1317, 650, 662, 2210, 2519, 2920, 1537, 1757, 3865, 1708, 2828, 2206, 4637, 1738, 3913, 2077, 4022, 4002, 2020, 1313, 1330, 3297, 190, 3917, 2569, 1790, 87, 541, 4180, 1084, 3309, 19, 3481, 3867, 4834, 3051, 3926, 1749, 2750, 2389, 1886, 1503, 3984, 3310, 2409, 370, 3936, 2, 4733, 4643, 614, 2558, 2561, 3213, 3240, 19, 3879, 605, 2754, 4734, 1117, 438, 2304, 3501, 1161, 1420, 2764, 1040, 1072, 572, 1442, 4810, 1816, 2683, 4483, 4045, 3914, 2172, 1204, 703, 4033, 1542, 712, 1358, 3385, 2334, 4282, 1084, 3512, 4293, 4376, 4244, 2877, 1599, 4911, 4581, 619, 3648, 2722, 2128, 4923, 865, 2676, 2936, 4262, 2347, 3463, 921, 4151, 2028, 2242, 697, 4879, 2686, 4313, 1591, 1740, 3793, 1932, 1351, 2407, 1705, 3041, 2220, 4904, 422, 4289, 2284, 4027, 1866, 1504, 2850, 718, 799, 186, 322, 1135, 1050, 3627, 2676, 3726, 1378, 4792, 4121, 325, 2088, 270, 4065, 1142, 3611, 4756, 2756, 1919, 601, 1944, 4218, 4731, 2085, 2518, 3104, 4032, 4426, 1614, 615, 274, 4382, 4577, 3982, 3239, 2463, 1345, 348, 1800, 43, 4798, 1503, 2533, 3155, 4915, 131, 4853, 2765, 2811, 1853, 2868, 3054, 2418, 4778, 736, 4262, 812, 2555, 4076, 3617, 4734, 532, 2110, 3532, 2943, 1395, 4100, 76, 4297, 4664, 29, 3270, 4632, 4192, 4640, 3706, 1014, 21, 4050, 3054, 1842, 1054, 570, 4259, 429, 1728, 4847, 596, 1370, 2800, 1058, 3259, 4215, 4230, 63, 2031, 3646, 3146, 1795, 4796, 218, 1452, 4021, 117, 2418, 4389, 1142, 4998, 750, 3101, 2362, 227, 753, 721, 4065, 2148, 3628, 2712, 2374, 4797, 1474, 3976, 3615, 513, 3783, 4926, 1847, 4635, 4495, 2176, 2734, 3619, 4239, 3065, 4135, 1444, 4518, 4709, 4039, 1972, 25, 704, 2535, 3024, 660, 142, 3563, 1197, 4732, 2689, 2861, 1851, 3809, 3385, 4099, 2285, 4892, 2210, 4698, 3616, 1456, 1443, 670, 3010, 1816, 1825, 2089, 1157, 413, 4957, 2539, 4394, 476, 1168, 2746, 763, 1483, 3370, 1478, 1974, 1178, 248, 562, 75, 2981, 178, 1382, 4542, 4427, 2014, 942, 408, 2177, 2005, 4939, 1048, 3729, 4481, 1159, 1380, 4377, 2239, 3447, 2724, 4739, 4201, 2932, 852, 4816, 965, 2719, 2505, 4029, 1572, 257, 4552, 4493, 3920, 2576, 2998, 4811, 1216, 3499, 106, 900, 3830, 4893, 2819, 1273, 4666, 991, 2994, 3400, 649, 4820, 167, 4248, 2546, 4791, 162, 3339, 4028, 321, 2922, 3603, 1778, 3395, 650, 1540, 3721, 4113, 3079, 2478, 291, 3551, 190, 113, 30, 4734, 467, 946, 3566, 2543, 879, 2636, 4392, 2695, 27, 1726, 4444, 3083, 4901, 1105, 1402, 322, 2147, 1886, 1775, 172, 873, 13, 4580, 2017, 3561, 3050, 1334, 4608, 4311, 1994, 236, 4235, 59, 4156, 3831, 933, 3495, 256, 4756, 3021, 757, 290, 970, 2614, 3228, 3925, 3884, 3925, 4312, 816, 2075] - sort unsortedList + sort(unsorted_list) |> Quicksort.show - |> PlatformTasks.putLine + |> PlatformTasks.put_line - Err GetIntError -> - PlatformTasks.putLine "Error: Failed to get Integer from stdin." + Err(GetIntError) -> + PlatformTasks.put_line("Error: Failed to get Integer from stdin.") sort : List I64 -> List I64 sort = \list -> - Quicksort.sortWith list (\x, y -> Num.compare x y) + Quicksort.sort_with(list, \x, y -> Num.compare(x, y)) diff --git a/crates/cli/tests/benchmarks/rBTreeCk.roc b/crates/cli/tests/benchmarks/rBTreeCk.roc index 8a8076690dc..4a6684ae350 100644 --- a/crates/cli/tests/benchmarks/rBTreeCk.roc +++ b/crates/cli/tests/benchmarks/rBTreeCk.roc @@ -10,75 +10,75 @@ Map : Tree I64 Bool ConsList a : [Nil, Cons a (ConsList a)] -makeMap : I64, I64 -> ConsList Map -makeMap = \freq, n -> - makeMapHelp freq n Leaf Nil +make_map : I64, I64 -> ConsList Map +make_map = \freq, n -> + make_map_help(freq, n, Leaf, Nil) -makeMapHelp : I64, I64, Map, ConsList Map -> ConsList Map -makeMapHelp = \freq, n, m, acc -> +make_map_help : I64, I64, Map, ConsList Map -> ConsList Map +make_map_help = \freq, n, m, acc -> when n is - 0 -> Cons m acc + 0 -> Cons(m, acc) _ -> - powerOf10 = + power_of10 = n % 10 == 0 - m1 = insert m n powerOf10 + m1 = insert(m, n, power_of10) - isFrequency = + is_frequency = n % freq == 0 - x = (if isFrequency then Cons m1 acc else acc) + x = (if is_frequency then Cons(m1, acc) else acc) - makeMapHelp freq (n - 1) m1 x + make_map_help(freq, (n - 1), m1, x) fold : (a, b, omega -> omega), Tree a b, omega -> omega fold = \f, tree, b -> when tree is Leaf -> b - Node _ l k v r -> fold f r (f k v (fold f l b)) + Node(_, l, k, v, r) -> fold(f, r, f(k, v, fold(f, l, b))) main : Task {} [] main = - { value, isError } = PlatformTasks.getInt! - inputResult = - if isError then - Err GetIntError + { value, is_error } = PlatformTasks.get_int! + input_result = + if is_error then + Err(GetIntError) else - Ok value + Ok(value) - when inputResult is - Ok n -> + when input_result is + Ok(n) -> # original koka n = 4_200_000 ms : ConsList Map - ms = makeMap 5 n + ms = make_map(5, n) when ms is - Cons head _ -> - val = fold (\_, v, r -> if v then r + 1 else r) head 0 + Cons(head, _) -> + val = fold(\_, v, r -> if v then r + 1 else r, head, 0) val - |> Num.toStr - |> PlatformTasks.putLine + |> Num.to_str + |> PlatformTasks.put_line Nil -> - PlatformTasks.putLine "fail" + PlatformTasks.put_line("fail") - Err GetIntError -> - PlatformTasks.putLine "Error: Failed to get Integer from stdin." + Err(GetIntError) -> + PlatformTasks.put_line("Error: Failed to get Integer from stdin.") insert : Tree (Num k) v, Num k, v -> Tree (Num k) v -insert = \t, k, v -> if isRed t then setBlack (ins t k v) else ins t k v +insert = \t, k, v -> if is_red(t) then set_black(ins(t, k, v)) else ins(t, k, v) -setBlack : Tree a b -> Tree a b -setBlack = \tree -> +set_black : Tree a b -> Tree a b +set_black = \tree -> when tree is - Node _ l k v r -> Node Black l k v r + Node(_, l, k, v, r) -> Node(Black, l, k, v, r) _ -> tree -isRed : Tree a b -> Bool -isRed = \tree -> +is_red : Tree a b -> Bool +is_red = \tree -> when tree is - Node Red _ _ _ _ -> Bool.true + Node(Red, _, _, _, _) -> Bool.true _ -> Bool.false lt = \x, y -> x < y @@ -86,43 +86,43 @@ lt = \x, y -> x < y ins : Tree (Num k) v, Num k, v -> Tree (Num k) v ins = \tree, kx, vx -> when tree is - Leaf -> Node Red Leaf kx vx Leaf - Node Red a ky vy b -> - if lt kx ky then - Node Red (ins a kx vx) ky vy b - else if lt ky kx then - Node Red a ky vy (ins b kx vx) + Leaf -> Node(Red, Leaf, kx, vx, Leaf) + Node(Red, a, ky, vy, b) -> + if lt(kx, ky) then + Node(Red, ins(a, kx, vx), ky, vy, b) + else if lt(ky, kx) then + Node(Red, a, ky, vy, ins(b, kx, vx)) else - Node Red a ky vy (ins b kx vx) + Node(Red, a, ky, vy, ins(b, kx, vx)) - Node Black a ky vy b -> - if lt kx ky then - if isRed a then - balance1 (Node Black Leaf ky vy b) (ins a kx vx) + Node(Black, a, ky, vy, b) -> + if lt(kx, ky) then + if is_red(a) then + balance1(Node(Black, Leaf, ky, vy, b), ins(a, kx, vx)) else - Node Black (ins a kx vx) ky vy b - else if lt ky kx then - if isRed b then - balance2 (Node Black a ky vy Leaf) (ins b kx vx) + Node(Black, ins(a, kx, vx), ky, vy, b) + else if lt(ky, kx) then + if is_red(b) then + balance2(Node(Black, a, ky, vy, Leaf), ins(b, kx, vx)) else - Node Black a ky vy (ins b kx vx) + Node(Black, a, ky, vy, ins(b, kx, vx)) else - Node Black a kx vx b + Node(Black, a, kx, vx, b) balance1 : Tree a b, Tree a b -> Tree a b balance1 = \tree1, tree2 -> when tree1 is Leaf -> Leaf - Node _ _ kv vv t -> + Node(_, _, kv, vv, t) -> when tree2 is - Node _ (Node Red l kx vx r1) ky vy r2 -> - Node Red (Node Black l kx vx r1) ky vy (Node Black r2 kv vv t) + Node(_, Node(Red, l, kx, vx, r1), ky, vy, r2) -> + Node(Red, Node(Black, l, kx, vx, r1), ky, vy, Node(Black, r2, kv, vv, t)) - Node _ l1 ky vy (Node Red l2 kx vx r) -> - Node Red (Node Black l1 ky vy l2) kx vx (Node Black r kv vv t) + Node(_, l1, ky, vy, Node(Red, l2, kx, vx, r)) -> + Node(Red, Node(Black, l1, ky, vy, l2), kx, vx, Node(Black, r, kv, vv, t)) - Node _ l ky vy r -> - Node Black (Node Red l ky vy r) kv vv t + Node(_, l, ky, vy, r) -> + Node(Black, Node(Red, l, ky, vy, r), kv, vv, t) Leaf -> Leaf @@ -130,16 +130,16 @@ balance2 : Tree a b, Tree a b -> Tree a b balance2 = \tree1, tree2 -> when tree1 is Leaf -> Leaf - Node _ t kv vv _ -> + Node(_, t, kv, vv, _) -> when tree2 is - Node _ (Node Red l kx1 vx1 r1) ky vy r2 -> - Node Red (Node Black t kv vv l) kx1 vx1 (Node Black r1 ky vy r2) + Node(_, Node(Red, l, kx1, vx1, r1), ky, vy, r2) -> + Node(Red, Node(Black, t, kv, vv, l), kx1, vx1, Node(Black, r1, ky, vy, r2)) - Node _ l1 ky vy (Node Red l2 kx2 vx2 r2) -> - Node Red (Node Black t kv vv l1) ky vy (Node Black l2 kx2 vx2 r2) + Node(_, l1, ky, vy, Node(Red, l2, kx2, vx2, r2)) -> + Node(Red, Node(Black, t, kv, vv, l1), ky, vy, Node(Black, l2, kx2, vx2, r2)) - Node _ l ky vy r -> - Node Black t kv vv (Node Red l ky vy r) + Node(_, l, ky, vy, r) -> + Node(Black, t, kv, vv, Node(Red, l, ky, vy, r)) Leaf -> Leaf diff --git a/crates/cli/tests/benchmarks/rBTreeInsert.roc b/crates/cli/tests/benchmarks/rBTreeInsert.roc index e419d8ff940..c41225eec6a 100644 --- a/crates/cli/tests/benchmarks/rBTreeInsert.roc +++ b/crates/cli/tests/benchmarks/rBTreeInsert.roc @@ -5,41 +5,41 @@ import pf.PlatformTasks main : Task {} [] main = tree : RedBlackTree I64 {} - tree = insert 0 {} Empty + tree = insert(0, {}, Empty) tree |> show - |> PlatformTasks.putLine + |> PlatformTasks.put_line show : RedBlackTree I64 {} -> Str -show = \tree -> showRBTree tree Num.toStr (\{} -> "{}") +show = \tree -> show_rb_tree(tree, Num.to_str, \{} -> "{}") -showRBTree : RedBlackTree k v, (k -> Str), (v -> Str) -> Str -showRBTree = \tree, showKey, showValue -> +show_rb_tree : RedBlackTree k v, (k -> Str), (v -> Str) -> Str +show_rb_tree = \tree, show_key, show_value -> when tree is Empty -> "Empty" - Node color key value left right -> - sColor = showColor color - sKey = showKey key - sValue = showValue value - sL = nodeInParens left showKey showValue - sR = nodeInParens right showKey showValue + Node(color, key, value, left, right) -> + s_color = show_color(color) + s_key = show_key(key) + s_value = show_value(value) + s_l = node_in_parens(left, show_key, show_value) + s_r = node_in_parens(right, show_key, show_value) - "Node $(sColor) $(sKey) $(sValue) $(sL) $(sR)" + "Node $(s_color) $(s_key) $(s_value) $(s_l) $(s_r)" -nodeInParens : RedBlackTree k v, (k -> Str), (v -> Str) -> Str -nodeInParens = \tree, showKey, showValue -> +node_in_parens : RedBlackTree k v, (k -> Str), (v -> Str) -> Str +node_in_parens = \tree, show_key, show_value -> when tree is Empty -> - showRBTree tree showKey showValue + show_rb_tree(tree, show_key, show_value) - Node _ _ _ _ _ -> - inner = showRBTree tree showKey showValue + Node(_, _, _, _, _) -> + inner = show_rb_tree(tree, show_key, show_value) "($(inner))" -showColor : NodeColor -> Str -showColor = \color -> +show_color : NodeColor -> Str +show_color = \color -> when color is Red -> "Red" Black -> "Black" @@ -52,49 +52,51 @@ Key k : Num k insert : Key k, v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v insert = \key, value, dict -> - when insertHelp key value dict is - Node Red k v l r -> Node Black k v l r + when insert_help(key, value, dict) is + Node(Red, k, v, l, r) -> Node(Black, k, v, l, r) x -> x -insertHelp : Key k, v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v -insertHelp = \key, value, dict -> +insert_help : Key k, v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v +insert_help = \key, value, dict -> when dict is Empty -> # New nodes are always red. If it violates the rules, it will be fixed # when balancing. - Node Red key value Empty Empty + Node(Red, key, value, Empty, Empty) - Node nColor nKey nValue nLeft nRight -> - when Num.compare key nKey is - LT -> balance nColor nKey nValue (insertHelp key value nLeft) nRight - EQ -> Node nColor nKey value nLeft nRight - GT -> balance nColor nKey nValue nLeft (insertHelp key value nRight) + Node(n_color, n_key, n_value, n_left, n_right) -> + when Num.compare(key, n_key) is + LT -> balance(n_color, n_key, n_value, insert_help(key, value, n_left), n_right) + EQ -> Node(n_color, n_key, value, n_left, n_right) + GT -> balance(n_color, n_key, n_value, n_left, insert_help(key, value, n_right)) balance : NodeColor, k, v, RedBlackTree k v, RedBlackTree k v -> RedBlackTree k v balance = \color, key, value, left, right -> when right is - Node Red rK rV rLeft rRight -> + Node(Red, r_k, r_v, r_left, r_right) -> when left is - Node Red lK lV lLeft lRight -> - Node - Red - key - value - (Node Black lK lV lLeft lRight) - (Node Black rK rV rLeft rRight) + Node(Red, l_k, l_v, l_left, l_right) -> + Node( + Red, + key, + value, + Node(Black, l_k, l_v, l_left, l_right), + Node(Black, r_k, r_v, r_left, r_right), + ) _ -> - Node color rK rV (Node Red key value left rLeft) rRight + Node(color, r_k, r_v, Node(Red, key, value, left, r_left), r_right) _ -> when left is - Node Red lK lV (Node Red llK llV llLeft llRight) lRight -> - Node - Red - lK - lV - (Node Black llK llV llLeft llRight) - (Node Black key value lRight right) + Node(Red, l_k, l_v, Node(Red, ll_k, ll_v, ll_left, ll_right), l_right) -> + Node( + Red, + l_k, + l_v, + Node(Black, ll_k, ll_v, ll_left, ll_right), + Node(Black, key, value, l_right, right), + ) _ -> - Node color key value left right + Node(color, key, value, left, right) diff --git a/crates/cli/tests/benchmarks/testAStar.roc b/crates/cli/tests/benchmarks/testAStar.roc index 555787fe0a2..cb0de876713 100644 --- a/crates/cli/tests/benchmarks/testAStar.roc +++ b/crates/cli/tests/benchmarks/testAStar.roc @@ -4,10 +4,10 @@ import pf.PlatformTasks import AStar main = - PlatformTasks.putLine! (showBool test1) + PlatformTasks.put_line!(show_bool(test1)) -showBool : Bool -> Str -showBool = \b -> +show_bool : Bool -> Str +show_bool = \b -> if b then @@ -24,14 +24,14 @@ example1 = step : I64 -> Set I64 step = \n -> when n is - 1 -> Set.fromList [2, 3] - 2 -> Set.fromList [4] - 3 -> Set.fromList [4] - _ -> Set.fromList [] + 1 -> Set.from_list([2, 3]) + 2 -> Set.from_list([4]) + 3 -> Set.from_list([4]) + _ -> Set.from_list([]) cost : I64, I64 -> F64 cost = \_, _ -> 1 - when AStar.findPath cost step 1 4 is - Ok path -> path - Err _ -> [] + when AStar.find_path(cost, step, 1, 4) is + Ok(path) -> path + Err(_) -> [] diff --git a/crates/cli/tests/benchmarks/testBase64.roc b/crates/cli/tests/benchmarks/testBase64.roc index c93ed7748db..106c4d9b7b6 100644 --- a/crates/cli/tests/benchmarks/testBase64.roc +++ b/crates/cli/tests/benchmarks/testBase64.roc @@ -7,11 +7,11 @@ IO a : Task a [] main : IO {} main = - when Base64.fromBytes (Str.toUtf8 "Hello World") is - Err _ -> PlatformTasks.putLine "sadness" - Ok encoded -> - PlatformTasks.putLine! (Str.concat "encoded: " encoded) + when Base64.from_bytes(Str.to_utf8("Hello World")) is + Err(_) -> PlatformTasks.put_line("sadness") + Ok(encoded) -> + PlatformTasks.put_line!(Str.concat("encoded: ", encoded)) - when Base64.toStr encoded is - Ok decoded -> PlatformTasks.putLine (Str.concat "decoded: " decoded) - Err _ -> PlatformTasks.putLine "sadness" + when Base64.to_str(encoded) is + Ok(decoded) -> PlatformTasks.put_line(Str.concat("decoded: ", decoded)) + Err(_) -> PlatformTasks.put_line("sadness") diff --git a/crates/cli/tests/cli_tests.rs b/crates/cli/tests/cli_tests.rs index 5d0217d4bfc..88450bacb8e 100644 --- a/crates/cli/tests/cli_tests.rs +++ b/crates/cli/tests/cli_tests.rs @@ -213,7 +213,8 @@ mod cli_tests { } #[test] - #[cfg_attr(windows, ignore)] + // #[cfg_attr(windows, ignore)] + #[ignore] fn false_interpreter() { let cli_build = ExecCli::new( CMD_BUILD, @@ -877,7 +878,7 @@ mod cli_tests { ), ); - let expected_output = "(@Community {friends: [{2}, {2}, {0, 1}], people: [(@Person {age: 27, favoriteColor: Blue, firstName: \"John\", hasBeard: Bool.true, lastName: \"Smith\"}), (@Person {age: 47, favoriteColor: Green, firstName: \"Debby\", hasBeard: Bool.false, lastName: \"Johnson\"}), (@Person {age: 33, favoriteColor: (RGB (255, 255, 0)), firstName: \"Jane\", hasBeard: Bool.false, lastName: \"Doe\"})]})\n"; + let expected_output = "(@Community {friends: [{2}, {2}, {0, 1}], people: [(@Person {age: 27, favorite_color: Blue, first_name: \"John\", has_beard: Bool.true, last_name: \"Smith\"}), (@Person {age: 47, favorite_color: Green, first_name: \"Debby\", has_beard: Bool.false, last_name: \"Johnson\"}), (@Person {age: 33, favorite_color: (RGB (255, 255, 0)), first_name: \"Jane\", has_beard: Bool.false, last_name: \"Doe\"})]})\n"; cli_build.full_check_build_and_run( expected_output, @@ -988,7 +989,7 @@ mod cli_tests { ), ); - let expected_output = "notEffectful: hardcoded\neffectful: from stdin\n"; + let expected_output = "not_effectful: hardcoded\neffectful: from stdin\n"; cli_build.check_build_and_run( expected_output, diff --git a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__expects_test_failure.snap b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__expects_test_failure.snap index e0bd3cb0fd2..69e6dceddcb 100644 --- a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__expects_test_failure.snap +++ b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__expects_test_failure.snap @@ -1,6 +1,7 @@ --- source: crates/cli/tests/cli_tests.rs expression: cli_test_out.normalize_stdout_and_stderr() +snapshot_kind: text --- ── EXPECT FAILED in tests/test-projects/expects/expects.roc ──────────────────── @@ -31,7 +32,7 @@ a = 1 This expectation failed: 11│> expect -12│> a = makeA +12│> a = make_a 13│> b = 2i64 14│> 15│> a == b diff --git a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_arity_mismatch.snap b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_arity_mismatch.snap index b43bfdcbe5e..f3bc460c4df 100644 --- a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_arity_mismatch.snap +++ b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_arity_mismatch.snap @@ -6,10 +6,10 @@ snapshot_kind: text ── TOO MANY ARGS in tests/test-projects/module_params/arity_mismatch.roc ─────── -The getUser function expects 1 argument, but it got 2 instead: +The get_user function expects 1 argument, but it got 2 instead: -12│ $(Api.getUser 1 2) - ^^^^^^^^^^^ +12│ $(Api.get_user(1, 2)) + ^^^^^^^^^^^^ Are there any missing commas? Or missing parentheses? @@ -18,18 +18,18 @@ Are there any missing commas? Or missing parentheses? This value is not a function, but it was given 1 argument: -13│ $(Api.baseUrl 1) - ^^^^^^^^^^^ +13│ $(Api.base_url(1)) + ^^^^^^^^^^^^ Are there any missing commas? Or missing parentheses? ── TOO FEW ARGS in tests/test-projects/module_params/arity_mismatch.roc ──────── -The getPostComment function expects 2 arguments, but it got only 1: +The get_post_comment function expects 2 arguments, but it got only 1: -16│ $(Api.getPostComment 1) - ^^^^^^^^^^^^^^^^^^ +16│ $(Api.get_post_comment(1)) + ^^^^^^^^^^^^^^^^^^^^ Roc does not allow functions to be partially applied. Use a closure to make partial application explicit. diff --git a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_bad_ann.snap b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_bad_ann.snap index 6abc4bcf2bd..70259aade42 100644 --- a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_bad_ann.snap +++ b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_bad_ann.snap @@ -6,34 +6,35 @@ snapshot_kind: text ── TYPE MISMATCH in tests/test-projects/module_params/BadAnn.roc ─────────────── -Something is off with the body of the fnAnnotatedAsValue definition: +Something is off with the body of the +fn_annotated_as_value definition: -3│ fnAnnotatedAsValue : Str -4│> fnAnnotatedAsValue = \postId, commentId -> -5│> "/posts/$(postId)/comments/$(Num.toStr commentId)" +3│ fn_annotated_as_value : Str +4│> fn_annotated_as_value = \post_id, comment_id -> +5│> "/posts/$(post_id)/comments/$(Num.to_str(comment_id))" The body is an anonymous function of type: Str, Num * -> Str -But the type annotation on fnAnnotatedAsValue says it should be: +But the type annotation on fn_annotated_as_value says it should be: Str ── TYPE MISMATCH in tests/test-projects/module_params/BadAnn.roc ─────────────── -Something is off with the body of the missingArg definition: +Something is off with the body of the missing_arg definition: -7│ missingArg : Str -> Str -8│> missingArg = \postId, _ -> -9│> "/posts/$(postId)/comments" +7│ missing_arg : Str -> Str +8│> missing_arg = \post_id, _ -> +9│> "/posts/$(post_id)/comments" The body is an anonymous function of type: (Str, ? -> Str) -But the type annotation on missingArg says it should be: +But the type annotation on missing_arg says it should be: (Str -> Str) diff --git a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_unexpected_fn.snap b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_unexpected_fn.snap index 55ed00e6a1a..61baf2e53ec 100644 --- a/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_unexpected_fn.snap +++ b/crates/cli/tests/snapshots/cli_tests__cli_tests__test_platform_simple_zig__module_params_unexpected_fn.snap @@ -8,9 +8,8 @@ snapshot_kind: text This argument to this string interpolation has an unexpected type: -10│ """ -11│> $(Api.getPost) -12│ """ +10│ "$(Api.get_post)" + ^^^^^^^^^^^^ The argument is an anonymous function of type: diff --git a/crates/cli/tests/test-projects/algorithms/fibonacci-platform/host.zig b/crates/cli/tests/test-projects/algorithms/fibonacci-platform/host.zig index 47e33d8bbd4..cd3d86499e3 100644 --- a/crates/cli/tests/test-projects/algorithms/fibonacci-platform/host.zig +++ b/crates/cli/tests/test-projects/algorithms/fibonacci-platform/host.zig @@ -11,8 +11,8 @@ const mem = std.mem; const Allocator = mem.Allocator; // NOTE the LLVM backend expects this signature -// extern fn roc__mainForHost_1_exposed(i64, *i64) void; -extern fn roc__mainForHost_1_exposed(i64) i64; +// extern fn roc__main_for_host_1_exposed(i64, *i64) void; +extern fn roc__main_for_host_1_exposed(i64) i64; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -110,7 +110,7 @@ comptime { pub export fn main() u8 { const stdout = std.io.getStdOut().writer(); - const result = roc__mainForHost_1_exposed(10); + const result = roc__main_for_host_1_exposed(10); stdout.print("{d}\n", .{result}) catch unreachable; diff --git a/crates/cli/tests/test-projects/algorithms/fibonacci-platform/main.roc b/crates/cli/tests/test-projects/algorithms/fibonacci-platform/main.roc index daaf2ff5c85..722540f8092 100644 --- a/crates/cli/tests/test-projects/algorithms/fibonacci-platform/main.roc +++ b/crates/cli/tests/test-projects/algorithms/fibonacci-platform/main.roc @@ -3,7 +3,7 @@ platform "fibonacci" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : I64 -> I64 -mainForHost = \a -> main a +main_for_host : I64 -> I64 +main_for_host = \a -> main(a) diff --git a/crates/cli/tests/test-projects/algorithms/fibonacci.roc b/crates/cli/tests/test-projects/algorithms/fibonacci.roc index cee96929eb5..b8f574b38ca 100644 --- a/crates/cli/tests/test-projects/algorithms/fibonacci.roc +++ b/crates/cli/tests/test-projects/algorithms/fibonacci.roc @@ -1,10 +1,10 @@ app [main] { pf: platform "fibonacci-platform/main.roc" } -main = \n -> fib n 0 1 +main = \n -> fib(n, 0, 1) # the clever implementation requires join points fib = \n, a, b -> if n == 0 then a else - fib (n - 1) b (a + b) + fib((n - 1), b, (a + b)) diff --git a/crates/cli/tests/test-projects/algorithms/quicksort-platform/host.zig b/crates/cli/tests/test-projects/algorithms/quicksort-platform/host.zig index 06b015c6907..7e2ad538dd3 100644 --- a/crates/cli/tests/test-projects/algorithms/quicksort-platform/host.zig +++ b/crates/cli/tests/test-projects/algorithms/quicksort-platform/host.zig @@ -9,7 +9,7 @@ const expect = testing.expect; const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed(input: RocList) callconv(.C) RocList; +extern fn roc__main_for_host_1_exposed(input: RocList) callconv(.C) RocList; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -128,7 +128,7 @@ pub export fn main() u8 { const roc_list = RocList{ .elements = numbers, .length = NUM_NUMS, .capacity = NUM_NUMS }; // actually call roc to populate the callresult - const callresult: RocList = roc__mainForHost_1_exposed(roc_list); + const callresult: RocList = roc__main_for_host_1_exposed(roc_list); // stdout the result const length = @min(20, callresult.length); diff --git a/crates/cli/tests/test-projects/algorithms/quicksort-platform/main.roc b/crates/cli/tests/test-projects/algorithms/quicksort-platform/main.roc index 37c5db99abe..8b2426b83a9 100644 --- a/crates/cli/tests/test-projects/algorithms/quicksort-platform/main.roc +++ b/crates/cli/tests/test-projects/algorithms/quicksort-platform/main.roc @@ -3,7 +3,7 @@ platform "quicksort" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : List I64 -> List I64 -mainForHost = \list -> quicksort list +main_for_host : List I64 -> List I64 +main_for_host = \list -> quicksort(list) diff --git a/crates/cli/tests/test-projects/algorithms/quicksort.roc b/crates/cli/tests/test-projects/algorithms/quicksort.roc index 7e62e4bbd0e..5a24537938e 100644 --- a/crates/cli/tests/test-projects/algorithms/quicksort.roc +++ b/crates/cli/tests/test-projects/algorithms/quicksort.roc @@ -1,54 +1,54 @@ app [quicksort] { pf: platform "quicksort-platform/main.roc" } -quicksort = \originalList -> - n = List.len originalList +quicksort = \original_list -> + n = List.len(original_list) - quicksortHelp originalList 0 (n - 1) + quicksort_help(original_list, 0, (n - 1)) -quicksortHelp : List (Num a), U64, U64 -> List (Num a) -quicksortHelp = \list, low, high -> +quicksort_help : List (Num a), U64, U64 -> List (Num a) +quicksort_help = \list, low, high -> if low < high then - when partition low high list is - Pair partitionIndex partitioned -> + when partition(low, high, list) is + Pair(partition_index, partitioned) -> partitioned - |> quicksortHelp low (partitionIndex - 1) - |> quicksortHelp (partitionIndex + 1) high + |> quicksort_help(low, (partition_index - 1)) + |> quicksort_help((partition_index + 1), high) else list partition : U64, U64, List (Num a) -> [Pair U64 (List (Num a))] -partition = \low, high, initialList -> - when List.get initialList high is - Ok pivot -> - when partitionHelp low low initialList high pivot is - Pair newI newList -> - Pair newI (swap newI high newList) - - Err _ -> - Pair low initialList - -partitionHelp : U64, U64, List (Num c), U64, Num c -> [Pair U64 (List (Num c))] -partitionHelp = \i, j, list, high, pivot -> +partition = \low, high, initial_list -> + when List.get(initial_list, high) is + Ok(pivot) -> + when partition_help(low, low, initial_list, high, pivot) is + Pair(new_i, new_list) -> + Pair(new_i, swap(new_i, high, new_list)) + + Err(_) -> + Pair(low, initial_list) + +partition_help : U64, U64, List (Num c), U64, Num c -> [Pair U64 (List (Num c))] +partition_help = \i, j, list, high, pivot -> if j < high then - when List.get list j is - Ok value -> + when List.get(list, j) is + Ok(value) -> if value <= pivot then - partitionHelp (i + 1) (j + 1) (swap i j list) high pivot + partition_help((i + 1), (j + 1), swap(i, j, list), high, pivot) else - partitionHelp i (j + 1) list high pivot + partition_help(i, (j + 1), list, high, pivot) - Err _ -> - Pair i list + Err(_) -> + Pair(i, list) else - Pair i list + Pair(i, list) swap : U64, U64, List a -> List a swap = \i, j, list -> - when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + when Pair(List.get(list, i), List.get(list, j)) is + Pair(Ok(at_i), Ok(at_j)) -> list - |> List.set i atJ - |> List.set j atI + |> List.set(i, at_j) + |> List.set(j, at_i) _ -> # to prevent a decrement on list diff --git a/crates/cli/tests/test-projects/effectful/Community.roc b/crates/cli/tests/test-projects/effectful/Community.roc index e19906a8f66..5fcada82f98 100644 --- a/crates/cli/tests/test-projects/effectful/Community.roc +++ b/crates/cli/tests/test-projects/effectful/Community.roc @@ -1,10 +1,10 @@ module [ Community, empty, - addPerson, - addFriend, + add_person, + add_friend, Person, - walkFriendNames, + walk_friend_names, ] ## Datatype representing a community for demonstration purposes in inspect-gui.roc and inspect-logging.roc @@ -16,11 +16,11 @@ Community := { implements [Inspect] Person := { - firstName : Str, - lastName : Str, + first_name : Str, + last_name : Str, age : U8, - hasBeard : Bool, - favoriteColor : Color, + has_beard : Bool, + favorite_color : Color, } implements [Inspect] @@ -31,52 +31,52 @@ Color : [ RGB (U8, U8, U8), ] -empty = @Community { people: [], friends: [] } +empty = @Community({ people: [], friends: [] }) -addPerson = \@Community { people, friends }, person -> - @Community { - people: List.append people (@Person person), - friends: List.append friends (Set.empty {}), - } +add_person = \@Community({ people, friends }), person -> + @Community({ + people: List.append(people, @Person(person)), + friends: List.append(friends, Set.empty({})), + }) -addFriend = \@Community { people, friends }, from, to -> - when (List.get friends from, List.get friends to) is - (Ok fromSet, Ok toSet) -> - @Community { +add_friend = \@Community({ people, friends }), from, to -> + when (List.get(friends, from), List.get(friends, to)) is + (Ok(from_set), Ok(to_set)) -> + @Community({ people, friends: friends - |> List.set from (Set.insert fromSet to) - |> List.set to (Set.insert toSet from), - } + |> List.set(from, Set.insert(from_set, to)) + |> List.set(to, Set.insert(to_set, from)), + }) _ -> - @Community { people, friends } + @Community({ people, friends }) -walkFriendNames : Community, state, (state, Str, Set Str -> state) -> state -walkFriendNames = \@Community { people, friends }, s0, nextFn -> +walk_friend_names : Community, state, (state, Str, Set Str -> state) -> state +walk_friend_names = \@Community({ people, friends }), s0, next_fn -> (out, _) = - List.walk friends (s0, 0) \(s1, id), friendSet -> - (@Person person) = - when List.get people id is - Ok v -> v - Err _ -> crash "Unknown Person" - personName = - person.firstName - |> Str.concat " " - |> Str.concat person.lastName + List.walk(friends, (s0, 0), \(s1, id), friend_set -> + @Person(person) = + when List.get(people, id) is + Ok(v) -> v + Err(_) -> crash("Unknown Person") + person_name = + person.first_name + |> Str.concat(" ") + |> Str.concat(person.last_name) - friendNames = - Set.walk friendSet (Set.empty {}) \friendsSet, friendId -> - (@Person friend) = - when List.get people friendId is - Ok v -> v - Err _ -> crash "Unknown Person" - friendName = - friend.firstName - |> Str.concat " " - |> Str.concat friend.lastName - Set.insert friendsSet friendName + friend_names = + Set.walk(friend_set, Set.empty({}), \friends_set, friend_id -> + @Person(friend) = + when List.get(people, friend_id) is + Ok(v) -> v + Err(_) -> crash("Unknown Person") + friend_name = + friend.first_name + |> Str.concat(" ") + |> Str.concat(friend.last_name) + Set.insert(friends_set, friend_name)) - (nextFn s1 personName friendNames, id + 1) + (next_fn(s1, person_name, friend_names), id + 1)) out diff --git a/crates/cli/tests/test-projects/effectful/combine-tasks.roc b/crates/cli/tests/test-projects/effectful/combine-tasks.roc index f801791df43..576275e925c 100644 --- a/crates/cli/tests/test-projects/effectful/combine-tasks.roc +++ b/crates/cli/tests/test-projects/effectful/combine-tasks.roc @@ -3,19 +3,19 @@ app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/downlo import pf.Stdout main = - multipleIn = + multiple_in = { sequential <- - a: Task.ok 123, - b: Task.ok "abc", - c: Task.ok [123], - _d: Task.ok ["abc"], - _: Task.ok (Dict.single "a" "b"), + a: Task.ok(123), + b: Task.ok("abc"), + c: Task.ok([123]), + _d: Task.ok(["abc"]), + _: Task.ok(Dict.single("a", "b")), }! - Stdout.line! "For multiple tasks: $(Inspect.toStr multipleIn)" + Stdout.line!("For multiple tasks: $(Inspect.to_str(multiple_in))") sequential : Task a err, Task b err, (a, b -> c) -> Task c err -sequential = \firstTask, secondTask, mapper -> - first = firstTask! - second = secondTask! - Task.ok (mapper first second) +sequential = \first_task, second_task, mapper -> + first = first_task! + second = second_task! + Task.ok(mapper(first, second)) diff --git a/crates/cli/tests/test-projects/effectful/echo.roc b/crates/cli/tests/test-projects/effectful/echo.roc index c3c51c1dfcd..047d3783dd9 100644 --- a/crates/cli/tests/test-projects/effectful/echo.roc +++ b/crates/cli/tests/test-projects/effectful/echo.roc @@ -3,33 +3,33 @@ app [main!] { pf: platform "../test-platform-effects-zig/main.roc" } import pf.Effect main! : {} => {} -main! = \{} -> tick! {} +main! = \{} -> tick!({}) tick! = \{} -> - line = Effect.getLine! {} + line = Effect.get_line!({}) - if !(Str.isEmpty line) then - Effect.putLine! (echo line) + if !(Str.is_empty(line)) then + Effect.put_line!(echo(line)) else - Effect.putLine! "Received no input." + Effect.put_line!("Received no input.") echo : Str -> Str echo = \shout -> - silence = \length -> List.repeat ' ' length + silence = \length -> List.repeat(' ', length) shout - |> Str.toUtf8 - |> List.mapWithIndex \_, i -> - length = (List.len (Str.toUtf8 shout) - i) - phrase = (List.splitAt (Str.toUtf8 shout) length).before + |> Str.to_utf8 + |> List.map_with_index(\_, i -> + length = (List.len(Str.to_utf8(shout)) - i) + phrase = (List.split_at(Str.to_utf8(shout), length)).before - List.concat (silence (if i == 0 then 2 * length else length)) phrase + List.concat(silence((if i == 0 then 2 * length else length)), phrase)) |> List.join - |> Str.fromUtf8 - |> Result.withDefault "" + |> Str.from_utf8 + |> Result.with_default("") expect message = "hello!" - echoedMessage = echo message + echoed_message = echo(message) - echoedMessage == " hello! hello hell hel he h" + echoed_message == " hello! hello hell hel he h" diff --git a/crates/cli/tests/test-projects/effectful/for_each_try.roc b/crates/cli/tests/test-projects/effectful/for_each_try.roc index a6a219c4282..e7f67091631 100644 --- a/crates/cli/tests/test-projects/effectful/for_each_try.roc +++ b/crates/cli/tests/test-projects/effectful/for_each_try.roc @@ -4,20 +4,19 @@ import pf.Effect main! : {} => {} main! = \{} -> - good = [0, 2, 4] |> List.forEachTry! validate! - expect good == Ok {} + good = [0, 2, 4] |> List.for_each_try!(validate!) + expect good == Ok({}) - bad = [6, 8, 9, 10] |> List.forEachTry! validate! - expect bad == Err 9 + bad = [6, 8, 9, 10] |> List.for_each_try!(validate!) + expect bad == Err(9) {} validate! : U32 => Result {} U32 validate! = \x -> - if Num.isEven x then - Effect.putLine! "✅ $(Num.toStr x)" - Ok {} - + if Num.is_even(x) then + Effect.put_line!("✅ $(Num.to_str(x))") + Ok({}) else - Effect.putLine! "$(Num.toStr x) is not even! ABORT!" - Err x + Effect.put_line!("$(Num.to_str(x)) is not even! ABORT!") + Err(x) diff --git a/crates/cli/tests/test-projects/effectful/form.roc b/crates/cli/tests/test-projects/effectful/form.roc index dd0a9b773fa..0f57f2a82bb 100644 --- a/crates/cli/tests/test-projects/effectful/form.roc +++ b/crates/cli/tests/test-projects/effectful/form.roc @@ -4,24 +4,24 @@ import pf.Effect main! : {} => {} main! = \{} -> - first = ask! "What's your first name?" - last = ask! "What's your last name?" + first = ask!("What's your first name?") + last = ask!("What's your last name?") - Effect.putLine! "\nHi, $(first) $(last)!\n" + Effect.put_line!("\nHi, $(first) $(last)!\n") - when Str.toU8 (ask! "How old are you?") is - Err InvalidNumStr -> - Effect.putLine! "Enter a valid number" + when Str.to_u8(ask!("How old are you?")) is + Err(InvalidNumStr) -> + Effect.put_line!("Enter a valid number") - Ok age if age >= 18 -> - Effect.putLine! "\nNice! You can vote!" + Ok(age) if age >= 18 -> + Effect.put_line!("\nNice! You can vote!") - Ok age -> - Effect.putLine! "\nYou'll be able to vote in $(Num.toStr (18 - age)) years" + Ok(age) -> + Effect.put_line!("\nYou'll be able to vote in $(Num.to_str((18 - age))) years") - Effect.putLine! "\nBye! 👋" + Effect.put_line!("\nBye! 👋") ask! : Str => Str ask! = \question -> - Effect.putLine! question - Effect.getLine! {} + Effect.put_line!(question) + Effect.get_line!({}) diff --git a/crates/cli/tests/test-projects/effectful/hello.roc b/crates/cli/tests/test-projects/effectful/hello.roc index 998ab4f8638..8a856861502 100644 --- a/crates/cli/tests/test-projects/effectful/hello.roc +++ b/crates/cli/tests/test-projects/effectful/hello.roc @@ -4,4 +4,4 @@ import pf.Effect main! : {} => {} main! = \{} -> - Effect.putLine! "I'm an effect 👻" + Effect.put_line!("I'm an effect 👻") diff --git a/crates/cli/tests/test-projects/effectful/ignore_result.roc b/crates/cli/tests/test-projects/effectful/ignore_result.roc index 828d24a73bd..9d9627fd12f 100644 --- a/crates/cli/tests/test-projects/effectful/ignore_result.roc +++ b/crates/cli/tests/test-projects/effectful/ignore_result.roc @@ -4,5 +4,5 @@ import pf.Effect main! : {} => {} main! = \{} -> - _ = Effect.getLine! {} - Effect.putLine! "I asked for input and I ignored it. Deal with it! 😎" + _ = Effect.get_line!({}) + Effect.put_line!("I asked for input and I ignored it. Deal with it! 😎") diff --git a/crates/cli/tests/test-projects/effectful/inspect-logging.roc b/crates/cli/tests/test-projects/effectful/inspect-logging.roc index eaa0cdd458f..06380f091e1 100644 --- a/crates/cli/tests/test-projects/effectful/inspect-logging.roc +++ b/crates/cli/tests/test-projects/effectful/inspect-logging.roc @@ -8,28 +8,28 @@ import Community main! = \{} -> Community.empty - |> Community.addPerson { - firstName: "John", - lastName: "Smith", + |> Community.add_person({ + first_name: "John", + last_name: "Smith", age: 27, - hasBeard: Bool.true, - favoriteColor: Blue, - } - |> Community.addPerson { - firstName: "Debby", - lastName: "Johnson", + has_beard: Bool.true, + favorite_color: Blue, + }) + |> Community.add_person({ + first_name: "Debby", + last_name: "Johnson", age: 47, - hasBeard: Bool.false, - favoriteColor: Green, - } - |> Community.addPerson { - firstName: "Jane", - lastName: "Doe", + has_beard: Bool.false, + favorite_color: Green, + }) + |> Community.add_person({ + first_name: "Jane", + last_name: "Doe", age: 33, - hasBeard: Bool.false, - favoriteColor: RGB (255, 255, 0), - } - |> Community.addFriend 0 2 - |> Community.addFriend 1 2 - |> Inspect.toStr - |> Effect.putLine! + has_beard: Bool.false, + favorite_color: RGB((255, 255, 0)), + }) + |> Community.add_friend(0, 2) + |> Community.add_friend(1, 2) + |> Inspect.to_str + |> Effect.put_line! diff --git a/crates/cli/tests/test-projects/effectful/loops.roc b/crates/cli/tests/test-projects/effectful/loops.roc index 170b1652f39..cb3b77199b1 100644 --- a/crates/cli/tests/test-projects/effectful/loops.roc +++ b/crates/cli/tests/test-projects/effectful/loops.roc @@ -5,12 +5,12 @@ import pf.Effect main! : {} => {} main! = \{} -> friends = ["Lu", "Marce", "Joaquin", "Chloé", "Mati", "Pedro"] - printAll! friends + print_all!(friends) -printAll! : List Str => {} -printAll! = \friends -> +print_all! : List Str => {} +print_all! = \friends -> when friends is [] -> {} [first, .. as remaining] -> - Effect.putLine! first - printAll! remaining + Effect.put_line!(first) + print_all!(remaining) diff --git a/crates/cli/tests/test-projects/effectful/on_err.roc b/crates/cli/tests/test-projects/effectful/on_err.roc index a8c4df24d8a..84370a40cdf 100644 --- a/crates/cli/tests/test-projects/effectful/on_err.roc +++ b/crates/cli/tests/test-projects/effectful/on_err.roc @@ -5,20 +5,20 @@ import pf.Effect main! : {} => {} main! = \{} -> _ = - authenticate! {} - |> Result.onErr! \BadPass -> - Effect.putLine! "LOG: Failed login attempt" - Ok "Bad password" + authenticate!({}) + |> Result.on_err!(\BadPass -> + Effect.put_line!("LOG: Failed login attempt") + Ok("Bad password")) {} authenticate! : {} => Result Str [BadPass] authenticate! = \{} -> - Effect.putLine! "Enter your password:" + Effect.put_line!("Enter your password:") - password = Effect.getLine! {} + password = Effect.get_line!({}) if password == "password" then - Ok "You are in" + Ok("You are in") else - Err BadPass + Err(BadPass) diff --git a/crates/cli/tests/test-projects/effectful/print-line.roc b/crates/cli/tests/test-projects/effectful/print-line.roc index b691400c452..64a55709344 100644 --- a/crates/cli/tests/test-projects/effectful/print-line.roc +++ b/crates/cli/tests/test-projects/effectful/print-line.roc @@ -5,15 +5,15 @@ import pf.Effect main! : {} => {} main! = \{} -> ["Welcome!", "What's your name?"] - |> List.forEach! Effect.putLine! + |> List.for_each!(Effect.put_line!) - line = Effect.getLine! {} + line = Effect.get_line!({}) if line == "secret" then - Effect.putLine! "You found the secret" - Effect.putLine! "Congratulations!" + Effect.put_line!("You found the secret") + Effect.put_line!("Congratulations!") else {} - Effect.putLine! "You entered: $(line)" - Effect.putLine! "It is known" + Effect.put_line!("You entered: $(line)") + Effect.put_line!("It is known") diff --git a/crates/cli/tests/test-projects/effectful/suffixed_record_field.roc b/crates/cli/tests/test-projects/effectful/suffixed_record_field.roc index f329cdbcb5a..c417a2388cb 100644 --- a/crates/cli/tests/test-projects/effectful/suffixed_record_field.roc +++ b/crates/cli/tests/test-projects/effectful/suffixed_record_field.roc @@ -3,20 +3,20 @@ app [main!] { pf: platform "../test-platform-effects-zig/main.roc" } import pf.Effect Fx : { - getLine!: {} => Str, + get_line! : {} => Str, } main! : {} => {} main! = \{} -> - notEffectful : Fx - notEffectful = { - getLine!: \{} -> "hardcoded" + not_effectful : Fx + not_effectful = { + get_line!: \{} -> "hardcoded", } effectful : Fx effectful = { - getLine!: Effect.getLine! + get_line!: Effect.get_line!, } - Effect.putLine! "notEffectful: $(notEffectful.getLine! {})" - Effect.putLine! "effectful: $(effectful.getLine! {})" + Effect.put_line!("not_effectful: $(not_effectful.get_line!({}))") + Effect.put_line!("effectful: $(effectful.get_line!({}))") diff --git a/crates/cli/tests/test-projects/effectful/untyped_passed_fx.roc b/crates/cli/tests/test-projects/effectful/untyped_passed_fx.roc index 98c4ad1fc90..5e2ef0f030a 100644 --- a/crates/cli/tests/test-projects/effectful/untyped_passed_fx.roc +++ b/crates/cli/tests/test-projects/effectful/untyped_passed_fx.roc @@ -4,9 +4,9 @@ import pf.Effect main! : {} => {} main! = \{} -> - logged! "hello" (\{} -> Effect.putLine! "Hello, World!") + logged!("hello", \{} -> Effect.put_line!("Hello, World!")) logged! = \name, fx! -> - Effect.putLine! "Before $(name)" - fx! {} - Effect.putLine! "After $(name)" + Effect.put_line!("Before $(name)") + fx!({}) + Effect.put_line!("After $(name)") diff --git a/crates/cli/tests/test-projects/expects/expects.roc b/crates/cli/tests/test-projects/expects/expects.roc index 0e9a57c0df9..7a64bc80741 100644 --- a/crates/cli/tests/test-projects/expects/expects.roc +++ b/crates/cli/tests/test-projects/expects/expects.roc @@ -1,6 +1,6 @@ app [main] { pf: platform "../test-platform-simple-zig/main.roc" } -makeA = +make_a = a = 1 expect a == 2 @@ -9,29 +9,29 @@ makeA = a expect - a = makeA + a = make_a b = 2i64 a == b -polyDbg = \x -> - dbg x +poly_dbg = \x -> + dbg(x) x main = str = "this will for sure be a large string so when we split it it will use seamless slices which affect printing" - words = Str.splitOn str " " + words = Str.split_on(str, " ") expect words == [] x = 42 - dbg x + dbg(x) - dbg "Fjoer en ferdjer frieten oan dyn geve lea" + dbg("Fjoer en ferdjer frieten oan dyn geve lea") - dbg "this is line 24" + dbg("this is line 24") - r = { x: polyDbg "abc", y: polyDbg 10u8, z: polyDbg (A (B C)) } + r = { x: poly_dbg("abc"), y: poly_dbg(10u8), z: poly_dbg(A(B(C))) } when r is _ -> "Program finished!\n" diff --git a/crates/cli/tests/test-projects/expects_transitive/Direct.roc b/crates/cli/tests/test-projects/expects_transitive/Direct.roc index 9e9d22ba723..d7d50ccad16 100644 --- a/crates/cli/tests/test-projects/expects_transitive/Direct.roc +++ b/crates/cli/tests/test-projects/expects_transitive/Direct.roc @@ -1,12 +1,12 @@ module [ - addAndStringify, + add_and_stringify, ] import Transitive -addAndStringify = \num1, num2 -> - Num.toStr (Transitive.add num1 num2) +add_and_stringify = \num1, num2 -> + Num.to_str(Transitive.add(num1, num2)) -expect addAndStringify 1 2 == "3" +expect add_and_stringify(1, 2) == "3" -expect addAndStringify 3 4 == "7" +expect add_and_stringify(3, 4) == "7" diff --git a/crates/cli/tests/test-projects/expects_transitive/Transitive.roc b/crates/cli/tests/test-projects/expects_transitive/Transitive.roc index 925c95d0e7c..db77221bae4 100644 --- a/crates/cli/tests/test-projects/expects_transitive/Transitive.roc +++ b/crates/cli/tests/test-projects/expects_transitive/Transitive.roc @@ -4,4 +4,4 @@ module [ add = \num1, num2 -> (num1 + num2) -expect add 1 2 == 3 +expect add(1, 2) == 3 diff --git a/crates/cli/tests/test-projects/false-interpreter/Context.roc b/crates/cli/tests/test-projects/false-interpreter/Context.roc index 99a4af99c8f..f0525deba20 100644 --- a/crates/cli/tests/test-projects/false-interpreter/Context.roc +++ b/crates/cli/tests/test-projects/false-interpreter/Context.roc @@ -1,4 +1,4 @@ -module [Context, Data, with!, getChar!, Option, pushStack, popStack, toStr, inWhileScope] +module [Context, Data, with!, get_char!, Option, push_stack, pop_stack, to_str, in_while_scope] import pf.File import Variable exposing [Variable] @@ -9,100 +9,100 @@ Option a : [Some a, None] Data : [Lambda (List U8), Number I32, Var Variable] # While loops are special and have their own Scope specific state. WhileState : { cond : List U8, body : List U8, state : [InCond, InBody] } -Scope : { data : Option File.Handle, index : U64, buf : List U8, whileInfo : Option WhileState } +Scope : { data : Option File.Handle, index : U64, buf : List U8, while_info : Option WhileState } State : [Executing, InComment, InLambda U64 (List U8), InString (List U8), InNumber I32, InSpecialChar, LoadChar] Context : { scopes : List Scope, stack : List Data, vars : List Data, state : State } -pushStack : Context, Data -> Context -pushStack = \ctx, data -> - { ctx & stack: List.append ctx.stack data } +push_stack : Context, Data -> Context +push_stack = \ctx, data -> + { ctx & stack: List.append(ctx.stack, data) } # I think an open tag union should just work here. # Instead at a call sites, I need to match on the error and then return the same error. # Otherwise it hits unreachable code in ir.rs -popStack : Context -> Result (Context, Data) [EmptyStack] -popStack = \ctx -> - when List.last ctx.stack is - Ok val -> - poppedCtx = { ctx & stack: List.dropAt ctx.stack (List.len ctx.stack - 1) } +pop_stack : Context -> Result (Context, Data) [EmptyStack] +pop_stack = \ctx -> + when List.last(ctx.stack) is + Ok(val) -> + popped_ctx = { ctx & stack: List.drop_at(ctx.stack, (List.len(ctx.stack) - 1)) } - Ok (poppedCtx, val) + Ok((popped_ctx, val)) - Err ListWasEmpty -> - Err EmptyStack + Err(ListWasEmpty) -> + Err(EmptyStack) -toStrData : Data -> Str -toStrData = \data -> +to_str_data : Data -> Str +to_str_data = \data -> when data is - Lambda _ -> "[]" - Number n -> Num.toStr (Num.intCast n) - Var v -> Variable.toStr v + Lambda(_) -> "[]" + Number(n) -> Num.to_str(Num.int_cast(n)) + Var(v) -> Variable.to_str(v) -toStrState : State -> Str -toStrState = \state -> +to_str_state : State -> Str +to_str_state = \state -> when state is Executing -> "Executing" InComment -> "InComment" - InString _ -> "InString" - InNumber _ -> "InNumber" - InLambda _ _ -> "InLambda" + InString(_) -> "InString" + InNumber(_) -> "InNumber" + InLambda(_, _) -> "InLambda" InSpecialChar -> "InSpecialChar" LoadChar -> "LoadChar" -toStr : Context -> Str -toStr = \{ scopes, stack, state, vars } -> - depth = Num.toStr (List.len scopes) - stateStr = toStrState state - stackStr = Str.joinWith (List.map stack toStrData) " " - varsStr = Str.joinWith (List.map vars toStrData) " " +to_str : Context -> Str +to_str = \{ scopes, stack, state, vars } -> + depth = Num.to_str(List.len(scopes)) + state_str = to_str_state(state) + stack_str = Str.join_with(List.map(stack, to_str_data), " ") + vars_str = Str.join_with(List.map(vars, to_str_data), " ") - "\n============\nDepth: $(depth)\nState: $(stateStr)\nStack: [$(stackStr)]\nVars: [$(varsStr)]\n============\n" + "\n============\nDepth: $(depth)\nState: $(state_str)\nStack: [$(stack_str)]\nVars: [$(vars_str)]\n============\n" with! : Str, (Context => a) => a with! = \path, callback! -> - File.withOpen! path \handle -> + File.with_open!(path, \handle -> # I cant define scope here and put it in the list in callback. It breaks alias anaysis. # Instead I have to inline this. # root_scope = { data: Some handle, index: 0, buf: [], whileInfo: None } - callback! { scopes: [{ data: Some handle, index: 0, buf: [], whileInfo: None }], state: Executing, stack: [], vars: List.repeat (Number 0) Variable.totalCount } + callback!({ scopes: [{ data: Some(handle), index: 0, buf: [], while_info: None }], state: Executing, stack: [], vars: List.repeat(Number(0), Variable.total_count) })) # I am pretty sure there is a syntax to destructure and keep a reference to the whole, but Im not sure what it is. -getChar! : Context => Result (U8, Context) [EndOfData, NoScope] -getChar! = \ctx -> - when List.last ctx.scopes is - Ok scope -> - (val, newScope) = getCharScope!? scope - Ok (val, { ctx & scopes: List.set ctx.scopes (List.len ctx.scopes - 1) newScope }) - - Err ListWasEmpty -> - Err NoScope - -getCharScope! : Scope => Result (U8, Scope) [EndOfData, NoScope] -getCharScope! = \scope -> - when List.get scope.buf scope.index is - Ok val -> - Ok (val, { scope & index: scope.index + 1 }) - - Err OutOfBounds -> +get_char! : Context => Result (U8, Context) [EndOfData, NoScope] +get_char! = \ctx -> + when List.last(ctx.scopes) is + Ok(scope) -> + (val, new_scope) = get_char_scope!?(scope) + Ok((val, { ctx & scopes: List.set(ctx.scopes, (List.len(ctx.scopes) - 1), new_scope) })) + + Err(ListWasEmpty) -> + Err(NoScope) + +get_char_scope! : Scope => Result (U8, Scope) [EndOfData, NoScope] +get_char_scope! = \scope -> + when List.get(scope.buf, scope.index) is + Ok(val) -> + Ok((val, { scope & index: scope.index + 1 })) + + Err(OutOfBounds) -> when scope.data is - Some h -> - bytes = File.chunk! h - when List.first bytes is - Ok val -> + Some(h) -> + bytes = File.chunk!(h) + when List.first(bytes) is + Ok(val) -> # This starts at 1 because the first character is already being returned. - Ok (val, { scope & buf: bytes, index: 1 }) + Ok((val, { scope & buf: bytes, index: 1 })) - Err ListWasEmpty -> - Err EndOfData + Err(ListWasEmpty) -> + Err(EndOfData) None -> - Err EndOfData + Err(EndOfData) -inWhileScope : Context -> Bool -inWhileScope = \ctx -> - when List.last ctx.scopes is - Ok scope -> - scope.whileInfo != None +in_while_scope : Context -> Bool +in_while_scope = \ctx -> + when List.last(ctx.scopes) is + Ok(scope) -> + scope.while_info != None - Err ListWasEmpty -> + Err(ListWasEmpty) -> Bool.false diff --git a/crates/cli/tests/test-projects/false-interpreter/Variable.roc b/crates/cli/tests/test-projects/false-interpreter/Variable.roc index f71f8cd577d..7bcf7db8a83 100644 --- a/crates/cli/tests/test-projects/false-interpreter/Variable.roc +++ b/crates/cli/tests/test-projects/false-interpreter/Variable.roc @@ -1,33 +1,33 @@ -module [Variable, fromUtf8, toIndex, totalCount, toStr] +module [Variable, from_utf8, to_index, total_count, to_str] # Variables in False can only be single letters. Thus, the valid variables are "a" to "z". # This opaque type deals with ensure we always have valid variables. Variable := U8 -totalCount : U64 -totalCount = +total_count : U64 +total_count = 0x7A # "z" - 0x61 # "a" + 1 -toStr : Variable -> Str -toStr = \@Variable char -> - when Str.fromUtf8 [char] is - Ok str -> str +to_str : Variable -> Str +to_str = \@Variable(char) -> + when Str.from_utf8([char]) is + Ok(str) -> str _ -> "_" -fromUtf8 : U8 -> Result Variable [InvalidVariableUtf8] -fromUtf8 = \char -> +from_utf8 : U8 -> Result Variable [InvalidVariableUtf8] +from_utf8 = \char -> if char >= 0x61 # "a" && char <= 0x7A # "z" then - Ok (@Variable char) + Ok(@Variable(char)) else - Err InvalidVariableUtf8 + Err(InvalidVariableUtf8) -toIndex : Variable -> U64 -toIndex = \@Variable char -> - Num.intCast (char - 0x61) # "a" +to_index : Variable -> U64 +to_index = \@Variable(char) -> + Num.int_cast((char - 0x61)) # "a" diff --git a/crates/cli/tests/test-projects/false-interpreter/main.roc b/crates/cli/tests/test-projects/false-interpreter/main.roc index 062e0f491e8..5553f4011ba 100644 --- a/crates/cli/tests/test-projects/false-interpreter/main.roc +++ b/crates/cli/tests/test-projects/false-interpreter/main.roc @@ -16,454 +16,454 @@ InterpreterErrors : [BadUtf8, DivByZero, EmptyStack, InvalidBooleanValue, Invali main! : Str => {} main! = \filename -> - when interpretFile! filename is - Ok {} -> + when interpret_file!(filename) is + Ok({}) -> {} - Err (StringErr e) -> - Stdout.line! "Ran into problem:\n$(e)\n" + Err(StringErr(e)) -> + Stdout.line!("Ran into problem:\n$(e)\n") -interpretFile! : Str => Result {} [StringErr Str] -interpretFile! = \filename -> - Context.with! filename \ctx -> - result = interpretCtx! ctx +interpret_file! : Str => Result {} [StringErr Str] +interpret_file! = \filename -> + Context.with!(filename, \ctx -> + result = interpret_ctx!(ctx) when result is - Ok _ -> - Ok {} + Ok(_) -> + Ok({}) - Err BadUtf8 -> - Err (StringErr "Failed to convert string from Utf8 bytes") + Err(BadUtf8) -> + Err(StringErr("Failed to convert string from Utf8 bytes")) - Err DivByZero -> - Err (StringErr "Division by zero") + Err(DivByZero) -> + Err(StringErr("Division by zero")) - Err EmptyStack -> - Err (StringErr "Tried to pop a value off of the stack when it was empty") + Err(EmptyStack) -> + Err(StringErr("Tried to pop a value off of the stack when it was empty")) - Err InvalidBooleanValue -> - Err (StringErr "Ran into an invalid boolean that was neither false (0) or true (-1)") + Err(InvalidBooleanValue) -> + Err(StringErr("Ran into an invalid boolean that was neither false (0) or true (-1)")) - Err (InvalidChar char) -> - Err (StringErr "Ran into an invalid character with ascii code: $(char)") + Err(InvalidChar(char)) -> + Err(StringErr("Ran into an invalid character with ascii code: $(char)")) - Err MaxInputNumber -> - Err (StringErr "Like the original false compiler, the max input number is 320,000") + Err(MaxInputNumber) -> + Err(StringErr("Like the original false compiler, the max input number is 320,000")) - Err NoLambdaOnStack -> - Err (StringErr "Tried to run a lambda when no lambda was on the stack") + Err(NoLambdaOnStack) -> + Err(StringErr("Tried to run a lambda when no lambda was on the stack")) - Err NoNumberOnStack -> - Err (StringErr "Tried to run a number when no number was on the stack") + Err(NoNumberOnStack) -> + Err(StringErr("Tried to run a number when no number was on the stack")) - Err NoVariableOnStack -> - Err (StringErr "Tried to load a variable when no variable was on the stack") + Err(NoVariableOnStack) -> + Err(StringErr("Tried to load a variable when no variable was on the stack")) - Err NoScope -> - Err (StringErr "Tried to run code when not in any scope") + Err(NoScope) -> + Err(StringErr("Tried to run code when not in any scope")) - Err OutOfBounds -> - Err (StringErr "Tried to load from an offset that was outside of the stack") + Err(OutOfBounds) -> + Err(StringErr("Tried to load from an offset that was outside of the stack")) - Err UnexpectedEndOfData -> - Err (StringErr "Hit end of data while still parsing something") + Err(UnexpectedEndOfData) -> + Err(StringErr("Hit end of data while still parsing something"))) -interpretCtx! : Context => Result Context InterpreterErrors -interpretCtx! = \ctx -> - when interpretCtxLoop! ctx is - Ok (Step next) -> - interpretCtx! next +interpret_ctx! : Context => Result Context InterpreterErrors +interpret_ctx! = \ctx -> + when interpret_ctx_loop!(ctx) is + Ok(Step(next)) -> + interpret_ctx!(next) - Ok (Done next) -> - Ok next + Ok(Done(next)) -> + Ok(next) - Err e -> - Err e + Err(e) -> + Err(e) -interpretCtxLoop! : Context => Result [Step Context, Done Context] InterpreterErrors -interpretCtxLoop! = \ctx -> +interpret_ctx_loop! : Context => Result [Step Context, Done Context] InterpreterErrors +interpret_ctx_loop! = \ctx -> when ctx.state is - Executing if Context.inWhileScope ctx -> + Executing if Context.in_while_scope(ctx) -> # Deal with the current while loop potentially looping. - last = (List.len ctx.scopes - 1) + last = (List.len(ctx.scopes) - 1) - scope = List.get ctx.scopes last |> Result.mapErr? \_ -> NoScope - when scope.whileInfo is - Some { state: InCond, body, cond } -> + scope = List.get(ctx.scopes, last) |> Result.map_err?(\_ -> NoScope) + when scope.while_info is + Some({ state: InCond, body, cond }) -> # Just ran condition. Check the top of stack to see if body should run. - (popCtx, n) = popNumber? ctx + (pop_ctx, n) = pop_number?(ctx) if n == 0 then - newScope = { scope & whileInfo: None } + new_scope = { scope & while_info: None } - Ok (Step { popCtx & scopes: List.set ctx.scopes last newScope }) + Ok(Step({ pop_ctx & scopes: List.set(ctx.scopes, last, new_scope) })) else - newScope = { scope & whileInfo: Some { state: InBody, body, cond } } + new_scope = { scope & while_info: Some({ state: InBody, body, cond }) } - Ok (Step { popCtx & scopes: List.append (List.set ctx.scopes last newScope) { data: None, buf: body, index: 0, whileInfo: None } }) + Ok(Step({ pop_ctx & scopes: List.append(List.set(ctx.scopes, last, new_scope), { data: None, buf: body, index: 0, while_info: None }) })) - Some { state: InBody, body, cond } -> + Some({ state: InBody, body, cond }) -> # Just rand the body. Run the condition again. - newScope = { scope & whileInfo: Some { state: InCond, body, cond } } + new_scope = { scope & while_info: Some({ state: InCond, body, cond }) } - Ok (Step { ctx & scopes: List.append (List.set ctx.scopes last newScope) { data: None, buf: cond, index: 0, whileInfo: None } }) + Ok(Step({ ctx & scopes: List.append(List.set(ctx.scopes, last, new_scope), { data: None, buf: cond, index: 0, while_info: None }) })) None -> - Err NoScope + Err(NoScope) Executing -> - # Stdout.line! (Context.toStr ctx) - result = Context.getChar! ctx + # Stdout.line! (Context.to_str ctx) + result = Context.get_char!(ctx) when result is - Ok (val, newCtx) -> - execCtx = stepExecCtx!? newCtx val - Ok (Step execCtx) + Ok((val, new_ctx)) -> + exec_ctx = step_exec_ctx!?(new_ctx, val) + Ok(Step(exec_ctx)) - Err NoScope -> - Err NoScope + Err(NoScope) -> + Err(NoScope) - Err EndOfData -> + Err(EndOfData) -> # Computation complete for this scope. # Drop a scope. - dropCtx = { ctx & scopes: List.dropAt ctx.scopes (List.len ctx.scopes - 1) } + drop_ctx = { ctx & scopes: List.drop_at(ctx.scopes, (List.len(ctx.scopes) - 1)) } # If no scopes left, all execution complete. - if List.isEmpty dropCtx.scopes then - Ok (Done dropCtx) + if List.is_empty(drop_ctx.scopes) then + Ok(Done(drop_ctx)) else - Ok (Step dropCtx) + Ok(Step(drop_ctx)) InComment -> - (val, newCtx) = Context.getChar! ctx |> Result.mapErr? endUnexpected + (val, new_ctx) = Context.get_char!(ctx) |> Result.map_err?(end_unexpected) if val == 0x7D then # `}` end of comment - Ok (Step { newCtx & state: Executing }) + Ok(Step({ new_ctx & state: Executing })) else - Ok (Step { newCtx & state: InComment }) + Ok(Step({ new_ctx & state: InComment })) - InNumber accum -> - (val, newCtx) = Context.getChar! ctx |> Result.mapErr? endUnexpected - if isDigit val then + InNumber(accum) -> + (val, new_ctx) = Context.get_char!(ctx) |> Result.map_err?(end_unexpected) + if is_digit(val) then # still in the number # i32 multiplication is kinda broken because it implicitly seems to want to upcast to i64. # so like should be (i32, i32) -> i32, but seems to be (i32, i32) -> i64 # so this is make i64 mul by 10 then convert back to i32. - nextAccum = (10 * Num.intCast accum) + Num.intCast (val - 0x30) + next_accum = (10 * Num.int_cast(accum)) + Num.int_cast((val - 0x30)) - Ok (Step { newCtx & state: InNumber (Num.intCast nextAccum) }) + Ok(Step({ new_ctx & state: InNumber(Num.int_cast(next_accum)) })) else # outside of number now, this needs to be executed. - pushCtx = Context.pushStack newCtx (Number accum) + push_ctx = Context.push_stack(new_ctx, Number(accum)) - execCtx = stepExecCtx!? { pushCtx & state: Executing } val - Ok (Step execCtx) + exec_ctx = step_exec_ctx!?({ push_ctx & state: Executing }, val) + Ok(Step(exec_ctx)) - InString bytes -> - (val, newCtx) = Context.getChar! ctx |> Result.mapErr? endUnexpected + InString(bytes) -> + (val, new_ctx) = Context.get_char!(ctx) |> Result.map_err?(end_unexpected) if val == 0x22 then # `"` end of string - when Str.fromUtf8 bytes is - Ok str -> - Stdout.raw! str - Ok (Step { newCtx & state: Executing }) + when Str.from_utf8(bytes) is + Ok(str) -> + Stdout.raw!(str) + Ok(Step({ new_ctx & state: Executing })) - Err _ -> - Err BadUtf8 + Err(_) -> + Err(BadUtf8) else - Ok (Step { newCtx & state: InString (List.append bytes val) }) + Ok(Step({ new_ctx & state: InString(List.append(bytes, val)) })) - InLambda depth bytes -> - (val, newCtx) = Context.getChar! ctx |> Result.mapErr? endUnexpected + InLambda(depth, bytes) -> + (val, new_ctx) = Context.get_char!(ctx) |> Result.map_err?(end_unexpected) if val == 0x5B then # start of a nested lambda `[` - Ok (Step { newCtx & state: InLambda (depth + 1) (List.append bytes val) }) + Ok(Step({ new_ctx & state: InLambda((depth + 1), List.append(bytes, val)) })) else if val == 0x5D then # `]` end of current lambda if depth == 0 then # end of all lambdas - Ok (Step (Context.pushStack { newCtx & state: Executing } (Lambda bytes))) + Ok(Step(Context.push_stack({ new_ctx & state: Executing }, Lambda(bytes)))) else # end of nested lambda - Ok (Step { newCtx & state: InLambda (depth - 1) (List.append bytes val) }) + Ok(Step({ new_ctx & state: InLambda((depth - 1), List.append(bytes, val)) })) else - Ok (Step { newCtx & state: InLambda depth (List.append bytes val) }) + Ok(Step({ new_ctx & state: InLambda(depth, List.append(bytes, val)) })) InSpecialChar -> - val = Context.getChar! { ctx & state: Executing } |> Result.mapErr? endUnexpected + val = Context.get_char!({ ctx & state: Executing }) |> Result.map_err?(end_unexpected) when val is - (0xB8, newCtx) -> - (popCtx, index) = popNumber? newCtx + (0xB8, new_ctx) -> + (pop_ctx, index) = pop_number?(new_ctx) # I think Num.abs is too restrictive, it should be able to produce a natural number, but it seem to be restricted to signed numbers. - size = List.len popCtx.stack - 1 - offset = Num.intCast size - index + size = List.len(pop_ctx.stack) - 1 + offset = Num.int_cast(size) - index if offset >= 0 then - stackVal = List.get? popCtx.stack (Num.intCast offset) - Ok (Step (Context.pushStack popCtx stackVal)) + stack_val = List.get?(pop_ctx.stack, Num.int_cast(offset)) + Ok(Step(Context.push_stack(pop_ctx, stack_val))) else - Err OutOfBounds + Err(OutOfBounds) - (0x9F, newCtx) -> + (0x9F, new_ctx) -> # This is supposed to flush io buffers. We don't buffer, so it does nothing - Ok (Step newCtx) + Ok(Step(new_ctx)) (x, _) -> - data = Num.toStr (Num.intCast x) + data = Num.to_str(Num.int_cast(x)) - Err (InvalidChar data) + Err(InvalidChar(data)) LoadChar -> - (x, newCtx) = Context.getChar! { ctx & state: Executing } |> Result.mapErr? endUnexpected - Ok (Step (Context.pushStack newCtx (Number (Num.intCast x)))) + (x, new_ctx) = Context.get_char!({ ctx & state: Executing }) |> Result.map_err?(end_unexpected) + Ok(Step(Context.push_stack(new_ctx, Number(Num.int_cast(x))))) # If it weren't for reading stdin or writing to stdout, this could return a result. -stepExecCtx! : Context, U8 => Result Context InterpreterErrors -stepExecCtx! = \ctx, char -> +step_exec_ctx! : Context, U8 => Result Context InterpreterErrors +step_exec_ctx! = \ctx, char -> when char is 0x21 -> # `!` execute lambda - (popCtx, bytes) = popLambda? ctx - Ok { popCtx & scopes: List.append popCtx.scopes { data: None, buf: bytes, index: 0, whileInfo: None } } + (pop_ctx, bytes) = pop_lambda?(ctx) + Ok({ pop_ctx & scopes: List.append(pop_ctx.scopes, { data: None, buf: bytes, index: 0, while_info: None }) }) 0x3F -> # `?` if - (popCtx1, bytes) = popLambda? ctx - (popCtx2, n1) = popNumber? popCtx1 + (pop_ctx1, bytes) = pop_lambda?(ctx) + (pop_ctx2, n1) = pop_number?(pop_ctx1) if n1 == 0 then - Ok popCtx2 + Ok(pop_ctx2) else - Ok { popCtx2 & scopes: List.append popCtx2.scopes { data: None, buf: bytes, index: 0, whileInfo: None } } + Ok({ pop_ctx2 & scopes: List.append(pop_ctx2.scopes, { data: None, buf: bytes, index: 0, while_info: None }) }) 0x23 -> # `#` while - (popCtx1, body) = popLambda? ctx - (popCtx2, cond) = popLambda? popCtx1 - last = (List.len popCtx2.scopes - 1) + (pop_ctx1, body) = pop_lambda?(ctx) + (pop_ctx2, cond) = pop_lambda?(pop_ctx1) + last = (List.len(pop_ctx2.scopes) - 1) - scope = List.get popCtx2.scopes last |> Result.mapErr? \_ -> NoScope + scope = List.get(pop_ctx2.scopes, last) |> Result.map_err?(\_ -> NoScope) # set the current scope to be in a while loop. - scopes = List.set popCtx2.scopes last { scope & whileInfo: Some { cond: cond, body: body, state: InCond } } + scopes = List.set(pop_ctx2.scopes, last, { scope & while_info: Some({ cond: cond, body: body, state: InCond }) }) # push a scope to execute the condition. - Ok { popCtx2 & scopes: List.append scopes { data: None, buf: cond, index: 0, whileInfo: None } } + Ok({ pop_ctx2 & scopes: List.append(scopes, { data: None, buf: cond, index: 0, while_info: None }) }) 0x24 -> # `$` dup # Switching this to List.last and changing the error to ListWasEmpty leads to a compiler bug. # Complains about the types eq not matching. - when List.get ctx.stack (List.len ctx.stack - 1) is - Ok dupItem -> Ok (Context.pushStack ctx dupItem) - Err OutOfBounds -> Err EmptyStack + when List.get(ctx.stack, (List.len(ctx.stack) - 1)) is + Ok(dup_item) -> Ok(Context.push_stack(ctx, dup_item)) + Err(OutOfBounds) -> Err(EmptyStack) 0x25 -> # `%` drop - when Context.popStack ctx is + when Context.pop_stack(ctx) is # Dropping with an empty stack, all results here are fine - Ok (popCtx, _) -> Ok popCtx - Err _ -> Ok ctx + Ok((pop_ctx, _)) -> Ok(pop_ctx) + Err(_) -> Ok(ctx) 0x5C -> # `\` swap - (popCtx1, n1) = Context.popStack? ctx - (popCtx2, n2) = Context.popStack? popCtx1 - Ok (Context.pushStack (Context.pushStack popCtx2 n1) n2) + (pop_ctx1, n1) = Context.pop_stack?(ctx) + (pop_ctx2, n2) = Context.pop_stack?(pop_ctx1) + Ok(Context.push_stack(Context.push_stack(pop_ctx2, n1), n2)) 0x40 -> # `@` rot result2 = - (popCtx1, n1) = Context.popStack? ctx - (popCtx2, n2) = Context.popStack? popCtx1 - (popCtx3, n3) = Context.popStack? popCtx2 - Ok (Context.pushStack (Context.pushStack (Context.pushStack popCtx3 n2) n1) n3) + (pop_ctx1, n1) = Context.pop_stack?(ctx) + (pop_ctx2, n2) = Context.pop_stack?(pop_ctx1) + (pop_ctx3, n3) = Context.pop_stack?(pop_ctx2) + Ok(Context.push_stack(Context.push_stack(Context.push_stack(pop_ctx3, n2), n1), n3)) when result2 is - Ok a -> - Ok a + Ok(a) -> + Ok(a) # Being explicit with error type is required to stop the need to propogate the error parameters to Context.popStack - Err EmptyStack -> - Err EmptyStack + Err(EmptyStack) -> + Err(EmptyStack) 0xC3 -> # `ø` pick or `ß` flush # these are actually 2 bytes, 0xC3 0xB8 or 0xC3 0x9F # requires special parsing - Ok { ctx & state: InSpecialChar } + Ok({ ctx & state: InSpecialChar }) 0x4F -> # `O` also treat this as pick for easier script writing - (popCtx, index) = popNumber? ctx + (pop_ctx, index) = pop_number?(ctx) # I think Num.abs is too restrictive, it should be able to produce a natural number, but it seem to be restricted to signed numbers. - size = List.len popCtx.stack - 1 - offset = Num.intCast size - index + size = List.len(pop_ctx.stack) - 1 + offset = Num.int_cast(size) - index if offset >= 0 then - stackVal = List.get? popCtx.stack (Num.intCast offset) - Ok (Context.pushStack popCtx stackVal) + stack_val = List.get?(pop_ctx.stack, Num.int_cast(offset)) + Ok(Context.push_stack(pop_ctx, stack_val)) else - Err OutOfBounds + Err(OutOfBounds) 0x42 -> # `B` also treat this as flush for easier script writing # This is supposed to flush io buffers. We don't buffer, so it does nothing - Ok ctx + Ok(ctx) 0x27 -> # `'` load next char - Ok { ctx & state: LoadChar } + Ok({ ctx & state: LoadChar }) 0x2B -> # `+` add - binaryOp ctx Num.addWrap + binary_op(ctx, Num.add_wrap) 0x2D -> # `-` sub - binaryOp ctx Num.subWrap + binary_op(ctx, Num.sub_wrap) 0x2A -> # `*` mul - binaryOp ctx Num.mulWrap + binary_op(ctx, Num.mul_wrap) 0x2F -> # `/` div # Due to possible division by zero error, this must be handled specially. - (popCtx1, numR) = popNumber? ctx - (popCtx2, numL) = popNumber? popCtx1 - res = Num.divTruncChecked? numL numR - Ok (Context.pushStack popCtx2 (Number res)) + (pop_ctx1, num_r) = pop_number?(ctx) + (pop_ctx2, num_l) = pop_number?(pop_ctx1) + res = Num.div_trunc_checked?(num_l, num_r) + Ok(Context.push_stack(pop_ctx2, Number(res))) 0x26 -> # `&` bitwise and - binaryOp ctx Num.bitwiseAnd + binary_op(ctx, Num.bitwise_and) 0x7C -> # `|` bitwise or - binaryOp ctx Num.bitwiseOr + binary_op(ctx, Num.bitwise_or) 0x3D -> # `=` equals - binaryOp ctx \a, b -> + binary_op(ctx, \a, b -> if a == b then -1 else - 0 + 0) 0x3E -> # `>` greater than - binaryOp ctx \a, b -> + binary_op(ctx, \a, b -> if a > b then -1 else - 0 + 0) 0x5F -> # `_` negate - unaryOp ctx Num.neg + unary_op(ctx, Num.neg) 0x7E -> # `~` bitwise not - unaryOp ctx (\x -> Num.bitwiseXor x -1) # xor with -1 should be bitwise not + unary_op(ctx, \x -> Num.bitwise_xor(x, -1)) # xor with -1 should be bitwise not 0x2C -> # `,` write char - (popCtx, num) = popNumber? ctx - str = Str.fromUtf8 [Num.intCast num] |> Result.mapErr? \_ -> BadUtf8 - Stdout.raw! str - Ok popCtx + (pop_ctx, num) = pop_number?(ctx) + str = Str.from_utf8([Num.int_cast(num)]) |> Result.map_err?(\_ -> BadUtf8) + Stdout.raw!(str) + Ok(pop_ctx) 0x2E -> # `.` write int - (popCtx, num) = popNumber? ctx - Stdout.raw! (Num.toStr (Num.intCast num)) - Ok popCtx + (pop_ctx, num) = pop_number?(ctx) + Stdout.raw!(Num.to_str(Num.int_cast(num))) + Ok(pop_ctx) 0x5E -> # `^` read char as int - in = Stdin.char! {} + in = Stdin.char!({}) if in == 255 then # max char sent on EOF. Change to -1 - Ok (Context.pushStack ctx (Number -1)) + Ok(Context.push_stack(ctx, Number(-1))) else - Ok (Context.pushStack ctx (Number (Num.intCast in))) + Ok(Context.push_stack(ctx, Number(Num.int_cast(in)))) 0x3A -> # `:` store to variable - (popCtx1, var) = popVariable? ctx - (popCtx2, n1) = Context.popStack? popCtx1 - Ok { popCtx2 & vars: List.set popCtx2.vars (Variable.toIndex var) n1 } + (pop_ctx1, var) = pop_variable?(ctx) + (pop_ctx2, n1) = Context.pop_stack?(pop_ctx1) + Ok({ pop_ctx2 & vars: List.set(pop_ctx2.vars, Variable.to_index(var), n1) }) 0x3B -> # `;` load from variable - (popCtx, var) = popVariable? ctx - elem = List.get? popCtx.vars (Variable.toIndex var) - Ok (Context.pushStack popCtx elem) + (pop_ctx, var) = pop_variable?(ctx) + elem = List.get?(pop_ctx.vars, Variable.to_index(var)) + Ok(Context.push_stack(pop_ctx, elem)) 0x22 -> # `"` string start - Ok { ctx & state: InString [] } + Ok({ ctx & state: InString([]) }) 0x5B -> # `"` string start - Ok { ctx & state: InLambda 0 [] } + Ok({ ctx & state: InLambda(0, []) }) 0x7B -> # `{` comment start - Ok { ctx & state: InComment } + Ok({ ctx & state: InComment }) - x if isDigit x -> + x if is_digit(x) -> # number start - Ok { ctx & state: InNumber (Num.intCast (x - 0x30)) } + Ok({ ctx & state: InNumber(Num.int_cast((x - 0x30))) }) - x if isWhitespace x -> - Ok ctx + x if is_whitespace(x) -> + Ok(ctx) x -> - when Variable.fromUtf8 x is + when Variable.from_utf8(x) is # letters are variable names - Ok var -> - Ok (Context.pushStack ctx (Var var)) - - Err _ -> - data = Num.toStr (Num.intCast x) - - Err (InvalidChar data) - -unaryOp : Context, (I32 -> I32) -> Result Context InterpreterErrors -unaryOp = \ctx, op -> - (popCtx, num) = popNumber? ctx - Ok (Context.pushStack popCtx (Number (op num))) - -binaryOp : Context, (I32, I32 -> I32) -> Result Context InterpreterErrors -binaryOp = \ctx, op -> - (popCtx1, numR) = popNumber? ctx - (popCtx2, numL) = popNumber? popCtx1 - Ok (Context.pushStack popCtx2 (Number (op numL numR))) - -popNumber : Context -> Result (Context, I32) InterpreterErrors -popNumber = \ctx -> - when Context.popStack? ctx is - (popCtx, Number num) -> Ok (popCtx, num) - _ -> Err NoNumberOnStack - -popLambda : Context -> Result (Context, List U8) InterpreterErrors -popLambda = \ctx -> - when Context.popStack? ctx is - (popCtx, Lambda bytes) -> Ok (popCtx, bytes) - _ -> Err NoLambdaOnStack - -popVariable : Context -> Result (Context, Variable) InterpreterErrors -popVariable = \ctx -> - when Context.popStack? ctx is - (popCtx, Var var) -> Ok (popCtx, var) - _ -> Err NoVariableOnStack - -isDigit : U8 -> Bool -isDigit = \char -> + Ok(var) -> + Ok(Context.push_stack(ctx, Var(var))) + + Err(_) -> + data = Num.to_str(Num.int_cast(x)) + + Err(InvalidChar(data)) + +unary_op : Context, (I32 -> I32) -> Result Context InterpreterErrors +unary_op = \ctx, op -> + (pop_ctx, num) = pop_number?(ctx) + Ok(Context.push_stack(pop_ctx, Number(op(num)))) + +binary_op : Context, (I32, I32 -> I32) -> Result Context InterpreterErrors +binary_op = \ctx, op -> + (pop_ctx1, num_r) = pop_number?(ctx) + (pop_ctx2, num_l) = pop_number?(pop_ctx1) + Ok(Context.push_stack(pop_ctx2, Number(op(num_l, num_r)))) + +pop_number : Context -> Result (Context, I32) InterpreterErrors +pop_number = \ctx -> + when Context.pop_stack?(ctx) is + (pop_ctx, Number(num)) -> Ok((pop_ctx, num)) + _ -> Err(NoNumberOnStack) + +pop_lambda : Context -> Result (Context, List U8) InterpreterErrors +pop_lambda = \ctx -> + when Context.pop_stack?(ctx) is + (pop_ctx, Lambda(bytes)) -> Ok((pop_ctx, bytes)) + _ -> Err(NoLambdaOnStack) + +pop_variable : Context -> Result (Context, Variable) InterpreterErrors +pop_variable = \ctx -> + when Context.pop_stack?(ctx) is + (pop_ctx, Var(var)) -> Ok((pop_ctx, var)) + _ -> Err(NoVariableOnStack) + +is_digit : U8 -> Bool +is_digit = \char -> char >= 0x30 # `0` && char <= 0x39 # `0` -isWhitespace : U8 -> Bool -isWhitespace = \char -> +is_whitespace : U8 -> Bool +is_whitespace = \char -> char == 0xA # new line || char @@ -473,7 +473,7 @@ isWhitespace = \char -> || char == 0x9 # tab -endUnexpected = \err -> +end_unexpected = \err -> when err is NoScope -> NoScope diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/File.roc b/crates/cli/tests/test-projects/false-interpreter/platform/File.roc index ccb0cffe128..8d9ea0db35d 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/File.roc +++ b/crates/cli/tests/test-projects/false-interpreter/platform/File.roc @@ -1,30 +1,30 @@ -module [line!, withOpen!, chunk!, Handle] +module [line!, with_open!, chunk!, Handle] import pf.Host Handle := U64 line! : Handle => Str -line! = \@Handle handle -> - Host.getFileLine! handle +line! = \@Handle(handle) -> + Host.get_file_line!(handle) chunk! : Handle => List U8 -chunk! = \@Handle handle -> - Host.getFileBytes! handle +chunk! = \@Handle(handle) -> + Host.get_file_bytes!(handle) open! : Str => Handle open! = \path -> - Host.openFile! path + Host.open_file!(path) |> @Handle close! : Handle => {} -close! = \@Handle handle -> - Host.closeFile! handle - -withOpen! : Str, (Handle => a) => a -withOpen! = \path, callback! -> - handle = open! path - result = callback! handle - close! handle +close! = \@Handle(handle) -> + Host.close_file!(handle) + +with_open! : Str, (Handle => a) => a +with_open! = \path, callback! -> + handle = open!(path) + result = callback!(handle) + close!(handle) result diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/Host.roc b/crates/cli/tests/test-projects/false-interpreter/platform/Host.roc index c1662d998c5..ef6aaaa5d70 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/Host.roc +++ b/crates/cli/tests/test-projects/false-interpreter/platform/Host.roc @@ -1,19 +1,19 @@ hosted Host - exposes [openFile!, closeFile!, getFileLine!, getFileBytes!, putLine!, putRaw!, getLine!, getChar!] + exposes [open_file!, close_file!, get_file_line!, get_file_bytes!, put_line!, put_raw!, get_line!, get_char!] imports [] -openFile! : Str => U64 +open_file! : Str => U64 -closeFile! : U64 => {} +close_file! : U64 => {} -getFileLine! : U64 => Str +get_file_line! : U64 => Str -getFileBytes! : U64 => List U8 +get_file_bytes! : U64 => List U8 -putLine! : Str => {} +put_line! : Str => {} -putRaw! : Str => {} +put_raw! : Str => {} -getLine! : {} => Str +get_line! : {} => Str -getChar! : {} => U8 +get_char! : {} => U8 diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/Stdin.roc b/crates/cli/tests/test-projects/false-interpreter/platform/Stdin.roc index fc33e16ad6d..b9ad5d2eac6 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/Stdin.roc +++ b/crates/cli/tests/test-projects/false-interpreter/platform/Stdin.roc @@ -4,8 +4,8 @@ import pf.Host line! : {} => Str line! = \{} -> - Host.getLine! {} + Host.get_line!({}) char! : {} => U8 char! = \{} -> - Host.getChar! {} + Host.get_char!({}) diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/Stdout.roc b/crates/cli/tests/test-projects/false-interpreter/platform/Stdout.roc index 9e56cc6ae11..c4c7656b5a5 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/Stdout.roc +++ b/crates/cli/tests/test-projects/false-interpreter/platform/Stdout.roc @@ -4,8 +4,8 @@ import pf.Host line! : Str => {} line! = \text -> - Host.putLine! text + Host.put_line!(text) raw! : Str => {} raw! = \text -> - Host.putRaw! text + Host.put_raw!(text) diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/main.roc b/crates/cli/tests/test-projects/false-interpreter/platform/main.roc index 62d643ed6de..b39ab41e9fc 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/main.roc +++ b/crates/cli/tests/test-projects/false-interpreter/platform/main.roc @@ -3,7 +3,7 @@ platform "false-interpreter" exposes [] packages {} imports [] - provides [mainForHost!] + provides [main_for_host!] -mainForHost! : Str => {} -mainForHost! = \file -> main! file +main_for_host! : Str => {} +main_for_host! = \file -> main!(file) diff --git a/crates/cli/tests/test-projects/false-interpreter/platform/src/lib.rs b/crates/cli/tests/test-projects/false-interpreter/platform/src/lib.rs index 616dd27a397..4bf8ce1d4b4 100644 --- a/crates/cli/tests/test-projects/false-interpreter/platform/src/lib.rs +++ b/crates/cli/tests/test-projects/false-interpreter/platform/src/lib.rs @@ -19,7 +19,7 @@ fn file_handles() -> &'static Mutex>> { } extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(void: *const c_void, args: *mut RocStr); } diff --git a/crates/cli/tests/test-projects/fixtures/format/formatted.roc b/crates/cli/tests/test-projects/fixtures/format/formatted.roc index 34dd7401faa..58f252bab69 100644 --- a/crates/cli/tests/test-projects/fixtures/format/formatted.roc +++ b/crates/cli/tests/test-projects/fixtures/format/formatted.roc @@ -1,4 +1,4 @@ app [main] { pf: "platform/main.roc" } main : Str -main = Dep1.value1 {} +main = Dep1.value1({}) diff --git a/crates/cli/tests/test-projects/fixtures/format/formatted_directory/Formatted.roc b/crates/cli/tests/test-projects/fixtures/format/formatted_directory/Formatted.roc index 34dd7401faa..58f252bab69 100644 --- a/crates/cli/tests/test-projects/fixtures/format/formatted_directory/Formatted.roc +++ b/crates/cli/tests/test-projects/fixtures/format/formatted_directory/Formatted.roc @@ -1,4 +1,4 @@ app [main] { pf: "platform/main.roc" } main : Str -main = Dep1.value1 {} +main = Dep1.value1({}) diff --git a/crates/cli/tests/test-projects/fixtures/format/not-formatted.roc b/crates/cli/tests/test-projects/fixtures/format/not-formatted.roc index 757a5e90edb..4a82e9b28cb 100644 --- a/crates/cli/tests/test-projects/fixtures/format/not-formatted.roc +++ b/crates/cli/tests/test-projects/fixtures/format/not-formatted.roc @@ -1,4 +1,4 @@ -app [main] { pf: "platform/main.roc" } +app [main] { pf: "platform/main.roc" } main : Str -main = Dep1.value1 {} +main = Dep1.value1({}) diff --git a/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/Dep1.roc b/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/Dep1.roc index a975704b4f1..bc291f49f3e 100644 --- a/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/Dep1.roc +++ b/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/Dep1.roc @@ -3,4 +3,4 @@ module [value1] import Dep2 value1 : {} -> Str -value1 = \_ -> Dep2.value2 {} +value1 = \_ -> Dep2.value2({}) diff --git a/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/main.roc b/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/main.roc index 00fb7fd1513..24ea147fc02 100644 --- a/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/main.roc +++ b/crates/cli/tests/test-projects/fixtures/multi-dep-thunk/main.roc @@ -3,4 +3,4 @@ app [main] { pf: platform "../../test-platform-simple-zig/main.roc" } import Dep1 main : Str -main = Dep1.value1 {} +main = Dep1.value1({}) diff --git a/crates/cli/tests/test-projects/known_bad/UnusedImport.roc b/crates/cli/tests/test-projects/known_bad/UnusedImport.roc index f7c19c024e4..4cf48d545d6 100644 --- a/crates/cli/tests/test-projects/known_bad/UnusedImport.roc +++ b/crates/cli/tests/test-projects/known_bad/UnusedImport.roc @@ -1,7 +1,7 @@ -module [plainText, emText] +module [plain_text, em_text] import Symbol exposing [Ident] -plainText = \str -> PlainText str +plain_text = \str -> PlainText(str) -emText = \str -> EmText str +em_text = \str -> EmText(str) diff --git a/crates/cli/tests/test-projects/known_bad/UnusedImportButWithALongFileNameForTesting.roc b/crates/cli/tests/test-projects/known_bad/UnusedImportButWithALongFileNameForTesting.roc index f7c19c024e4..4cf48d545d6 100644 --- a/crates/cli/tests/test-projects/known_bad/UnusedImportButWithALongFileNameForTesting.roc +++ b/crates/cli/tests/test-projects/known_bad/UnusedImportButWithALongFileNameForTesting.roc @@ -1,7 +1,7 @@ -module [plainText, emText] +module [plain_text, em_text] import Symbol exposing [Ident] -plainText = \str -> PlainText str +plain_text = \str -> PlainText(str) -emText = \str -> EmText str +em_text = \str -> EmText(str) diff --git a/crates/cli/tests/test-projects/module_imports_pkg/ImportsUnknownPkg.roc b/crates/cli/tests/test-projects/module_imports_pkg/ImportsUnknownPkg.roc index dbe6b03e87c..62bd9a5b5f3 100644 --- a/crates/cli/tests/test-projects/module_imports_pkg/ImportsUnknownPkg.roc +++ b/crates/cli/tests/test-projects/module_imports_pkg/ImportsUnknownPkg.roc @@ -1,7 +1,7 @@ -module [valueFromPkg] +module [value_from_pkg] import cli.Foo -valueFromPkg = Foo.foo +value_from_pkg = Foo.foo -expect valueFromPkg == "Foo" +expect value_from_pkg == "Foo" diff --git a/crates/cli/tests/test-projects/module_imports_pkg/Module.roc b/crates/cli/tests/test-projects/module_imports_pkg/Module.roc index 8b4b21aef21..28c245d4c86 100644 --- a/crates/cli/tests/test-projects/module_imports_pkg/Module.roc +++ b/crates/cli/tests/test-projects/module_imports_pkg/Module.roc @@ -1,7 +1,7 @@ -module [valueFromPkg] +module [value_from_pkg] import pkg.Foo -valueFromPkg = Foo.foo +value_from_pkg = Foo.foo -expect valueFromPkg == "Foo" +expect value_from_pkg == "Foo" diff --git a/crates/cli/tests/test-projects/module_imports_pkg/app.roc b/crates/cli/tests/test-projects/module_imports_pkg/app.roc index dc81319d256..7e663b62003 100644 --- a/crates/cli/tests/test-projects/module_imports_pkg/app.roc +++ b/crates/cli/tests/test-projects/module_imports_pkg/app.roc @@ -5,4 +5,4 @@ app [main] { import Module main = - Module.valueFromPkg + Module.value_from_pkg diff --git a/crates/cli/tests/test-projects/module_params/Api.roc b/crates/cli/tests/test-projects/module_params/Api.roc index cd3a7792d05..cd407b71229 100644 --- a/crates/cli/tests/test-projects/module_params/Api.roc +++ b/crates/cli/tests/test-projects/module_params/Api.roc @@ -1,69 +1,69 @@ -module { appId, protocol } -> [ - baseUrl, - getUser, - getPost, - getPosts, - getPostComments, - getCompanies, - baseUrlAliased, - getPostAliased, - getUserSafe, - getPostComment, +module { app_id, protocol } -> [ + base_url, + get_user, + get_post, + get_posts, + get_post_comments, + get_companies, + base_url_aliased, + get_post_aliased, + get_user_safe, + get_post_comment, ] ## value def referencing params -baseUrl : Str -baseUrl = - protocol "api.example.com/$(appId)" +base_url : Str +base_url = + protocol("api.example.com/$(app_id)") ## function def referencing params -getUser : U32 -> Str -getUser = \userId -> +get_user : U32 -> Str +get_user = \user_id -> # purposefully not using baseUrl to test top-level fn referencing param - protocol "api.example.com/$(appId)/users/$(Num.toStr userId)" + protocol("api.example.com/$(app_id)/users/$(Num.to_str(user_id))") ## function def referencing top-level value -getPost : U32 -> Str -getPost = \postId -> - "$(baseUrl)/posts/$(Num.toStr postId)" +get_post : U32 -> Str +get_post = \post_id -> + "$(base_url)/posts/$(Num.to_str(post_id))" ## function def passing top-level function -getPosts : List U32 -> List Str -getPosts = \ids -> - List.map ids getPost +get_posts : List U32 -> List Str +get_posts = \ids -> + List.map(ids, get_post) ## function def calling top-level function -getPostComments : U32 -> Str -getPostComments = \postId -> - "$(getPost postId)/comments" +get_post_comments : U32 -> Str +get_post_comments = \post_id -> + "$(get_post(post_id))/comments" ## function def passing nested function -getCompanies : List U32 -> List Str -getCompanies = \ids -> - getCompany = \id -> - protocol "api.example.com/$(appId)/companies/$(Num.toStr id)" +get_companies : List U32 -> List Str +get_companies = \ids -> + get_company = \id -> + protocol("api.example.com/$(app_id)/companies/$(Num.to_str(id))") - List.map ids getCompany + List.map(ids, get_company) ## aliasing top-level value -baseUrlAliased : Str -baseUrlAliased = - baseUrl +base_url_aliased : Str +base_url_aliased = + base_url ## aliasing top-level fn -getPostAliased : U32 -> Str -getPostAliased = - getPost +get_post_aliased : U32 -> Str +get_post_aliased = + get_post ## top-level value returning functions -getUserSafe : U32 -> Str -getUserSafe = - if Str.startsWith appId "prod_" then - \id -> "$(getUser id)?safe=true" +get_user_safe : U32 -> Str +get_user_safe = + if Str.starts_with(app_id, "prod_") then + \id -> "$(get_user(id))?safe=true" else - getUser + get_user ## two-argument function -getPostComment : U32, U32 -> Str -getPostComment = \postId, commentId -> - "$(getPost postId)/comments/$(Num.toStr commentId)" +get_post_comment : U32, U32 -> Str +get_post_comment = \post_id, comment_id -> + "$(get_post(post_id))/comments/$(Num.to_str(comment_id))" diff --git a/crates/cli/tests/test-projects/module_params/BadAnn.roc b/crates/cli/tests/test-projects/module_params/BadAnn.roc index 2ccfce872e8..1c67aef6089 100644 --- a/crates/cli/tests/test-projects/module_params/BadAnn.roc +++ b/crates/cli/tests/test-projects/module_params/BadAnn.roc @@ -1,9 +1,9 @@ -module { appId } -> [fnAnnotatedAsValue, missingArg] +module { app_id } -> [fn_annotated_as_value, missing_arg] -fnAnnotatedAsValue : Str -fnAnnotatedAsValue = \postId, commentId -> - "/posts/$(postId)/comments/$(Num.toStr commentId)" +fn_annotated_as_value : Str +fn_annotated_as_value = \post_id, comment_id -> + "/posts/$(post_id)/comments/$(Num.to_str(comment_id))" -missingArg : Str -> Str -missingArg = \postId, _ -> - "/posts/$(postId)/comments" +missing_arg : Str -> Str +missing_arg = \post_id, _ -> + "/posts/$(post_id)/comments" diff --git a/crates/cli/tests/test-projects/module_params/ImportInExpect.roc b/crates/cli/tests/test-projects/module_params/ImportInExpect.roc index 477d23f50af..02bc3a38e68 100644 --- a/crates/cli/tests/test-projects/module_params/ImportInExpect.roc +++ b/crates/cli/tests/test-projects/module_params/ImportInExpect.roc @@ -3,12 +3,12 @@ module [] https = \url -> "https://$(url)" expect - import Api { appId: "one", protocol: https } - Api.baseUrl == "https://api.example.com/one" + import Api { app_id: "one", protocol: https } + Api.base_url == "https://api.example.com/one" expect - import Api { appId: "two", protocol: https } - Api.getUser 1 == "https://api.example.com/two/users/1" + import Api { app_id: "two", protocol: https } + Api.get_user(1) == "https://api.example.com/two/users/1" expect import NoParams diff --git a/crates/cli/tests/test-projects/module_params/Menu.roc b/crates/cli/tests/test-projects/module_params/Menu.roc index e16090caf54..52afd5dd11d 100644 --- a/crates/cli/tests/test-projects/module_params/Menu.roc +++ b/crates/cli/tests/test-projects/module_params/Menu.roc @@ -1,7 +1,7 @@ module { echo } -> [menu] menu = \name -> - indirect name + indirect(name) indirect = \name -> - echo "Hi, $(name)!" + echo("Hi, $(name)!") diff --git a/crates/cli/tests/test-projects/module_params/MultilineParams.roc b/crates/cli/tests/test-projects/module_params/MultilineParams.roc index 7c8906376c4..7371b4cdc7b 100644 --- a/crates/cli/tests/test-projects/module_params/MultilineParams.roc +++ b/crates/cli/tests/test-projects/module_params/MultilineParams.roc @@ -1,4 +1,4 @@ -module { sendHttpReq, getEnvVar } -> [hi] +module { send_http_req, get_env_var } -> [hi] hi : Str hi = diff --git a/crates/cli/tests/test-projects/module_params/app.roc b/crates/cli/tests/test-projects/module_params/app.roc index 5f4a38c3a2c..692fee536a9 100644 --- a/crates/cli/tests/test-projects/module_params/app.roc +++ b/crates/cli/tests/test-projects/module_params/app.roc @@ -2,58 +2,58 @@ app [main] { pf: platform "../test-platform-simple-zig/main.roc", } -import Api { appId: "one", protocol: https } as App1 -import Api { appId: "two", protocol: http } as App2 -import Api { appId: "prod_1", protocol: http } as Prod +import Api { app_id: "one", protocol: https } as App1 +import Api { app_id: "two", protocol: http } as App2 +import Api { app_id: "prod_1", protocol: http } as Prod https = \url -> "https://$(url)" http = \url -> "http://$(url)" -usersApp1 = +users_app1 = # pass top-level fn in a module with params - List.map [1, 2, 3] App1.getUser + List.map([1, 2, 3], App1.get_user) main = - app3Id = "three" + app3_id = "three" - import Api { appId: app3Id, protocol: https } as App3 + import Api { app_id: app3_id, protocol: https } as App3 - getUserApp3Nested = \userId -> + get_user_app3_nested = \user_id -> # use captured params def - App3.getUser userId + App3.get_user(user_id) - usersApp3Passed = + users_app3_passed = # pass top-level fn in a nested def - List.map [1, 2, 3] App3.getUser + List.map([1, 2, 3], App3.get_user) """ - App1.baseUrl: $(App1.baseUrl) - App2.baseUrl: $(App2.baseUrl) - App3.baseUrl: $(App3.baseUrl) - App1.getUser 1: $(App1.getUser 1) - App2.getUser 2: $(App2.getUser 2) - App3.getUser 3: $(App3.getUser 3) - App1.getPost 1: $(App1.getPost 1) - App2.getPost 2: $(App2.getPost 2) - App3.getPost 3: $(App3.getPost 3) - App1.getPosts [1, 2]: $(Inspect.toStr (App1.getPosts [1, 2])) - App2.getPosts [3, 4]: $(Inspect.toStr (App2.getPosts [3, 4])) - App2.getPosts [5, 6]: $(Inspect.toStr (App2.getPosts [5, 6])) - App1.getPostComments 1: $(App1.getPostComments 1) - App2.getPostComments 2: $(App2.getPostComments 2) - App2.getPostComments 3: $(App2.getPostComments 3) - App1.getCompanies [1, 2]: $(Inspect.toStr (App1.getCompanies [1, 2])) - App2.getCompanies [3, 4]: $(Inspect.toStr (App2.getCompanies [3, 4])) - App2.getCompanies [5, 6]: $(Inspect.toStr (App2.getCompanies [5, 6])) - App1.getPostAliased 1: $(App1.getPostAliased 1) - App2.getPostAliased 2: $(App2.getPostAliased 2) - App3.getPostAliased 3: $(App3.getPostAliased 3) - App1.baseUrlAliased: $(App1.baseUrlAliased) - App2.baseUrlAliased: $(App2.baseUrlAliased) - App3.baseUrlAliased: $(App3.baseUrlAliased) - App1.getUserSafe 1: $(App1.getUserSafe 1) - Prod.getUserSafe 2: $(Prod.getUserSafe 2) - usersApp1: $(Inspect.toStr usersApp1) - getUserApp3Nested 3: $(getUserApp3Nested 3) - usersApp3Passed: $(Inspect.toStr usersApp3Passed) + App1.baseUrl: $(App1.base_url) + App2.baseUrl: $(App2.base_url) + App3.baseUrl: $(App3.base_url) + App1.getUser 1: $(App1.get_user(1)) + App2.getUser 2: $(App2.get_user(2)) + App3.getUser 3: $(App3.get_user(3)) + App1.getPost 1: $(App1.get_post(1)) + App2.getPost 2: $(App2.get_post(2)) + App3.getPost 3: $(App3.get_post(3)) + App1.getPosts [1, 2]: $(Inspect.to_str(App1.get_posts([1, 2]))) + App2.getPosts [3, 4]: $(Inspect.to_str(App2.get_posts([3, 4]))) + App2.getPosts [5, 6]: $(Inspect.to_str(App2.get_posts([5, 6]))) + App1.getPostComments 1: $(App1.get_post_comments(1)) + App2.getPostComments 2: $(App2.get_post_comments(2)) + App2.getPostComments 3: $(App2.get_post_comments(3)) + App1.getCompanies [1, 2]: $(Inspect.to_str(App1.get_companies([1, 2]))) + App2.getCompanies [3, 4]: $(Inspect.to_str(App2.get_companies([3, 4]))) + App2.getCompanies [5, 6]: $(Inspect.to_str(App2.get_companies([5, 6]))) + App1.getPostAliased 1: $(App1.get_post_aliased(1)) + App2.getPostAliased 2: $(App2.get_post_aliased(2)) + App3.getPostAliased 3: $(App3.get_post_aliased(3)) + App1.baseUrlAliased: $(App1.base_url_aliased) + App2.baseUrlAliased: $(App2.base_url_aliased) + App3.baseUrlAliased: $(App3.base_url_aliased) + App1.getUserSafe 1: $(App1.get_user_safe(1)) + Prod.getUserSafe 2: $(Prod.get_user_safe(2)) + usersApp1: $(Inspect.to_str(users_app1)) + getUserApp3Nested 3: $(get_user_app3_nested(3)) + usersApp3Passed: $(Inspect.to_str(users_app3_passed)) """ diff --git a/crates/cli/tests/test-projects/module_params/arity_mismatch.roc b/crates/cli/tests/test-projects/module_params/arity_mismatch.roc index 2c7cc3679db..a2f600ed348 100644 --- a/crates/cli/tests/test-projects/module_params/arity_mismatch.roc +++ b/crates/cli/tests/test-projects/module_params/arity_mismatch.roc @@ -2,16 +2,16 @@ app [main] { pf: platform "../test-platform-simple-zig/main.roc", } -import Api { appId: "one", protocol: https } +import Api { app_id: "one", protocol: https } https = \url -> "https://$(url)" main = """ # too many args - $(Api.getUser 1 2) - $(Api.baseUrl 1) + $(Api.get_user(1, 2)) + $(Api.base_url(1)) # too few args - $(Api.getPostComment 1) + $(Api.get_post_comment(1)) """ diff --git a/crates/cli/tests/test-projects/module_params/bad_ann.roc b/crates/cli/tests/test-projects/module_params/bad_ann.roc index d0529076b7e..a9c977e1272 100644 --- a/crates/cli/tests/test-projects/module_params/bad_ann.roc +++ b/crates/cli/tests/test-projects/module_params/bad_ann.roc @@ -2,7 +2,7 @@ app [main] { pf: platform "../test-platform-simple-zig/main.roc", } -import BadAnn { appId: "one" } +import BadAnn { app_id: "one" } main = "" diff --git a/crates/cli/tests/test-projects/module_params/different_types.roc b/crates/cli/tests/test-projects/module_params/different_types.roc index 2f0412e4651..d144467f04a 100644 --- a/crates/cli/tests/test-projects/module_params/different_types.roc +++ b/crates/cli/tests/test-projects/module_params/different_types.roc @@ -9,6 +9,6 @@ import Alias { passed: Stdin.line } as In import Alias { passed: Stdout.line } as Out main = - Out.exposed! "Write something:" + Out.exposed!("Write something:") input = In.exposed! - Out.exposed! input + Out.exposed!(input) diff --git a/crates/cli/tests/test-projects/module_params/effect_module.roc b/crates/cli/tests/test-projects/module_params/effect_module.roc index 8728f52e556..9e745eb553b 100644 --- a/crates/cli/tests/test-projects/module_params/effect_module.roc +++ b/crates/cli/tests/test-projects/module_params/effect_module.roc @@ -1,3 +1,3 @@ module { stdout! } -> [log!] -log! = \msg, level -> stdout! "$(level):$(msg)" +log! = \msg, level -> stdout!("$(level):$(msg)") diff --git a/crates/cli/tests/test-projects/module_params/issue_7116.roc b/crates/cli/tests/test-projects/module_params/issue_7116.roc index 891ad5a9aef..dc2d64363bd 100644 --- a/crates/cli/tests/test-projects/module_params/issue_7116.roc +++ b/crates/cli/tests/test-projects/module_params/issue_7116.roc @@ -2,10 +2,10 @@ app [main] { cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br", } -import Alias { passed: Task.ok {} } +import Alias { passed: Task.ok({}) } main = - Task.loop! {} loop + Task.loop!({}, loop) loop = \{} -> - Task.map Alias.exposed \x -> Done x + Task.map(Alias.exposed, \x -> Done(x)) diff --git a/crates/cli/tests/test-projects/module_params/multiline_params.roc b/crates/cli/tests/test-projects/module_params/multiline_params.roc index f12c466b449..fb6c4dea3fa 100644 --- a/crates/cli/tests/test-projects/module_params/multiline_params.roc +++ b/crates/cli/tests/test-projects/module_params/multiline_params.roc @@ -3,8 +3,8 @@ app [main] { } import MultilineParams { - sendHttpReq: \_ -> crash "todo", - getEnvVar: \_ -> crash "todo", + send_http_req: \_ -> crash("todo"), + get_env_var: \_ -> crash("todo"), } main = diff --git a/crates/cli/tests/test-projects/module_params/pass_task.roc b/crates/cli/tests/test-projects/module_params/pass_task.roc index 5d3d17f176f..9d80f5b0ea1 100644 --- a/crates/cli/tests/test-projects/module_params/pass_task.roc +++ b/crates/cli/tests/test-projects/module_params/pass_task.roc @@ -1,7 +1,7 @@ app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br" } import pf.Stdout -import Menu { echo: \str -> Stdout.line str } +import Menu { echo: \str -> Stdout.line(str) } main = - Menu.menu "Agus" + Menu.menu("Agus") diff --git a/crates/cli/tests/test-projects/module_params/unexpected_fn.roc b/crates/cli/tests/test-projects/module_params/unexpected_fn.roc index 1867f57238e..6c3a49a5d9c 100644 --- a/crates/cli/tests/test-projects/module_params/unexpected_fn.roc +++ b/crates/cli/tests/test-projects/module_params/unexpected_fn.roc @@ -2,11 +2,9 @@ app [main] { pf: platform "../test-platform-simple-zig/main.roc", } -import Api { appId: "one", protocol: https } +import Api { app_id: "one", protocol: https } https = \url -> "https://$(url)" main = - """ - $(Api.getPost) - """ + "$(Api.get_post)" diff --git a/crates/cli/tests/test-projects/multiple_exposed/main.roc b/crates/cli/tests/test-projects/multiple_exposed/main.roc index f2f40e7eaf3..2c49df47b7a 100644 --- a/crates/cli/tests/test-projects/multiple_exposed/main.roc +++ b/crates/cli/tests/test-projects/multiple_exposed/main.roc @@ -1,20 +1,20 @@ app [exposed1, exposed2, add1, sub1] { pf: platform "platform/main.roc" } -exposed1 = \n -> fib n 0 1 +exposed1 = \n -> fib(n, 0, 1) fib = \n, a, b -> if n == 0 then a else - fib (n - 1) b (a + b) + fib((n - 1), b, (a + b)) -exposed2 = \n -> fact n 1 +exposed2 = \n -> fact(n, 1) fact = \n, x -> if n == 0 then x else - fact (n - 1) (n * x) + fact((n - 1), (n * x)) add1 = \n -> n + 1 sub1 = \n -> n - 1 diff --git a/crates/cli/tests/test-projects/multiple_exposed/platform/host.zig b/crates/cli/tests/test-projects/multiple_exposed/platform/host.zig index 5ab48472ced..c3885f6223b 100644 --- a/crates/cli/tests/test-projects/multiple_exposed/platform/host.zig +++ b/crates/cli/tests/test-projects/multiple_exposed/platform/host.zig @@ -10,8 +10,8 @@ const maxInt = std.math.maxInt; const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__exposedForHost1_1_exposed(i64) i64; -extern fn roc__exposedForHost2_1_exposed(i64) i64; +extern fn roc__exposed_for_host1_1_exposed(i64) i64; +extern fn roc__exposed_for_host2_1_exposed(i64) i64; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -109,8 +109,8 @@ comptime { pub export fn main() u8 { const stdout = std.io.getStdOut().writer(); - const result = roc__exposedForHost1_1_exposed(10); - const result2 = roc__exposedForHost2_1_exposed(10); + const result = roc__exposed_for_host1_1_exposed(10); + const result2 = roc__exposed_for_host2_1_exposed(10); stdout.print("{d}\n", .{result}) catch unreachable; stdout.print("{d}\n", .{result2}) catch unreachable; diff --git a/crates/cli/tests/test-projects/multiple_exposed/platform/main.roc b/crates/cli/tests/test-projects/multiple_exposed/platform/main.roc index 4b5f5a0277c..04c89821e52 100644 --- a/crates/cli/tests/test-projects/multiple_exposed/platform/main.roc +++ b/crates/cli/tests/test-projects/multiple_exposed/platform/main.roc @@ -3,10 +3,10 @@ platform "multiple_exposed" exposes [] packages {} imports [] - provides [exposedForHost1, exposedForHost2] + provides [exposed_for_host1, exposed_for_host2] -exposedForHost1 : I64 -> I64 -exposedForHost1 = \a -> exposed1 a |> sub1 |> add1 +exposed_for_host1 : I64 -> I64 +exposed_for_host1 = \a -> exposed1(a) |> sub1 |> add1 -exposedForHost2 : I64 -> I64 -exposedForHost2 = \a -> exposed2 a |> add1 |> sub1 +exposed_for_host2 : I64 -> I64 +exposed_for_host2 = \a -> exposed2(a) |> add1 |> sub1 diff --git a/crates/cli/tests/test-projects/platform_requires_pkg/platform/host.zig b/crates/cli/tests/test-projects/platform_requires_pkg/platform/host.zig index 0d8574224a5..441240d1692 100644 --- a/crates/cli/tests/test-projects/platform_requires_pkg/platform/host.zig +++ b/crates/cli/tests/test-projects/platform_requires_pkg/platform/host.zig @@ -101,7 +101,7 @@ comptime { const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic(*RocStr) void; +extern fn roc__main_for_host_1_exposed_generic(*RocStr) void; const Unit = extern struct {}; @@ -110,7 +110,7 @@ pub export fn main() u8 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed_generic(&callresult); + roc__main_for_host_1_exposed_generic(&callresult); // stdout the result stdout.print("{s}", .{callresult.asSlice()}) catch unreachable; diff --git a/crates/cli/tests/test-projects/platform_requires_pkg/platform/main.roc b/crates/cli/tests/test-projects/platform_requires_pkg/platform/main.roc index b8c40ae927d..56565e7ec6b 100644 --- a/crates/cli/tests/test-projects/platform_requires_pkg/platform/main.roc +++ b/crates/cli/tests/test-projects/platform_requires_pkg/platform/main.roc @@ -5,10 +5,10 @@ platform "test" foo: "../foo/main.roc", } imports [] - provides [mainForHost] + provides [main_for_host] import foo.Foo -mainForHost : Str -mainForHost = +main_for_host : Str +main_for_host = "$(main) $(Foo.foo)" diff --git a/crates/cli/tests/test-projects/test-platform-effects-zig/Effect.roc b/crates/cli/tests/test-projects/test-platform-effects-zig/Effect.roc index 8b1ab6d69fa..c719a7886cc 100644 --- a/crates/cli/tests/test-projects/test-platform-effects-zig/Effect.roc +++ b/crates/cli/tests/test-projects/test-platform-effects-zig/Effect.roc @@ -1,7 +1,7 @@ hosted Effect - exposes [putLine!, getLine!] + exposes [put_line!, get_line!] imports [] -putLine! : Str => {} +put_line! : Str => {} -getLine! : {} => Str +get_line! : {} => Str diff --git a/crates/cli/tests/test-projects/test-platform-effects-zig/app-stub.roc b/crates/cli/tests/test-projects/test-platform-effects-zig/app-stub.roc index 09149a4d3c5..b5f3d90d2a0 100644 --- a/crates/cli/tests/test-projects/test-platform-effects-zig/app-stub.roc +++ b/crates/cli/tests/test-projects/test-platform-effects-zig/app-stub.roc @@ -5,6 +5,6 @@ import pf.Effect # just a stubbed app for building the test platform main! = \{} -> - Effect.putLine! "" + Effect.put_line!("") {} diff --git a/crates/cli/tests/test-projects/test-platform-effects-zig/host.zig b/crates/cli/tests/test-projects/test-platform-effects-zig/host.zig index 4380a947223..93247117dd2 100644 --- a/crates/cli/tests/test-projects/test-platform-effects-zig/host.zig +++ b/crates/cli/tests/test-projects/test-platform-effects-zig/host.zig @@ -10,8 +10,8 @@ const maxInt = std.math.maxInt; const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic([*]u8) void; -extern fn roc__mainForHost_1_exposed_size() i64; +extern fn roc__main_for_host_1_exposed_generic([*]u8) void; +extern fn roc__main_for_host_1_exposed_size() i64; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -111,7 +111,7 @@ pub export fn main() u8 { const allocator = std.heap.page_allocator; // NOTE the return size can be zero, which will segfault. Always allocate at least 8 bytes - const size = @max(8, @as(usize, @intCast(roc__mainForHost_1_exposed_size()))); + const size = @max(8, @as(usize, @intCast(roc__main_for_host_1_exposed_size()))); const raw_output = allocator.alignedAlloc(u8, @alignOf(u64), @as(usize, @intCast(size))) catch unreachable; const output = @as([*]u8, @ptrCast(raw_output)); @@ -119,16 +119,16 @@ pub export fn main() u8 { allocator.free(raw_output); } - roc__mainForHost_1_exposed_generic(output); + roc__main_for_host_1_exposed_generic(output); return 0; } -pub export fn roc_fx_getLine() str.RocStr { - return roc_fx_getLine_help() catch return str.RocStr.empty(); +pub export fn roc_fx_get_line() str.RocStr { + return roc_fx_get_line_help() catch return str.RocStr.empty(); } -fn roc_fx_getLine_help() !RocStr { +fn roc_fx_get_line_help() !RocStr { const stdin = std.io.getStdIn().reader(); var buf: [400]u8 = undefined; @@ -137,7 +137,7 @@ fn roc_fx_getLine_help() !RocStr { return str.RocStr.init(@as([*]const u8, @ptrCast(line)), line.len); } -pub export fn roc_fx_putLine(rocPath: *str.RocStr) i64 { +pub export fn roc_fx_put_line(rocPath: *str.RocStr) i64 { const stdout = std.io.getStdOut().writer(); for (rocPath.asSlice()) |char| { @@ -155,8 +155,8 @@ const GetInt = extern struct { is_error: bool, }; -pub export fn roc_fx_getInt() GetInt { - if (roc_fx_getInt_help()) |value| { +pub export fn roc_fx_get_int() GetInt { + if (roc_fx_get_int_help()) |value| { const get_int = GetInt{ .is_error = false, .value = value, .error_code = 0 }; return get_int; } else |err| switch (err) { @@ -171,7 +171,7 @@ pub export fn roc_fx_getInt() GetInt { return 0; } -fn roc_fx_getInt_help() !i64 { +fn roc_fx_get_int_help() !i64 { const stdin = std.io.getStdIn().reader(); var buf: [40]u8 = undefined; diff --git a/crates/cli/tests/test-projects/test-platform-effects-zig/main.roc b/crates/cli/tests/test-projects/test-platform-effects-zig/main.roc index bcaccafe040..beaf945cd5c 100644 --- a/crates/cli/tests/test-projects/test-platform-effects-zig/main.roc +++ b/crates/cli/tests/test-projects/test-platform-effects-zig/main.roc @@ -3,7 +3,7 @@ platform "effects" exposes [] packages {} imports [] - provides [mainForHost!] + provides [main_for_host!] -mainForHost! : {} => {} -mainForHost! = \{} -> main! {} +main_for_host! : {} => {} +main_for_host! = \{} -> main!({}) diff --git a/crates/cli/tests/test-projects/test-platform-simple-zig/host.zig b/crates/cli/tests/test-projects/test-platform-simple-zig/host.zig index d621b10bf34..4da7370c432 100644 --- a/crates/cli/tests/test-projects/test-platform-simple-zig/host.zig +++ b/crates/cli/tests/test-projects/test-platform-simple-zig/host.zig @@ -9,7 +9,7 @@ const expect = testing.expect; const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic(*RocStr) void; +extern fn roc__main_for_host_1_exposed_generic(*RocStr) void; const Align = 2 * @alignOf(usize); extern fn malloc(size: usize) callconv(.C) ?*align(Align) anyopaque; @@ -96,7 +96,7 @@ pub export fn main() i32 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed_generic(&callresult); + roc__main_for_host_1_exposed_generic(&callresult); // stdout the result stdout.print("{s}\n", .{callresult.asSlice()}) catch unreachable; diff --git a/crates/cli/tests/test-projects/test-platform-simple-zig/main.roc b/crates/cli/tests/test-projects/test-platform-simple-zig/main.roc index e141577dcb2..45ca32d1a2b 100644 --- a/crates/cli/tests/test-projects/test-platform-simple-zig/main.roc +++ b/crates/cli/tests/test-projects/test-platform-simple-zig/main.roc @@ -3,7 +3,7 @@ platform "" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/crates/cli/tests/test-projects/tui/main.roc b/crates/cli/tests/test-projects/tui/main.roc index b882363b8b3..35f3cc08c09 100644 --- a/crates/cli/tests/test-projects/tui/main.roc +++ b/crates/cli/tests/test-projects/tui/main.roc @@ -7,6 +7,6 @@ Model : Str main : Program Model main = { init: \{} -> "Hello World", - update: \model, new -> Str.concat model new, - view: \model -> Str.concat model "!", + update: \model, new -> Str.concat(model, new), + view: \model -> Str.concat(model, "!"), } diff --git a/crates/cli/tests/test-projects/tui/platform/host.zig b/crates/cli/tests/test-projects/tui/platform/host.zig index b3e6da41e58..370ca907d42 100644 --- a/crates/cli/tests/test-projects/tui/platform/host.zig +++ b/crates/cli/tests/test-projects/tui/platform/host.zig @@ -12,18 +12,18 @@ const Allocator = mem.Allocator; const Program = extern struct { init: RocStr, update: Unit, view: Unit }; -extern fn roc__mainForHost_1_exposed() Program; -extern fn roc__mainForHost_size() i64; +extern fn roc__main_for_host_1_exposed() Program; +extern fn roc__main_for_host_size() i64; const ConstModel = [*]const u8; const MutModel = [*]u8; -extern fn roc__mainForHost_0_caller([*]u8, [*]u8, MutModel) void; -extern fn roc__mainForHost_0_size() i64; -extern fn roc__mainForHost_0_result_size() i64; +extern fn roc__main_for_host_0_caller([*]u8, [*]u8, MutModel) void; +extern fn roc__main_for_host_0_size() i64; +extern fn roc__main_for_host_0_result_size() i64; fn allocate_model(allocator: *Allocator) MutModel { - const size = roc__mainForHost_0_result_size(); + const size = roc__main_for_host_0_result_size(); const raw_output = allocator.alignedAlloc(u8, @alignOf(u64), @as(usize, @intCast(size))) catch unreachable; const output = @as([*]u8, @ptrCast(raw_output)); @@ -34,33 +34,33 @@ fn init(allocator: *Allocator) ConstModel { const closure: [*]u8 = undefined; const output = allocate_model(allocator); - roc__mainForHost_0_caller(closure, closure, output); + roc__main_for_host_0_caller(closure, closure, output); return output; } -extern fn roc__mainForHost_1_caller(ConstModel, *const RocStr, [*]u8, MutModel) void; -extern fn roc__mainForHost_1_size() i64; -extern fn roc__mainForHost_1_result_size() i64; +extern fn roc__main_for_host_1_caller(ConstModel, *const RocStr, [*]u8, MutModel) void; +extern fn roc__main_for_host_1_size() i64; +extern fn roc__main_for_host_1_result_size() i64; fn update(allocator: *Allocator, model: ConstModel, msg: RocStr) ConstModel { const closure: [*]u8 = undefined; const output = allocate_model(allocator); - roc__mainForHost_1_caller(model, &msg, closure, output); + roc__main_for_host_1_caller(model, &msg, closure, output); return output; } -extern fn roc__mainForHost_2_caller(ConstModel, [*]u8, *RocStr) void; -extern fn roc__mainForHost_2_size() i64; -extern fn roc__mainForHost_2_result_size() i64; +extern fn roc__main_for_host_2_caller(ConstModel, [*]u8, *RocStr) void; +extern fn roc__main_for_host_2_size() i64; +extern fn roc__main_for_host_2_result_size() i64; fn view(input: ConstModel) RocStr { const closure: [*]u8 = undefined; var output: RocStr = undefined; - roc__mainForHost_2_caller(input, closure, &output); + roc__main_for_host_2_caller(input, closure, &output); return output; } @@ -171,7 +171,7 @@ comptime { const Unit = extern struct {}; pub export fn main() callconv(.C) u8 { - const program = roc__mainForHost_1_exposed(); + const program = roc__main_for_host_1_exposed(); call_the_closure(program); @@ -206,7 +206,7 @@ fn call_the_closure(program: Program) void { return; } -pub export fn roc_fx_putInt(int: i64) i64 { +pub export fn roc_fx_put_int(int: i64) i64 { const stdout = std.io.getStdOut().writer(); stdout.print("{d}", .{int}) catch unreachable; @@ -216,7 +216,7 @@ pub export fn roc_fx_putInt(int: i64) i64 { return 0; } -export fn roc_fx_putLine(rocPath: str.RocStr) callconv(.C) void { +export fn roc_fx_put_line(rocPath: str.RocStr) callconv(.C) void { const stdout = std.io.getStdOut().writer(); for (rocPath.asSlice()) |char| { @@ -234,14 +234,14 @@ const GetInt = extern struct { comptime { if (@sizeOf(usize) == 8) { - @export(roc_fx_getInt_64bit, .{ .name = "roc_fx_getInt" }); + @export(roc_fx_get_int_64bit, .{ .name = "roc_fx_get_int" }); } else { - @export(roc_fx_getInt_32bit, .{ .name = "roc_fx_getInt" }); + @export(roc_fx_get_int_32bit, .{ .name = "roc_fx_get_int" }); } } -fn roc_fx_getInt_64bit() callconv(.C) GetInt { - if (roc_fx_getInt_help()) |value| { +fn roc_fx_get_int_64bit() callconv(.C) GetInt { + if (roc_fx_get_int_help()) |value| { const get_int = GetInt{ .is_error = false, .value = value, .error_code = false }; return get_int; } else |err| switch (err) { @@ -256,8 +256,8 @@ fn roc_fx_getInt_64bit() callconv(.C) GetInt { return 0; } -fn roc_fx_getInt_32bit(output: *GetInt) callconv(.C) void { - if (roc_fx_getInt_help()) |value| { +fn roc_fx_get_int_32bit(output: *GetInt) callconv(.C) void { + if (roc_fx_get_int_help()) |value| { const get_int = GetInt{ .is_error = false, .value = value, .error_code = false }; output.* = get_int; } else |err| switch (err) { @@ -272,7 +272,7 @@ fn roc_fx_getInt_32bit(output: *GetInt) callconv(.C) void { return; } -fn roc_fx_getInt_help() !i64 { +fn roc_fx_get_int_help() !i64 { const stdin = std.io.getStdIn().reader(); var buf: [40]u8 = undefined; diff --git a/crates/cli/tests/test-projects/tui/platform/main.roc b/crates/cli/tests/test-projects/tui/platform/main.roc index f4f2386d262..d7a0c963249 100644 --- a/crates/cli/tests/test-projects/tui/platform/main.roc +++ b/crates/cli/tests/test-projects/tui/platform/main.roc @@ -3,7 +3,7 @@ platform "tui" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : { init : ({} -> Model) as Init, update : (Model, Str -> Model) as Update, view : (Model -> Str) as View } -mainForHost = main +main_for_host : { init : ({} -> Model) as Init, update : (Model, Str -> Model) as Update, view : (Model -> Str) as View } +main_for_host = main diff --git a/crates/compiler/alias_analysis/src/lib.rs b/crates/compiler/alias_analysis/src/lib.rs index abbbe813fa4..925efc3bf29 100644 --- a/crates/compiler/alias_analysis/src/lib.rs +++ b/crates/compiler/alias_analysis/src/lib.rs @@ -28,7 +28,7 @@ pub const MOD_APP: ModName = ModName(b"UserApp"); pub const STATIC_STR_NAME: ConstName = ConstName(&Symbol::STR_ALIAS_ANALYSIS_STATIC.to_ne_bytes()); pub const STATIC_LIST_NAME: ConstName = ConstName(b"THIS IS A STATIC LIST"); -const DEFAULT_ENTRY_POINT_NAME: &[u8] = b"mainForHost"; +const DEFAULT_ENTRY_POINT_NAME: &[u8] = b"main_for_host"; pub fn func_name_bytes(proc: &Proc) -> [u8; SIZE] { let bytes = func_name_bytes_help( diff --git a/crates/compiler/builtins/bitcode/src/dec.zig b/crates/compiler/builtins/bitcode/src/dec.zig index 53a4cb3df77..f93eca695ff 100644 --- a/crates/compiler/builtins/bitcode/src/dec.zig +++ b/crates/compiler/builtins/bitcode/src/dec.zig @@ -144,7 +144,7 @@ pub const RocDec = extern struct { return (c -% 48) <= 9; } - pub fn toStr(self: RocDec) RocStr { + pub fn to_str(self: RocDec) RocStr { // Special case if (self.num == 0) { return RocStr.init("0.0", 3); @@ -1031,97 +1031,97 @@ test "fromStr: .123.1" { try expectEqual(dec, null); } -test "toStr: 100.00" { +test "to_str: 100.00" { var dec: RocDec = .{ .num = 100000000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "100.0"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 123.45" { +test "to_str: 123.45" { var dec: RocDec = .{ .num = 123450000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "123.45"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: -123.45" { +test "to_str: -123.45" { var dec: RocDec = .{ .num = -123450000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "-123.45"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 123.0" { +test "to_str: 123.0" { var dec: RocDec = .{ .num = 123000000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "123.0"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: -123.0" { +test "to_str: -123.0" { var dec: RocDec = .{ .num = -123000000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "-123.0"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 0.45" { +test "to_str: 0.45" { var dec: RocDec = .{ .num = 450000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "0.45"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: -0.45" { +test "to_str: -0.45" { var dec: RocDec = .{ .num = -450000000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "-0.45"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 0.00045" { +test "to_str: 0.00045" { var dec: RocDec = .{ .num = 450000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "0.00045"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: -0.00045" { +test "to_str: -0.00045" { var dec: RocDec = .{ .num = -450000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "-0.00045"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: -111.123456" { +test "to_str: -111.123456" { var dec: RocDec = .{ .num = -111123456000000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "-111.123456"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 123.1111111" { +test "to_str: 123.1111111" { var dec: RocDec = .{ .num = 123111111100000000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "123.1111111"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 123.1111111111111 (big str)" { +test "to_str: 123.1111111111111 (big str)" { var dec: RocDec = .{ .num = 123111111111111000000 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); errdefer res_roc_str.decref(); defer res_roc_str.decref(); @@ -1129,9 +1129,9 @@ test "toStr: 123.1111111111111 (big str)" { try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 123.111111111111444444 (max number of decimal places)" { +test "to_str: 123.111111111111444444 (max number of decimal places)" { var dec: RocDec = .{ .num = 123111111111111444444 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); errdefer res_roc_str.decref(); defer res_roc_str.decref(); @@ -1139,9 +1139,9 @@ test "toStr: 123.111111111111444444 (max number of decimal places)" { try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 12345678912345678912.111111111111111111 (max number of digits)" { +test "to_str: 12345678912345678912.111111111111111111 (max number of digits)" { var dec: RocDec = .{ .num = 12345678912345678912111111111111111111 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); errdefer res_roc_str.decref(); defer res_roc_str.decref(); @@ -1149,9 +1149,9 @@ test "toStr: 12345678912345678912.111111111111111111 (max number of digits)" { try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: std.math.maxInt" { +test "to_str: std.math.maxInt" { var dec: RocDec = .{ .num = std.math.maxInt(i128) }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); errdefer res_roc_str.decref(); defer res_roc_str.decref(); @@ -1159,9 +1159,9 @@ test "toStr: std.math.maxInt" { try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: std.math.minInt" { +test "to_str: std.math.minInt" { var dec: RocDec = .{ .num = std.math.minInt(i128) }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); errdefer res_roc_str.decref(); defer res_roc_str.decref(); @@ -1169,9 +1169,9 @@ test "toStr: std.math.minInt" { try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); } -test "toStr: 0" { +test "to_str: 0" { var dec: RocDec = .{ .num = 0 }; - var res_roc_str = dec.toStr(); + var res_roc_str = dec.to_str(); const res_slice: []const u8 = "0.0"[0..]; try expectEqualSlices(u8, res_slice, res_roc_str.asSlice()); @@ -1443,8 +1443,8 @@ pub fn fromStr(arg: RocStr) callconv(.C) num_.NumParseResult(i128) { } } -pub fn toStr(arg: RocDec) callconv(.C) RocStr { - return @call(.always_inline, RocDec.toStr, .{arg}); +pub fn to_str(arg: RocDec) callconv(.C) RocStr { + return @call(.always_inline, RocDec.to_str, .{arg}); } pub fn fromF64C(arg: f64) callconv(.C) i128 { diff --git a/crates/compiler/builtins/bitcode/src/main.zig b/crates/compiler/builtins/bitcode/src/main.zig index f1b3ccfaa13..52a02c75c7d 100644 --- a/crates/compiler/builtins/bitcode/src/main.zig +++ b/crates/compiler/builtins/bitcode/src/main.zig @@ -50,7 +50,7 @@ comptime { exportDecFn(dec.toF64, "to_f64"); exportDecFn(dec.toI128, "to_i128"); exportDecFn(dec.fromI128, "from_i128"); - exportDecFn(dec.toStr, "to_str"); + exportDecFn(dec.to_str, "to_str"); for (INTEGERS) |T| { dec.exportFromInt(T, ROC_BUILTINS ++ ".dec.from_int."); diff --git a/crates/compiler/builtins/roc/Num.roc b/crates/compiler/builtins/roc/Num.roc index 4b85aef6cf6..906dc43207e 100644 --- a/crates/compiler/builtins/roc/Num.roc +++ b/crates/compiler/builtins/roc/Num.roc @@ -199,8 +199,8 @@ import Result exposing [Result] ## ends up having the type `U64`. ## ## Sometimes number literals don't become more specific. For example, -## the `Num.toStr` function has the type `Num * -> Str`. This means that -## when calling `Num.toStr(5 + 6)`, the expression `5 + 6` +## the `Num.to_str` function has the type `Num * -> Str`. This means that +## when calling `Num.to_str(5 + 6)`, the expression `5 + 6` ## still has the type `Num *`. When this happens, `Num *` defaults to ## being an [I64] - so this addition expression would overflow ## if either 5 or 6 were replaced with a number big enough to cause @@ -209,7 +209,7 @@ import Result exposing [Result] ## If this default of [I64] is not big enough for your purposes, ## you can add an `i128` to the end of the number literal, like so: ## ```roc -## Num.toStr(5_000_000_000i128) +## Num.to_str(5_000_000_000i128) ## ``` ## This `i128` suffix specifies that you want this number literal to be ## an [I128] instead of a `Num *`. All the other numeric types have diff --git a/crates/compiler/can/src/desugar.rs b/crates/compiler/can/src/desugar.rs index fdbd99ccb77..4dd2cc70fa3 100644 --- a/crates/compiler/can/src/desugar.rs +++ b/crates/compiler/can/src/desugar.rs @@ -1494,7 +1494,7 @@ pub fn desugar_record_destructures<'a>( /// value produced by `expr`. Essentially: /// ( /// tmpVar = expr -/// LowLevelDbg (Inspect.toStr tmpVar) +/// LowLevelDbg (Inspect.to_str tmpVar) /// tmpVar /// ) fn desugar_dbg_expr<'a>( @@ -1552,7 +1552,7 @@ pub fn desugar_invalid_dbg_expr<'a>( desugar_dbg_expr(env, scope, placeholder_expr, outer_region) } -/// Desugars a `dbg x` statement into essentially `Inspect.toStr x |> LowLevelDbg` +/// Desugars a `dbg x` statement into essentially `Inspect.to_str x |> LowLevelDbg` fn desugar_dbg_stmt<'a>( env: &mut Env<'a>, condition: &'a Loc>, @@ -1562,7 +1562,7 @@ fn desugar_dbg_stmt<'a>( let inspect_fn = Var { module_name: ModuleName::INSPECT, - ident: "toStr", + ident: "to_str", }; let loc_inspect_fn_var = env.arena.alloc(Loc { value: inspect_fn, diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_expr.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_expr.snap index e671cbec8b1..b09bbd401a2 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_expr.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_expr.snap @@ -98,7 +98,7 @@ Defs { @21-26 Apply( @21-26 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @21-26 Var { @@ -126,7 +126,7 @@ Defs { @16-27 Apply( @16-27 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @16-27 Var { diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_simple.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_simple.snap index c6e36e9cc7f..706625b7ab0 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_simple.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_simple.snap @@ -49,7 +49,7 @@ Defs { @33-36 Apply( @33-36 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @33-36 Var { diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_stmt_arg.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_stmt_arg.snap index 7c505c58a76..f7cc5f82347 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_stmt_arg.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__dbg_stmt_arg.snap @@ -49,7 +49,7 @@ Defs { @15-16 Apply( @15-16 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @15-16 Var { diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__pizza_dbg.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__pizza_dbg.snap index 947dc76d843..d064a11fd38 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__pizza_dbg.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__pizza_dbg.snap @@ -87,7 +87,7 @@ Defs { @11-12 Apply( @11-12 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @11-12 Var { @@ -122,7 +122,7 @@ Defs { @11-40 Apply( @11-40 Var { module_name: "Inspect", - ident: "toStr", + ident: "to_str", }, [ @11-40 Var { diff --git a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__simple_double_question.snap b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__simple_double_question.snap index eef6b18099c..db3bd62f196 100644 --- a/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__simple_double_question.snap +++ b/crates/compiler/can/tests/snapshots/test_suffixed__suffixed_tests__simple_double_question.snap @@ -8,7 +8,7 @@ Defs { EitherIndex(2147483648), ], regions: [ - @0-85, + @0-86, ], space_before: [ Slice { start: 0, length: 0 }, @@ -25,19 +25,19 @@ Defs { @0-4 Identifier { ident: "main", }, - @11-69 Apply( - @11-69 Var { + @11-70 Apply( + @11-70 Var { module_name: "Task", ident: "await", }, [ - @11-69 Defs( + @11-70 Defs( Defs { tags: [ EitherIndex(2147483648), ], regions: [ - @11-69, + @11-70, ], space_before: [ Slice { start: 0, length: 0 }, @@ -49,34 +49,34 @@ Defs { type_defs: [], value_defs: [ AnnotatedBody { - ann_pattern: @11-69 Identifier { + ann_pattern: @11-70 Identifier { ident: "#!0_stmt", }, - ann_type: @11-69 Apply( + ann_type: @11-70 Apply( "", "Task", [ - @11-69 Record { + @11-70 Record { fields: [], ext: None, }, - @11-69 Inferred, + @11-70 Inferred, ], ), lines_between: [], - body_pattern: @11-69 Identifier { + body_pattern: @11-70 Identifier { ident: "#!0_stmt", }, - body_expr: @11-69 Apply( - @11-69 Var { + body_expr: @11-70 Apply( + @11-70 Var { module_name: "", ident: "line", }, [ - @11-56 Apply( - @47-56 Var { + @11-57 Apply( + @47-57 Var { module_name: "Num", - ident: "toStr", + ident: "to_str", }, [ @11-39 Apply( @@ -151,24 +151,24 @@ Defs { }, ], }, - @11-69 Var { + @11-70 Var { module_name: "", ident: "#!0_stmt", }, ), - @11-69 Closure( + @11-70 Closure( [ - @11-69 Underscore( + @11-70 Underscore( "#!stmt", ), ], - @75-85 Apply( - @75-82 Var { + @76-86 Apply( + @76-83 Var { module_name: "Task", ident: "ok", }, [ - @83-85 Record( + @84-86 Record( [], ), ], diff --git a/crates/compiler/can/tests/test_suffixed.rs b/crates/compiler/can/tests/test_suffixed.rs index 34183b49411..0740ed66b13 100644 --- a/crates/compiler/can/tests/test_suffixed.rs +++ b/crates/compiler/can/tests/test_suffixed.rs @@ -164,7 +164,7 @@ mod suffixed_tests { main = "123" |> Str.toU8 ?? 255 - |> Num.toStr + |> Num.to_str |> line! Task.ok {} diff --git a/crates/compiler/checkmate/www/src/components/Graph/VariablesGraph.tsx b/crates/compiler/checkmate/www/src/components/Graph/VariablesGraph.tsx index 6b646c8d4cb..ed659541a7f 100644 --- a/crates/compiler/checkmate/www/src/components/Graph/VariablesGraph.tsx +++ b/crates/compiler/checkmate/www/src/components/Graph/VariablesGraph.tsx @@ -409,10 +409,10 @@ function Graph({ const edgeChanges: EdgeChange[] = []; while (toVariable !== undefined) { - const toVariableName = toVariable.toString(); + const toVariableName = toVariable.to_string(); if (canAddVariable(toVariableName, nodes)) { const newVariableNode = newVariable( - toVariable.toString(), + toVariable.to_string(), { subs, rawVariable: toVariable, @@ -440,7 +440,7 @@ function Graph({ const newEdge = addEdge({ id: `${fromVariable}->${toVariable}`, - source: fromVariable.toString(), + source: fromVariable.to_string(), target: toVariableName, markerEnd, }); diff --git a/crates/compiler/collections/src/small_string_interner.rs b/crates/compiler/collections/src/small_string_interner.rs index 29efa29e541..f9f009266c8 100644 --- a/crates/compiler/collections/src/small_string_interner.rs +++ b/crates/compiler/collections/src/small_string_interner.rs @@ -1,4 +1,3 @@ -use std::borrow::Cow; use std::{fmt::Debug, mem::ManuallyDrop}; /// Collection of small (length < u16::MAX) strings, stored compactly. @@ -114,7 +113,6 @@ impl SmallStringInterner { /// Insert without deduplicating pub fn insert(&mut self, string: &str) -> usize { - let string = Self::snakify_ident(string); let bytes = string.as_bytes(); assert!(bytes.len() < (1 << 15)); @@ -177,7 +175,6 @@ impl SmallStringInterner { pub fn find_indices<'a>(&'a self, string: &'a str) -> impl Iterator + 'a { use std::slice::from_raw_parts; - let string = Self::snakify_ident(string); let target_length = string.len(); let lengths: &[i16] = @@ -229,7 +226,6 @@ impl SmallStringInterner { } pub fn update(&mut self, index: usize, new_string: &str) { - let new_string = Self::snakify_ident(new_string); let length = new_string.len(); let offset = self.buffer.len(); @@ -244,8 +240,7 @@ impl SmallStringInterner { pub fn find_and_update(&mut self, old_string: &str, new_string: &str) -> Option { match self.find_index(old_string) { Some(index) => { - let new_string = Self::snakify_ident(new_string); - self.update(index, &new_string); + self.update(index, new_string); Some(index) } @@ -260,52 +255,6 @@ impl SmallStringInterner { pub fn is_empty(&self) -> bool { self.lengths.is_empty() } - - fn snakify_ident(s: &str) -> Cow<'_, str> { - if s.chars() - .next() - .is_some_and(|first_char| first_char.is_ascii_uppercase()) - || s.contains('_') - { - return s.into(); - } - - let chars: Vec = s.chars().collect(); - let mut index = 0; - let len = chars.len(); - let mut out = String::new(); - - while index < len { - let prev = if index == 0 { - None - } else { - Some(chars[index - 1]) - }; - let c = chars[index]; - let next = chars.get(index + 1); - let boundary = match (prev, c, next) { - // LUU, LUN, and LUL (simplified to LU_) - (Some(p), curr, _) if !p.is_ascii_uppercase() && curr.is_ascii_uppercase() => true, - // UUL - (Some(p), curr, Some(n)) - if p.is_ascii_uppercase() - && curr.is_ascii_uppercase() - && n.is_ascii_lowercase() => - { - true - } - _ => false, - }; - // those are boundary transitions - should push _ and curr - if boundary { - out.push('_'); - } - out.push(c.to_ascii_lowercase()); - index += 1; - } - - out.into() - } } #[allow(dead_code)] diff --git a/crates/compiler/gen_llvm/src/llvm/build.rs b/crates/compiler/gen_llvm/src/llvm/build.rs index 241d35c2570..1dca00d0b23 100644 --- a/crates/compiler/gen_llvm/src/llvm/build.rs +++ b/crates/compiler/gen_llvm/src/llvm/build.rs @@ -5799,8 +5799,8 @@ fn expose_alias_to_host<'a>( RawFunctionLayout::Function(arguments, closure, result) => { // define closure size and return value size, e.g. // - // * roc__mainForHost_1_Update_size() -> i64 - // * roc__mainForHost_1_Update_result_size() -> i64 + // * roc__main_for_host_1_Update_size() -> i64 + // * roc__main_for_host_1_Update_result_size() -> i64 let it = hels.proc_layout.arguments.iter().copied(); let bytes = roc_alias_analysis::func_name_bytes_help( @@ -5847,7 +5847,7 @@ fn expose_alias_to_host<'a>( RawFunctionLayout::ZeroArgumentThunk(result) => { // Define only the return value size, since this is a thunk // - // * roc__mainForHost_1_Update_result_size() -> i64 + // * roc__main_for_host_1_Update_result_size() -> i64 let result_type = basic_type_from_layout(env, layout_interner, layout_interner.get_repr(result)); @@ -5894,7 +5894,7 @@ fn build_closure_caller<'a, 'ctx>( // STEP 1: build function header - // e.g. `roc__mainForHost_0_caller` (def_name is `mainForHost_0`) + // e.g. `roc__main_for_host_0_caller` (def_name is `main_for_host_0`) let function_name = format!("roc__{def_name}_caller"); let function_spec = FunctionSpec::cconv(env, CCReturn::Void, None, &argument_types); diff --git a/crates/compiler/gen_llvm/src/llvm/build_str.rs b/crates/compiler/gen_llvm/src/llvm/build_str.rs index 7e23c88e03f..3e1a5a4ce6d 100644 --- a/crates/compiler/gen_llvm/src/llvm/build_str.rs +++ b/crates/compiler/gen_llvm/src/llvm/build_str.rs @@ -28,7 +28,7 @@ pub(crate) fn decode_from_utf8_result<'a, 'ctx>( ) } -/// Dec.toStr : Dec -> Str +/// Dec.to_str : Dec -> Str /// Str.equal : Str, Str -> Bool pub(crate) fn str_equal<'ctx>( diff --git a/crates/compiler/gen_llvm/src/llvm/lowlevel.rs b/crates/compiler/gen_llvm/src/llvm/lowlevel.rs index d414ce8dc3b..0947b9ee312 100644 --- a/crates/compiler/gen_llvm/src/llvm/lowlevel.rs +++ b/crates/compiler/gen_llvm/src/llvm/lowlevel.rs @@ -871,7 +871,7 @@ pub(crate) fn run_low_level<'a, 'ctx>( } } NumToStr => { - // Num.toStr : Num a -> Str + // Num.to_str : Num a -> Str arguments_with_layouts!((num, num_layout)); match layout_interner.get_repr(num_layout) { diff --git a/crates/compiler/gen_wasm/README.md b/crates/compiler/gen_wasm/README.md index 5957c02cb3e..02f73eb396d 100644 --- a/crates/compiler/gen_wasm/README.md +++ b/crates/compiler/gen_wasm/README.md @@ -186,7 +186,7 @@ The [official spec](https://webassembly.github.io/spec/core/binary/modules.html# We implement a few linking operations in the Wasm backend. The most important are host-to-app calls. -In the host .wasm file, `roc__mainForHost_1_exposed` is defined as a Wasm Import, as if it were an external JavaScript function. But when we link the host and app, we need to make it an internal function instead. +In the host .wasm file, `roc__main_for_host_1_exposed` is defined as a Wasm Import, as if it were an external JavaScript function. But when we link the host and app, we need to make it an internal function instead. There are a few important facts to note about the Wasm binary format: @@ -197,8 +197,8 @@ There are a few important facts to note about the Wasm binary format: With that background, here are the linking steps for a single app function that gets called by the host: -- Remove `roc__mainForHost_1_exposed` from the imports, updating all call sites to the new index, which is somewhere in the app. -- Swap the _last_ JavaScript import into the slot where `roc__mainForHost_1_exposed` was, updating all of its call sites in the host. +- Remove `roc__main_for_host_1_exposed` from the imports, updating all call sites to the new index, which is somewhere in the app. +- Swap the _last_ JavaScript import into the slot where `roc__main_for_host_1_exposed` was, updating all of its call sites in the host. - Insert an internally-defined dummy function at the index where the last JavaScript import used to be. The diagram below illustrates this process. diff --git a/crates/compiler/gen_wasm/docs/host-to-app-calls.svg b/crates/compiler/gen_wasm/docs/host-to-app-calls.svg index c6c2e64d259..0c11f8d5b35 100644 --- a/crates/compiler/gen_wasm/docs/host-to-app-calls.svg +++ b/crates/compiler/gen_wasm/docs/host-to-app-calls.svg @@ -1 +1 @@ -ImportsDefined0456mainForHost (must be removed from imports)18194104mainForHost (Roc)194648hostapp4142insertdummy@ 18185relocate18→56now only 17 importshost defined functionskeep the same indices!preprocessed hostfinal binaryImport section: swap_remove(5)Function section: signatures[5] = signatures[18]Code section: relocate calls 5→46 relocate calls 18→5 prepend 1 dummy functionOne host-to-app callImportsDefined04565 and 11 to be linked18194104Linked Roc functions194648hostapp4142insertdummy@ 17,18185relocate18→5, 17→116now only 16 importshost defined functionskeep the same indices!preprocessed hostfinal binaryImport section: swap_remove(5) swap_remove(11)Function section: signatures[5] = signatures[18] signatures[11] = signatures[17]Code section: relocate calls 5→46 relocate calls 18→5 relocate calls 11→44 relocate calls 17→11 prepend 2 dummy functionsTwo host-to-app calls11 \ No newline at end of file +ImportsDefined0456main_for_host (must be removed from imports)18194104main_for_host (Roc)194648hostapp4142insertdummy@ 18185relocate18→56now only 17 importshost defined functionskeep the same indices!preprocessed hostfinal binaryImport section: swap_remove(5)Function section: signatures[5] = signatures[18]Code section: relocate calls 5→46 relocate calls 18→5 prepend 1 dummy functionOne host-to-app callImportsDefined04565 and 11 to be linked18194104Linked Roc functions194648hostapp4142insertdummy@ 17,18185relocate18→5, 17→116now only 16 importshost defined functionskeep the same indices!preprocessed hostfinal binaryImport section: swap_remove(5) swap_remove(11)Function section: signatures[5] = signatures[18] signatures[11] = signatures[17]Code section: relocate calls 5→46 relocate calls 18→5 relocate calls 11→44 relocate calls 17→11 prepend 2 dummy functionsTwo host-to-app calls11 \ No newline at end of file diff --git a/crates/compiler/load/tests/platform.roc b/crates/compiler/load/tests/platform.roc index 3403eed8586..18d29729ee2 100644 --- a/crates/compiler/load/tests/platform.roc +++ b/crates/compiler/load/tests/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : {} -> {} -mainForHost = \{} -> {} +main_for_host : {} -> {} +main_for_host = \{} -> {} diff --git a/crates/compiler/load/tests/test_reporting.rs b/crates/compiler/load/tests/test_reporting.rs index d3bbf36b60f..b4fc81d9e59 100644 --- a/crates/compiler/load/tests/test_reporting.rs +++ b/crates/compiler/load/tests/test_reporting.rs @@ -6353,7 +6353,7 @@ All branches in an `if` must have the same type! exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] effects fx.Effect { putChar : I64 -> Effect {}, @@ -14638,7 +14638,7 @@ All branches in an `if` must have the same type! indoc!( r#" myFunction = \x -> - y = Num.toStr x + y = Num.to_str x return y @@ -14927,7 +14927,7 @@ All branches in an `if` must have the same type! main! = \{} -> Effect.putLine! "hello" - Num.toStr 123 + Num.to_str 123 Ok {} "# @@ -14935,9 +14935,9 @@ All branches in an `if` must have the same type! @r#" ── IGNORED RESULT in /code/proj/Main.roc ─────────────────────────────────────── - The result of this call to `Num.toStr` is ignored: + The result of this call to `Num.to_str` is ignored: - 8│ Num.toStr 123 + 8│ Num.to_str 123 ^^^^^^^^^ Standalone statements are required to produce an empty record, but the @@ -14953,7 +14953,7 @@ All branches in an `if` must have the same type! This statement does not produce any effects: - 8│ Num.toStr 123 + 8│ Num.to_str 123 ^^^^^^^^^^^^^ Standalone statements are only useful if they call effectful @@ -14974,7 +14974,7 @@ All branches in an `if` must have the same type! main! = \{} -> Effect.putLine! "hello" - _ignored = Num.toStr 123 + _ignored = Num.to_str 123 Ok {} "# @@ -14984,7 +14984,7 @@ All branches in an `if` must have the same type! This assignment doesn't introduce any new variables: - 8│ _ignored = Num.toStr 123 + 8│ _ignored = Num.to_str 123 ^^^^^^^^ Since it doesn't call any effectful functions, this assignment cannot @@ -15042,7 +15042,7 @@ All branches in an `if` must have the same type! u64Nums = parseItemsWith Str.toU64 u8Nums = parseItemsWith Str.toU8 - "$(Inspect.toStr u64Nums) $(Inspect.toStr u8Nums)" + "$(Inspect.to_str u64Nums) $(Inspect.to_str u8Nums)" "# ), @"" // no errors diff --git a/crates/compiler/load_internal/src/module.rs b/crates/compiler/load_internal/src/module.rs index 76953675cf4..e29c5385781 100644 --- a/crates/compiler/load_internal/src/module.rs +++ b/crates/compiler/load_internal/src/module.rs @@ -228,7 +228,7 @@ pub struct Expectations { #[derive(Clone, Debug, Default)] pub struct ExposedToHost { - /// usually `mainForHost` + /// usually `main_for_host` pub top_level_values: MutMap, /// exposed closure types, typically `Fx` pub closure_types: Vec, diff --git a/crates/compiler/load_internal/tests/test_load.rs b/crates/compiler/load_internal/tests/test_load.rs index d623f0854f2..fb0387d2305 100644 --- a/crates/compiler/load_internal/tests/test_load.rs +++ b/crates/compiler/load_internal/tests/test_load.rs @@ -855,10 +855,10 @@ fn platform_exposes_main_return_by_pointer_issue() { exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] - mainForHost : { content: Str, other: Str } - mainForHost = main + main_for_host : { content: Str, other: Str } + main_for_host = main "# ), ), @@ -1839,7 +1839,7 @@ fn module_params_missing() { r#" module { key, exp } -> [url] - url = "example.com/$(key)?exp=$(Num.toStr exp)" + url = "example.com/$(key)?exp=$(Num.to_str exp)" "# ), ), @@ -1896,10 +1896,10 @@ fn issue_2863_module_type_does_not_exist() { exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] - mainForHost : Str - mainForHost = main + main_for_host : Str + main_for_host = main "# ), ), @@ -1957,12 +1957,12 @@ fn import_builtin_in_platform_and_check_app() { exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] import Str - mainForHost : Str - mainForHost = main + main_for_host : Str + main_for_host = main "# ), ), diff --git a/crates/compiler/mono/src/ir.rs b/crates/compiler/mono/src/ir.rs index be065c998fd..01c19f9a008 100644 --- a/crates/compiler/mono/src/ir.rs +++ b/crates/compiler/mono/src/ir.rs @@ -3222,7 +3222,7 @@ fn specialize_external_help<'a>( } if procs.host_exposed_symbols.contains(&proc.name.name()) { - // layouts that are (transitively) used in the type of `mainForHost`. + // layouts that are (transitively) used in the type of `main_for_host`. let mut host_exposed_layouts: Vec<_> = top_level .arguments .iter() diff --git a/crates/compiler/mono/src/layout.rs b/crates/compiler/mono/src/layout.rs index 941395edce6..f24c42d83d8 100644 --- a/crates/compiler/mono/src/layout.rs +++ b/crates/compiler/mono/src/layout.rs @@ -1290,7 +1290,7 @@ enum NichePriv<'a> { /// ```roc /// capture : _ -> ({} -> Str) /// capture = \val -> -/// forcer = \{} -> Num.toStr val +/// forcer = \{} -> Num.to_str val /// forcer /// /// fun = \x -> diff --git a/crates/compiler/solve/tests/solve_expr.rs b/crates/compiler/solve/tests/solve_expr.rs index 58330cbe949..434a4f31c0f 100644 --- a/crates/compiler/solve/tests/solve_expr.rs +++ b/crates/compiler/solve/tests/solve_expr.rs @@ -150,7 +150,7 @@ mod solve_expr { infer_eq_without_problem( indoc!( r" - Num.toStr + Num.to_str " ), "Num * -> Str", @@ -4584,8 +4584,8 @@ mod solve_expr { |> Str.concat ") (" |> Str.concat (printExpr b) |> Str.concat ")" - Val v -> Num.toStr v - Var v -> "Var " |> Str.concat (Num.toStr v) + Val v -> Num.to_str v + Var v -> "Var " |> Str.concat (Num.to_str v) main : Str main = printExpr (Var 3) diff --git a/crates/compiler/test_gen/src/gen_abilities.rs b/crates/compiler/test_gen/src/gen_abilities.rs index d8829ae0ad7..f8b43953b4e 100644 --- a/crates/compiler/test_gen/src/gen_abilities.rs +++ b/crates/compiler/test_gen/src/gen_abilities.rs @@ -48,13 +48,13 @@ fn hash_specialization_multiple_add() { MHash implements hash : a -> U64 where a implements MHash - Id := U64 implements [ MHash {hash: hashId} ] + Id := U64 implements [ MHash {hash: hash_id} ] - hashId = \@Id n -> n + hash_id = \@Id n -> n - One := {} implements [ MHash {hash: hashOne} ] + One := {} implements [ MHash {hash: hash_one} ] - hashOne = \@One _ -> 1 + hash_one = \@One _ -> 1 main = hash (@Id 1234) + hash (@One {}) "# @@ -80,8 +80,8 @@ fn alias_member_specialization() { hash = \@Id n -> n main = - aliasedMHash = hash - aliasedMHash (@Id 1234) + aliased_m_hash = hash + aliased_m_hash (@Id 1234) "# ), 1234, @@ -100,13 +100,13 @@ fn ability_constrained_in_non_member_usage() { MHash implements hash : a -> U64 where a implements MHash - mulMHashes : a, a -> U64 where a implements MHash - mulMHashes = \x, y -> hash x * hash y + mul_m_hashes : a, a -> U64 where a implements MHash + mul_m_hashes = \x, y -> hash x * hash y Id := U64 implements [MHash {hash}] hash = \@Id n -> n - result = mulMHashes (@Id 5) (@Id 7) + result = mul_m_hashes (@Id 5) (@Id 7) "# ), 35, @@ -125,12 +125,12 @@ fn ability_constrained_in_non_member_usage_inferred() { MHash implements hash : a -> U64 where a implements MHash - mulMHashes = \x, y -> hash x * hash y + mul_m_hashes = \x, y -> hash x * hash y Id := U64 implements [MHash {hash}] hash = \@Id n -> n - result = mulMHashes (@Id 5) (@Id 7) + result = mul_m_hashes (@Id 5) (@Id 7) "# ), 35, @@ -149,16 +149,16 @@ fn ability_constrained_in_non_member_multiple_specializations() { MHash implements hash : a -> U64 where a implements MHash - mulMHashes : a, b -> U64 where a implements MHash, b implements MHash - mulMHashes = \x, y -> hash x * hash y + mul_m_hashes : a, b -> U64 where a implements MHash, b implements MHash + mul_m_hashes = \x, y -> hash x * hash y - Id := U64 implements [MHash { hash: hashId }] - hashId = \@Id n -> n + Id := U64 implements [MHash { hash: hash_id }] + hash_id = \@Id n -> n - Three := {} implements [MHash { hash: hashThree }] - hashThree = \@Three _ -> 3 + Three := {} implements [MHash { hash: hash_three }] + hash_three = \@Three _ -> 3 - result = mulMHashes (@Id 100) (@Three {}) + result = mul_m_hashes (@Id 100) (@Three {}) "# ), 300, @@ -177,15 +177,15 @@ fn ability_constrained_in_non_member_multiple_specializations_inferred() { MHash implements hash : a -> U64 where a implements MHash - mulMHashes = \x, y -> hash x * hash y + mul_m_hashes = \x, y -> hash x * hash y - Id := U64 implements [MHash { hash: hashId }] - hashId = \@Id n -> n + Id := U64 implements [MHash { hash: hash_id }] + hash_id = \@Id n -> n - Three := {} implements [MHash { hash: hashThree }] - hashThree = \@Three _ -> 3 + Three := {} implements [MHash { hash: hash_three }] + hash_three = \@Three _ -> 3 - result = mulMHashes (@Id 100) (@Three {}) + result = mul_m_hashes (@Id 100) (@Three {}) "# ), 300, @@ -204,16 +204,16 @@ fn ability_used_as_type_still_compiles() { MHash implements hash : a -> U64 where a implements MHash - mulMHashes : MHash, MHash -> U64 - mulMHashes = \x, y -> hash x * hash y + mul_m_hashes : MHash, MHash -> U64 + mul_m_hashes = \x, y -> hash x * hash y - Id := U64 implements [MHash { hash: hashId }] - hashId = \@Id n -> n + Id := U64 implements [MHash { hash: hash_id }] + hash_id = \@Id n -> n - Three := {} implements [MHash { hash: hashThree }] - hashThree = \@Three _ -> 3 + Three := {} implements [MHash { hash: hash_three }] + hash_three = \@Three _ -> 3 - result = mulMHashes (@Id 100) (@Three {}) + result = mul_m_hashes (@Id 100) (@Three {}) "# ), 300, @@ -232,10 +232,10 @@ fn bounds_to_multiple_abilities() { Idempot implements idempot : a -> a where a implements Idempot Consume implements consume : a -> Str where a implements Consume - Hello := Str implements [Idempot { idempot: idempotHello }, Consume { consume: consumeHello }] + Hello := Str implements [Idempot { idempot: idempot_hello }, Consume { consume: consume_hello }] - idempotHello = \@Hello msg -> @Hello msg - consumeHello = \@Hello msg -> msg + idempot_hello = \@Hello msg -> @Hello msg + consume_hello = \@Hello msg -> msg lifecycle : a -> Str where a implements Idempot & Consume lifecycle = \x -> idempot x |> consume @@ -254,37 +254,37 @@ fn encode() { assert_evals_to!( indoc!( r#" - app "test" provides [myU8Bytes] to "./platform" + app "test" provides [my_u8_bytes] to "./platform" MEncoder fmt := List U8, fmt -> List U8 where fmt implements Format MEncoding implements - toEncoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format + to_encoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format Format implements u8 : U8 -> MEncoder fmt where fmt implements Format - appendWith : List U8, MEncoder fmt, fmt -> List U8 where fmt implements Format - appendWith = \lst, (@MEncoder doFormat), fmt -> doFormat lst fmt + append_with : List U8, MEncoder fmt, fmt -> List U8 where fmt implements Format + append_with = \lst, (@MEncoder do_format), fmt -> do_format lst fmt - toBytes : val, fmt -> List U8 where val implements MEncoding, fmt implements Format - toBytes = \val, fmt -> appendWith [] (toEncoder val) fmt + to_bytes : val, fmt -> List U8 where val implements MEncoding, fmt implements Format + to_bytes = \val, fmt -> append_with [] (to_encoder val) fmt Linear := {} implements [Format {u8}] u8 = \n -> @MEncoder (\lst, @Linear {} -> List.append lst n) - Rgba := { r : U8, g : U8, b : U8, a : U8 } implements [MEncoding {toEncoder}] + Rgba := { r : U8, g : U8, b : U8, a : U8 } implements [MEncoding {to_encoder}] - toEncoder = \@Rgba {r, g, b, a} -> + to_encoder = \@Rgba {r, g, b, a} -> @MEncoder \lst, fmt -> lst - |> appendWith (u8 r) fmt - |> appendWith (u8 g) fmt - |> appendWith (u8 b) fmt - |> appendWith (u8 a) fmt + |> append_with (u8 r) fmt + |> append_with (u8 g) fmt + |> append_with (u8 b) fmt + |> append_with (u8 a) fmt - myU8Bytes = toBytes (@Rgba { r: 106, g: 90, b: 205, a: 255 }) (@Linear {}) + my_u8_bytes = to_bytes (@Rgba { r: 106, g: 90, b: 205, a: 255 }) (@Linear {}) "# ), RocList::from_slice(&[106, 90, 205, 255]), @@ -311,16 +311,16 @@ fn decode() { MDecoderFormatting implements u8 : MDecoder U8 fmt where fmt implements MDecoderFormatting - decodeWith : List U8, MDecoder val fmt, fmt -> { result: Result val MDecodeError, rest: List U8 } where fmt implements MDecoderFormatting - decodeWith = \lst, (@MDecoder doDecode), fmt -> doDecode lst fmt + decode_with : List U8, MDecoder val fmt, fmt -> { result: Result val MDecodeError, rest: List U8 } where fmt implements MDecoderFormatting + decode_with = \lst, (@MDecoder doDecode), fmt -> doDecode lst fmt - fromBytes : List U8, fmt -> Result val MDecodeError + from_bytes : List U8, fmt -> Result val MDecodeError where fmt implements MDecoderFormatting, val implements MDecoding - fromBytes = \lst, fmt -> - when decodeWith lst decoder fmt is + from_bytes = \lst, fmt -> + when decode_with lst decoder fmt is { result, rest } -> Result.try result \val -> - if List.isEmpty rest + if List.is_empty rest then Ok val else Err (Leftover rest) @@ -329,18 +329,18 @@ fn decode() { u8 = @MDecoder \lst, @Linear {} -> when List.first lst is - Ok n -> { result: Ok n, rest: List.dropFirst lst 1 } + Ok n -> { result: Ok n, rest: List.drop_first lst 1 } Err _ -> { result: Err TooShort, rest: [] } MyU8 := U8 implements [MDecoding {decoder}] # impl MDecoding for MyU8 decoder = @MDecoder \lst, fmt -> - { result, rest } = decodeWith lst u8 fmt + { result, rest } = decode_with lst u8 fmt { result: Result.map result (\n -> @MyU8 n), rest } myU8 = - when fromBytes [15] (@Linear {}) is + when from_bytes [15] (@Linear {}) is Ok (@MyU8 n) -> n _ -> 27u8 "# @@ -360,14 +360,14 @@ fn encode_use_stdlib() { {TAG_LEN_ENCODER_FMT} - HelloWorld := {{}} implements [Encoding {{toEncoder}}] - toEncoder = \@HelloWorld {{}} -> + HelloWorld := {{}} implements [Encoding {{to_encoder}}] + to_encoder = \@HelloWorld {{}} -> Encode.custom \bytes, fmt -> bytes - |> Encode.appendWith (Encode.string "Hello, World!\n") fmt + |> Encode.append_with (Encode.string "Hello, World!\n") fmt main = - result = Str.fromUtf8 (Encode.toBytes (@HelloWorld {{}}) tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes (@HelloWorld {{}}) tag_len_fmt) when result is Ok s -> s _ -> "" @@ -388,11 +388,11 @@ fn encode_use_stdlib_without_wrapping_custom() { {TAG_LEN_ENCODER_FMT} - HelloWorld := {{}} implements [Encoding {{toEncoder}}] - toEncoder = \@HelloWorld {{}} -> Encode.string "Hello, World!\n" + HelloWorld := {{}} implements [Encoding {{to_encoder}}] + to_encoder = \@HelloWorld {{}} -> Encode.string "Hello, World!\n" main = - result = Str.fromUtf8 (Encode.toBytes (@HelloWorld {{}}) tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes (@HelloWorld {{}}) tag_len_fmt) when result is Ok s -> s _ -> "" @@ -417,7 +417,7 @@ fn encode_derive_to_encoder_for_opaque() { HelloWorld := {{ a: Str }} implements [Encoding] main = - result = Str.fromUtf8 (Encode.toBytes (@HelloWorld {{ a: "Hello, World!" }}) tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes (@HelloWorld {{ a: "Hello, World!" }}) tag_len_fmt) when result is Ok s -> s _ -> "" @@ -438,14 +438,14 @@ fn to_encoder_encode_custom_has_capture() { {TAG_LEN_ENCODER_FMT} - HelloWorld := Str implements [Encoding {{toEncoder}}] - toEncoder = \@HelloWorld s1 -> + HelloWorld := Str implements [Encoding {{to_encoder}}] + to_encoder = \@HelloWorld s1 -> Encode.custom \bytes, fmt -> bytes - |> Encode.appendWith (Encode.string s1) fmt + |> Encode.append_with (Encode.string s1) fmt main = - result = Str.fromUtf8 (Encode.toBytes (@HelloWorld "Hello, World!\n") tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes (@HelloWorld "Hello, World!\n") tag_len_fmt) when result is Ok s -> s _ -> "" @@ -482,7 +482,7 @@ mod encode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.fromUtf8 (Encode.toBytes "foo" tagLenFmt) is + when Str.from_utf8 (Encode.to_bytes "foo" tag_len_fmt) is Ok s -> s _ -> "" "# @@ -503,7 +503,7 @@ mod encode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.fromUtf8 (Encode.toBytes [1, 2, 3] tagLenFmt) is + when Str.from_utf8 (Encode.to_bytes [1, 2, 3] tag_len_fmt) is Ok s -> s _ -> "" "# @@ -524,7 +524,7 @@ mod encode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.fromUtf8 (Encode.toBytes Bool.false tagLenFmt) is + when Str.from_utf8 (Encode.to_bytes Bool.false tag_len_fmt) is Ok s -> s _ -> "" "# @@ -547,7 +547,7 @@ mod encode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.fromUtf8 (Encode.toBytes {}{} tagLenFmt) is + when Str.from_utf8 (Encode.to_bytes {}{} tag_len_fmt) is Ok s -> s _ -> "" "#, $num, stringify!($typ)), @@ -587,7 +587,7 @@ fn encode_derived_record_one_field_string() { {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes {{a: "foo"}} tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes {{a: "foo"}} tag_len_fmt) when result is Ok s -> s _ -> "" @@ -611,7 +611,7 @@ fn encode_derived_record_two_fields_strings() { main = rcd = {{a: "foo", b: "bar"}} - result = Str.fromUtf8 (Encode.toBytes rcd tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes rcd tag_len_fmt) when result is Ok s -> s _ -> "" @@ -635,8 +635,8 @@ fn encode_derived_nested_record_string() { main = rcd = {{a: {{b: "bar"}}}} - encoded = Encode.toBytes rcd tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes rcd tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -659,7 +659,7 @@ fn encode_derived_tag_one_payload_string() { main = x = A "foo" - result = Str.fromUtf8 (Encode.toBytes x tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes x tag_len_fmt) when result is Ok s -> s _ -> "" @@ -682,7 +682,7 @@ fn encode_derived_tag_two_payloads_string() { main = x = A "foo" "bar" - result = Str.fromUtf8 (Encode.toBytes x tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes x tag_len_fmt) when result is Ok s -> s _ -> "" @@ -705,8 +705,8 @@ fn encode_derived_nested_tag_string() { main = x = A (B "foo" "bar") - encoded = Encode.toBytes x tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes x tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -730,8 +730,8 @@ fn encode_derived_nested_record_tag_record() { main = x = {{a: (B ({{c: "foo"}}))}} - encoded = Encode.toBytes x tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes x tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -754,8 +754,8 @@ fn encode_derived_list_string() { main = lst = ["foo", "bar", "baz"] - encoded = Encode.toBytes lst tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes lst tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -779,8 +779,8 @@ fn encode_derived_list_of_records() { main = lst = [{{a: "foo"}}, {{a: "bar"}}, {{a: "baz"}}] - encoded = Encode.toBytes lst tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes lst tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -803,8 +803,8 @@ fn encode_derived_list_of_lists_of_strings() { main = lst = [["a", "b"], ["c", "d", "e"], ["f"]] - encoded = Encode.toBytes lst tagLenFmt - result = Str.fromUtf8 encoded + encoded = Encode.to_bytes lst tag_len_fmt + result = Str.from_utf8 encoded when result is Ok s -> s _ -> "" @@ -830,7 +830,7 @@ fn encode_derived_record_with_many_types() { fresh : [Fresh Str, Rotten Str] fresh = Fresh "tomatoes" rcd = {{actors: ["Idris Elba", "Mila Kunis"], year: 2004u16, rating: {{average: 7u8, min: 1u8, max: 10u8, sentiment: fresh}}}} - result = Str.fromUtf8 (Encode.toBytes rcd tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes rcd tag_len_fmt) when result is Ok s -> s _ -> "" @@ -855,7 +855,7 @@ fn encode_derived_tuple_two_fields() { main = tup = ("foo", 10u8) - result = Str.fromUtf8 (Encode.toBytes tup tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes tup tag_len_fmt) when result is Ok s -> s _ -> "" @@ -878,7 +878,7 @@ fn encode_derived_tuple_of_tuples() { main = tup = ( ("foo", 10u8), (23u8, "bar", 15u8) ) - result = Str.fromUtf8 (Encode.toBytes tup tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes tup tag_len_fmt) when result is Ok s -> s _ -> "" @@ -905,7 +905,7 @@ fn encode_derived_generic_record_with_different_field_types() { q = @Q {{a: 10u32, b: "fieldb"}} main = - result = Str.fromUtf8 (Encode.toBytes q tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes q tag_len_fmt) when result is Ok s -> s _ -> "" @@ -932,7 +932,7 @@ fn encode_derived_generic_tag_with_different_field_types() { q = @Q (B 67) main = - result = Str.fromUtf8 (Encode.toBytes q tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes q tag_len_fmt) when result is Ok s -> s _ -> "" @@ -955,8 +955,8 @@ fn specialize_unique_newtype_records() { {TAG_LEN_ENCODER_FMT} main = - when Str.fromUtf8 (Encode.toBytes {{a: Bool.true}} tagLenFmt) is - Ok s -> when Str.fromUtf8 (Encode.toBytes {{b: Bool.true}} tagLenFmt) is + when Str.from_utf8 (Encode.to_bytes {{a: Bool.true}} tag_len_fmt) is + Ok s -> when Str.from_utf8 (Encode.to_bytes {{b: Bool.true}} tag_len_fmt) is Ok t -> "$(s)$(t)" _ -> "" _ -> "" @@ -982,14 +982,14 @@ fn decode_use_stdlib() { myDecoder = Decode.custom \bytes, fmt -> - when Decode.decodeWith bytes Decode.u8 fmt is + when Decode.decode_with bytes Decode.u8 fmt is {{result, rest}} -> when result is Ok n -> {{result: Ok (@MyNum n), rest}} Err e -> {{result: Err e, rest}} main = - when Decode.fromBytes [110, 49, 53, 32] tagLenFmt is + when Decode.from_bytes [110, 49, 53, 32] tag_len_fmt is Ok (@MyNum n) -> n _ -> 101 "# @@ -1015,7 +1015,7 @@ fn decode_derive_decoder_for_opaque() { HelloWorld := {{ a: Str }} implements [Decoding] main = - when Str.toUtf8 "r1 s1 a s13 Hello, World! " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r1 s1 a s13 Hello, World! " |> Decode.from_bytes tag_len_fmt is Ok (@HelloWorld {{a}}) -> a _ -> "FAIL" "# @@ -1037,13 +1037,13 @@ fn decode_use_stdlib_custom_list() { MyNumList := List U8 implements [Decoding {{decoder: myDecoder}}] myDecoder = Decode.custom \bytes, fmt -> - when Decode.decodeWith bytes (Decode.list Decode.u8) fmt is + when Decode.decode_with bytes (Decode.list Decode.u8) fmt is {{result, rest}} -> when result is Ok lst -> {{result: Ok (@MyNumList lst), rest}} Err e -> {{result: Err e, rest}} main = - when Str.toUtf8 "l3 n1 n2 n3 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "l3 n1 n2 n3 " |> Decode.from_bytes tag_len_fmt is Ok (@MyNumList lst) -> lst _ -> [] "# @@ -1080,7 +1080,7 @@ mod decode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "s3 foo " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "s3 foo " |> Decode.from_bytes tag_len_fmt is Ok s -> s _ -> "" "# @@ -1102,10 +1102,10 @@ mod decode_immediate { {TAG_LEN_ENCODER_FMT} main = - input = Str.toUtf8 "l3 n1 n2 n3 " + input = Str.to_utf8 "l3 n1 n2 n3 " expected = [1,2,3] - actual = Decode.fromBytes input tagLenFmt |> Result.withDefault [] + actual = Decode.from_bytes input tag_len_fmt |> Result.with_default [] actual == expected "# @@ -1126,7 +1126,7 @@ mod decode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "n0 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "n0 " |> Decode.from_bytes tag_len_fmt is Ok s -> s _ -> Bool.true "# @@ -1149,7 +1149,7 @@ mod decode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "n{} " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "n{} " |> Decode.from_bytes tag_len_fmt is Ok n -> n _ -> 101{} "#, @@ -1189,7 +1189,7 @@ mod decode_immediate { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "n17.23 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "n17.23 " |> Decode.from_bytes tag_len_fmt is Ok n -> n _ -> 101dec "# @@ -1212,8 +1212,8 @@ fn decode_list_of_strings() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "l3 s1 a s1 b s1 c " |> Decode.fromBytes tagLenFmt is - Ok l -> Str.joinWith l "," + when Str.to_utf8 "l3 s1 a s1 b s1 c " |> Decode.from_bytes tag_len_fmt is + Ok l -> Str.join_with l "," _ -> "" "# ), @@ -1235,8 +1235,8 @@ fn encode_then_decode_list_of_strings() { {TAG_LEN_ENCODER_FMT} main = - when Encode.toBytes ["a", "b", "c"] tagLenFmt |> Decode.fromBytes tagLenFmt is - Ok l -> Str.joinWith l "," + when Encode.to_bytes ["a", "b", "c"] tag_len_fmt |> Decode.from_bytes tag_len_fmt is + Ok l -> Str.join_with l "," _ -> "something went wrong" "# ), @@ -1258,8 +1258,8 @@ fn encode_then_decode_list_of_lists_of_strings() { {TAG_LEN_ENCODER_FMT} main = - when Encode.toBytes [["a", "b"], ["c", "d", "e"], ["f"]] tagLenFmt |> Decode.fromBytes tagLenFmt is - Ok list -> (List.map list \inner -> Str.joinWith inner ",") |> Str.joinWith ";" + when Encode.to_bytes [["a", "b"], ["c", "d", "e"], ["f"]] tag_len_fmt |> Decode.from_bytes tag_len_fmt is + Ok list -> (List.map list \inner -> Str.join_with inner ",") |> Str.join_with ";" _ -> "something went wrong" "# ), @@ -1283,7 +1283,7 @@ fn decode_record_two_fields() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "r2 s6 second s2 cd s5 first s2 ab " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r2 s6 second s2 cd s5 first s2 ab " |> Decode.from_bytes tag_len_fmt is Ok {{first: "ab", second: "cd"}} -> "abcd" _ -> "something went wrong" "# @@ -1307,7 +1307,7 @@ fn decode_record_two_fields_string_and_int() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "r2 s5 first s2 ab s6 second n10 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r2 s5 first s2 ab s6 second n10 " |> Decode.from_bytes tag_len_fmt is Ok {{first: "ab", second: 10u8}} -> "ab10" _ -> "something went wrong" "# @@ -1331,7 +1331,7 @@ fn decode_record_two_fields_string_and_string_infer() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.from_bytes tag_len_fmt is Ok {{first, second}} -> Str.concat first second _ -> "something went wrong" "# @@ -1355,7 +1355,7 @@ fn decode_record_two_fields_string_and_string_infer_local_var() { {TAG_LEN_ENCODER_FMT} main = - decoded = Str.toUtf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.fromBytes tagLenFmt + decoded = Str.to_utf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.from_bytes tag_len_fmt when decoded is Ok rcd -> Str.concat rcd.first rcd.second _ -> "something went wrong" @@ -1380,7 +1380,7 @@ fn decode_record_two_fields_string_and_string_infer_local_var_destructured() { {TAG_LEN_ENCODER_FMT} main = - decoded = Str.toUtf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.fromBytes tagLenFmt + decoded = Str.to_utf8 "r2 s5 first s2 ab s6 second s2 cd " |> Decode.from_bytes tag_len_fmt when decoded is Ok {{first, second}} -> Str.concat first second _ -> "something went wrong" @@ -1402,7 +1402,7 @@ fn decode_empty_record() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "r0 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r0 " |> Decode.from_bytes tag_len_fmt is Ok {{}} -> "empty" _ -> "something went wrong" "# @@ -1427,7 +1427,7 @@ fn decode_record_of_record() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "r2 s5 other r2 s3 one s1 b s3 two n10 s5 outer r1 s5 inner s1 a " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "r2 s5 other r2 s3 one s1 b s3 two n10 s5 outer r1 s5 inner s1 a " |> Decode.from_bytes tag_len_fmt is Ok {{outer: {{inner: "a"}}, other: {{one: "b", two: 10u8}}}} -> "ab10" _ -> "something went wrong" "# @@ -1451,7 +1451,7 @@ fn decode_tuple_two_elements() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "l2 s2 ab n10 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "l2 s2 ab n10 " |> Decode.from_bytes tag_len_fmt is Ok ("ab", 10u8) -> "abcd" _ -> "something went wrong" "# @@ -1475,7 +1475,7 @@ fn decode_tuple_of_tuples() { {TAG_LEN_ENCODER_FMT} main = - when Str.toUtf8 "l2 l2 s2 ab n10 l2 s2 cd n25 " |> Decode.fromBytes tagLenFmt is + when Str.to_utf8 "l2 l2 s2 ab n10 l2 s2 cd n25 " |> Decode.from_bytes tag_len_fmt is Ok ( ("ab", 10u8), ("cd", 25u8) ) -> "abcd" _ -> "something went wrong" "# @@ -1498,53 +1498,53 @@ mod hash { const TEST_HASHER: &str = indoc!( r" THasher := List U8 implements [Hasher { - addBytes: tAddBytes, - addU8: tAddU8, - addU16: tAddU16, - addU32: tAddU32, - addU64: tAddU64, - addU128: tAddU128, - complete: tComplete, + add_bytes: t_add_bytes, + add_u8: t_add_u8, + add_u16: t_add_u16, + add_u32: t_add_u32, + add_u64: t_add_u64, + add_u128: t_add_u128, + complete: t_complete, }] # ignores endian-ness - byteAt = \n, shift -> - Num.bitwiseAnd (Num.shiftRightBy n (shift * 8)) 0xFF - |> Num.toU8 + byte_at = \n, shift -> + Num.bitwise_and (Num.shift_right_by n (shift * 8)) 0xFF + |> Num.to_u8 do8 = \total, n -> total - |> List.append (byteAt n 0) + |> List.append (byte_at n 0) do16 = \total, n -> total - |> do8 (n |> Num.toU8) - |> do8 (Num.shiftRightBy n 8 |> Num.toU8) + |> do8 (n |> Num.to_u8) + |> do8 (Num.shift_right_by n 8 |> Num.to_u8) do32 = \total, n -> total - |> do16 (n |> Num.toU16) - |> do16 (Num.shiftRightBy n 16 |> Num.toU16) + |> do16 (n |> Num.to_u16) + |> do16 (Num.shift_right_by n 16 |> Num.to_u16) do64 = \total, n -> total - |> do32 (n |> Num.toU32) - |> do32 (Num.shiftRightBy n 32 |> Num.toU32) + |> do32 (n |> Num.to_u32) + |> do32 (Num.shift_right_by n 32 |> Num.to_u32) do128 = \total, n -> total - |> do64 (n |> Num.toU64) - |> do64 (Num.shiftRightBy n 64 |> Num.toU64) - - tAddBytes = \@THasher total, bytes -> @THasher (List.concat total bytes) - tAddU8 = \@THasher total, n -> @THasher (do8 total n) - tAddU16 = \@THasher total, n -> @THasher (do16 total n) - tAddU32 = \@THasher total, n -> @THasher (do32 total n) - tAddU64 = \@THasher total, n -> @THasher (do64 total n) - tAddU128 = \@THasher total, n -> @THasher (do128 total n) - tComplete = \@THasher _ -> Num.maxU64 - - tRead = \@THasher bytes -> bytes + |> do64 (n |> Num.to_u64) + |> do64 (Num.shift_right_by n 64 |> Num.to_u64) + + t_add_bytes = \@THasher total, bytes -> @THasher (List.concat total bytes) + t_add_u8 = \@THasher total, n -> @THasher (do8 total n) + t_add_u16 = \@THasher total, n -> @THasher (do16 total n) + t_add_u32 = \@THasher total, n -> @THasher (do32 total n) + t_add_u64 = \@THasher total, n -> @THasher (do64 total n) + t_add_u128 = \@THasher total, n -> @THasher (do128 total n) + t_complete = \@THasher _ -> Num.max_u64 + + t_read = \@THasher bytes -> bytes " ); @@ -1559,7 +1559,7 @@ mod hash { main = @THasher [] |> Hash.hash ({}) - |> tRead + |> t_read "# ), TEST_HASHER, input, @@ -1618,7 +1618,7 @@ mod hash { #[test] fn u16() { assert_evals_to!( - &build_test("Num.maxU16 - 1"), + &build_test("Num.max_u16 - 1"), RocList::from_slice(&[254, 255]), RocList ) @@ -1636,7 +1636,7 @@ mod hash { #[test] fn u32() { assert_evals_to!( - &build_test("Num.maxU32 - 1"), + &build_test("Num.max_u32 - 1"), RocList::from_slice(&[254, 255, 255, 255]), RocList ) @@ -1654,7 +1654,7 @@ mod hash { #[test] fn u64() { assert_evals_to!( - &build_test("Num.maxU64 - 1"), + &build_test("Num.max_u64 - 1"), RocList::from_slice(&[254, 255, 255, 255, 255, 255, 255, 255]), RocList ) @@ -1676,7 +1676,7 @@ mod hash { #[cfg(not(feature = "gen-wasm"))] // shr not implemented for U128 fn u128() { assert_evals_to!( - &build_test("Num.maxU128 - 1"), + &build_test("Num.max_u128 - 1"), RocList::from_slice(&[ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 ]), @@ -1818,7 +1818,7 @@ mod hash { main = @THasher [] |> Hash.hash a - |> tRead + |> t_read "# ), TEST_HASHER, @@ -1850,7 +1850,7 @@ mod hash { @THasher [] |> Hash.hash a |> Hash.hash b - |> tRead + |> t_read "# ), TEST_HASHER, @@ -1879,7 +1879,7 @@ mod hash { main = @THasher [] |> Hash.hash l - |> tRead + |> t_read "# ), TEST_HASHER, @@ -1914,7 +1914,7 @@ mod hash { main = @THasher [] |> Hash.hash a - |> tRead + |> t_read "# ), TEST_HASHER, @@ -1943,7 +1943,7 @@ mod hash { main = @THasher [] |> Hash.hash a - |> tRead + |> t_read "# ), TEST_HASHER, @@ -1981,7 +1981,7 @@ mod hash { |> Hash.hash a |> Hash.hash b |> Hash.hash c - |> tRead + |> t_read "# ), TEST_HASHER, @@ -2016,7 +2016,7 @@ mod hash { main = @THasher [] |> Hash.hash c - |> tRead + |> t_read "# ), TEST_HASHER, @@ -2047,7 +2047,7 @@ mod hash { main = @THasher [] |> Hash.hash q - |> tRead + |> t_read "# ), TEST_HASHER, @@ -2093,15 +2093,15 @@ mod eq { r#" app "test" provides [main] to "./platform" - LyingEq := U8 implements [Eq {isEq}] + LyingEq := U8 implements [Eq {is_eq}] - isEq = \@LyingEq m, @LyingEq n -> m != n + is_eq = \@LyingEq m, @LyingEq n -> m != n main = a = @LyingEq 10 b = @LyingEq 5 c = @LyingEq 5 - if Bool.isEq a b && !(Bool.isEq b c) then + if Bool.is_eq a b && !(Bool.is_eq b c) then "okay" else "fail" @@ -2119,11 +2119,11 @@ mod eq { r#" app "test" provides [main] to "./platform" - Q := ({} -> Str) implements [Eq {isEq: isEqQ}] + Q := ({} -> Str) implements [Eq {is_eq: is_eq_q}] - isEqQ = \@Q _, @Q _ -> Bool.true + is_eq_q = \@Q _, @Q _ -> Bool.true - main = isEqQ (@Q \{} -> "a") (@Q \{} -> "a") + main = is_eq_q (@Q \{} -> "a") (@Q \{} -> "a") "# ), true, @@ -2139,11 +2139,11 @@ mod eq { r#" app "test" provides [main] to "./platform" - Q := ({} -> Str) implements [Eq {isEq: isEqQ}] + Q := ({} -> Str) implements [Eq {is_eq: is_eq_q}] - isEqQ = \@Q f1, @Q f2 -> (f1 {} == f2 {}) + is_eq_q = \@Q f1, @Q f2 -> (f1 {} == f2 {}) - main = isEqQ (@Q \{} -> "a") (@Q \{} -> "a") + main = is_eq_q (@Q \{} -> "a") (@Q \{} -> "a") "# ), true, @@ -2158,7 +2158,7 @@ mod eq { r#" app "test" provides [main] to "./platform" - main = Bool.isEq 10u8 10u8 + main = Bool.is_eq 10u8 10u8 "# ), true, @@ -2195,12 +2195,12 @@ fn issue_4772_weakened_monomorphic_destructure() { {TAG_LEN_ENCODER_FMT} - getNumber = - {{ result, rest }} = Decode.fromBytesPartial (Str.toUtf8 "s4 1234 ") tagLenFmt + get_number = + {{ result, rest }} = Decode.from_bytes_partial (Str.to_utf8 "s4 1234 ") tag_len_fmt when result is Ok val -> - when Str.toI64 val is + when Str.to_i64 val is Ok number -> Ok {{ val : number, input : rest }} Err InvalidNumStr -> @@ -2210,7 +2210,7 @@ fn issue_4772_weakened_monomorphic_destructure() { Err (ParsingFailure "not a number") main = - getNumber |> Result.map .val |> Result.withDefault 0 + get_number |> Result.map .val |> Result.with_default 0 "# ), 1234i64, @@ -2241,9 +2241,9 @@ mod inspect { app "test" provides [main] to "./platform" main = [ - Inspect.toStr Bool.true, - Inspect.toStr Bool.false, - ] |> Str.joinWith ", " + Inspect.to_str Bool.true, + Inspect.to_str Bool.false, + ] |> Str.join_with ", " "# ), RocStr::from("Bool.true, Bool.false"), @@ -2260,22 +2260,22 @@ mod inspect { app "test" provides [main] to "./platform" main = [ - Inspect.toStr 0, # Num a - Inspect.toStr 1u8, # U8 - Inspect.toStr 2i8, # I8 - Inspect.toStr 3u16, # U16 - Inspect.toStr 4i16, # I16 - Inspect.toStr 5u32, # U32 - Inspect.toStr 6i32, # I32 - Inspect.toStr 7u64, # U64 - Inspect.toStr 8i64, # I64 - Inspect.toStr 9u128, # U128 - Inspect.toStr 10i128, # I128 - Inspect.toStr 0.5, # Frac a - Inspect.toStr 1.5f32, # F32 - Inspect.toStr 2.2f64, # F64 - Inspect.toStr (1.1dec + 2.2), # Dec - ] |> Str.joinWith ", " + Inspect.to_str 0, # Num a + Inspect.to_str 1u8, # U8 + Inspect.to_str 2i8, # I8 + Inspect.to_str 3u16, # U16 + Inspect.to_str 4i16, # I16 + Inspect.to_str 5u32, # U32 + Inspect.to_str 6i32, # I32 + Inspect.to_str 7u64, # U64 + Inspect.to_str 8i64, # I64 + Inspect.to_str 9u128, # U128 + Inspect.to_str 10i128, # I128 + Inspect.to_str 0.5, # Frac a + Inspect.to_str 1.5f32, # F32 + Inspect.to_str 2.2f64, # F64 + Inspect.to_str (1.1dec + 2.2), # Dec + ] |> Str.join_with ", " "# ), RocStr::from("0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0.5, 1.5, 2.2, 3.3"), @@ -2292,12 +2292,12 @@ mod inspect { app "test" provides [main] to "./platform" main = [ - Inspect.toStr [0, 1, 2], # List (Num *) - Inspect.toStr [1, 0x2, 3], # List (Int *) - Inspect.toStr [0.1 + 0.2, 0.4], # List (Frac *) - Inspect.toStr [1u8, 2u8], # List U8 - Inspect.toStr ["foo"], # List Str - ] |> Str.joinWith ", " + Inspect.to_str [0, 1, 2], # List (Num *) + Inspect.to_str [1, 0x2, 3], # List (Int *) + Inspect.to_str [0.1 + 0.2, 0.4], # List (Frac *) + Inspect.to_str [1u8, 2u8], # List U8 + Inspect.to_str ["foo"], # List Str + ] |> Str.join_with ", " "# ), RocStr::from("[0, 1, 2], [1, 2, 3], [0.3, 0.4], [1, 2], [\"foo\"]"), @@ -2314,10 +2314,10 @@ mod inspect { app "test" provides [main] to "./platform" main = [ - Inspect.toStr "", - Inspect.toStr "a small string", - Inspect.toStr "an extraordinarily long string - so long it's on the heap!", - ] |> Str.joinWith ", " + Inspect.to_str "", + Inspect.to_str "a small string", + Inspect.to_str "an extraordinarily long string - so long it's on the heap!", + ] |> Str.join_with ", " "# ), RocStr::from( @@ -2337,7 +2337,7 @@ mod inspect { Op := {} - main = Inspect.toStr (@Op {}) + main = Inspect.to_str (@Op {}) "# ), RocStr::from(r""), @@ -2355,7 +2355,7 @@ mod inspect { Op := {} - late = \a -> Inspect.toStr a + late = \a -> Inspect.to_str a main = late (@Op {}) "# diff --git a/crates/compiler/test_gen/src/gen_compare.rs b/crates/compiler/test_gen/src/gen_compare.rs index 7e2f31dc932..621d9458fe2 100644 --- a/crates/compiler/test_gen/src/gen_compare.rs +++ b/crates/compiler/test_gen/src/gen_compare.rs @@ -291,10 +291,10 @@ fn eq_expr() { Expr : [Add Expr Expr, Mul Expr Expr, Val I64, Var I64] x : Expr - x = Val 0 + x = Val(0) y : Expr - y = Val 0 + y = Val(0) x == y "# @@ -331,10 +331,10 @@ fn eq_linked_list() { LinkedList a : [Nil, Cons a (LinkedList a)] x : LinkedList I64 - x = Cons 1 Nil + x = Cons(1, Nil) y : LinkedList I64 - y = Cons 1 Nil + y = Cons(1, Nil) x == y "# @@ -349,10 +349,10 @@ fn eq_linked_list() { LinkedList a : [Nil, Cons a (LinkedList a)] x : LinkedList I64 - x = Cons 1 (Cons 2 Nil) + x = Cons(1, Cons(2, Nil)) y : LinkedList I64 - y = Cons 1 (Cons 2 Nil) + y = Cons(1, Cons(2, Nil)) x == y "# @@ -371,10 +371,10 @@ fn eq_linked_list_false() { LinkedList a : [Nil, Cons a (LinkedList a)] x : LinkedList I64 - x = Cons 1 Nil + x = Cons(1, Nil) y : LinkedList I64 - y = Cons 1 (Cons 2 Nil) + y = Cons(1, Cons(2, Nil)) y == x "# @@ -394,20 +394,20 @@ fn eq_linked_list_long() { LinkedList a : [Nil, Cons a (LinkedList a)] - prependOnes = \n, tail -> + prepend_ones = \n, tail -> if n == 0 then tail else - prependOnes (n-1) (Cons 1 tail) + prepend_ones (n-1) (Cons 1 tail) main = n = 100_000 # be careful, can make a noticeble difference to test_gen total time! x : LinkedList I64 - x = prependOnes n (Cons 999 Nil) + x = prepend_ones n (Cons 999 Nil) y : LinkedList I64 - y = prependOnes n (Cons 123 Nil) + y = prepend_ones n (Cons 123 Nil) y == x "# diff --git a/crates/compiler/test_gen/src/gen_dict.rs b/crates/compiler/test_gen/src/gen_dict.rs index a9d71357405..2e1de654373 100644 --- a/crates/compiler/test_gen/src/gen_dict.rs +++ b/crates/compiler/test_gen/src/gen_dict.rs @@ -111,7 +111,7 @@ fn dict_nonempty_remove() { empty |> Dict.remove 42 |> Dict.len - |> Num.toI64 + |> Num.to_i64 " ), 0, @@ -128,7 +128,7 @@ fn dict_nonempty_get() { empty : Dict.Dict I64 F64 empty = Dict.insert (Dict.empty {}) 42 1.23 - withDefault = \x, def -> + with_default = \x, def -> when x is Ok v -> v Err _ -> def @@ -136,7 +136,7 @@ fn dict_nonempty_get() { empty |> Dict.insert 42 1.23f64 |> Dict.get 42 - |> withDefault 0 + |> with_default 0 " ), 1.23, @@ -146,15 +146,15 @@ fn dict_nonempty_get() { assert_evals_to!( indoc!( r" - withDefault = \x, def -> - when x is + with_default = \x, def -> + when x is Ok v -> v Err _ -> def Dict.empty {} |> Dict.insert 42 1.23f64 |> Dict.get 43 - |> withDefault 0 + |> with_default 0 " ), 0.0, @@ -168,15 +168,15 @@ fn keys() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 I64 - myDict = + my_dict : Dict.Dict I64 I64 + my_dict = Dict.empty {} |> Dict.insert 0 100 |> Dict.insert 1 100 |> Dict.insert 2 100 - Dict.keys myDict + Dict.keys my_dict " ), RocList::from_slice(&[0, 1, 2]), @@ -190,15 +190,15 @@ fn values() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 I64 - myDict = + my_dict : Dict.Dict I64 I64 + my_dict = Dict.empty {} |> Dict.insert 0 100 |> Dict.insert 1 200 |> Dict.insert 2 300 - Dict.values myDict + Dict.values my_dict " ), RocList::from_slice(&[100, 200, 300]), @@ -212,12 +212,12 @@ fn from_list_with_fold_simple() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 I64 - myDict = + my_dict : Dict.Dict I64 I64 + my_dict = [1,2,3] |> List.walk (Dict.empty {}) (\accum, value -> Dict.insert accum value value) - Dict.values myDict + Dict.values my_dict " ), RocList::from_slice(&[1, 2, 3]), @@ -238,13 +238,13 @@ fn from_list_with_fold_reallocates() { else accum - myDict : Dict.Dict I64 I64 - myDict = + my_dict : Dict.Dict I64 I64 + my_dict = # 25 elements (8 + 16 + 1) is guaranteed to overflow/reallocate at least twice range 0 25 [] |> List.walk (Dict.empty {}) (\accum, value -> Dict.insert accum value value) - Dict.values myDict + Dict.values my_dict " ), RocList::from_slice(&[ @@ -261,12 +261,12 @@ fn small_str_keys() { assert_evals_to!( indoc!( r#" - myDict : Dict.Dict Str I64 - myDict = + my_dict : Dict.Dict Str I64 + my_dict = Dict.empty {} |> Dict.insert "a" 100 - Dict.keys myDict + Dict.keys my_dict "# ), RocList::from_slice(&["a".into()]), @@ -280,14 +280,14 @@ fn big_str_keys() { assert_evals_to!( indoc!( r#" - myDict : Dict.Dict Str I64 - myDict = + my_dict : Dict.Dict Str I64 + my_dict = Dict.empty {} |> Dict.insert "Leverage agile frameworks to provide a robust" 100 |> Dict.insert "synopsis for high level overviews. Iterative approaches" 200 |> Dict.insert "to corporate strategy foster collaborative thinking to" 300 - Dict.keys myDict + Dict.keys my_dict "# ), RocList::from_slice(&[ @@ -305,14 +305,14 @@ fn big_str_values() { assert_evals_to!( indoc!( r#" - myDict : Dict.Dict I64 Str - myDict = + my_dict : Dict.Dict I64 Str + my_dict = Dict.empty {} |> Dict.insert 100 "Leverage agile frameworks to provide a robust" |> Dict.insert 200 "synopsis for high level overviews. Iterative approaches" |> Dict.insert 300 "to corporate strategy foster collaborative thinking to" - Dict.values myDict + Dict.values my_dict "# ), RocList::from_slice(&[ @@ -330,15 +330,15 @@ fn unit_values() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 {} - myDict = + my_dict : Dict.Dict I64 {} + my_dict = Dict.empty {} |> Dict.insert 0 {} |> Dict.insert 1 {} |> Dict.insert 2 {} |> Dict.insert 3 {} - Num.toI64 (Dict.len myDict) + Num.to_i64 (Dict.len my_dict) " ), 4, @@ -352,11 +352,11 @@ fn single() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 {} - myDict = + my_dict : Dict.Dict I64 {} + my_dict = Dict.single 12345 {} - Num.toI64 (Dict.len myDict) + Num.to_i64 (Dict.len my_dict) " ), 1, @@ -370,12 +370,12 @@ fn insert_all() { assert_evals_to!( indoc!( r" - myDict : Dict I64 {} - myDict = - Dict.insertAll (Dict.single 0 {}) (Dict.single 1 {}) + my_dict : Dict I64 {} + my_dict = + Dict.insert_all (Dict.single 0 {}) (Dict.single 1 {}) - Dict.len myDict - |> Num.toI64 + Dict.len my_dict + |> Num.to_i64 " ), 2, @@ -389,12 +389,12 @@ fn insert_all_prefer_second() { assert_evals_to!( indoc!( r" - myDict : Dict.Dict I64 I64 - myDict = + my_dict : Dict.Dict I64 I64 + my_dict = (Dict.single 0 100) - |> Dict.insertAll (Dict.single 0 200) + |> Dict.insert_all (Dict.single 0 200) - Dict.values myDict + Dict.values my_dict " ), RocList::from_slice(&[200]), @@ -424,9 +424,9 @@ fn keep_shared() { |> Dict.insert 2 {} |> Dict.insert 4 {} - Dict.keepShared dict1 dict2 + Dict.keep_shared dict1 dict2 |> Dict.len - |> Num.toI64 + |> Num.to_i64 " ), 2, @@ -456,7 +456,7 @@ fn keep_shared_value_must_match() { |> Dict.insert 2 2 |> Dict.insert 4 300 - Dict.keepShared dict1 dict2 + Dict.keep_shared dict1 dict2 |> Dict.values " ), @@ -487,9 +487,9 @@ fn remove_all() { |> Dict.insert 2 {} |> Dict.insert 4 {} - Dict.removeAll dict1 dict2 + Dict.remove_all dict1 dict2 |> Dict.len - |> Num.toI64 + |> Num.to_i64 " ), 3, @@ -519,7 +519,7 @@ fn remove_all_prefer_first() { |> Dict.insert 2 200 |> Dict.insert 4 300 - Dict.removeAll dict1 dict2 + Dict.remove_all dict1 dict2 |> Dict.values " ), diff --git a/crates/compiler/test_gen/src/gen_erased.rs b/crates/compiler/test_gen/src/gen_erased.rs index de089d30979..f5b509730a9 100644 --- a/crates/compiler/test_gen/src/gen_erased.rs +++ b/crates/compiler/test_gen/src/gen_erased.rs @@ -34,7 +34,7 @@ fn multi_branch_capturing() { f = \t, s -> if t then \{} -> 15u64 - else \{} -> Str.countUtf8Bytes s + else \{} -> Str.count_utf8_bytes s main = ((f Bool.true "abc") {}, (f Bool.false "abc") {}) "# diff --git a/crates/compiler/test_gen/src/gen_list.rs b/crates/compiler/test_gen/src/gen_list.rs index 59f4805091a..cea420c42dd 100644 --- a/crates/compiler/test_gen/src/gen_list.rs +++ b/crates/compiler/test_gen/src/gen_list.rs @@ -226,22 +226,22 @@ fn list_append_basic() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_take_first() { assert_evals_to!( - "List.takeFirst [1, 2, 3] 2", + "List.take_first [1, 2, 3] 2", RocList::from_slice(&[1, 2]), RocList ); assert_evals_to!( - "List.takeFirst [1, 2, 3] 0", + "List.take_first [1, 2, 3] 0", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.takeFirst [] 1", + "List.take_first [] 1", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.takeFirst [1,2] 5", + "List.take_first [1,2] 5", RocList::from_slice(&[1, 2]), RocList ); @@ -251,22 +251,22 @@ fn list_take_first() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_take_last() { assert_evals_to!( - "List.takeLast [1, 2, 3] 2", + "List.take_last [1, 2, 3] 2", RocList::from_slice(&[2, 3]), RocList ); assert_evals_to!( - "List.takeLast [1, 2, 3] 0", + "List.take_last [1, 2, 3] 0", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.takeLast [] 1", + "List.take_last [] 1", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.takeLast [1,2] 5", + "List.take_last [1,2] 5", RocList::from_slice(&[1, 2]), RocList ); @@ -318,7 +318,7 @@ fn list_map_try_ok() { assert_evals_to!( // No transformation r" - List.mapTry [1, 2, 3] \elem -> Ok elem + List.map_try [1, 2, 3] \elem -> Ok elem ", // Result I64 [] is unwrapped to just I64 RocList::::from_slice(&[1, 2, 3]), @@ -327,8 +327,8 @@ fn list_map_try_ok() { assert_evals_to!( // Transformation r#" - List.mapTry [1, 2, 3] \num -> - str = Num.toStr (num * 2) + List.map_try [1, 2, 3] \num -> + str = Num.to_str (num * 2) Ok "$(str)!" "#, @@ -349,7 +349,7 @@ fn list_map_try_err() { assert_evals_to!( r" - List.mapTry [1, 2, 3] \_ -> Err -1 + List.map_try [1, 2, 3] \_ -> Err -1 ", RocResult::err(-1), RocResult, i64> @@ -358,7 +358,7 @@ fn list_map_try_err() { assert_evals_to!( // If any element returns Err, the whole thing returns Err r" - List.mapTry [1, 2, 3] \num -> + List.map_try [1, 2, 3] \num -> if num > 2 then Err -1 else @@ -374,7 +374,7 @@ fn list_map_try_err() { fn list_split_at() { assert_evals_to!( r" - list = List.splitAt [1, 2, 3] 0 + list = List.split_at [1, 2, 3] 0 list.before ", RocList::::from_slice(&[]), @@ -382,7 +382,7 @@ fn list_split_at() { ); assert_evals_to!( r" - list = List.splitAt [1, 2, 3] 0 + list = List.split_at [1, 2, 3] 0 list.others ", RocList::from_slice(&[1, 2, 3]), @@ -390,13 +390,13 @@ fn list_split_at() { ); assert_evals_to!( r" - List.splitAt [1, 2, 3] 1 + List.split_at [1, 2, 3] 1 ", (RocList::from_slice(&[1]), RocList::from_slice(&[2, 3])), (RocList, RocList,) ); assert_evals_to!( - "List.splitAt [1, 2, 3] 3", + "List.split_at [1, 2, 3] 3", ( RocList::from_slice(&[1, 2, 3]), RocList::::from_slice(&[]), @@ -404,7 +404,7 @@ fn list_split_at() { (RocList, RocList,) ); assert_evals_to!( - "List.splitAt [1, 2, 3] 4", + "List.split_at [1, 2, 3] 4", ( RocList::from_slice(&[1, 2, 3]), RocList::::from_slice(&[]), @@ -412,7 +412,7 @@ fn list_split_at() { (RocList, RocList,) ); assert_evals_to!( - "List.splitAt [] 1", + "List.split_at [] 1", ( RocList::::from_slice(&[]), RocList::::from_slice(&[]), @@ -426,14 +426,14 @@ fn list_split_at() { fn list_split_on() { assert_evals_to!( r" - List.splitOn [] 1 + List.split_on [] 1 ", RocList::>::from_slice(&[RocList::::from_slice(&[])]), RocList> ); assert_evals_to!( r" - List.splitOn [1] 1 + List.split_on [1] 1 ", RocList::>::from_slice(&[ RocList::::from_slice(&[]), @@ -443,14 +443,14 @@ fn list_split_on() { ); assert_evals_to!( r" - List.splitOn [1, 2, 3] 47 + List.split_on [1, 2, 3] 47 ", RocList::>::from_slice(&[RocList::::from_slice(&[1, 2, 3])]), RocList> ); assert_evals_to!( r" - List.splitOn [1, 2, 3, 4, 5] 3 + List.split_on [1, 2, 3, 4, 5] 3 ", RocList::>::from_slice(&[ RocList::::from_slice(&[1, 2]), @@ -460,7 +460,7 @@ fn list_split_on() { ); assert_evals_to!( r" - List.splitOn [1, 0, 1, 0, 1] 1 + List.split_on [1, 0, 1, 0, 1] 1 ", RocList::>::from_slice(&[ RocList::::from_slice(&[]), @@ -472,7 +472,7 @@ fn list_split_on() { ); assert_evals_to!( r" - List.splitOn [1, 0, 1, 0, 1] 0 + List.split_on [1, 0, 1, 0, 1] 0 ", RocList::>::from_slice(&[ RocList::::from_slice(&[1]), @@ -488,28 +488,28 @@ fn list_split_on() { fn list_split_on_list() { assert_evals_to!( r" - List.splitOnList [] [] + List.split_on_list [] [] ", RocList::>::from_slice(&[RocList::::from_slice(&[])]), RocList> ); assert_evals_to!( r" - List.splitOnList [] [1, 2, 3] + List.split_on_list [] [1, 2, 3] ", RocList::>::from_slice(&[RocList::::from_slice(&[]),]), RocList> ); assert_evals_to!( r" - List.splitOnList [1, 2, 3] [] + List.split_on_list [1, 2, 3] [] ", RocList::>::from_slice(&[RocList::::from_slice(&[1, 2, 3]),]), RocList> ); assert_evals_to!( r" - List.splitOnList [1] [1] + List.split_on_list [1] [1] ", RocList::>::from_slice(&[ RocList::::from_slice(&[]), @@ -519,14 +519,14 @@ fn list_split_on_list() { ); assert_evals_to!( r" - List.splitOnList [1, 2, 3] [47] + List.split_on_list [1, 2, 3] [47] ", RocList::>::from_slice(&[RocList::::from_slice(&[1, 2, 3])]), RocList> ); assert_evals_to!( r" - List.splitOnList [1, 2, 3, 4, 5] [2, 3] + List.split_on_list [1, 2, 3, 4, 5] [2, 3] ", RocList::>::from_slice(&[ RocList::::from_slice(&[1]), @@ -536,7 +536,7 @@ fn list_split_on_list() { ); assert_evals_to!( r" - List.splitOnList [1, 0, 1, 0, 1] [1] + List.split_on_list [1, 0, 1, 0, 1] [1] ", RocList::>::from_slice(&[ RocList::::from_slice(&[]), @@ -553,7 +553,7 @@ fn list_split_on_list() { fn list_split_first() { assert_evals_to!( r" - List.splitFirst [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 + List.split_first [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 |> Result.map .before ", RocResult::ok(RocList::::from_slice(&[2, 3])), @@ -561,7 +561,7 @@ fn list_split_first() { ); assert_evals_to!( r" - List.splitFirst [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 + List.split_first [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 |> Result.map .after ", RocResult::ok(RocList::::from_slice(&[4, 0, 6, 0, 8, 9])), @@ -569,13 +569,13 @@ fn list_split_first() { ); assert_evals_to!( - "List.splitFirst [1, 2, 3] 0", + "List.split_first [1, 2, 3] 0", RocResult::err(()), RocResult<(RocList, RocList), ()> ); assert_evals_to!( - "List.splitFirst [] 1", + "List.split_first [] 1", RocResult::err(()), RocResult<(RocList, RocList), ()> ); @@ -586,7 +586,7 @@ fn list_split_first() { fn list_split_last() { assert_evals_to!( r" - List.splitLast [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 + List.split_last [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 |> Result.map .before ", RocResult::ok(RocList::::from_slice(&[2, 3, 0, 4, 0, 6])), @@ -594,7 +594,7 @@ fn list_split_last() { ); assert_evals_to!( r" - List.splitLast [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 + List.split_last [2, 3, 0, 4, 0, 6, 0, 8, 9] 0 |> Result.map .after ", RocResult::ok(RocList::::from_slice(&[8, 9])), @@ -602,13 +602,13 @@ fn list_split_last() { ); assert_evals_to!( - "List.splitLast [1, 2, 3] 0", + "List.split_last [1, 2, 3] 0", RocResult::err(()), RocResult<(RocList, RocList), ()> ); assert_evals_to!( - "List.splitLast [] 1", + "List.split_last [] 1", RocResult::err(()), RocResult<(RocList, RocList), ()> ); @@ -618,7 +618,7 @@ fn list_split_last() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn list_chunks_of() { assert_evals_to!( - "List.chunksOf [1, 2, 3, 4, 5, 6, 7, 8] 3", + "List.chunks_of [1, 2, 3, 4, 5, 6, 7, 8] 3", RocList::>::from_slice(&[ RocList::from_slice(&[1, 2, 3]), RocList::from_slice(&[4, 5, 6]), @@ -628,19 +628,19 @@ fn list_chunks_of() { ); assert_evals_to!( - "List.chunksOf [1, 2, 3, 4] 5", + "List.chunks_of [1, 2, 3, 4] 5", RocList::>::from_slice(&[RocList::from_slice(&[1, 2, 3, 4]),]), RocList> ); assert_evals_to!( - "List.chunksOf [1, 2, 3] 0", + "List.chunks_of [1, 2, 3] 0", RocList::>::from_slice(&[]), RocList> ); assert_evals_to!( - "List.chunksOf [] 5", + "List.chunks_of [] 5", RocList::>::from_slice(&[]), RocList> ); @@ -650,17 +650,17 @@ fn list_chunks_of() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_drop_first() { assert_evals_to!( - "List.dropFirst [1,2,3] 2", + "List.drop_first [1,2,3] 2", RocList::from_slice(&[3]), RocList ); assert_evals_to!( - "List.dropFirst [] 1", + "List.drop_first [] 1", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.dropFirst [1,2] 5", + "List.drop_first [1,2] 5", RocList::::from_slice(&[]), RocList ); @@ -670,27 +670,27 @@ fn list_drop_first() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_drop_at() { assert_evals_to!( - "List.dropAt [1, 2, 3] 0", + "List.drop_at [1, 2, 3] 0", RocList::from_slice(&[2, 3]), RocList ); assert_evals_to!( - "List.dropAt [1, 2, 3] 1", + "List.drop_at [1, 2, 3] 1", RocList::from_slice(&[1, 3]), RocList ); assert_evals_to!( - "List.dropAt [0, 0, 0] 3", + "List.drop_at [0, 0, 0] 3", RocList::from_slice(&[0, 0, 0]), RocList ); assert_evals_to!( - "List.dropAt [] 1", + "List.drop_at [] 1", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.dropAt [0] 0", + "List.drop_at [0] 0", RocList::::from_slice(&[]), RocList ); @@ -728,7 +728,7 @@ fn list_drop_at_shared() { list : List I64 list = [if Bool.true then 4 else 4, 5, 6] - { newList: List.dropAt list 0, original: list } + { new_list: List.drop_at list 0, original: list } " ), ( @@ -750,7 +750,7 @@ fn list_drop_if_empty_list_of_int() { empty : List I64 empty = [] - List.dropIf empty \_ -> Bool.true + List.drop_if empty \_ -> Bool.true " ), RocList::::from_slice(&[]), @@ -764,10 +764,10 @@ fn list_drop_if_empty_list() { assert_evals_to!( indoc!( r" - alwaysTrue : I64 -> Bool - alwaysTrue = \_ -> Bool.true + always_true : I64 -> Bool + always_true = \_ -> Bool.true - List.dropIf [] alwaysTrue + List.drop_if [] always_true " ), RocList::::from_slice(&[]), @@ -781,7 +781,7 @@ fn list_drop_if_always_false_for_non_empty_list() { assert_evals_to!( indoc!( r" - List.dropIf [1,2,3,4,5,6,7,8] (\_ -> Bool.false) + List.drop_if [1,2,3,4,5,6,7,8] (\_ -> Bool.false) " ), RocList::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]), @@ -795,7 +795,7 @@ fn list_drop_if_always_true_for_non_empty_list() { assert_evals_to!( indoc!( r" - List.dropIf [1,2,3,4,5,6,7,8] (\_ -> Bool.true) + List.drop_if [1,2,3,4,5,6,7,8] (\_ -> Bool.true) " ), RocList::::from_slice(&[]), @@ -809,7 +809,7 @@ fn list_drop_if_geq3() { assert_evals_to!( indoc!( r" - List.dropIf [1,2,3,4,5,6,7,8] (\n -> n >= 3) + List.drop_if [1,2,3,4,5,6,7,8] (\n -> n >= 3) " ), RocList::from_slice(&[1, 2]), @@ -823,7 +823,7 @@ fn list_drop_if_string_eq() { assert_evals_to!( indoc!( r#" - List.dropIf ["x", "y", "x"] (\s -> s == "y") + List.drop_if ["x", "y", "x"] (\s -> s == "y") "# ), RocList::from_slice(&[RocStr::from("x"), RocStr::from("x")]), @@ -835,17 +835,17 @@ fn list_drop_if_string_eq() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_drop_last() { assert_evals_to!( - "List.dropLast [1, 2, 3] 1", + "List.drop_last [1, 2, 3] 1", RocList::from_slice(&[1, 2]), RocList ); assert_evals_to!( - "List.dropLast [] 5", + "List.drop_last [] 5", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.dropLast [0] 0", + "List.drop_last [0] 0", RocList::::from_slice(&[0]), RocList ); @@ -860,7 +860,7 @@ fn list_drop_last_mutable() { list : List I64 list = [if Bool.true then 4 else 4, 5, 6] - { newList: List.dropLast list 1, original: list } + { new_list: List.drop_last list 1, original: list } " ), ( @@ -921,11 +921,11 @@ fn list_append_to_empty_list_of_int() { assert_evals_to!( indoc!( r" - initThrees : List I64 - initThrees = + init_threes : List I64 + init_threes = [] - List.append (List.append initThrees 3) 3 + List.append (List.append init_threes 3) 3 " ), RocList::from_slice(&[3, 3]), @@ -1067,7 +1067,7 @@ fn list_walk_backwards_empty_all_inline() { assert_evals_to!( indoc!( r" - List.walkBackwards [0x1] 0 \state, elem -> state + elem + List.walk_backwards [0x1] 0 \state, elem -> state + elem " ), 1, @@ -1081,7 +1081,7 @@ fn list_walk_backwards_empty_all_inline() { empty = [] - List.walkBackwards empty 0 \state, elem -> state + elem + List.walk_backwards empty 0 \state, elem -> state + elem " ), 0, @@ -1093,13 +1093,13 @@ fn list_walk_backwards_empty_all_inline() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_walk_backwards_with_str() { assert_evals_to!( - r#"List.walkBackwards ["x", "y", "z"] "<" Str.concat"#, + r#"List.walk_backwards ["x", "y", "z"] "<" Str.concat"#, RocStr::from(" when b is Zero -> { r & zeroes: r.zeroes + 1 } One -> { r & ones: r.ones + 1 } - finalCounts = List.walkBackwards byte initialCounts acc + final_counts = List.walk_backwards byte initial_counts acc - finalCounts.ones * 10 + finalCounts.zeroes + final_counts.ones * 10 + final_counts.zeroes " ), 35, @@ -1158,7 +1158,7 @@ fn list_walk_subtraction() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_walk_until_sum() { - assert_evals_to!(r"List.walkUntil [1, 2] 0 \a,b -> Continue (a + b)", 3, i64); + assert_evals_to!(r"List.walk_until [1, 2] 0 \a,b -> Continue (a + b)", 3, i64); } #[test] @@ -1166,14 +1166,14 @@ fn list_walk_until_sum() { fn list_walk_with_index_until_sum() { assert_evals_to!( r" - List.walkWithIndexUntil [5, 7, 2, 3] 0 (\state, elem, index -> + List.walk_with_index_until [5, 7, 2, 3] 0 (\state, elem, index -> if elem % 2 == 0 then Break state else # Convert to I64 to sidestep weird bug with WASM codegen - a = Num.toI64 elem - b = Num.toI64 index - c = Num.toI64 state + a = Num.to_i64 elem + b = Num.to_i64 index + c = Num.to_i64 state Continue (a + b + c) ) ", @@ -1191,11 +1191,11 @@ fn list_walk_implements_position() { find : List a, a -> Option U64 where a implements Eq find = \list, needle -> - findHelp list needle + find_help list needle |> .v - findHelp = \list, needle -> - List.walkUntil list { n: 0, v: None } \{ n, v }, element -> + find_help = \list, needle -> + List.walk_until list { n: 0, v: None } \{ n, v }, element -> if element == needle then Break { n, v: Some n } else @@ -1216,13 +1216,13 @@ fn list_walk_until_even_prefix_sum() { assert_evals_to!( r" helper = \a, b -> - if Num.isEven b then + if Num.is_even b then Continue (a + b) else Break a - List.walkUntil [2, 4, 8, 9] 0 helper", + List.walk_until [2, 4, 8, 9] 0 helper", 2 + 4 + 8, i64 ); @@ -1231,7 +1231,7 @@ fn list_walk_until_even_prefix_sum() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_walk_from_sum() { - assert_evals_to!(r"List.walkFrom [1, 2, 3] 1 0 Num.add", 5, i64); + assert_evals_to!(r"List.walk_from [1, 2, 3] 1 0 Num.add", 5, i64); } #[test] @@ -1244,7 +1244,7 @@ fn list_keep_if_empty_list_of_int() { empty = [] - List.keepIf empty \_ -> Bool.true + List.keep_if empty \_ -> Bool.true " ), RocList::::from_slice(&[]), @@ -1258,12 +1258,12 @@ fn list_keep_if_empty_list() { assert_evals_to!( indoc!( r" - alwaysTrue : I64 -> Bool - alwaysTrue = \_ -> + always_true : I64 -> Bool + always_true = \_ -> Bool.true - List.keepIf [] alwaysTrue + List.keep_if [] always_true " ), RocList::::from_slice(&[]), @@ -1277,15 +1277,15 @@ fn list_keep_if_always_true_for_non_empty_list() { assert_evals_to!( indoc!( r" - alwaysTrue : I64 -> Bool - alwaysTrue = \_ -> + always_true : I64 -> Bool + always_true = \_ -> Bool.true - oneThroughEight : List I64 - oneThroughEight = + one_through_eight : List I64 + one_through_eight = [1,2,3,4,5,6,7,8] - List.keepIf oneThroughEight alwaysTrue + List.keep_if one_through_eight always_true " ), RocList::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]), @@ -1299,11 +1299,11 @@ fn list_keep_if_always_false_for_non_empty_list() { assert_evals_to!( indoc!( r" - alwaysFalse : I64 -> Bool - alwaysFalse = \_ -> + always_false : I64 -> Bool + always_false = \_ -> Bool.false - List.keepIf [1,2,3,4,5,6,7,8] alwaysFalse + List.keep_if [1,2,3,4,5,6,7,8] always_false " ), RocList::::from_slice(&[]), @@ -1317,11 +1317,11 @@ fn list_keep_if_one() { assert_evals_to!( indoc!( r" - intIsLessThanThree : I64 -> Bool - intIsLessThanThree = \i -> + int_is_less_than_three : I64 -> Bool + int_is_less_than_three = \i -> i < 3 - List.keepIf [1,2,3,4,5,6,7,8] intIsLessThanThree + List.keep_if [1,2,3,4,5,6,7,8] int_is_less_than_three " ), RocList::from_slice(&[1, 2]), @@ -1335,7 +1335,7 @@ fn list_keep_if_str_is_hello() { assert_evals_to!( indoc!( r#" - List.keepIf ["x", "y", "x"] (\x -> x == "x") + List.keep_if ["x", "y", "x"] (\x -> x == "x") "# ), RocList::from_slice(&[RocStr::from("x"), RocStr::from("x")]), @@ -1349,7 +1349,7 @@ fn list_count_if_empty_list() { assert_evals_to!( indoc!( r" - List.countIf [] \_ -> Bool.true + List.count_if [] \_ -> Bool.true " ), 0, @@ -1363,15 +1363,15 @@ fn list_count_if_always_true_for_non_empty_list() { assert_evals_to!( indoc!( r" - alwaysTrue : I64 -> Bool - alwaysTrue = \_ -> + always_true : I64 -> Bool + always_true = \_ -> Bool.true - oneThroughEight : List I64 - oneThroughEight = + one_through_eight : List I64 + one_through_eight = [1,2,3,4,5,6,7,8] - List.countIf oneThroughEight alwaysTrue + List.count_if one_through_eight always_true " ), 8, @@ -1385,11 +1385,11 @@ fn list_count_if_always_false_for_non_empty_list() { assert_evals_to!( indoc!( r" - alwaysFalse : I64 -> Bool - alwaysFalse = \_ -> + always_false : I64 -> Bool + always_false = \_ -> Bool.false - List.countIf [1,2,3,4,5,6,7,8] alwaysFalse + List.count_if [1,2,3,4,5,6,7,8] always_false " ), 0, @@ -1403,11 +1403,11 @@ fn list_count_if_condition() { assert_evals_to!( indoc!( r" - intIsLessThanThree : I64 -> Bool - intIsLessThanThree = \i -> + int_is_less_than_three : I64 -> Bool + int_is_less_than_three = \i -> i < 3 - List.countIf [1,2,3,4,5,6,7,8] intIsLessThanThree + List.count_if [1,2,3,4,5,6,7,8] int_is_less_than_three " ), 2, @@ -1421,7 +1421,7 @@ fn list_count_if_str() { assert_evals_to!( indoc!( r#" - List.countIf ["x", "y", "x"] (\x -> x == "x") + List.count_if ["x", "y", "x"] (\x -> x == "x") "# ), 2, @@ -1453,11 +1453,11 @@ fn list_map_on_non_empty_list() { assert_evals_to!( indoc!( r" - nonEmpty : List I64 - nonEmpty = + non_empty : List I64 + non_empty = [1] - List.map nonEmpty (\x -> x) + List.map non_empty (\x -> x) " ), RocList::from_slice(&[1]), @@ -1471,11 +1471,11 @@ fn list_map_changes_input() { assert_evals_to!( indoc!( r" - nonEmpty : List I64 - nonEmpty = + non_empty : List I64 + non_empty = [1] - List.map nonEmpty (\x -> x + 1) + List.map non_empty (\x -> x + 1) " ), RocList::from_slice(&[2]), @@ -1489,11 +1489,11 @@ fn list_map_on_big_list() { assert_evals_to!( indoc!( r" - nonEmpty : List I64 - nonEmpty = + non_empty : List I64 + non_empty = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] - List.map nonEmpty (\x -> x * 2) + List.map non_empty (\x -> x * 2) " ), RocList::from_slice(&[ @@ -1509,12 +1509,12 @@ fn list_map_with_type_change() { assert_evals_to!( indoc!( r" - nonEmpty : List I64 - nonEmpty = + non_empty : List I64 + non_empty = [1, 1, -4, 1, 2] - List.map nonEmpty (\x -> x > 0) + List.map non_empty (\x -> x > 0) " ), RocList::from_slice(&[true, true, false, true, true]), @@ -1528,15 +1528,15 @@ fn list_map_using_defined_function() { assert_evals_to!( indoc!( r" - nonEmpty : List I64 - nonEmpty = + non_empty : List I64 + non_empty = [2, 2, -4, 2, 3] - greaterThanOne : I64 -> Bool - greaterThanOne = \i -> + greater_than_one : I64 -> Bool + greater_than_one = \i -> i > 1 - List.map nonEmpty greaterThanOne + List.map non_empty greater_than_one " ), RocList::from_slice(&[true, true, false, true, true]), @@ -1857,11 +1857,11 @@ fn list_repeat() { assert_evals_to!( indoc!( r" - noStrs : List Str - noStrs = + no_strs : List Str + no_strs = [] - List.repeat noStrs 2 + List.repeat no_strs 2 " ), RocList::from_slice(&[RocList::::default(), RocList::default()]), @@ -1897,11 +1897,11 @@ fn list_reverse_empty_list_of_int() { assert_evals_to!( indoc!( r" - emptyList : List I64 - emptyList = + empty_list : List I64 + empty_list = [] - List.reverse emptyList + List.reverse empty_list " ), RocList::::from_slice(&[]), @@ -1935,15 +1935,15 @@ fn list_concat_two_empty_lists_of_int() { assert_evals_to!( indoc!( r" - firstList : List I64 - firstList = + first_list : List I64 + first_list = [] - secondList : List I64 - secondList = + second_list : List I64 + second_list = [] - List.concat firstList secondList + List.concat first_list second_list " ), RocList::::from_slice(&[]), @@ -2106,11 +2106,11 @@ fn fn_int_list_len() { assert_evals_to!( indoc!( r" - getLen = \list -> List.len list + get_len = \list -> List.len list nums = [2, 4, 6, 8] - getLen nums + get_len nums " ), 4, @@ -2121,13 +2121,13 @@ fn fn_int_list_len() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_list_is_empty() { - assert_evals_to!("List.isEmpty [12, 9, 6, 3]", false, bool); + assert_evals_to!("List.is_empty [12, 9, 6, 3]", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn empty_list_is_empty() { - assert_evals_to!("List.isEmpty []", true, bool); + assert_evals_to!("List.is_empty []", true, bool); } #[test] @@ -2527,10 +2527,10 @@ fn gen_wrap_len() { assert_evals_to!( indoc!( r" - wrapLen = \list -> + wrap_len = \list -> [List.len list] - wrapLen [1, 7, 9] + wrap_len [1, 7, 9] " ), RocList::from_slice(&[3]), @@ -2544,10 +2544,10 @@ fn gen_wrap_first() { assert_evals_to!( indoc!( r" - wrapFirst = \list -> + wrap_first = \list -> [List.first list] - wrapFirst [1, 2] + wrap_first [1, 2] " ), RocList::from_slice(&[1]), @@ -2590,10 +2590,10 @@ fn gen_swap() { swap : U64, U64, List a -> List a swap = \i, j, list -> when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + Pair (Ok at_i) (Ok at_j) -> list - |> List.set i atJ - |> List.set j atI + |> List.set i at_j + |> List.set j at_i _ -> [] @@ -2619,17 +2619,17 @@ fn gen_quicksort() { quicksort : List (Num a) -> List (Num a) quicksort = \list -> n = List.len list - quicksortHelp list 0 (n - 1) + quicksort_help list 0 (n - 1) - quicksortHelp : List (Num a), U64, U64 -> List (Num a) - quicksortHelp = \list, low, high -> + quicksort_help : List (Num a), U64, U64 -> List (Num a) + quicksort_help = \list, low, high -> if low < high then when partition low high list is - Pair partitionIndex partitioned -> + Pair partition_index partitioned -> partitioned - |> quicksortHelp low (Num.subSaturated partitionIndex 1) - |> quicksortHelp (partitionIndex + 1) high + |> quicksort_help low (Num.sub_saturated partition_index 1) + |> quicksort_help (partition_index + 1) high else list @@ -2637,35 +2637,35 @@ fn gen_quicksort() { swap : U64, U64, List a -> List a swap = \i, j, list -> when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + Pair (Ok at_i) (Ok at_j) -> list - |> List.set i atJ - |> List.set j atI + |> List.set i at_j + |> List.set j at_i _ -> [] partition : U64, U64, List (Num a) -> [Pair U64 (List (Num a))] - partition = \low, high, initialList -> - when List.get initialList high is + partition = \low, high, initial_list -> + when List.get initial_list high is Ok pivot -> - when partitionHelp low low initialList high pivot is - Pair newI newList -> - Pair newI (swap newI high newList) + when partition_help low low initial_list high pivot is + Pair new_i new_list -> + Pair new_i (swap new_i high new_list) Err _ -> - Pair low initialList + Pair low initial_list - partitionHelp : U64, U64, List (Num a), U64, (Num a) -> [Pair U64 (List (Num a))] - partitionHelp = \i, j, list, high, pivot -> + partition_help : U64, U64, List (Num a), U64, (Num a) -> [Pair U64 (List (Num a))] + partition_help = \i, j, list, high, pivot -> if j < high then when List.get list j is Ok value -> if value <= pivot then - partitionHelp (i + 1) (j + 1) (swap i j list) high pivot + partition_help (i + 1) (j + 1) (swap i j list) high pivot else - partitionHelp i (j + 1) list high pivot + partition_help i (j + 1) list high pivot Err _ -> Pair i list @@ -2692,17 +2692,17 @@ fn quicksort() { quicksort : List (Num a) -> List (Num a) quicksort = \list -> - quicksortHelp list 0 (List.len list - 1) + quicksort_help list 0 (List.len list - 1) - quicksortHelp : List (Num a), U64, U64 -> List (Num a) - quicksortHelp = \list, low, high -> + quicksort_help : List (Num a), U64, U64 -> List (Num a) + quicksort_help = \list, low, high -> if low < high then when partition low high list is - Pair partitionIndex partitioned -> + Pair partition_index partitioned -> partitioned - |> quicksortHelp low (Num.subSaturated partitionIndex 1) - |> quicksortHelp (partitionIndex + 1) high + |> quicksort_help low (Num.sub_saturated partition_index 1) + |> quicksort_help (partition_index + 1) high else list @@ -2710,36 +2710,36 @@ fn quicksort() { swap : U64, U64, List a -> List a swap = \i, j, list -> when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + Pair (Ok at_i) (Ok at_j) -> list - |> List.set i atJ - |> List.set j atI + |> List.set i at_j + |> List.set j at_i _ -> [] partition : U64, U64, List (Num a) -> [Pair U64 (List (Num a))] - partition = \low, high, initialList -> - when List.get initialList high is + partition = \low, high, initial_list -> + when List.get initial_list high is Ok pivot -> - when partitionHelp low low initialList high pivot is - Pair newI newList -> - Pair newI (swap newI high newList) + when partition_help low low initial_list high pivot is + Pair new_i new_list -> + Pair new_i (swap new_i high new_list) Err _ -> - Pair low initialList + Pair low initial_list - partitionHelp : U64, U64, List (Num a), U64, Num a -> [Pair U64 (List (Num a))] - partitionHelp = \i, j, list, high, pivot -> + partition_help : U64, U64, List (Num a), U64, Num a -> [Pair U64 (List (Num a))] + partition_help = \i, j, list, high, pivot -> # if j < high then if Bool.false then when List.get list j is Ok value -> if value <= pivot then - partitionHelp (i + 1) (j + 1) (swap i j list) high pivot + partition_help (i + 1) (j + 1) (swap i j list) high pivot else - partitionHelp i (j + 1) list high pivot + partition_help i (j + 1) list high pivot Err _ -> Pair i list @@ -2768,17 +2768,17 @@ fn quicksort_singleton() { quicksort : List (Num a) -> List (Num a) quicksort = \list -> - quicksortHelp list 0 (List.len list - 1) + quicksort_help list 0 (List.len list - 1) - quicksortHelp : List (Num a), U64, U64 -> List (Num a) - quicksortHelp = \list, low, high -> + quicksort_help : List (Num a), U64, U64 -> List (Num a) + quicksort_help = \list, low, high -> if low < high then when partition low high list is - Pair partitionIndex partitioned -> + Pair partition_index partitioned -> partitioned - |> quicksortHelp low (Num.subSaturated partitionIndex 1) - |> quicksortHelp (partitionIndex + 1) high + |> quicksort_help low (Num.sub_saturated partition_index 1) + |> quicksort_help (partition_index + 1) high else list @@ -2786,35 +2786,35 @@ fn quicksort_singleton() { swap : U64, U64, List a -> List a swap = \i, j, list -> when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> + Pair (Ok at_i) (Ok at_j) -> list - |> List.set i atJ - |> List.set j atI + |> List.set i at_j + |> List.set j at_i _ -> [] partition : U64, U64, List (Num a) -> [Pair U64 (List (Num a))] - partition = \low, high, initialList -> - when List.get initialList high is + partition = \low, high, initial_list -> + when List.get initial_list high is Ok pivot -> - when partitionHelp low low initialList high pivot is - Pair newI newList -> - Pair newI (swap newI high newList) + when partition_help low low initial_list high pivot is + Pair new_i new_list -> + Pair new_i (swap new_i high new_list) Err _ -> - Pair low initialList + Pair low initial_list - partitionHelp : U64, U64, List (Num a), U64, Num a -> [Pair U64 (List (Num a))] - partitionHelp = \i, j, list, high, pivot -> + partition_help : U64, U64, List (Num a), U64, Num a -> [Pair U64 (List (Num a))] + partition_help = \i, j, list, high, pivot -> if j < high then when List.get list j is Ok value -> if value <= pivot then - partitionHelp (i + 1) (j + 1) (swap i j list) high pivot + partition_help (i + 1) (j + 1) (swap i j list) high pivot else - partitionHelp i (j + 1) list high pivot + partition_help i (j + 1) list high pivot Err _ -> Pair i list @@ -3047,13 +3047,13 @@ fn list_product() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_keep_void() { assert_evals_to!( - "List.keepOks [] (\\x -> x)", + "List.keep_oks [] (\\x -> x)", RocList::from_slice(&[]), RocList<()> ); assert_evals_to!( - "List.keepErrs [] (\\x -> x)", + "List.keep_errs [] (\\x -> x)", RocList::from_slice(&[]), RocList<()> ); @@ -3063,22 +3063,22 @@ fn list_keep_void() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_keep_oks() { assert_evals_to!( - "List.keepOks [Ok {}, Ok {}] (\\x -> x)", + "List.keep_oks [Ok {}, Ok {}] (\\x -> x)", RocList::from_slice(&[(), ()]), RocList<()> ); assert_evals_to!( - "List.keepOks [1,2] (\\x -> Ok x)", + "List.keep_oks [1,2] (\\x -> Ok x)", RocList::from_slice(&[1, 2]), RocList ); assert_evals_to!( - "List.keepOks [1,2] (\\x -> Num.remChecked x 2)", + "List.keep_oks [1,2] (\\x -> Num.rem_checked x 2)", RocList::from_slice(&[1, 0]), RocList ); assert_evals_to!( - "List.keepOks [Ok 1, Err 2] (\\x -> x)", + "List.keep_oks [Ok 1, Err 2] (\\x -> x)", RocList::from_slice(&[1]), RocList ); @@ -3088,19 +3088,19 @@ fn list_keep_oks() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_keep_errs() { assert_evals_to!( - "List.keepErrs [Err {}, Err {}] (\\x -> x)", + "List.keep_errs [Err {}, Err {}] (\\x -> x)", RocList::from_slice(&[(), ()]), RocList<()> ); assert_evals_to!( - "List.keepErrs [1,2] (\\x -> Err x)", + "List.keep_errs [1,2] (\\x -> Err x)", RocList::from_slice(&[1, 2]), RocList ); assert_evals_to!( indoc!( r" - List.keepErrs [0,1,2] (\x -> Num.remChecked x 0 |> Result.mapErr (\_ -> 32)) + List.keep_errs [0,1,2] (\x -> Num.rem_checked x 0 |> Result.map_err (\_ -> 32)) " ), RocList::from_slice(&[32, 32, 32]), @@ -3108,7 +3108,7 @@ fn list_keep_errs() { ); assert_evals_to!( - "List.keepErrs [Ok 1, Err 2] (\\x -> x)", + "List.keep_errs [Ok 1, Err 2] (\\x -> x)", RocList::from_slice(&[2]), RocList ); @@ -3118,7 +3118,7 @@ fn list_keep_errs() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_map_with_index() { assert_evals_to!( - "List.mapWithIndex [0,0,0] (\\x, index -> Num.intCast index + x)", + "List.map_with_index [0,0,0] (\\x, index -> Num.int_cast index + x)", RocList::from_slice(&[0, 1, 2]), RocList ); @@ -3136,7 +3136,7 @@ fn cleanup_because_exception() { five : I64 five = 5 - five + Num.maxI64 + 3 + (Num.intCast (List.len x)) + five + Num.max_i64 + 3 + (Num.int_cast (List.len x)) " ), 9, @@ -3148,17 +3148,17 @@ fn cleanup_because_exception() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_sort_with() { assert_evals_to!( - "List.sortWith [] Num.compare", + "List.sort_with [] Num.compare", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.sortWith [4,3,2,1] Num.compare", + "List.sort_with [4,3,2,1] Num.compare", RocList::from_slice(&[1, 2, 3, 4]), RocList ); assert_evals_to!( - "List.sortWith [1,2,3,4] (\\a,b -> Num.compare b a)", + "List.sort_with [1,2,3,4] (\\a,b -> Num.compare b a)", RocList::from_slice(&[4, 3, 2, 1]), RocList ); @@ -3168,12 +3168,12 @@ fn list_sort_with() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_sort_asc() { assert_evals_to!( - "List.sortAsc []", + "List.sort_asc []", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.sortAsc [4,3,2,1]", + "List.sort_asc [4,3,2,1]", RocList::from_slice(&[1, 2, 3, 4]), RocList ); @@ -3183,12 +3183,12 @@ fn list_sort_asc() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_sort_desc() { assert_evals_to!( - "List.sortDesc []", + "List.sort_desc []", RocList::::from_slice(&[]), RocList ); assert_evals_to!( - "List.sortDesc [1,2,3,4]", + "List.sort_desc [1,2,3,4]", RocList::from_slice(&[4, 3, 2, 1]), RocList ); @@ -3224,7 +3224,7 @@ fn list_all_empty_with_unknown_element_type() { } #[test] -// This doesn't work on Windows. If you make it return a `bool`, e.g. with `|> Str.isEmpty` at the end, +// This doesn't work on Windows. If you make it return a `bool`, e.g. with `|> Str.is_empty` at the end, // then it works. We don't know what the problem is here! #[cfg(all( not(target_family = "windows"), @@ -3256,7 +3256,7 @@ fn map_with_index_multi_record() { assert_evals_to!( indoc!( r" - List.mapWithIndex [{ x: {}, y: {} }] \_, _ -> {} + List.map_with_index [{ x: {}, y: {} }] \_, _ -> {} " ), RocList::from_slice(&[((), ())]), @@ -3271,17 +3271,17 @@ fn empty_list_of_function_type() { assert_evals_to!( indoc!( r#" - myList : List (Str -> Str) - myList = [] + my_list : List (Str -> Str) + my_list = [] - myClosure : Str -> Str - myClosure = \_ -> "bar" + my_closure : Str -> Str + my_closure = \_ -> "bar" choose = if Bool.false then - myList + my_list else - [myClosure] + [my_closure] when List.get choose 0 is Ok f -> f "foo" @@ -3299,7 +3299,7 @@ fn list_join_map() { assert_evals_to!( indoc!( r#" - List.joinMap ["guava,apple,pear", "bailey,cyrus"] (\s -> Str.splitOn s ",") + List.join_map ["guava,apple,pear", "bailey,cyrus"] (\s -> Str.split_on s ",") "# ), RocList::from_slice(&[ @@ -3319,7 +3319,7 @@ fn list_join_map_empty() { assert_evals_to!( indoc!( r#" - List.joinMap [] (\s -> Str.splitOn s ",") + List.join_map [] (\s -> Str.split_on s ",") "# ), RocList::from_slice(&[]), @@ -3333,7 +3333,7 @@ fn list_find() { assert_evals_to!( indoc!( r#" - when List.findFirst ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 1) is + when List.find_first ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 1) is Ok v -> v Err _ -> "not found" "# @@ -3345,7 +3345,7 @@ fn list_find() { assert_evals_to!( indoc!( r#" - when List.findLast ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 1) is + when List.find_last ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 1) is Ok v -> v Err _ -> "not found" "# @@ -3361,7 +3361,7 @@ fn list_find_not_found() { assert_evals_to!( indoc!( r#" - when List.findFirst ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_first ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> "not found" "# @@ -3373,7 +3373,7 @@ fn list_find_not_found() { assert_evals_to!( indoc!( r#" - when List.findLast ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_last ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> "not found" "# @@ -3389,7 +3389,7 @@ fn list_find_empty_typed_list() { assert_evals_to!( indoc!( r#" - when List.findFirst [] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_first [] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> "not found" "# @@ -3401,7 +3401,7 @@ fn list_find_empty_typed_list() { assert_evals_to!( indoc!( r#" - when List.findLast [] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_last [] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> "not found" "# @@ -3417,7 +3417,7 @@ fn list_find_empty_layout() { assert_evals_to!( indoc!( r" - List.findFirst [] \_ -> Bool.true + List.find_first [] \_ -> Bool.true " ), // [Ok [], Err [NotFound]] gets unwrapped all the way to just [NotFound], @@ -3429,7 +3429,7 @@ fn list_find_empty_layout() { assert_evals_to!( indoc!( r" - List.findLast [] \_ -> Bool.true + List.find_last [] \_ -> Bool.true " ), // [Ok [], Err [NotFound]] gets unwrapped all the way to just [NotFound], @@ -3445,7 +3445,7 @@ fn list_find_index() { assert_evals_to!( indoc!( r#" - when List.findFirstIndex ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 1) is + when List.find_first_index ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 1) is Ok v -> v Err _ -> 999 "# @@ -3457,7 +3457,7 @@ fn list_find_index() { assert_evals_to!( indoc!( r#" - when List.findLastIndex ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 1) is + when List.find_last_index ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 1) is Ok v -> v Err _ -> 999 "# @@ -3473,7 +3473,7 @@ fn list_find_index_not_found() { assert_evals_to!( indoc!( r#" - when List.findFirstIndex ["a", "bc", "def", "g"] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_first_index ["a", "bc", "def", "g"] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> 999 "# @@ -3485,7 +3485,7 @@ fn list_find_index_not_found() { assert_evals_to!( indoc!( r#" - when List.findLastIndex ["a", "bc", "def"] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_last_index ["a", "bc", "def"] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> 999 "# @@ -3501,7 +3501,7 @@ fn list_find_index_empty_typed_list() { assert_evals_to!( indoc!( r" - when List.findFirstIndex [] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_first_index [] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> 999 " @@ -3513,7 +3513,7 @@ fn list_find_index_empty_typed_list() { assert_evals_to!( indoc!( r" - when List.findLastIndex [] (\s -> Str.countUtf8Bytes s > 5) is + when List.find_last_index [] (\s -> Str.count_utf8_bytes s > 5) is Ok v -> v Err _ -> 999 " @@ -3529,7 +3529,7 @@ fn list_ends_with_empty() { assert_evals_to!( indoc!( r" - List.endsWith [] [] + List.ends_with [] [] " ), true, @@ -3539,7 +3539,7 @@ fn list_ends_with_empty() { assert_evals_to!( indoc!( r#" - List.endsWith ["a"] [] + List.ends_with ["a"] [] "# ), true, @@ -3549,7 +3549,7 @@ fn list_ends_with_empty() { assert_evals_to!( indoc!( r#" - List.endsWith [] ["a"] + List.ends_with [] ["a"] "# ), false, @@ -3563,7 +3563,7 @@ fn list_ends_with_nonempty() { assert_evals_to!( indoc!( r#" - List.endsWith ["a", "bc", "def"] ["def"] + List.ends_with ["a", "bc", "def"] ["def"] "# ), true, @@ -3573,7 +3573,7 @@ fn list_ends_with_nonempty() { assert_evals_to!( indoc!( r#" - List.endsWith ["a", "bc", "def"] ["bc", "def"] + List.ends_with ["a", "bc", "def"] ["bc", "def"] "# ), true, @@ -3583,7 +3583,7 @@ fn list_ends_with_nonempty() { assert_evals_to!( indoc!( r#" - List.endsWith ["a", "bc", "def"] ["a"] + List.ends_with ["a", "bc", "def"] ["a"] "# ), false, @@ -3593,7 +3593,7 @@ fn list_ends_with_nonempty() { assert_evals_to!( indoc!( r#" - List.endsWith ["a", "bc", "def"] [""] + List.ends_with ["a", "bc", "def"] [""] "# ), false, @@ -3607,7 +3607,7 @@ fn list_starts_with_empty() { assert_evals_to!( indoc!( r" - List.startsWith [] [] + List.starts_with [] [] " ), true, @@ -3617,7 +3617,7 @@ fn list_starts_with_empty() { assert_evals_to!( indoc!( r#" - List.startsWith ["a"] [] + List.starts_with ["a"] [] "# ), true, @@ -3627,7 +3627,7 @@ fn list_starts_with_empty() { assert_evals_to!( indoc!( r#" - List.startsWith [] ["a"] + List.starts_with [] ["a"] "# ), false, @@ -3641,7 +3641,7 @@ fn list_starts_with_nonempty() { assert_evals_to!( indoc!( r#" - List.startsWith ["a", "bc", "def"] ["a"] + List.starts_with ["a", "bc", "def"] ["a"] "# ), true, @@ -3651,7 +3651,7 @@ fn list_starts_with_nonempty() { assert_evals_to!( indoc!( r#" - List.startsWith ["a", "bc", "def"] ["a", "bc"] + List.starts_with ["a", "bc", "def"] ["a", "bc"] "# ), true, @@ -3661,7 +3661,7 @@ fn list_starts_with_nonempty() { assert_evals_to!( indoc!( r#" - List.startsWith ["a", "bc", "def"] ["def"] + List.starts_with ["a", "bc", "def"] ["def"] "# ), false, @@ -3671,7 +3671,7 @@ fn list_starts_with_nonempty() { assert_evals_to!( indoc!( r#" - List.startsWith ["a", "bc", "def"] [""] + List.starts_with ["a", "bc", "def"] [""] "# ), false, @@ -3705,7 +3705,7 @@ fn with_capacity() { indoc!( r" l : List U64 - l = List.withCapacity 10 + l = List.with_capacity 10 l " @@ -3724,7 +3724,7 @@ fn with_capacity_append() { assert_evals_to!( indoc!( r" - List.withCapacity 10 + List.with_capacity 10 |> List.append 0u64 |> List.append 1u64 |> List.append 2u64 @@ -3783,7 +3783,7 @@ fn release_excess_capacity() { indoc!( r" List.reserve [] 15 - |> List.releaseExcessCapacity + |> List.release_excess_capacity " ), (0, RocList::empty()), @@ -3799,7 +3799,7 @@ fn release_excess_capacity_with_len() { indoc!( r" List.reserve [1] 50 - |> List.releaseExcessCapacity + |> List.release_excess_capacity " ), (1, RocList::from_slice(&[1])), @@ -3814,7 +3814,7 @@ fn release_excess_capacity_empty() { assert_evals_to!( indoc!( r" - List.releaseExcessCapacity [] + List.release_excess_capacity [] " ), (0, RocList::empty()), @@ -3864,10 +3864,10 @@ fn issue_3571_lowlevel_call_function_with_bool_lambda_set() { apply : List (a -> b), List a -> List b apply = \funs, vals -> - initial = List.withCapacity ((List.len funs) * (List.len vals)) - List.walk funs initial \state, fun -> - mappedVals = List.map vals fun - List.concat state mappedVals + initial = List.with_capacity ((List.len funs) * (List.len vals)) + List.walk funs initial \state, fun -> + mapped_vals = List.map vals fun + List.concat state mapped_vals add2 : Str -> Str add2 = \x -> "added $(x)" @@ -3878,7 +3878,7 @@ fn issue_3571_lowlevel_call_function_with_bool_lambda_set() { foo = [add2, mul2] bar = ["1", "2", "3", "4"] - main = foo |> apply bar |> Str.joinWith ", " + main = foo |> apply bar |> Str.join_with ", " "# ), RocStr::from("added 1, added 2, added 3, added 4, multiplied 1, multiplied 2, multiplied 3, multiplied 4"), @@ -3930,11 +3930,11 @@ fn list_walk_backwards_implements_position() { find : List a, a -> Option U64 where a implements Eq find = \list, needle -> - findHelp list needle + find_help list needle |> .v - findHelp = \list, needle -> - List.walkBackwardsUntil list { n: 0, v: None } \{ n, v }, element -> + find_help = \list, needle -> + List.walk_backwards_until list { n: 0, v: None } \{ n, v }, element -> if element == needle then Break { n, v: Some n } else @@ -3953,7 +3953,7 @@ fn list_walk_backwards_implements_position() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_walk_backwards_until_sum() { assert_evals_to!( - r"List.walkBackwardsUntil [1, 2] 0 \a,b -> Continue (a + b)", + r"List.walk_backwards_until [1, 2] 0 \a,b -> Continue (a + b)", 3, i64 ); @@ -3965,13 +3965,13 @@ fn list_walk_backwards_until_even_prefix_sum() { assert_evals_to!( r" helper = \a, b -> - if Num.isEven b then + if Num.is_even b then Continue (a + b) else Break a - List.walkBackwardsUntil [9, 8, 4, 2] 0 helper", + List.walk_backwards_until [9, 8, 4, 2] 0 helper", 2 + 4 + 8, i64 ); @@ -3981,7 +3981,7 @@ fn list_walk_backwards_until_even_prefix_sum() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn list_walk_from_until_sum() { assert_evals_to!( - r"List.walkFromUntil [1, 2, 3, 4] 2 0 \a,b -> Continue (a + b)", + r"List.walk_from_until [1, 2, 3, 4] 2 0 \a,b -> Continue (a + b)", 7, i64 ); @@ -3992,13 +3992,13 @@ fn list_walk_from_until_sum() { fn concat_unique_to_nonunique_overlapping_issue_4697() { assert_evals_to!( r" - # originalList is shared, but others is unique. - # When we concat originalList with others, others should be re-used. + # original_list is shared, but others is unique. + # When we concat original_list with others, others should be re-used. - originalList = [1u8] + original_list = [1u8] others = [2u8, 3u8, 4u8] - new = List.concat originalList others - {a: originalList, b: new} + new = List.concat original_list others + {a: original_list, b: new} ", ( RocList::from_slice(&[1u8]), @@ -4014,13 +4014,13 @@ fn list_walk_from_even_prefix_sum() { assert_evals_to!( r" helper = \a, b -> - if Num.isEven b then + if Num.is_even b then Continue (a + b) else Break a - List.walkFromUntil [2, 4, 8, 9] 1 0 helper", + List.walk_from_until [2, 4, 8, 9] 1 0 helper", 4 + 8, i64 ); @@ -4281,7 +4281,7 @@ mod pattern_match { fn list_concat_utf8() { assert_evals_to!( r#" - List.concatUtf8 [1, 2, 3, 4] "🐦" + List.concat_utf8 [1, 2, 3, 4] "🐦" "#, RocList::from_slice(&[1u8, 2, 3, 4, 240, 159, 144, 166]), RocList diff --git a/crates/compiler/test_gen/src/gen_num.rs b/crates/compiler/test_gen/src/gen_num.rs index b3d50dd07d3..e374c061d41 100644 --- a/crates/compiler/test_gen/src/gen_num.rs +++ b/crates/compiler/test_gen/src/gen_num.rs @@ -482,13 +482,13 @@ fn f64_sqrt_checked_0() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn f64_sqrt_checked_positive() { - assert_evals_to!("Num.sqrtChecked 100f64", RocResult::ok(10.0), RocResult); + assert_evals_to!("Num.sqrt_checked 100f64", RocResult::ok(10.0), RocResult); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn f64_sqrt_checked_negative() { - assert_evals_to!("Num.sqrtChecked -1f64", RocResult::err(()), RocResult); + assert_evals_to!("Num.sqrt_checked -1f64", RocResult::err(()), RocResult); } #[test] @@ -500,13 +500,13 @@ fn f64_log() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn f64_log_checked_one() { - assert_evals_to!("Num.logChecked 1f64", RocResult::ok(0.0), RocResult); + assert_evals_to!("Num.log_checked 1f64", RocResult::ok(0.0), RocResult); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn f64_log_checked_zero() { - assert_evals_to!("Num.logChecked 0f64", RocResult::err(()), RocResult); + assert_evals_to!("Num.log_checked 0f64", RocResult::err(()), RocResult); } #[test] @@ -531,8 +531,8 @@ fn f64_abs() { assert_evals_to!("Num.abs -4.7f64", 4.7, f64); assert_evals_to!("Num.abs 5.8f64", 5.8, f64); - assert_evals_to!("Num.abs Num.maxF64", f64::MAX, f64); - assert_evals_to!("Num.abs Num.minF64", f64::MAX, f64); + assert_evals_to!("Num.abs Num.max_f64", f64::MAX, f64); + assert_evals_to!("Num.abs Num.min_f64", f64::MAX, f64); } #[test] @@ -541,8 +541,8 @@ fn f32_abs() { assert_evals_to!("Num.abs -4.7f32", 4.7, f32); assert_evals_to!("Num.abs 5.8f32", 5.8, f32); - assert_evals_to!("Num.abs Num.maxF32", f32::MAX, f32); - assert_evals_to!("Num.abs Num.minF32", f32::MAX, f32); + assert_evals_to!("Num.abs Num.max_f32", f32::MAX, f32); + assert_evals_to!("Num.abs Num.min_f32", f32::MAX, f32); } #[test] @@ -556,8 +556,8 @@ fn i64_abs() { assert_evals_to!("Num.abs 1", 1, i64); assert_evals_to!("Num.abs 9_000_000_000_000", 9_000_000_000_000, i64); assert_evals_to!("Num.abs -9_000_000_000_000", 9_000_000_000_000, i64); - assert_evals_to!("Num.abs Num.maxI64", i64::MAX, i64); - assert_evals_to!("Num.abs (Num.minI64 + 1)", -(i64::MIN + 1), i64); + assert_evals_to!("Num.abs Num.max_i64", i64::MAX, i64); + assert_evals_to!("Num.abs (Num.min_i64 + 1)", -(i64::MIN + 1), i64); } #[test] @@ -588,7 +588,7 @@ fn abs_min_int_overflow() { assert_evals_to!( indoc!( r" - Num.abs Num.minI64 + Num.abs Num.min_i64 " ), 0, @@ -602,7 +602,7 @@ fn gen_if_fn() { assert_evals_to!( indoc!( r" - limitedNegate = \num -> + limited_negate = \num -> x = if num == 1 then -1 @@ -612,7 +612,7 @@ fn gen_if_fn() { num x - limitedNegate 1 + limited_negate 1 " ), -1, @@ -701,7 +701,7 @@ fn gen_div_checked_f64() { assert_evals_to!( indoc!( r" - when Num.divChecked 48 2f64 is + when Num.div_checked 48 2f64 is Ok val -> val Err _ -> -1 " @@ -717,7 +717,7 @@ fn gen_div_checked_by_zero_f64() { assert_evals_to!( indoc!( r" - when Num.divChecked 47 0f64 is + when Num.div_checked 47 0f64 is Ok val -> val Err _ -> -1 " @@ -759,7 +759,7 @@ fn gen_div_checked_dec() { y : Dec y = 3 - when Num.divChecked x y is + when Num.div_checked x y is Ok val -> val Err _ -> -1 " @@ -780,7 +780,7 @@ fn gen_div_checked_by_zero_dec() { y : Dec y = 0 - when Num.divChecked x y is + when Num.div_checked x y is Ok val -> val Err _ -> -1 " @@ -810,7 +810,7 @@ fn gen_div_dec_by_zero() { fn gen_div_ceil_by_zero() { assert_evals_to!( r" - Num.divCeil 5 0 == 0 + Num.div_ceil 5 0 == 0 ", false, bool @@ -909,11 +909,11 @@ fn gen_wrap_int_neq() { assert_evals_to!( indoc!( r" - wrappedNotEq : a, a -> Bool where a implements Eq - wrappedNotEq = \num1, num2 -> + wrapped_not_eq : a, a -> Bool where a implements Eq + wrapped_not_eq = \num1, num2 -> num1 != num2 - wrappedNotEq 2 3 + wrapped_not_eq 2 3 " ), true, @@ -1172,7 +1172,7 @@ fn gen_div_by_zero_i64() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_div_checked_i64() { assert_evals_to!( - "Num.divTruncChecked 1000 10", + "Num.div_trunc_checked 1000 10", RocResult::ok(100), RocResult ); @@ -1182,7 +1182,7 @@ fn gen_div_checked_i64() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_div_checked_by_zero_i64() { assert_evals_to!( - "Num.divTruncChecked 1000 0", + "Num.div_trunc_checked 1000 0", RocResult::err(()), RocResult ); @@ -1205,7 +1205,7 @@ fn gen_rem_div_by_zero_i64() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_rem_checked_i64() { assert_evals_to!( - "Num.remChecked 42 40", + "Num.rem_checked 42 40", RocResult::ok(2), RocResult ); @@ -1215,7 +1215,7 @@ fn gen_rem_checked_i64() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_rem_checked_div_by_zero_i64() { assert_evals_to!( - "Num.remChecked 8 0", + "Num.rem_checked 8 0", RocResult::err(()), RocResult ); @@ -1224,67 +1224,67 @@ fn gen_rem_checked_div_by_zero_i64() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_positive_i64() { - assert_evals_to!("Num.isPositive 0", false, bool); - assert_evals_to!("Num.isPositive 1", true, bool); - assert_evals_to!("Num.isPositive -5", false, bool); + assert_evals_to!("Num.is_positive 0", false, bool); + assert_evals_to!("Num.is_positive 1", true, bool); + assert_evals_to!("Num.is_positive -5", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_negative_i64() { - assert_evals_to!("Num.isNegative 0", false, bool); - assert_evals_to!("Num.isNegative 3", false, bool); - assert_evals_to!("Num.isNegative -2", true, bool); + assert_evals_to!("Num.is_negative 0", false, bool); + assert_evals_to!("Num.is_negative 3", false, bool); + assert_evals_to!("Num.is_negative -2", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_positive_f64() { - assert_evals_to!("Num.isPositive 0.0", false, bool); - assert_evals_to!("Num.isPositive 4.7", true, bool); - assert_evals_to!("Num.isPositive -8.5", false, bool); + assert_evals_to!("Num.is_positive 0.0", false, bool); + assert_evals_to!("Num.is_positive 4.7", true, bool); + assert_evals_to!("Num.is_positive -8.5", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_negative_f64() { - assert_evals_to!("Num.isNegative 0.0", false, bool); - assert_evals_to!("Num.isNegative 9.9", false, bool); - assert_evals_to!("Num.isNegative -4.4", true, bool); + assert_evals_to!("Num.is_negative 0.0", false, bool); + assert_evals_to!("Num.is_negative 9.9", false, bool); + assert_evals_to!("Num.is_negative -4.4", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_zero_i64() { - assert_evals_to!("Num.isZero 0", true, bool); - assert_evals_to!("Num.isZero 0_0", true, bool); - assert_evals_to!("Num.isZero 1", false, bool); + assert_evals_to!("Num.is_zero 0", true, bool); + assert_evals_to!("Num.is_zero 0_0", true, bool); + assert_evals_to!("Num.is_zero 1", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_zero_f64() { - assert_evals_to!("Num.isZero 0.0f64", true, bool); + assert_evals_to!("Num.is_zero 0.0f64", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_zero_dec() { - assert_evals_to!("Num.isZero 0.0dec", true, bool); + assert_evals_to!("Num.is_zero 0.0dec", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_odd() { - assert_evals_to!("Num.isOdd 4", false, bool); - assert_evals_to!("Num.isOdd 5", true, bool); + assert_evals_to!("Num.is_odd 4", false, bool); + assert_evals_to!("Num.is_odd 5", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_even() { - assert_evals_to!("Num.isEven 6", true, bool); - assert_evals_to!("Num.isEven 7", false, bool); + assert_evals_to!("Num.is_even 6", true, bool); + assert_evals_to!("Num.is_even 7", false, bool); } #[test] @@ -1331,25 +1331,25 @@ fn tan() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn bitwise_and() { - assert_evals_to!("Num.bitwiseAnd 20 20", 20, i64); - assert_evals_to!("Num.bitwiseAnd 25 10", 8, i64); - assert_evals_to!("Num.bitwiseAnd 200 0", 0, i64); + assert_evals_to!("Num.bitwise_and 20 20", 20, i64); + assert_evals_to!("Num.bitwise_and 25 10", 8, i64); + assert_evals_to!("Num.bitwise_and 200 0", 0, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn bitwise_xor() { - assert_evals_to!("Num.bitwiseXor 20 20", 0, i64); - assert_evals_to!("Num.bitwiseXor 15 14", 1, i64); - assert_evals_to!("Num.bitwiseXor 7 15", 8, i64); - assert_evals_to!("Num.bitwiseXor 200 0", 200, i64); + assert_evals_to!("Num.bitwise_xor 20 20", 0, i64); + assert_evals_to!("Num.bitwise_xor 15 14", 1, i64); + assert_evals_to!("Num.bitwise_xor 7 15", 8, i64); + assert_evals_to!("Num.bitwise_xor 200 0", 200, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn bitwise_or() { - assert_evals_to!("Num.bitwiseOr 1 1", 1, i64); - assert_evals_to!("Num.bitwiseOr 1 2", 3, i64); + assert_evals_to!("Num.bitwise_or 1 1", 1, i64); + assert_evals_to!("Num.bitwise_or 1 2", 3, i64); } #[test] @@ -1507,21 +1507,25 @@ fn gte_f64() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn gen_is_approx_eq() { - assert_evals_to!("Num.isApproxEq 1e10f64 1.00001e10f64 {}", true, bool); - assert_evals_to!("Num.isApproxEq 1e-7f64 1e-8f64 {}", false, bool); - assert_evals_to!("Num.isApproxEq 1e-8f32 1e-9f32 {}", true, bool); - assert_evals_to!("Num.isApproxEq 1e10f64 1.0001e10f64 {}", false, bool); - assert_evals_to!("Num.isApproxEq 1.0f32 1.0 {}", true, bool); - assert_evals_to!("Num.isApproxEq (1f64 / 0.0) (1f64 / 0.0) {}", true, bool); - assert_evals_to!("Num.isApproxEq (0f64 / 0.0) (0f64 / 0.0) {}", false, bool); - assert_evals_to!("Num.isApproxEq 1e-8f64 0f64 {}", true, bool); - assert_evals_to!("Num.isApproxEq 1e-7f64 0f64 {}", false, bool); - assert_evals_to!("Num.isApproxEq 1e-100f64 0f64 { atol: 0f64 }", false, bool); - assert_evals_to!("Num.isApproxEq 1e-7f64 0f64 { atol: 0f64 }", false, bool); - assert_evals_to!("Num.isApproxEq 1e-10f64 1e-20f64 {}", true, bool); - assert_evals_to!("Num.isApproxEq 1e-10f64 0f64 {}", true, bool); - assert_evals_to!( - "Num.isApproxEq 1e-10f64 0.999999e-10f64 { atol: 0f64 }", + assert_evals_to!("Num.is_approx_eq 1e10f64 1.00001e10f64 {}", true, bool); + assert_evals_to!("Num.is_approx_eq 1e-7f64 1e-8f64 {}", false, bool); + assert_evals_to!("Num.is_approx_eq 1e-8f32 1e-9f32 {}", true, bool); + assert_evals_to!("Num.is_approx_eq 1e10f64 1.0001e10f64 {}", false, bool); + assert_evals_to!("Num.is_approx_eq 1.0f32 1.0 {}", true, bool); + assert_evals_to!("Num.is_approx_eq (1f64 / 0.0) (1f64 / 0.0) {}", true, bool); + assert_evals_to!("Num.is_approx_eq (0f64 / 0.0) (0f64 / 0.0) {}", false, bool); + assert_evals_to!("Num.is_approx_eq 1e-8f64 0f64 {}", true, bool); + assert_evals_to!("Num.is_approx_eq 1e-7f64 0f64 {}", false, bool); + assert_evals_to!( + "Num.is_approx_eq 1e-100f64 0f64 { atol: 0f64 }", + false, + bool + ); + assert_evals_to!("Num.is_approx_eq 1e-7f64 0f64 { atol: 0f64 }", false, bool); + assert_evals_to!("Num.is_approx_eq 1e-10f64 1e-20f64 {}", true, bool); + assert_evals_to!("Num.is_approx_eq 1e-10f64 0f64 {}", true, bool); + assert_evals_to!( + "Num.is_approx_eq 1e-10f64 0.999999e-10f64 { atol: 0f64 }", true, bool ); @@ -1616,36 +1620,36 @@ fn tail_call_elimination() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_negate() { assert_evals_to!("Num.neg 123i8", -123, i8); - assert_evals_to!("Num.neg Num.maxI8", -i8::MAX, i8); - assert_evals_to!("Num.neg (Num.minI8 + 1)", i8::MAX, i8); + assert_evals_to!("Num.neg Num.max_i8", -i8::MAX, i8); + assert_evals_to!("Num.neg (Num.min_i8 + 1)", i8::MAX, i8); assert_evals_to!("Num.neg 123i16", -123, i16); - assert_evals_to!("Num.neg Num.maxI16", -i16::MAX, i16); - assert_evals_to!("Num.neg (Num.minI16 + 1)", i16::MAX, i16); + assert_evals_to!("Num.neg Num.max_i16", -i16::MAX, i16); + assert_evals_to!("Num.neg (Num.min_i16 + 1)", i16::MAX, i16); assert_evals_to!("Num.neg 123i32", -123, i32); - assert_evals_to!("Num.neg Num.maxI32", -i32::MAX, i32); - assert_evals_to!("Num.neg (Num.minI32 + 1)", i32::MAX, i32); + assert_evals_to!("Num.neg Num.max_i32", -i32::MAX, i32); + assert_evals_to!("Num.neg (Num.min_i32 + 1)", i32::MAX, i32); assert_evals_to!("Num.neg 123", -123, i64); - assert_evals_to!("Num.neg Num.maxI64", -i64::MAX, i64); - assert_evals_to!("Num.neg (Num.minI64 + 1)", i64::MAX, i64); + assert_evals_to!("Num.neg Num.max_i64", -i64::MAX, i64); + assert_evals_to!("Num.neg (Num.min_i64 + 1)", i64::MAX, i64); assert_evals_to!("Num.neg 12.3f32", -12.3, f32); assert_evals_to!("Num.neg 0.0f32", -0.0, f32); - assert_evals_to!("Num.neg Num.maxF32", -f32::MAX, f32); - assert_evals_to!("Num.neg Num.minF32", -f32::MIN, f32); - assert_evals_to!("Num.neg Num.infinityF32", -f32::INFINITY, f32); + assert_evals_to!("Num.neg Num.max_f32", -f32::MAX, f32); + assert_evals_to!("Num.neg Num.min_f32", -f32::MIN, f32); + assert_evals_to!("Num.neg Num.infinity_f32", -f32::INFINITY, f32); // can't test equality for nan - assert_evals_to!("Num.isNaN (Num.neg Num.nanF32)", true, bool); + assert_evals_to!("Num.is_nan (Num.neg Num.nan_f32)", true, bool); assert_evals_to!("Num.neg 12.3f64", -12.3, f64); assert_evals_to!("Num.neg 0.0f64", -0.0, f64); - assert_evals_to!("Num.neg Num.maxF64", -f64::MAX, f64); - assert_evals_to!("Num.neg Num.minF64", -f64::MIN, f64); - assert_evals_to!("Num.neg Num.infinityF64", -f64::INFINITY, f64); + assert_evals_to!("Num.neg Num.max_f64", -f64::MAX, f64); + assert_evals_to!("Num.neg Num.min_f64", -f64::MIN, f64); + assert_evals_to!("Num.neg Num.infinity_f64", -f64::INFINITY, f64); // can't test equality for nan - assert_evals_to!("Num.isNaN (Num.neg Num.nanF64)", true, bool); + assert_evals_to!("Num.is_nan (Num.neg Num.nan_f64)", true, bool); assert_evals_to!("Num.neg 123dec", RocDec::from(-123), RocDec); // 0 is signless, unlike f32/f64 @@ -1661,7 +1665,7 @@ fn neg_min_int_overflow() { assert_evals_to!( indoc!( r" - Num.neg Num.minI64 + Num.neg Num.min_i64 " ), 0, @@ -1675,9 +1679,9 @@ fn gen_wrap_int_neg() { assert_evals_to!( indoc!( r" - wrappedNeg = \num -> -num + wrapped_neg = \num -> -num - wrappedNeg 3 + wrapped_neg 3 " ), -3, @@ -1705,13 +1709,13 @@ fn gen_basic_fn() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_to_float() { - assert_evals_to!("Num.toFrac 0x9", RocDec::from(9i32), RocDec); + assert_evals_to!("Num.to_frac 0x9", RocDec::from(9i32), RocDec); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_to_frac() { - assert_evals_to!("Num.toFrac 9", RocDec::from(9i32), RocDec); + assert_evals_to!("Num.to_frac 9", RocDec::from(9i32), RocDec); } #[test] @@ -1724,7 +1728,7 @@ fn num_to_frac_f64_to_f32() { f64 = 9.0 f32 : F32 - f32 = Num.toFrac f64 + f32 = Num.to_frac f64 f32 " ), @@ -1744,7 +1748,7 @@ fn num_to_frac_f32_to_f32() { arg = 9.0 ret : F32 - ret = Num.toFrac arg + ret = Num.to_frac arg ret " ), @@ -1764,7 +1768,7 @@ fn num_to_frac_f64_to_f64() { arg = 9.0 ret : F64 - ret = Num.toFrac arg + ret = Num.to_frac arg ret " ), @@ -1784,7 +1788,7 @@ fn num_to_frac_f32_to_f64() { f32 = 9.0 f64 : F64 - f64 = Num.toFrac f32 + f64 = Num.to_frac f32 f64 " ), @@ -1800,7 +1804,7 @@ fn float_to_float() { indoc!( r" x : F64 - x = Num.toFrac 0.5f64 + x = Num.to_frac 0.5f64 x " @@ -1813,29 +1817,29 @@ fn float_to_float() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn frac_is_nan() { - assert_evals_to!("Num.isNaN (0 / 0f64)", true, bool); - assert_evals_to!("Num.isNaN (1 / 0f64)", false, bool); - assert_evals_to!("Num.isNaN 42f64", false, bool); - assert_evals_to!("Num.isNaN 42dec", false, bool); + assert_evals_to!("Num.is_nan (0 / 0f64)", true, bool); + assert_evals_to!("Num.is_nan (1 / 0f64)", false, bool); + assert_evals_to!("Num.is_nan 42f64", false, bool); + assert_evals_to!("Num.is_nan 42dec", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn frac_is_infinite() { - assert_evals_to!("Num.isInfinite (1 / 0f64)", true, bool); - assert_evals_to!("Num.isInfinite (-1 / 0f64)", true, bool); - assert_evals_to!("Num.isInfinite (0 / 0f64)", false, bool); - assert_evals_to!("Num.isInfinite 42f64", false, bool); - assert_evals_to!("Num.isInfinite 42dec", false, bool); + assert_evals_to!("Num.is_infinite (1 / 0f64)", true, bool); + assert_evals_to!("Num.is_infinite (-1 / 0f64)", true, bool); + assert_evals_to!("Num.is_infinite (0 / 0f64)", false, bool); + assert_evals_to!("Num.is_infinite 42f64", false, bool); + assert_evals_to!("Num.is_infinite 42dec", false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn frac_is_finite() { - assert_evals_to!("Num.isFinite 42f64", true, bool); - assert_evals_to!("Num.isFinite (1 / 0f64)", false, bool); - assert_evals_to!("Num.isFinite (0 / 0f64)", false, bool); - assert_evals_to!("Num.isFinite 42dec", true, bool); + assert_evals_to!("Num.is_finite 42f64", true, bool); + assert_evals_to!("Num.is_finite (1 / 0f64)", false, bool); + assert_evals_to!("Num.is_finite (0 / 0f64)", false, bool); + assert_evals_to!("Num.is_finite 42dec", true, bool); } #[test] @@ -1923,14 +1927,14 @@ fn floor_dec() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn pow_int() { - assert_evals_to!("Num.powInt 2 3", 8, i64); + assert_evals_to!("Num.pow_int 2 3", 8, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] #[should_panic(expected = r#"Roc failed with message: "Integer raised to power overflowed!"#)] fn pow_int_overflow() { - assert_evals_to!("Num.powInt 2u8 8", 0, u8); + assert_evals_to!("Num.pow_int 2u8 8", 0, u8); } #[test] @@ -1950,7 +1954,7 @@ fn int_add_overflow() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_add_checked_ok() { assert_evals_to!( - "Num.addChecked 1 2", + "Num.add_checked 1 2", RocResult::ok(3), RocResult ); @@ -1960,7 +1964,7 @@ fn int_add_checked_ok() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_add_checked_err() { assert_evals_to!( - "Num.addChecked 9_223_372_036_854_775_807 1", + "Num.add_checked 9_223_372_036_854_775_807 1", RocResult::err(()), RocResult ); @@ -1970,7 +1974,7 @@ fn int_add_checked_err() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn float_add_checked_pass() { assert_evals_to!( - "Num.addChecked 1.0 0.0f64", + "Num.add_checked 1.0 0.0f64", RocResult::ok(1.0), RocResult ); @@ -1980,7 +1984,7 @@ fn float_add_checked_pass() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn float_add_checked_fail() { assert_evals_to!( - "Num.addChecked 1.7976931348623157e308f64 1.7976931348623157e308", + "Num.add_checked 1.7976931348623157e308f64 1.7976931348623157e308", RocResult::err(()), RocResult ); @@ -1999,38 +2003,38 @@ fn float_add_overflow() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn add_wrap() { - assert_evals_to!("Num.addWrap 255u8 10u8", 9u8, u8); - assert_evals_to!("Num.addWrap 127i8 10i8", -119i8, i8); - assert_evals_to!("Num.addWrap -127i8 -10i8", 119i8, i8); - assert_evals_to!("Num.addWrap 65535u16 10", 9u16, u16); - assert_evals_to!("Num.addWrap 32767i16 10", -32759i16, i16); - assert_evals_to!("Num.addWrap -32767i16 -10", 32759i16, i16); - assert_evals_to!("Num.addWrap 4294967295u32 10", 9u32, u32); - assert_evals_to!("Num.addWrap 2147483647i32 10", -2147483639i32, i32); - assert_evals_to!("Num.addWrap -2147483647i32 -10", 2147483639i32, i32); - assert_evals_to!("Num.addWrap 18446744073709551615u64 10", 9u64, u64); - assert_evals_to!( - "Num.addWrap 9223372036854775807i64 10", + assert_evals_to!("Num.add_wrap 255u8 10u8", 9u8, u8); + assert_evals_to!("Num.add_wrap 127i8 10i8", -119i8, i8); + assert_evals_to!("Num.add_wrap -127i8 -10i8", 119i8, i8); + assert_evals_to!("Num.add_wrap 65535u16 10", 9u16, u16); + assert_evals_to!("Num.add_wrap 32767i16 10", -32759i16, i16); + assert_evals_to!("Num.add_wrap -32767i16 -10", 32759i16, i16); + assert_evals_to!("Num.add_wrap 4294967295u32 10", 9u32, u32); + assert_evals_to!("Num.add_wrap 2147483647i32 10", -2147483639i32, i32); + assert_evals_to!("Num.add_wrap -2147483647i32 -10", 2147483639i32, i32); + assert_evals_to!("Num.add_wrap 18446744073709551615u64 10", 9u64, u64); + assert_evals_to!( + "Num.add_wrap 9223372036854775807i64 10", -9223372036854775799i64, i64 ); assert_evals_to!( - "Num.addWrap -9223372036854775807i64 -10", + "Num.add_wrap -9223372036854775807i64 -10", 9223372036854775799i64, i64 ); assert_evals_to!( - "Num.addWrap 340282366920938463463374607431768211455u128 10", + "Num.add_wrap 340282366920938463463374607431768211455u128 10", U128::from(9u128), U128 ); assert_evals_to!( - "Num.addWrap 170141183460469231731687303715884105727i128 10", + "Num.add_wrap 170141183460469231731687303715884105727i128 10", I128::from(-170141183460469231731687303715884105719i128), I128 ); assert_evals_to!( - "Num.addWrap -170141183460469231731687303715884105727i128 -10", + "Num.add_wrap -170141183460469231731687303715884105727i128 -10", I128::from(170141183460469231731687303715884105719i128), I128 ); @@ -2039,85 +2043,85 @@ fn add_wrap() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn add_saturated() { - assert_evals_to!("Num.addSaturated 200u8 200u8", 255u8, u8); - assert_evals_to!("Num.addSaturated 100i8 100i8", 127i8, i8); - assert_evals_to!("Num.addSaturated -100i8 -100i8", -128i8, i8); - assert_evals_to!("Num.addSaturated 40000u16 40000u16", 65535u16, u16); - assert_evals_to!("Num.addSaturated 20000i16 20000i16", 32767i16, i16); - assert_evals_to!("Num.addSaturated -20000i16 -20000i16", -32768i16, i16); - assert_evals_to!( - "Num.addSaturated 3000000000u32 3000000000u32", + assert_evals_to!("Num.add_saturated 200u8 200u8", 255u8, u8); + assert_evals_to!("Num.add_saturated 100i8 100i8", 127i8, i8); + assert_evals_to!("Num.add_saturated -100i8 -100i8", -128i8, i8); + assert_evals_to!("Num.add_saturated 40000u16 40000u16", 65535u16, u16); + assert_evals_to!("Num.add_saturated 20000i16 20000i16", 32767i16, i16); + assert_evals_to!("Num.add_saturated -20000i16 -20000i16", -32768i16, i16); + assert_evals_to!( + "Num.add_saturated 3000000000u32 3000000000u32", 4294967295u32, u32 ); assert_evals_to!( - "Num.addSaturated 2000000000i32 2000000000i32", + "Num.add_saturated 2000000000i32 2000000000i32", 2147483647i32, i32 ); assert_evals_to!( - "Num.addSaturated -2000000000i32 -2000000000i32", + "Num.add_saturated -2000000000i32 -2000000000i32", -2147483648i32, i32 ); assert_evals_to!( - "Num.addSaturated 10000000000000000000u64 10000000000000000000u64", + "Num.add_saturated 10000000000000000000u64 10000000000000000000u64", 18446744073709551615u64, u64 ); assert_evals_to!( - "Num.addSaturated 5000000000000000000i64 5000000000000000000i64 ", + "Num.add_saturated 5000000000000000000i64 5000000000000000000i64 ", 9223372036854775807i64, i64 ); assert_evals_to!( - "Num.addSaturated -5000000000000000000i64 -5000000000000000000i64 ", + "Num.add_saturated -5000000000000000000i64 -5000000000000000000i64 ", -9223372036854775808i64, i64 ); assert_evals_to!( - "Num.addSaturated 200000000000000000000000000000000000000u128 200000000000000000000000000000000000000u128", + "Num.add_saturated 200000000000000000000000000000000000000u128 200000000000000000000000000000000000000u128", U128::from(340282366920938463463374607431768211455u128), U128 ); assert_evals_to!( - "Num.addSaturated 100000000000000000000000000000000000000i128 100000000000000000000000000000000000000i128", + "Num.add_saturated 100000000000000000000000000000000000000i128 100000000000000000000000000000000000000i128", I128::from(170141183460469231731687303715884105727i128), I128 ); assert_evals_to!( - "Num.addSaturated -100000000000000000000000000000000000000i128 -100000000000000000000000000000000000000i128", + "Num.add_saturated -100000000000000000000000000000000000000i128 -100000000000000000000000000000000000000i128", I128::from(-170141183460469231731687303715884105728i128), I128 ); assert_evals_to!( - "Num.addSaturated Num.maxF32 Num.maxF32", + "Num.add_saturated Num.max_f32 Num.max_f32", std::f32::INFINITY, f32 ); assert_evals_to!( - "Num.addSaturated Num.minF32 Num.minF32", + "Num.add_saturated Num.min_f32 Num.min_f32", std::f32::NEG_INFINITY, f32 ); assert_evals_to!( - "Num.addSaturated Num.maxF64 Num.maxF64", + "Num.add_saturated Num.max_f64 Num.max_f64", std::f64::INFINITY, f64 ); assert_evals_to!( - "Num.addSaturated Num.minF64 Num.minF64", + "Num.add_saturated Num.min_f64 Num.min_f64", std::f64::NEG_INFINITY, f64 ); assert_evals_to!( - "Num.addSaturated 170_141_183_460_469_231_731dec 1", + "Num.add_saturated 170_141_183_460_469_231_731dec 1", RocDec::from_str("170141183460469231731.687303715884105727").unwrap(), RocDec ); assert_evals_to!( - "Num.addSaturated -170_141_183_460_469_231_731dec -1", + "Num.add_saturated -170_141_183_460_469_231_731dec -1", RocDec::from_str("-170141183460469231731.687303715884105728").unwrap(), RocDec ); @@ -2137,13 +2141,13 @@ fn float_sub_overflow() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_sub_checked() { assert_evals_to!( - "Num.subChecked 5 2", + "Num.sub_checked 5 2", RocResult::ok(3), RocResult ); assert_evals_to!( - "Num.subChecked Num.minI64 1 ", + "Num.sub_checked Num.min_i64 1 ", RocResult::err(()), RocResult ); @@ -2153,13 +2157,13 @@ fn int_sub_checked() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn float_sub_checked() { assert_evals_to!( - "Num.subChecked 1.0 0.0f64", + "Num.sub_checked 1.0 0.0f64", RocResult::ok(1.0), RocResult ); assert_evals_to!( - "Num.subChecked -1.7976931348623157e308f64 1.7976931348623157e308", + "Num.sub_checked -1.7976931348623157e308f64 1.7976931348623157e308", RocResult::err(()), RocResult ); @@ -2175,38 +2179,38 @@ fn int_sub_overflow() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn sub_wrap() { - assert_evals_to!("Num.subWrap 1u8 10u8", 247u8, u8); - assert_evals_to!("Num.subWrap 127i8 -10i8", -119i8, i8); - assert_evals_to!("Num.subWrap -127i8 10i8", 119i8, i8); - assert_evals_to!("Num.subWrap 1u16 10", 65527u16, u16); - assert_evals_to!("Num.subWrap 32767i16 -10", -32759i16, i16); - assert_evals_to!("Num.subWrap -32767i16 10", 32759i16, i16); - assert_evals_to!("Num.subWrap 1u32 10", 4294967287u32, u32); - assert_evals_to!("Num.subWrap 2147483647i32 -10", -2147483639i32, i32); - assert_evals_to!("Num.subWrap -2147483647i32 10", 2147483639i32, i32); - assert_evals_to!("Num.subWrap 1u64 10", 18446744073709551607u64, u64); - assert_evals_to!( - "Num.subWrap 9223372036854775807i64 -10", + assert_evals_to!("Num.sub_wrap 1u8 10u8", 247u8, u8); + assert_evals_to!("Num.sub_wrap 127i8 -10i8", -119i8, i8); + assert_evals_to!("Num.sub_wrap -127i8 10i8", 119i8, i8); + assert_evals_to!("Num.sub_wrap 1u16 10", 65527u16, u16); + assert_evals_to!("Num.sub_wrap 32767i16 -10", -32759i16, i16); + assert_evals_to!("Num.sub_wrap -32767i16 10", 32759i16, i16); + assert_evals_to!("Num.sub_wrap 1u32 10", 4294967287u32, u32); + assert_evals_to!("Num.sub_wrap 2147483647i32 -10", -2147483639i32, i32); + assert_evals_to!("Num.sub_wrap -2147483647i32 10", 2147483639i32, i32); + assert_evals_to!("Num.sub_wrap 1u64 10", 18446744073709551607u64, u64); + assert_evals_to!( + "Num.sub_wrap 9223372036854775807i64 -10", -9223372036854775799i64, i64 ); assert_evals_to!( - "Num.subWrap -9223372036854775807i64 10", + "Num.sub_wrap -9223372036854775807i64 10", 9223372036854775799i64, i64 ); assert_evals_to!( - "Num.subWrap 1u128 10", + "Num.sub_wrap 1u128 10", U128::from(340282366920938463463374607431768211447u128), U128 ); assert_evals_to!( - "Num.subWrap 170141183460469231731687303715884105727i128 -10", + "Num.sub_wrap 170141183460469231731687303715884105727i128 -10", I128::from(-170141183460469231731687303715884105719i128), I128 ); assert_evals_to!( - "Num.subWrap -170141183460469231731687303715884105727i128 10", + "Num.sub_wrap -170141183460469231731687303715884105727i128 10", I128::from(170141183460469231731687303715884105719i128), I128 ); @@ -2215,73 +2219,73 @@ fn sub_wrap() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn sub_saturated() { - assert_evals_to!("Num.subSaturated 1u8 10u8", 0u8, u8); - assert_evals_to!("Num.subSaturated 100i8 -100i8", 127i8, i8); - assert_evals_to!("Num.subSaturated -100i8 100i8", -128i8, i8); - assert_evals_to!("Num.subSaturated 1u16 10u16", 0u16, u16); - assert_evals_to!("Num.subSaturated 20000i16 -20000i16", 32767i16, i16); - assert_evals_to!("Num.subSaturated -20000i16 20000i16", -32768i16, i16); - assert_evals_to!("Num.subSaturated 1u32 10u32", 0u32, u32); - assert_evals_to!( - "Num.subSaturated 2000000000i32 -2000000000i32", + assert_evals_to!("Num.sub_saturated 1u8 10u8", 0u8, u8); + assert_evals_to!("Num.sub_saturated 100i8 -100i8", 127i8, i8); + assert_evals_to!("Num.sub_saturated -100i8 100i8", -128i8, i8); + assert_evals_to!("Num.sub_saturated 1u16 10u16", 0u16, u16); + assert_evals_to!("Num.sub_saturated 20000i16 -20000i16", 32767i16, i16); + assert_evals_to!("Num.sub_saturated -20000i16 20000i16", -32768i16, i16); + assert_evals_to!("Num.sub_saturated 1u32 10u32", 0u32, u32); + assert_evals_to!( + "Num.sub_saturated 2000000000i32 -2000000000i32", 2147483647i32, i32 ); assert_evals_to!( - "Num.subSaturated -2000000000i32 2000000000i32", + "Num.sub_saturated -2000000000i32 2000000000i32", -2147483648i32, i32 ); - assert_evals_to!("Num.subSaturated 1u64 10u64", 0u64, u64); + assert_evals_to!("Num.sub_saturated 1u64 10u64", 0u64, u64); assert_evals_to!( - "Num.subSaturated 5000000000000000000i64 -5000000000000000000i64 ", + "Num.sub_saturated 5000000000000000000i64 -5000000000000000000i64 ", 9223372036854775807i64, i64 ); assert_evals_to!( - "Num.subSaturated -5000000000000000000i64 5000000000000000000i64 ", + "Num.sub_saturated -5000000000000000000i64 5000000000000000000i64 ", -9223372036854775808i64, i64 ); - assert_evals_to!("Num.subSaturated 1u128 10", U128::from(0u128), U128); + assert_evals_to!("Num.sub_saturated 1u128 10", U128::from(0u128), U128); assert_evals_to!( - "Num.subSaturated 100000000000000000000000000000000000000i128 -100000000000000000000000000000000000000i128", + "Num.sub_saturated 100000000000000000000000000000000000000i128 -100000000000000000000000000000000000000i128", I128::from(170141183460469231731687303715884105727i128), I128 ); assert_evals_to!( - "Num.subSaturated -100000000000000000000000000000000000000i128 100000000000000000000000000000000000000i128", + "Num.sub_saturated -100000000000000000000000000000000000000i128 100000000000000000000000000000000000000i128", I128::from(-170141183460469231731687303715884105728i128), I128 ); assert_evals_to!( - "Num.subSaturated Num.maxF32 -Num.maxF32", + "Num.sub_saturated Num.max_f32 -Num.max_f32", std::f32::INFINITY, f32 ); assert_evals_to!( - "Num.subSaturated Num.minF32 -Num.minF32", + "Num.sub_saturated Num.min_f32 -Num.min_f32", std::f32::NEG_INFINITY, f32 ); assert_evals_to!( - "Num.subSaturated Num.maxF64 -Num.maxF64", + "Num.sub_saturated Num.max_f64 -Num.max_f64", std::f64::INFINITY, f64 ); assert_evals_to!( - "Num.subSaturated Num.minF64 -Num.minF64", + "Num.sub_saturated Num.min_f64 -Num.min_f64", std::f64::NEG_INFINITY, f64 ); assert_evals_to!( - "Num.subSaturated 170_141_183_460_469_231_731dec -1", + "Num.sub_saturated 170_141_183_460_469_231_731dec -1", RocDec::from_str("170141183460469231731.687303715884105727").unwrap(), RocDec ); assert_evals_to!( - "Num.subSaturated -170_141_183_460_469_231_731dec 1", + "Num.sub_saturated -170_141_183_460_469_231_731dec 1", RocDec::from_str("-170141183460469231731.687303715884105728").unwrap(), RocDec ); @@ -2317,13 +2321,13 @@ fn float_negative_mul_overflow() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn int_mul_checked() { assert_evals_to!( - "Num.mulChecked 20 2", + "Num.mul_checked 20 2", RocResult::ok(40), RocResult:: ); assert_evals_to!( - "Num.mulChecked Num.maxI64 2", + "Num.mul_checked Num.max_i64 2", RocResult::err(()), RocResult:: ); @@ -2333,13 +2337,13 @@ fn int_mul_checked() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn float_mul_checked() { assert_evals_to!( - "Num.mulChecked 20.0 2.0f64", + "Num.mul_checked 20.0 2.0f64", RocResult::ok(40.0), RocResult:: ); assert_evals_to!( - "Num.mulChecked 1.7976931348623157e308f64 2", + "Num.mul_checked 1.7976931348623157e308f64 2", RocResult::err(()), RocResult:: ); @@ -2348,34 +2352,34 @@ fn float_mul_checked() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn mul_wrap() { - assert_evals_to!("Num.mulWrap 255u8 2", 254u8, u8); - assert_evals_to!("Num.mulWrap 127i8 2", -2i8, i8); - assert_evals_to!("Num.mulWrap -127i8 2", 2i8, i8); - assert_evals_to!("Num.mulWrap 65535u16 2", 65534u16, u16); - assert_evals_to!("Num.mulWrap 32767i16 2", -2i16, i16); - assert_evals_to!("Num.mulWrap -32767i16 2", 2i16, i16); - assert_evals_to!("Num.mulWrap 4294967295u32 2", 4294967294u32, u32); - assert_evals_to!("Num.mulWrap 2147483647i32 2", -2i32, i32); - assert_evals_to!("Num.mulWrap -2147483647i32 2", 2i32, i32); - assert_evals_to!( - "Num.mulWrap 18446744073709551615u64 2", + assert_evals_to!("Num.mul_wrap 255u8 2", 254u8, u8); + assert_evals_to!("Num.mul_wrap 127i8 2", -2i8, i8); + assert_evals_to!("Num.mul_wrap -127i8 2", 2i8, i8); + assert_evals_to!("Num.mul_wrap 65535u16 2", 65534u16, u16); + assert_evals_to!("Num.mul_wrap 32767i16 2", -2i16, i16); + assert_evals_to!("Num.mul_wrap -32767i16 2", 2i16, i16); + assert_evals_to!("Num.mul_wrap 4294967295u32 2", 4294967294u32, u32); + assert_evals_to!("Num.mul_wrap 2147483647i32 2", -2i32, i32); + assert_evals_to!("Num.mul_wrap -2147483647i32 2", 2i32, i32); + assert_evals_to!( + "Num.mul_wrap 18446744073709551615u64 2", 18446744073709551614u64, u64 ); - assert_evals_to!("Num.mulWrap 9223372036854775807i64 2", -2i64, i64); - assert_evals_to!("Num.mulWrap -9223372036854775807i64 2", 2i64, i64); + assert_evals_to!("Num.mul_wrap 9223372036854775807i64 2", -2i64, i64); + assert_evals_to!("Num.mul_wrap -9223372036854775807i64 2", 2i64, i64); assert_evals_to!( - "Num.mulWrap 340282366920938463463374607431768211455u128 2", + "Num.mul_wrap 340282366920938463463374607431768211455u128 2", U128::from(340282366920938463463374607431768211454u128), U128 ); assert_evals_to!( - "Num.mulWrap 170141183460469231731687303715884105727i128 2", + "Num.mul_wrap 170141183460469231731687303715884105727i128 2", I128::from(-2i128), I128 ); assert_evals_to!( - "Num.mulWrap -170141183460469231731687303715884105727i128 2", + "Num.mul_wrap -170141183460469231731687303715884105727i128 2", I128::from(2i128), I128 ); @@ -2383,59 +2387,67 @@ fn mul_wrap() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn mul_saturated() { - assert_evals_to!("Num.mulSaturated 200u8 2", 255u8, u8); - assert_evals_to!("Num.mulSaturated 100i8 2", 127i8, i8); - assert_evals_to!("Num.mulSaturated -100i8 2", -128i8, i8); - assert_evals_to!("Num.mulSaturated 40000u16 2", 65535u16, u16); - assert_evals_to!("Num.mulSaturated 20000i16 2", 32767i16, i16); - assert_evals_to!("Num.mulSaturated -20000i16 2", -32768i16, i16); - assert_evals_to!("Num.mulSaturated 3000000000u32 2", 4294967295u32, u32); - assert_evals_to!("Num.mulSaturated 2000000000i32 2", 2147483647i32, i32); - assert_evals_to!("Num.mulSaturated -2000000000i32 2", -2147483648i32, i32); - assert_evals_to!( - "Num.mulSaturated 10000000000000000000u64 2", + assert_evals_to!("Num.mul_saturated 200u8 2", 255u8, u8); + assert_evals_to!("Num.mul_saturated 100i8 2", 127i8, i8); + assert_evals_to!("Num.mul_saturated -100i8 2", -128i8, i8); + assert_evals_to!("Num.mul_saturated 40000u16 2", 65535u16, u16); + assert_evals_to!("Num.mul_saturated 20000i16 2", 32767i16, i16); + assert_evals_to!("Num.mul_saturated -20000i16 2", -32768i16, i16); + assert_evals_to!("Num.mul_saturated 3000000000u32 2", 4294967295u32, u32); + assert_evals_to!("Num.mul_saturated 2000000000i32 2", 2147483647i32, i32); + assert_evals_to!("Num.mul_saturated -2000000000i32 2", -2147483648i32, i32); + assert_evals_to!( + "Num.mul_saturated 10000000000000000000u64 2", 18446744073709551615u64, u64 ); assert_evals_to!( - "Num.mulSaturated 5000000000000000000i64 2", + "Num.mul_saturated 5000000000000000000i64 2", 9223372036854775807i64, i64 ); assert_evals_to!( - "Num.mulSaturated -5000000000000000000i64 2", + "Num.mul_saturated -5000000000000000000i64 2", -9223372036854775808i64, i64 ); assert_evals_to!( - "Num.mulSaturated 200000000000000000000000000000000000000u128 2", + "Num.mul_saturated 200000000000000000000000000000000000000u128 2", U128::from(340282366920938463463374607431768211455u128), U128 ); assert_evals_to!( - "Num.mulSaturated 100000000000000000000000000000000000000i128 2", + "Num.mul_saturated 100000000000000000000000000000000000000i128 2", I128::from(170141183460469231731687303715884105727i128), I128 ); assert_evals_to!( - "Num.mulSaturated -100000000000000000000000000000000000000i128 2", + "Num.mul_saturated -100000000000000000000000000000000000000i128 2", I128::from(-170141183460469231731687303715884105728i128), I128 ); - assert_evals_to!("Num.mulSaturated Num.maxF32 2", std::f32::INFINITY, f32); - assert_evals_to!("Num.mulSaturated Num.minF32 2", std::f32::NEG_INFINITY, f32); - assert_evals_to!("Num.mulSaturated Num.maxF64 2", std::f64::INFINITY, f64); - assert_evals_to!("Num.mulSaturated Num.minF64 2", std::f64::NEG_INFINITY, f64); + assert_evals_to!("Num.mul_saturated Num.max_f32 2", std::f32::INFINITY, f32); + assert_evals_to!( + "Num.mul_saturated Num.min_f32 2", + std::f32::NEG_INFINITY, + f32 + ); + assert_evals_to!("Num.mul_saturated Num.max_f64 2", std::f64::INFINITY, f64); + assert_evals_to!( + "Num.mul_saturated Num.min_f64 2", + std::f64::NEG_INFINITY, + f64 + ); // TODO: This doesn't work anywhere? It returns -1.374607431768211456 : Dec ? /* assert_evals_to!( - "Num.mulSaturated 170_141_183_460_469_231_731dec 2", + "Num.mul_saturated 170_141_183_460_469_231_731dec 2", RocDec::from_str("170141183460469231731.687303715884105727").unwrap(), RocDec ); assert_evals_to!( - "Num.mulSaturated -170_141_183_460_469_231_731dec 2", + "Num.mul_saturated -170_141_183_460_469_231_731dec 2", RocDec::from_str("-170141183460469231731.687303715884105728").unwrap(), RocDec ); @@ -2445,10 +2457,10 @@ fn mul_saturated() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn shift_left_by() { - assert_evals_to!("Num.shiftLeftBy 0b0000_0001 0", 0b0000_0001, i64); - assert_evals_to!("Num.shiftLeftBy 0b0000_0001 1", 0b0000_0010, i64); - assert_evals_to!("Num.shiftLeftBy 0b0000_0011 2", 0b0000_1100, i64); - assert_evals_to!("Num.shiftLeftBy 2u16 2", 8, u16); + assert_evals_to!("Num.shift_left_by 0b0000_0001 0", 0b0000_0001, i64); + assert_evals_to!("Num.shift_left_by 0b0000_0001 1", 0b0000_0010, i64); + assert_evals_to!("Num.shift_left_by 0b0000_0011 2", 0b0000_1100, i64); + assert_evals_to!("Num.shift_left_by 2u16 2", 8, u16); } #[test] @@ -2458,36 +2470,36 @@ fn shift_right_by() { let is_llvm_release_mode = cfg!(feature = "gen-llvm") && !cfg!(debug_assertions); - assert_evals_to!("Num.shiftRightBy 0b0100_0000i8 2", 0b0001_0000i8, i8); - assert_evals_to!("Num.shiftRightBy 0b1110_0000u8 1", 0b1111_0000u8, u8); - assert_evals_to!("Num.shiftRightBy 0b1100_0000u8 2", 0b1111_0000u8, u8); - assert_evals_to!("Num.shiftRightBy 0b0100_0000u8 12", 0b0000_0000u8, u8); + assert_evals_to!("Num.shift_right_by 0b0100_0000i8 2", 0b0001_0000i8, i8); + assert_evals_to!("Num.shift_right_by 0b1110_0000u8 1", 0b1111_0000u8, u8); + assert_evals_to!("Num.shift_right_by 0b1100_0000u8 2", 0b1111_0000u8, u8); + assert_evals_to!("Num.shift_right_by 0b0100_0000u8 12", 0b0000_0000u8, u8); // LLVM in release mode returns 0 instead of -1 for some reason if !is_llvm_release_mode { - assert_evals_to!("Num.shiftRightBy 0b1000_0000u8 12", 0b1111_1111u8, u8); + assert_evals_to!("Num.shift_right_by 0b1000_0000u8 12", 0b1111_1111u8, u8); } - assert_evals_to!("Num.shiftRightBy 12 0", 12, i64); - assert_evals_to!("Num.shiftRightBy 12 1", 6, i64); - assert_evals_to!("Num.shiftRightBy -12 1", -6, i64); - assert_evals_to!("Num.shiftRightBy 12 8", 0, i64); - assert_evals_to!("Num.shiftRightBy -12 8", -1, i64); - assert_evals_to!("Num.shiftRightBy 0 0", 0, i64); - assert_evals_to!("Num.shiftRightBy 0 1", 0, i64); - - assert_evals_to!("Num.shiftRightBy 12i32 0", 12, i32); - assert_evals_to!("Num.shiftRightBy 12i32 1", 6, i32); - assert_evals_to!("Num.shiftRightBy -12i32 1", -6, i32); - assert_evals_to!("Num.shiftRightBy 12i32 8", 0, i32); - assert_evals_to!("Num.shiftRightBy -12i32 8", -1, i32); - - assert_evals_to!("Num.shiftRightBy 12i8 0", 12, i8); - assert_evals_to!("Num.shiftRightBy 12i8 1", 6, i8); - assert_evals_to!("Num.shiftRightBy -12i8 1", -6, i8); - assert_evals_to!("Num.shiftRightBy 12i8 8", 0, i8); + assert_evals_to!("Num.shift_right_by 12 0", 12, i64); + assert_evals_to!("Num.shift_right_by 12 1", 6, i64); + assert_evals_to!("Num.shift_right_by -12 1", -6, i64); + assert_evals_to!("Num.shift_right_by 12 8", 0, i64); + assert_evals_to!("Num.shift_right_by -12 8", -1, i64); + assert_evals_to!("Num.shift_right_by 0 0", 0, i64); + assert_evals_to!("Num.shift_right_by 0 1", 0, i64); + + assert_evals_to!("Num.shift_right_by 12i32 0", 12, i32); + assert_evals_to!("Num.shift_right_by 12i32 1", 6, i32); + assert_evals_to!("Num.shift_right_by -12i32 1", -6, i32); + assert_evals_to!("Num.shift_right_by 12i32 8", 0, i32); + assert_evals_to!("Num.shift_right_by -12i32 8", -1, i32); + + assert_evals_to!("Num.shift_right_by 12i8 0", 12, i8); + assert_evals_to!("Num.shift_right_by 12i8 1", 6, i8); + assert_evals_to!("Num.shift_right_by -12i8 1", -6, i8); + assert_evals_to!("Num.shift_right_by 12i8 8", 0, i8); if !is_llvm_release_mode { - assert_evals_to!("Num.shiftRightBy -12i8 8", -1, i8); + assert_evals_to!("Num.shift_right_by -12i8 8", -1, i8); } } @@ -2495,10 +2507,10 @@ fn shift_right_by() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn shift_right_zf_by() { // Logical Right Shift - assert_evals_to!("Num.shiftRightZfBy 0b1100_0000u8 2", 0b0011_0000u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b0000_0010u8 1", 0b0000_0001u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b0000_1100u8 2", 0b0000_0011u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b1000_0000u8 12", 0b0000_0000u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b1100_0000u8 2", 0b0011_0000u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b0000_0010u8 1", 0b0000_0001u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b0000_1100u8 2", 0b0000_0011u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b1000_0000u8 12", 0b0000_0000u8, u8); } #[test] @@ -2506,28 +2518,28 @@ fn shift_right_zf_by() { fn shift_right_cast_i8() { // arithmetic assert_evals_to!( - "Num.shiftRightBy (Num.toI8 0b1100_0000u8) 2", + "Num.shift_right_by (Num.to_i8 0b1100_0000u8) 2", 0b1111_0000u8 as i8, i8 ); // logical assert_evals_to!( - "Num.shiftRightZfBy (Num.toI8 0b1100_0000u8) 2", + "Num.shift_right_zf_by (Num.to_i8 0b1100_0000u8) 2", 0b0011_0000i8, i8 ); - assert_evals_to!("Num.shiftRightZfBy 0b1100_0000u8 2", 0b0011_0000u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b0000_0010u8 1", 0b0000_0001u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b0000_1100u8 2", 0b0000_0011u8, u8); - assert_evals_to!("Num.shiftRightZfBy 0b1000_0000u8 12", 0b0000_0000u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b1100_0000u8 2", 0b0011_0000u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b0000_0010u8 1", 0b0000_0001u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b0000_1100u8 2", 0b0000_0011u8, u8); + assert_evals_to!("Num.shift_right_zf_by 0b1000_0000u8 12", 0b0000_0000u8, u8); assert_evals_to!( - "Num.shiftRightZfBy 0xffff_0000_0000_0000_0000_0000_0000_ffffu128 4", + "Num.shift_right_zf_by 0xffff_0000_0000_0000_0000_0000_0000_ffffu128 4", 0x0fff_f000_0000_0000_0000_0000_0000_0fffu128, u128 ); assert_evals_to!( - "Num.shiftRightZfBy 0xaaaa_0000_0000_bbbb_ffff_ffff_ffff_ffffu128 68", + "Num.shift_right_zf_by 0xaaaa_0000_0000_bbbb_ffff_ffff_ffff_ffffu128 68", 0x0000_0000_0000_0000_0aaa_a000_0000_0bbbu128, u128 ); @@ -2536,133 +2548,133 @@ fn shift_right_cast_i8() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_i128() { - assert_evals_to!("Num.minI128", I128::from(i128::MIN), I128); + assert_evals_to!("Num.min_i128", I128::from(i128::MIN), I128); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_i128() { - assert_evals_to!("Num.maxI128", I128::from(i128::MAX), I128); + assert_evals_to!("Num.max_i128", I128::from(i128::MAX), I128); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_i64() { - assert_evals_to!("Num.minI64", i64::MIN, i64); + assert_evals_to!("Num.min_i64", i64::MIN, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_i64() { - assert_evals_to!("Num.maxI64", i64::MAX, i64); + assert_evals_to!("Num.max_i64", i64::MAX, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_u64() { - assert_evals_to!("Num.minU64", u64::MIN, u64); + assert_evals_to!("Num.min_u64", u64::MIN, u64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_u64() { - assert_evals_to!("Num.maxU64", u64::MAX, u64); + assert_evals_to!("Num.max_u64", u64::MAX, u64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_i32() { - assert_evals_to!("Num.minI32", i32::MIN, i32); + assert_evals_to!("Num.min_i32", i32::MIN, i32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_i32() { - assert_evals_to!("Num.maxI32", i32::MAX, i32); + assert_evals_to!("Num.max_i32", i32::MAX, i32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_u32() { - assert_evals_to!("Num.minU32", u32::MIN, u32); + assert_evals_to!("Num.min_u32", u32::MIN, u32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_u32() { - assert_evals_to!("Num.maxU32", u32::MAX, u32); + assert_evals_to!("Num.max_u32", u32::MAX, u32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_i16() { - assert_evals_to!("Num.minI16", i16::MIN, i16); + assert_evals_to!("Num.min_i16", i16::MIN, i16); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_i16() { - assert_evals_to!("Num.maxI16", i16::MAX, i16); + assert_evals_to!("Num.max_i16", i16::MAX, i16); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_u16() { - assert_evals_to!("Num.minU16", u16::MIN, u16); + assert_evals_to!("Num.min_u16", u16::MIN, u16); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_u16() { - assert_evals_to!("Num.maxU16", u16::MAX, u16); + assert_evals_to!("Num.max_u16", u16::MAX, u16); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_i8() { - assert_evals_to!("Num.minI8", i8::MIN, i8); + assert_evals_to!("Num.min_i8", i8::MIN, i8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_i8() { - assert_evals_to!("Num.maxI8", i8::MAX, i8); + assert_evals_to!("Num.max_i8", i8::MAX, i8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_u8() { - assert_evals_to!("Num.minU8", u8::MIN, u8); + assert_evals_to!("Num.min_u8", u8::MIN, u8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_u8() { - assert_evals_to!("Num.maxU8", u8::MAX, u8); + assert_evals_to!("Num.max_u8", u8::MAX, u8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_f64() { - assert_evals_to!("Num.maxF64", f64::MAX, f64); + assert_evals_to!("Num.max_f64", f64::MAX, f64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_f64() { - assert_evals_to!("Num.minF64", f64::MIN, f64); + assert_evals_to!("Num.min_f64", f64::MIN, f64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn max_f32() { - assert_evals_to!("Num.maxF32", f32::MAX, f32); + assert_evals_to!("Num.max_f32", f32::MAX, f32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn min_f32() { - assert_evals_to!("Num.minF32", f32::MIN, f32); + assert_evals_to!("Num.min_f32", f32::MIN, f32); } macro_rules! num_conversion_tests { @@ -2677,19 +2689,19 @@ macro_rules! num_conversion_tests { } num_conversion_tests! { - "Num.toI8", i8, ( + "Num.to_i8", i8, ( to_i8_same_width, "15u8", 15, ["gen-wasm", "gen-dev"] to_i8_truncate, "115i32", 115, ["gen-wasm", "gen-dev"] to_i8_truncate_wraps, "500i32", -12, ["gen-wasm", "gen-dev"] ) - "Num.toI16", i16, ( + "Num.to_i16", i16, ( to_i16_same_width, "15u16", 15, ["gen-wasm", "gen-dev"] to_i16_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_i16_sign_extend_i8, "-15i8", -15, ["gen-wasm", "gen-dev"] to_i16_truncate, "115i32", 115, ["gen-wasm", "gen-dev"] to_i16_truncate_wraps, "60000i32", -5536, ["gen-wasm", "gen-dev"] ) - "Num.toI32", i32, ( + "Num.to_i32", i32, ( to_i32_same_width, "15u32", 15, ["gen-wasm", "gen-dev"] to_i32_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_i32_sign_extend_i8, "-15i8", -15, ["gen-wasm", "gen-dev"] @@ -2697,7 +2709,7 @@ num_conversion_tests! { to_i32_truncate, "115i64", 115, ["gen-wasm", "gen-dev"] to_i32_truncate_wraps, "5000000000i64", 705032704, ["gen-wasm", "gen-dev"] ) - "Num.toI64", i64, ( + "Num.to_i64", i64, ( to_i64_same_width, "15u64", 15, ["gen-wasm", "gen-dev"] to_i64_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_i64_sign_extend_i8, "-15i8", -15, ["gen-wasm", "gen-dev"] @@ -2706,39 +2718,39 @@ num_conversion_tests! { to_i64_truncate, "115i128", 115 to_i64_truncate_wraps, "10_000_000_000_000_000_000i128", -8446744073709551616 ) - "Num.toI128", i128, ( + "Num.to_i128", i128, ( to_i128_same_width, "15u128", 15, ["gen-dev"] to_i128_extend, "15i8", 15 ) - "Num.toU8", u8, ( + "Num.to_u8", u8, ( to_u8_same_width, "15i8", 15, ["gen-wasm", "gen-dev"] to_u8_truncate, "115i32", 115, ["gen-wasm", "gen-dev"] to_u8_truncate_wraps, "500i32", 244, ["gen-wasm", "gen-dev"] ) - "Num.toU16", u16, ( + "Num.to_u16", u16, ( to_u16_same_width, "15i16", 15, ["gen-wasm", "gen-dev"] to_u16_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_u16_truncate, "115i32", 115, ["gen-wasm", "gen-dev"] to_u16_truncate_wraps, "600000000i32", 17920, ["gen-wasm", "gen-dev"] ) - "Num.toU32", u32, ( + "Num.to_u32", u32, ( to_u32_same_width, "15i32", 15, ["gen-wasm", "gen-dev"] to_u32_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_u32_truncate, "115i64", 115, ["gen-wasm", "gen-dev"] to_u32_truncate_wraps, "5000000000000000000i64", 1156841472, ["gen-wasm", "gen-dev"] ) - "Num.toU64", u64, ( + "Num.to_u64", u64, ( to_u64_same_width, "15i64", 15, ["gen-wasm", "gen-dev"] to_u64_extend, "15i8", 15, ["gen-wasm", "gen-dev"] to_u64_truncate, "115i128", 115 to_u64_truncate_wraps, "10_000_000_000_000_000_000_000i128", 1864712049423024128 ) - "Num.toU128", u128, ( + "Num.to_u128", u128, ( to_u128_same_width, "15i128", 15, ["gen-dev"] to_u128_extend, "15i8", 15 to_u128_big, "11562537357600483583u64", 11562537357600483583, ["gen-dev"] ) - "Num.toF32", f32, ( + "Num.to_f32", f32, ( to_f32_from_i8, "15i8", 15.0, ["gen-wasm", "gen-dev"] to_f32_from_i16, "15i16", 15.0, ["gen-wasm", "gen-dev"] to_f32_from_i32, "15i32", 15.0, ["gen-wasm", "gen-dev"] @@ -2752,7 +2764,7 @@ num_conversion_tests! { to_f32_from_f32, "1.5f32", 1.5, ["gen-wasm", "gen-dev"] to_f32_from_f64, "1.5f64", 1.5, ["gen-wasm", "gen-dev"] ) - "Num.toF64", f64, ( + "Num.to_f64", f64, ( to_f64_from_i8, "15i8", 15.0, ["gen-wasm", "gen-dev"] to_f64_from_i16, "15i16", 15.0, ["gen-wasm", "gen-dev"] to_f64_from_i32, "15i32", 15.0, ["gen-wasm", "gen-dev"] @@ -2782,14 +2794,14 @@ macro_rules! to_int_checked_tests { n } }; - let input = format!("Result.withDefault ({} {}) {}", $fn, $input, sentinel); + let input = format!("Result.with_default ({} {}) {}", $fn, $input, sentinel); assert_evals_to!(&input, expected, $typ) } )*)*} } to_int_checked_tests! { - "Num.toI8Checked", i8, ( + "Num.to_i8_checked", i8, ( to_i8_checked_same, "15i8", 15 to_i8_checked_same_width_unsigned_fits, "15u8", 15 to_i8_checked_same_width_unsigned_oob, "128u8", None @@ -2800,7 +2812,7 @@ to_int_checked_tests! { to_i8_checked_larger_width_unsigned_fits_pos, "15u16", 15 to_i8_checked_larger_width_unsigned_oob_pos, "128u16", None ) - "Num.toI16Checked", i16, ( + "Num.to_i16_checked", i16, ( to_i16_checked_smaller_width_pos, "15i8", 15 to_i16_checked_smaller_width_neg, "-15i8", -15 to_i16_checked_same, "15i16", 15 @@ -2813,7 +2825,7 @@ to_int_checked_tests! { to_i16_checked_larger_width_unsigned_fits_pos, "15u32", 15 to_i16_checked_larger_width_unsigned_oob_pos, "32768u32", None ) - "Num.toI32Checked", i32, ( + "Num.to_i32_checked", i32, ( to_i32_checked_smaller_width_pos, "15i8", 15 to_i32_checked_smaller_width_neg, "-15i8", -15 to_i32_checked_same, "15i32", 15 @@ -2826,7 +2838,7 @@ to_int_checked_tests! { to_i32_checked_larger_width_unsigned_fits_pos, "15u64", 15 to_i32_checked_larger_width_unsigned_oob_pos, "2147483648u64", None ) - "Num.toI64Checked", i64, ( + "Num.to_i64_checked", i64, ( to_i64_checked_smaller_width_pos, "15i8", 15 to_i64_checked_smaller_width_neg, "-15i8", -15 to_i64_checked_same, "15i64", 15 @@ -2839,7 +2851,7 @@ to_int_checked_tests! { to_i64_checked_larger_width_unsigned_fits_pos, "15u128", 15 to_i64_checked_larger_width_unsigned_oob_pos, "9223372036854775808u128", None ) - "Num.toU8Checked", u8, ( + "Num.to_u8_checked", u8, ( to_u8_checked_same, "15u8", 15 to_u8_checked_same_width_signed_fits, "15i8", 15 to_u8_checked_same_width_signed_oob, "-1i8", None @@ -2849,7 +2861,7 @@ to_int_checked_tests! { to_u8_checked_larger_width_unsigned_fits_pos, "15u16", 15 to_u8_checked_larger_width_unsigned_oob_pos, "256u16", None ) - "Num.toU16Checked", u16, ( + "Num.to_u16_checked", u16, ( to_u16_checked_smaller_width_pos, "15i8", 15 to_u16_checked_smaller_width_neg_oob, "-15i8", None to_u16_checked_same, "15u16", 15 @@ -2861,7 +2873,7 @@ to_int_checked_tests! { to_u16_checked_larger_width_unsigned_fits_pos, "15u32", 15 to_u16_checked_larger_width_unsigned_oob_pos, "65536u32", None ) - "Num.toU32Checked", u32, ( + "Num.to_u32_checked", u32, ( to_u32_checked_smaller_width_pos, "15i8", 15 to_u32_checked_smaller_width_neg_oob, "-15i8", None to_u32_checked_same, "15u32", 15 @@ -2873,7 +2885,7 @@ to_int_checked_tests! { to_u32_checked_larger_width_unsigned_fits_pos, "15u64", 15 to_u32_checked_larger_width_unsigned_oob_pos, "4294967296u64", None ) - "Num.toU64Checked", u64, ( + "Num.to_u64_checked", u64, ( to_u64_checked_smaller_width_pos, "15i8", 15 to_u64_checked_smaller_width_neg_oob, "-15i8", None to_u64_checked_same, "15u64", 15 @@ -2888,34 +2900,34 @@ to_int_checked_tests! { } fn wrap_with_default(test_roc_code: &str) -> String { - format!("Result.withDefault ({}) 123454321", test_roc_code) + format!("Result.with_default ({}) 123454321", test_roc_code) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_i128_checked_smaller_width_pos() { - let test_roc_code = wrap_with_default("Num.toI128Checked 15i8"); + let test_roc_code = wrap_with_default("Num.to_i128_checked 15i8"); assert_evals_to!(&test_roc_code, I128::from(15), I128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_i128_checked_smaller_width_neg() { - let test_roc_code = wrap_with_default("Num.toI128Checked -15i8"); + let test_roc_code = wrap_with_default("Num.to_i128_checked -15i8"); assert_evals_to!(&test_roc_code, I128::from(-15), I128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_i128_checked_same() { - let test_roc_code = wrap_with_default("Num.toI128Checked 15i128"); + let test_roc_code = wrap_with_default("Num.to_i128_checked 15i128"); assert_evals_to!(&test_roc_code, I128::from(15), I128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_i128_checked_same_width_unsigned_fits() { - let test_roc_code = wrap_with_default("Num.toI128Checked 15u128"); + let test_roc_code = wrap_with_default("Num.to_i128_checked 15u128"); assert_evals_to!(&test_roc_code, I128::from(15), I128) } @@ -2923,42 +2935,42 @@ fn to_i128_checked_same_width_unsigned_fits() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_i128_checked_same_width_unsigned_oob() { let test_roc_code = - "Result.isErr (Num.toI128Checked 170141183460469231731687303715884105728u128)"; + "Result.is_err (Num.to_i128_checked 170141183460469231731687303715884105728u128)"; assert_evals_to!(&test_roc_code, true, bool) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_u128_checked_smaller_width_pos() { - let test_roc_code = wrap_with_default("Num.toU128Checked 15i8"); + let test_roc_code = wrap_with_default("Num.to_u128_checked 15i8"); assert_evals_to!(&test_roc_code, U128::from(15), U128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_u128_checked_smaller_width_neg_oob() { - let test_roc_code = "Result.isErr (Num.toU128Checked -15i8)"; + let test_roc_code = "Result.is_err (Num.to_u128_checked -15i8)"; assert_evals_to!(&test_roc_code, true, bool) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_u128_checked_same() { - let test_roc_code = wrap_with_default("Num.toU128Checked 15u128"); + let test_roc_code = wrap_with_default("Num.to_u128_checked 15u128"); assert_evals_to!(&test_roc_code, U128::from(15), U128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_u128_checked_same_width_signed_fits() { - let test_roc_code = wrap_with_default("Num.toU128Checked 15i128"); + let test_roc_code = wrap_with_default("Num.to_u128_checked 15i128"); assert_evals_to!(&test_roc_code, U128::from(15), U128) } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm"))] fn to_u128_checked_same_width_signed_oob() { - let test_roc_code = "Result.isErr (Num.toU128Checked -1i128)"; + let test_roc_code = "Result.is_err (Num.to_u128_checked -1i128)"; assert_evals_to!(&test_roc_code, true, bool) } @@ -2966,35 +2978,35 @@ fn to_u128_checked_same_width_signed_oob() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn is_multiple_of_signed() { // true - assert_evals_to!("Num.isMultipleOf 5 1", true, bool); - assert_evals_to!("Num.isMultipleOf 5 -1", true, bool); - assert_evals_to!("Num.isMultipleOf 0 0", true, bool); - assert_evals_to!("Num.isMultipleOf 0 1", true, bool); - assert_evals_to!("Num.isMultipleOf 0 -1", true, bool); + assert_evals_to!("Num.is_multiple_of 5 1", true, bool); + assert_evals_to!("Num.is_multiple_of 5 -1", true, bool); + assert_evals_to!("Num.is_multiple_of 0 0", true, bool); + assert_evals_to!("Num.is_multiple_of 0 1", true, bool); + assert_evals_to!("Num.is_multiple_of 0 -1", true, bool); // false - assert_evals_to!("Num.isMultipleOf 5 2", false, bool); - assert_evals_to!("Num.isMultipleOf 5 0", false, bool); + assert_evals_to!("Num.is_multiple_of 5 2", false, bool); + assert_evals_to!("Num.is_multiple_of 5 0", false, bool); // overflow - assert_evals_to!("Num.isMultipleOf -9223372036854775808 -1", true, bool); + assert_evals_to!("Num.is_multiple_of -9223372036854775808 -1", true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn is_multiple_of_unsigned() { // true - assert_evals_to!("Num.isMultipleOf 5u8 1", true, bool); - assert_evals_to!("Num.isMultipleOf 0u8 0", true, bool); - assert_evals_to!("Num.isMultipleOf 0u8 1", true, bool); - assert_evals_to!("Num.isMultipleOf 0u8 0xFF", true, bool); + assert_evals_to!("Num.is_multiple_of 5u8 1", true, bool); + assert_evals_to!("Num.is_multiple_of 0u8 0", true, bool); + assert_evals_to!("Num.is_multiple_of 0u8 1", true, bool); + assert_evals_to!("Num.is_multiple_of 0u8 0xFF", true, bool); // false - assert_evals_to!("Num.isMultipleOf 5u8 2", false, bool); - assert_evals_to!("Num.isMultipleOf 5u8 0", false, bool); + assert_evals_to!("Num.is_multiple_of 5u8 2", false, bool); + assert_evals_to!("Num.is_multiple_of 5u8 0", false, bool); // unsigned result is different from signed - assert_evals_to!("Num.isMultipleOf 5u8 0xFF", false, bool); - assert_evals_to!("Num.isMultipleOf 0xFCu8 0xFE", false, bool); + assert_evals_to!("Num.is_multiple_of 5u8 0xFF", false, bool); + assert_evals_to!("Num.is_multiple_of 0xFCu8 0xFE", false, bool); } #[test] @@ -3048,15 +3060,23 @@ fn when_on_i16() { fn num_to_str() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr 1234", RocStr::from("1234"), RocStr); - assert_evals_to!(r"Num.toStr 0", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr -1", RocStr::from("-1"), RocStr); + assert_evals_to!(r"Num.to_str 1234", RocStr::from("1234"), RocStr); + assert_evals_to!(r"Num.to_str 0", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str -1", RocStr::from("-1"), RocStr); let max = format!("{}", i64::MAX); - assert_evals_to!(r"Num.toStr Num.maxI64", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_i64", + RocStr::from(max.as_str()), + RocStr + ); let min = format!("{}", i64::MIN); - assert_evals_to!(r"Num.toStr Num.minI64", RocStr::from(min.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.min_i64", + RocStr::from(min.as_str()), + RocStr + ); } #[test] @@ -3064,12 +3084,12 @@ fn num_to_str() { fn num_to_str_u8() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr 0u8", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1u8", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10u8", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str 0u8", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1u8", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10u8", RocStr::from("10"), RocStr); let max = format!("{}", u8::MAX); - assert_evals_to!(r"Num.toStr Num.maxU8", RocStr::from(max.as_str()), RocStr); + assert_evals_to!(r"Num.to_str Num.max_u8", RocStr::from(max.as_str()), RocStr); } #[test] @@ -3077,12 +3097,16 @@ fn num_to_str_u8() { fn num_to_str_u16() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr 0u16", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1u16", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10u16", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str 0u16", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1u16", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10u16", RocStr::from("10"), RocStr); let max = format!("{}", u16::MAX); - assert_evals_to!(r"Num.toStr Num.maxU16", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_u16", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3090,12 +3114,16 @@ fn num_to_str_u16() { fn num_to_str_u32() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr 0u32", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1u32", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10u32", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str 0u32", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1u32", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10u32", RocStr::from("10"), RocStr); let max = format!("{}", u32::MAX); - assert_evals_to!(r"Num.toStr Num.maxU32", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_u32", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3103,12 +3131,16 @@ fn num_to_str_u32() { fn num_to_str_u64() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr 0u64", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1u64", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10u64", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str 0u64", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1u64", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10u64", RocStr::from("10"), RocStr); let max = format!("{}", u64::MAX); - assert_evals_to!(r"Num.toStr Num.maxU64", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_u64", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3116,17 +3148,17 @@ fn num_to_str_u64() { fn num_to_str_i8() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10i8", RocStr::from("-10"), RocStr); - assert_evals_to!(r"Num.toStr -1i8", RocStr::from("-1"), RocStr); - assert_evals_to!(r"Num.toStr 0i8", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1i8", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10i8", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str -10i8", RocStr::from("-10"), RocStr); + assert_evals_to!(r"Num.to_str -1i8", RocStr::from("-1"), RocStr); + assert_evals_to!(r"Num.to_str 0i8", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1i8", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10i8", RocStr::from("10"), RocStr); let max = format!("{}", i8::MAX); - assert_evals_to!(r"Num.toStr Num.maxI8", RocStr::from(max.as_str()), RocStr); + assert_evals_to!(r"Num.to_str Num.max_i8", RocStr::from(max.as_str()), RocStr); let max = format!("{}", i8::MIN); - assert_evals_to!(r"Num.toStr Num.minI8", RocStr::from(max.as_str()), RocStr); + assert_evals_to!(r"Num.to_str Num.min_i8", RocStr::from(max.as_str()), RocStr); } #[test] @@ -3134,17 +3166,25 @@ fn num_to_str_i8() { fn num_to_str_i16() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10i16", RocStr::from("-10"), RocStr); - assert_evals_to!(r"Num.toStr -1i16", RocStr::from("-1"), RocStr); - assert_evals_to!(r"Num.toStr 0i16", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1i16", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10i16", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str -10i16", RocStr::from("-10"), RocStr); + assert_evals_to!(r"Num.to_str -1i16", RocStr::from("-1"), RocStr); + assert_evals_to!(r"Num.to_str 0i16", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1i16", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10i16", RocStr::from("10"), RocStr); let max = format!("{}", i16::MAX); - assert_evals_to!(r"Num.toStr Num.maxI16", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_i16", + RocStr::from(max.as_str()), + RocStr + ); let max = format!("{}", i16::MIN); - assert_evals_to!(r"Num.toStr Num.minI16", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.min_i16", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3152,17 +3192,25 @@ fn num_to_str_i16() { fn num_to_str_i32() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10i32", RocStr::from("-10"), RocStr); - assert_evals_to!(r"Num.toStr -1i32", RocStr::from("-1"), RocStr); - assert_evals_to!(r"Num.toStr 0i32", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1i32", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10i32", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str -10i32", RocStr::from("-10"), RocStr); + assert_evals_to!(r"Num.to_str -1i32", RocStr::from("-1"), RocStr); + assert_evals_to!(r"Num.to_str 0i32", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1i32", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10i32", RocStr::from("10"), RocStr); let max = format!("{}", i32::MAX); - assert_evals_to!(r"Num.toStr Num.maxI32", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_i32", + RocStr::from(max.as_str()), + RocStr + ); let max = format!("{}", i32::MIN); - assert_evals_to!(r"Num.toStr Num.minI32", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.min_i32", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3170,17 +3218,25 @@ fn num_to_str_i32() { fn num_to_str_i64() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10i64", RocStr::from("-10"), RocStr); - assert_evals_to!(r"Num.toStr -1i64", RocStr::from("-1"), RocStr); - assert_evals_to!(r"Num.toStr 0i64", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1i64", RocStr::from("1"), RocStr); - assert_evals_to!(r"Num.toStr 10i64", RocStr::from("10"), RocStr); + assert_evals_to!(r"Num.to_str -10i64", RocStr::from("-10"), RocStr); + assert_evals_to!(r"Num.to_str -1i64", RocStr::from("-1"), RocStr); + assert_evals_to!(r"Num.to_str 0i64", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1i64", RocStr::from("1"), RocStr); + assert_evals_to!(r"Num.to_str 10i64", RocStr::from("10"), RocStr); let max = format!("{}", i64::MAX); - assert_evals_to!(r"Num.toStr Num.maxI64", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.max_i64", + RocStr::from(max.as_str()), + RocStr + ); let max = format!("{}", i64::MIN); - assert_evals_to!(r"Num.toStr Num.minI64", RocStr::from(max.as_str()), RocStr); + assert_evals_to!( + r"Num.to_str Num.min_i64", + RocStr::from(max.as_str()), + RocStr + ); } #[test] @@ -3188,21 +3244,21 @@ fn num_to_str_i64() { fn num_to_str_f32() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10.75f32", RocStr::from("-10.75"), RocStr); - assert_evals_to!(r"Num.toStr -1.75f32", RocStr::from("-1.75"), RocStr); - assert_evals_to!(r"Num.toStr 0f32", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1.75f32", RocStr::from("1.75"), RocStr); - assert_evals_to!(r"Num.toStr 10.75f32", RocStr::from("10.75"), RocStr); + assert_evals_to!(r"Num.to_str -10.75f32", RocStr::from("-10.75"), RocStr); + assert_evals_to!(r"Num.to_str -1.75f32", RocStr::from("-1.75"), RocStr); + assert_evals_to!(r"Num.to_str 0f32", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1.75f32", RocStr::from("1.75"), RocStr); + assert_evals_to!(r"Num.to_str 10.75f32", RocStr::from("10.75"), RocStr); assert_evals_to!( - r"Num.toStr Num.maxF32", + r"Num.to_str Num.max_f32", f32::MAX, RocStr, |roc_str: RocStr| { roc_str.as_str().parse::().unwrap() } ); assert_evals_to!( - r"Num.toStr Num.minF32", + r"Num.to_str Num.min_f32", f32::MIN, RocStr, |roc_str: RocStr| { roc_str.as_str().parse::().unwrap() } @@ -3214,20 +3270,20 @@ fn num_to_str_f32() { fn num_to_str_f64() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10.75f64", RocStr::from("-10.75"), RocStr); - assert_evals_to!(r"Num.toStr -1.75f64", RocStr::from("-1.75"), RocStr); - assert_evals_to!(r"Num.toStr 0f64", RocStr::from("0"), RocStr); - assert_evals_to!(r"Num.toStr 1.75f64", RocStr::from("1.75"), RocStr); - assert_evals_to!(r"Num.toStr 10.75f64", RocStr::from("10.75"), RocStr); + assert_evals_to!(r"Num.to_str -10.75f64", RocStr::from("-10.75"), RocStr); + assert_evals_to!(r"Num.to_str -1.75f64", RocStr::from("-1.75"), RocStr); + assert_evals_to!(r"Num.to_str 0f64", RocStr::from("0"), RocStr); + assert_evals_to!(r"Num.to_str 1.75f64", RocStr::from("1.75"), RocStr); + assert_evals_to!(r"Num.to_str 10.75f64", RocStr::from("10.75"), RocStr); assert_evals_to!( - r"Num.toStr Num.maxF64", + r"Num.to_str Num.max_f64", RocStr::from(f64::MAX.to_string().as_str()), RocStr ); assert_evals_to!( - r"Num.toStr Num.minF64", + r"Num.to_str Num.min_f64", RocStr::from(f64::MIN.to_string().as_str()), RocStr ); @@ -3238,20 +3294,20 @@ fn num_to_str_f64() { fn num_to_str_dec() { use roc_std::RocStr; - assert_evals_to!(r"Num.toStr -10.75dec", RocStr::from("-10.75"), RocStr); - assert_evals_to!(r"Num.toStr -1.75dec", RocStr::from("-1.75"), RocStr); - assert_evals_to!(r"Num.toStr 0dec", RocStr::from("0.0"), RocStr); - assert_evals_to!(r"Num.toStr 1.75dec", RocStr::from("1.75"), RocStr); - assert_evals_to!(r"Num.toStr 10.75dec", RocStr::from("10.75"), RocStr); + assert_evals_to!(r"Num.to_str -10.75dec", RocStr::from("-10.75"), RocStr); + assert_evals_to!(r"Num.to_str -1.75dec", RocStr::from("-1.75"), RocStr); + assert_evals_to!(r"Num.to_str 0dec", RocStr::from("0.0"), RocStr); + assert_evals_to!(r"Num.to_str 1.75dec", RocStr::from("1.75"), RocStr); + assert_evals_to!(r"Num.to_str 10.75dec", RocStr::from("10.75"), RocStr); assert_evals_to!( - r"Num.toStr 170141183460469.105727dec", + r"Num.to_str 170141183460469.105727dec", RocStr::from("170141183460469.105727"), RocStr ); assert_evals_to!( - r"Num.toStr -170141183460469.105727dec", + r"Num.to_str -170141183460469.105727dec", RocStr::from("-170141183460469.105727"), RocStr ); @@ -3409,7 +3465,7 @@ fn to_float_f32() { n = 100 f : F32 - f = Num.toFrac n + f = Num.to_frac n f " ), @@ -3428,7 +3484,7 @@ fn to_float_f64() { n = 100 f : F64 - f = Num.toFrac n + f = Num.to_frac n f " ), @@ -3444,7 +3500,7 @@ fn upcast_of_int_is_zext() { assert_evals_to!( indoc!( r" - Num.toU16 0b1000_0000u8 + Num.to_u16 0b1000_0000u8 " ), 128, @@ -3459,7 +3515,7 @@ fn upcast_of_int_checked_is_zext() { assert_evals_to!( indoc!( r" - when Num.toU16Checked 0b1000_0000u8 is + when Num.to_u16_checked 0b1000_0000u8 is Ok 128u16 -> 1u8 _ -> 0u8 " @@ -3706,49 +3762,49 @@ fn condition_polymorphic_num_becomes_float() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_count_leading_zero_bits() { - assert_evals_to!(r"Num.countLeadingZeroBits 0b0010_1000u8", 2, u8); - assert_evals_to!(r"Num.countLeadingZeroBits 0b0010_1000u16", 10, u8); - assert_evals_to!(r"Num.countLeadingZeroBits 0b0010_1000u32", 26, u8); - assert_evals_to!(r"Num.countLeadingZeroBits 0b0010_1000u64", 58, u8); + assert_evals_to!(r"Num.count_leading_zero_bits 0b0010_1000u8", 2, u8); + assert_evals_to!(r"Num.count_leading_zero_bits 0b0010_1000u16", 10, u8); + assert_evals_to!(r"Num.count_leading_zero_bits 0b0010_1000u32", 26, u8); + assert_evals_to!(r"Num.count_leading_zero_bits 0b0010_1000u64", 58, u8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_count_trailing_zero_bits() { - assert_evals_to!(r"Num.countTrailingZeroBits 0b0010_1000u8", 3, u8); - assert_evals_to!(r"Num.countTrailingZeroBits 0b0010_0000u16", 5, u8); - assert_evals_to!(r"Num.countTrailingZeroBits 0u32", 32, u8); - assert_evals_to!(r"Num.countTrailingZeroBits 0b0010_1111u64", 0, u8); + assert_evals_to!(r"Num.count_trailing_zero_bits 0b0010_1000u8", 3, u8); + assert_evals_to!(r"Num.count_trailing_zero_bits 0b0010_0000u16", 5, u8); + assert_evals_to!(r"Num.count_trailing_zero_bits 0u32", 32, u8); + assert_evals_to!(r"Num.count_trailing_zero_bits 0b0010_1111u64", 0, u8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_count_one_bits() { - assert_evals_to!(r"Num.countOneBits 0b0010_1000u8", 2, u8); - assert_evals_to!(r"Num.countOneBits 0b0010_0000u16", 1, u8); - assert_evals_to!(r"Num.countOneBits 0u32", 0, u8); - assert_evals_to!(r"Num.countOneBits 0b0010_1111u64", 5, u8); + assert_evals_to!(r"Num.count_one_bits 0b0010_1000u8", 2, u8); + assert_evals_to!(r"Num.count_one_bits 0b0010_0000u16", 1, u8); + assert_evals_to!(r"Num.count_one_bits 0u32", 0, u8); + assert_evals_to!(r"Num.count_one_bits 0b0010_1111u64", 5, u8); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_abs_diff_int() { - assert_evals_to!(r"Num.absDiff 0u8 0u8", 0, u8); - assert_evals_to!(r"Num.absDiff 1u8 2u8", 1, u8); - assert_evals_to!(r"Num.absDiff 2u8 1u8", 1, u8); - assert_evals_to!(r"Num.absDiff -1 1", 2, i64); - assert_evals_to!(r"Num.absDiff 1 -1", 2, i64); - assert_evals_to!(r"Num.absDiff Num.minI64 -1", i64::MAX, i64); + assert_evals_to!(r"Num.abs_diff 0u8 0u8", 0, u8); + assert_evals_to!(r"Num.abs_diff 1u8 2u8", 1, u8); + assert_evals_to!(r"Num.abs_diff 2u8 1u8", 1, u8); + assert_evals_to!(r"Num.abs_diff -1 1", 2, i64); + assert_evals_to!(r"Num.abs_diff 1 -1", 2, i64); + assert_evals_to!(r"Num.abs_diff Num.min_i64 -1", i64::MAX, i64); } #[test] #[cfg(feature = "gen-llvm")] fn num_abs_diff_large_bits() { - assert_evals_to!(r"Num.absDiff 0u128 0u128", U128::from(0), U128); - assert_evals_to!(r"Num.absDiff 1u128 2u128", U128::from(1), U128); - assert_evals_to!(r"Num.absDiff -1i128 1i128", I128::from(2), I128); + assert_evals_to!(r"Num.abs_diff 0u128 0u128", U128::from(0), U128); + assert_evals_to!(r"Num.abs_diff 1u128 2u128", U128::from(1), U128); + assert_evals_to!(r"Num.abs_diff -1i128 1i128", I128::from(2), I128); assert_evals_to!( - r"Num.absDiff Num.minI128 -1i128", + r"Num.abs_diff Num.min_i128 -1i128", I128::from(i128::MAX), I128 ); @@ -3757,38 +3813,38 @@ fn num_abs_diff_large_bits() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_abs_diff_float() { - assert_evals_to!(r"Num.absDiff 0.0f64 0.0", 0.0, f64); - assert_evals_to!(r"Num.absDiff 1.0f64 2.0", 1.0, f64); - assert_evals_to!(r"Num.absDiff 2.0f64 1.0", 1.0, f64); - assert_evals_to!(r"Num.absDiff -1.0f64 1.0", 2.0, f64); - assert_evals_to!(r"Num.absDiff 1.0f64 -1.0", 2.0, f64); + assert_evals_to!(r"Num.abs_diff 0.0f64 0.0", 0.0, f64); + assert_evals_to!(r"Num.abs_diff 1.0f64 2.0", 1.0, f64); + assert_evals_to!(r"Num.abs_diff 2.0f64 1.0", 1.0, f64); + assert_evals_to!(r"Num.abs_diff -1.0f64 1.0", 2.0, f64); + assert_evals_to!(r"Num.abs_diff 1.0f64 -1.0", 2.0, f64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] #[should_panic(expected = r#"Roc failed with message: "Integer subtraction overflowed!"#)] fn num_abs_max_overflow() { - assert_evals_to!(r"Num.absDiff Num.maxI64 -1", 0, i64); + assert_evals_to!(r"Num.abs_diff Num.max_i64 -1", 0, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] #[should_panic(expected = r#"Roc failed with message: "Integer subtraction overflowed!"#)] fn num_abs_int_min_overflow() { - assert_evals_to!(r"Num.absDiff Num.minI64 0", 0, i64); + assert_evals_to!(r"Num.abs_diff Num.min_i64 0", 0, i64); } #[test] #[cfg(feature = "gen-llvm")] #[should_panic(expected = r#"Roc failed with message: "Integer subtraction overflowed!"#)] fn num_abs_large_bits_min_overflow() { - assert_evals_to!(r"Num.absDiff Num.minI128 0", I128::from(0), I128); + assert_evals_to!(r"Num.abs_diff Num.min_i128 0", I128::from(0), I128); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn num_abs_float_overflow() { - assert_evals_to!("Num.absDiff Num.maxF64 Num.minF64", f64::INFINITY, f64); + assert_evals_to!("Num.abs_diff Num.max_f64 Num.min_f64", f64::INFINITY, f64); } #[test] @@ -3821,7 +3877,7 @@ fn add_checked_dec() { assert_evals_to!( indoc!( r" - Num.addChecked 2.0dec 4.0dec + Num.add_checked 2.0dec 4.0dec " ), RocResult::ok(RocDec::from(6)), @@ -3835,7 +3891,7 @@ fn sub_checked_dec() { assert_evals_to!( indoc!( r" - Num.subChecked 5.0dec 2.0dec + Num.sub_checked 5.0dec 2.0dec " ), RocResult::ok(RocDec::from(3)), @@ -3849,7 +3905,7 @@ fn mul_checked_dec() { assert_evals_to!( indoc!( r" - Num.mulChecked 5.0dec 2.0dec + Num.mul_checked 5.0dec 2.0dec " ), RocResult::ok(RocDec::from_str("10.0").unwrap()), @@ -3864,7 +3920,7 @@ fn mul_checked_u128() { indoc!( r" x : Result U128 [ Overflow ] - x = Num.mulChecked 5u128 2u128 + x = Num.mul_checked 5u128 2u128 x " @@ -3881,7 +3937,7 @@ fn sub_checked_u128() { indoc!( r" x : Result U128 [ Overflow ] - x = Num.subChecked 5u128 2u128 + x = Num.sub_checked 5u128 2u128 x " @@ -3898,7 +3954,7 @@ fn add_checked_u128() { indoc!( r" x : Result U128 [ Overflow ] - x = Num.addChecked 5u128 2u128 + x = Num.add_checked 5u128 2u128 x " @@ -3916,8 +3972,8 @@ fn num_min() { assert_evals_to!(r"Num.min 2 1", 1, i64); assert_evals_to!(r"Num.min 2 -2", -2, i64); assert_evals_to!(r"Num.min -2 2", -2, i64); - assert_evals_to!(r"Num.min Num.minI64 Num.maxI64", i64::MIN, i64); - assert_evals_to!(r"Num.min Num.maxI64 Num.minI64", i64::MIN, i64); + assert_evals_to!(r"Num.min Num.min_i64 Num.max_i64", i64::MIN, i64); + assert_evals_to!(r"Num.min Num.max_i64 Num.min_i64", i64::MIN, i64); } #[test] @@ -3928,30 +3984,30 @@ fn num_max() { assert_evals_to!(r"Num.max 2 1", 2, i64); assert_evals_to!(r"Num.max 2 -2", 2, i64); assert_evals_to!(r"Num.max -2 2", 2, i64); - assert_evals_to!(r"Num.max Num.minI64 Num.maxI64", i64::MAX, i64); - assert_evals_to!(r"Num.max Num.maxI64 Num.minI64", i64::MAX, i64); + assert_evals_to!(r"Num.max Num.min_i64 Num.max_i64", i64::MAX, i64); + assert_evals_to!(r"Num.max Num.max_i64 Num.min_i64", i64::MAX, i64); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn with_decimal_point() { assert_evals_to!( - r"Num.withDecimalPoint 0", + r"Num.with_decimal_point 0", RocDec::from_str("0").unwrap(), RocDec ); assert_evals_to!( - r"Num.withDecimalPoint 123000000000000000000", + r"Num.with_decimal_point 123000000000000000000", RocDec::from_str("123.0").unwrap(), RocDec ); assert_evals_to!( - r"Num.withDecimalPoint Num.maxI128", + r"Num.with_decimal_point Num.max_i128", RocDec::from_str("170141183460469231731.687303715884105727").unwrap(), RocDec ); assert_evals_to!( - r"Num.withDecimalPoint Num.minI128", + r"Num.with_decimal_point Num.min_i128", RocDec::from_str("-170141183460469231731.687303715884105728").unwrap(), RocDec ); @@ -3961,22 +4017,22 @@ fn with_decimal_point() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn without_decimal_point() { assert_evals_to!( - r"Num.withoutDecimalPoint 0", + r"Num.without_decimal_point 0", RocDec::from_str("0").unwrap(), RocDec ); assert_evals_to!( - r"Num.withoutDecimalPoint 123.000000000000000000", + r"Num.without_decimal_point 123.000000000000000000", I128::from(123000000000000000000), I128 ); assert_evals_to!( - r"Num.withoutDecimalPoint 170141183460469231731.687303715884105727", + r"Num.without_decimal_point 170141183460469231731.687303715884105727", I128::from(i128::MAX), I128 ); assert_evals_to!( - r"Num.withoutDecimalPoint -170141183460469231731.687303715884105728", + r"Num.without_decimal_point -170141183460469231731.687303715884105728", I128::from(i128::MIN), I128 ); @@ -3985,14 +4041,14 @@ fn without_decimal_point() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn f32_to_parts() { - assert_evals_to!(r"Num.f32ToParts 0", (0, 0, false), (u32, u8, bool)); + assert_evals_to!(r"Num.f32_to_parts 0", (0, 0, false), (u32, u8, bool)); assert_evals_to!( - r"Num.f32ToParts Num.maxF32", + r"Num.f32_to_parts Num.max_f32", (0x7FFFFF, 0xFE, false), (u32, u8, bool) ); assert_evals_to!( - r"Num.f32ToParts Num.minF32", + r"Num.f32_to_parts Num.min_f32", (0x7FFFFF, 0xFE, true), (u32, u8, bool) ); @@ -4001,14 +4057,14 @@ fn f32_to_parts() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn f64_to_parts() { - assert_evals_to!(r"Num.f64ToParts 0", (0, 0, false), (u64, u16, bool)); + assert_evals_to!(r"Num.f64_to_parts 0", (0, 0, false), (u64, u16, bool)); assert_evals_to!( - r"Num.f64ToParts Num.maxF64", + r"Num.f64_to_parts Num.max_f64", (0xFFFFFFFFFFFFF, 0x7FE, false), (u64, u16, bool) ); assert_evals_to!( - r"Num.f64ToParts Num.minF64", + r"Num.f64_to_parts Num.min_f64", (0xFFFFFFFFFFFFF, 0x7FE, true), (u64, u16, bool) ); @@ -4019,7 +4075,7 @@ fn f64_to_parts() { fn f32_from_parts() { assert_evals_to!( r" - Num.f32FromParts { + Num.f32_from_parts { sign: Bool.false, exponent: 0, fraction: 0 @@ -4029,7 +4085,7 @@ fn f32_from_parts() { ); assert_evals_to!( r" - Num.f32FromParts { + Num.f32_from_parts { sign: Bool.false, exponent: 0xFE, fraction: 0x7FFFFF @@ -4039,7 +4095,7 @@ fn f32_from_parts() { ); assert_evals_to!( r" - Num.f32FromParts { + Num.f32_from_parts { sign: Bool.true, exponent: 0xFE, fraction: 0x7FFFFF @@ -4054,7 +4110,7 @@ fn f32_from_parts() { fn f64_from_parts() { assert_evals_to!( r" - Num.f64FromParts { + Num.f64_from_parts { sign: Bool.false, exponent: 0, fraction: 0 @@ -4064,7 +4120,7 @@ fn f64_from_parts() { ); assert_evals_to!( r" - Num.f64FromParts { + Num.f64_from_parts { sign: Bool.false, exponent: 0x7FE, fraction: 0xFFFFFFFFFFFFF @@ -4074,7 +4130,7 @@ fn f64_from_parts() { ); assert_evals_to!( r" - Num.f64FromParts { + Num.f64_from_parts { sign: Bool.true, exponent: 0x7FE, fraction: 0xFFFFFFFFFFFFF @@ -4093,7 +4149,7 @@ fn from_bool_true() { bool : Bool bool = Bool.true - Num.fromBool bool + Num.from_bool bool " ), 1, @@ -4110,7 +4166,7 @@ fn from_bool_false() { bool : Bool bool = Bool.false - Num.fromBool bool + Num.from_bool bool " ), 0, @@ -4121,32 +4177,32 @@ fn from_bool_false() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn nan_f32() { - assert_evals_to!(r"Num.nanF32", true, f32, |f: f32| f.is_nan()); + assert_evals_to!(r"Num.nan_f32", true, f32, |f: f32| f.is_nan()); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn nan_f64() { - assert_evals_to!(r"Num.nanF64", true, f64, |f: f64| f.is_nan()); + assert_evals_to!(r"Num.nan_f64", true, f64, |f: f64| f.is_nan()); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn infinity_f32() { - assert_evals_to!(r"Num.infinityF32", f32::INFINITY, f32); + assert_evals_to!(r"Num.infinity_f32", f32::INFINITY, f32); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev", feature = "gen-wasm"))] fn infinity_f64() { - assert_evals_to!(r"Num.infinityF64", f64::INFINITY, f64); + assert_evals_to!(r"Num.infinity_f64", f64::INFINITY, f64); } #[allow(clippy::non_minimal_cfg)] #[test] #[cfg(any(feature = "gen-llvm"))] fn cast_signed_unsigned() { - assert_evals_to!(r"Num.toI16 255u8", 255, i16); - assert_evals_to!(r"Num.toU16 127i8", 127, u16); - assert_evals_to!(r"Num.toU8 127i8", 127, u8); - assert_evals_to!(r"Num.toI8 127u8", 127, i8); + assert_evals_to!(r"Num.to_i16 255u8", 255, i16); + assert_evals_to!(r"Num.to_u16 127i8", 127, u16); + assert_evals_to!(r"Num.to_u8 127i8", 127, u8); + assert_evals_to!(r"Num.to_i8 127u8", 127, i8); } diff --git a/crates/compiler/test_gen/src/gen_panic.rs b/crates/compiler/test_gen/src/gen_panic.rs index b39c945b76a..10e790da6be 100644 --- a/crates/compiler/test_gen/src/gen_panic.rs +++ b/crates/compiler/test_gen/src/gen_panic.rs @@ -55,14 +55,14 @@ fn crash_in_call() { r#" app "test" provides [main] to "./platform" - getInfallible = \result -> when result is + get_infallible = \result -> when result is Ok x -> x _ -> crash "turns out this was fallible" main = x : [Ok U64, Err Str] x = Err "" - getInfallible x + get_infallible x "# ), 1u64, diff --git a/crates/compiler/test_gen/src/gen_primitives.rs b/crates/compiler/test_gen/src/gen_primitives.rs index fdad8eb2d3b..36130badbf4 100644 --- a/crates/compiler/test_gen/src/gen_primitives.rs +++ b/crates/compiler/test_gen/src/gen_primitives.rs @@ -310,11 +310,11 @@ fn return_unnamed_fn() { indoc!( r" wrapper = \{} -> - alwaysFloatIdentity : Int * -> (Frac a -> Frac a) - alwaysFloatIdentity = \_ -> + always_float_identity : Int * -> (Frac a -> Frac a) + always_float_identity = \_ -> (\a -> a) - (alwaysFloatIdentity 2) 1.23f64 + (always_float_identity 2) 1.23f64 wrapper {} " @@ -330,13 +330,13 @@ fn gen_when_fn() { assert_evals_to!( indoc!( r" - limitedNegate = \num -> + limited_negate = \num -> when num is 1 -> -1 -1 -> 1 _ -> num - limitedNegate 1 + limited_negate 1 " ), -1, @@ -944,7 +944,7 @@ fn when_peano() { } #[test] -// This doesn't work on Windows. If you make it return a Result.withDefault 0 (so it's returning +// This doesn't work on Windows. If you make it return a Result.with_default 0 (so it's returning // an integer instead of a Result), then it works on Windows, suggesting this is a C ABI issue. // We should try this out on Windows again after making adjustments to the Result C ABI! #[cfg(all( @@ -956,17 +956,17 @@ fn overflow_frees_list() { assert_evals_to!( indoc!( r" - myList = [1,2,3] + my_list = [1,2,3] # integer overflow; must use the list so it is defined before the overflow # the list will then be freed in a cleanup block n : I64 - n = 9_223_372_036_854_775_807 + (Num.intCast (List.len myList)) + n = 9_223_372_036_854_775_807 + (Num.int_cast (List.len my_list)) index : U64 - index = Num.intCast n + index = Num.int_cast n - List.get myList index + List.get my_list index " ), (3, 0), @@ -1117,7 +1117,7 @@ fn specialize_closure() { y = [1] f = \{} -> x - g = \{} -> x + Num.intCast (List.len y) + g = \{} -> x + Num.int_cast (List.len y) [f, g] @@ -1147,8 +1147,8 @@ fn io_poc_effect() { succeed : a -> Effect a succeed = \x -> @Effect \{} -> x - runEffect : Effect a -> a - runEffect = \@Effect thunk -> thunk {} + run_effect : Effect a -> a + run_effect = \@Effect thunk -> thunk {} foo : Effect F64 foo = @@ -1156,7 +1156,7 @@ fn io_poc_effect() { main : F64 main = - runEffect foo + run_effect foo "# ), @@ -1180,12 +1180,12 @@ fn io_poc_desugared() { foo = succeed 1.23 - # runEffect : ({} -> a) -> a - runEffect = \thunk -> thunk "" + # run_effect : ({} -> a) -> a + run_effect = \thunk -> thunk "" main : F64 main = - runEffect foo + run_effect foo "# ), 1.23, @@ -1274,8 +1274,8 @@ fn linked_list_is_singleton() { empty : {} -> ConsList a empty = \{} -> Nil - isSingleton : ConsList a -> Bool - isSingleton = \list -> + is_singleton : ConsList a -> Bool + is_singleton = \list -> when list is Cons _ Nil -> Bool.true @@ -1285,10 +1285,10 @@ fn linked_list_is_singleton() { main : Bool main = - myList : ConsList I64 - myList = empty {} + my_list : ConsList I64 + my_list = empty {} - isSingleton myList + is_singleton my_list "# ), false, @@ -1309,8 +1309,8 @@ fn linked_list_is_empty_1() { empty : {} -> ConsList a empty = \{} -> Nil - isEmpty : ConsList a -> Bool - isEmpty = \list -> + is_empty : ConsList a -> Bool + is_empty = \list -> when list is Cons _ _ -> Bool.false @@ -1320,10 +1320,10 @@ fn linked_list_is_empty_1() { main : Bool main = - myList : ConsList U8 - myList = empty {} + my_list : ConsList U8 + my_list = empty {} - isEmpty myList + is_empty my_list "# ), true, @@ -1341,8 +1341,8 @@ fn linked_list_is_empty_2() { ConsList a : [Cons a (ConsList a), Nil] - isEmpty : ConsList a -> Bool - isEmpty = \list -> + is_empty : ConsList a -> Bool + is_empty = \list -> when list is Cons _ _ -> Bool.false @@ -1352,10 +1352,10 @@ fn linked_list_is_empty_2() { main : Bool main = - myList : ConsList I64 - myList = Cons 0x1 Nil + my_list : ConsList I64 + my_list = Cons 0x1 Nil - isEmpty myList + is_empty my_list "# ), false, @@ -1428,57 +1428,57 @@ fn rbtree_insert() { insert : Key k, v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v insert = \key, value, dict -> - when insertHelp key value dict is + when insert_help key value dict is Node Red k v l r -> Node Black k v l r x -> x - insertHelp : (Key k), v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v - insertHelp = \key, value, dict -> + insert_help : (Key k), v, RedBlackTree (Key k) v -> RedBlackTree (Key k) v + insert_help = \key, value, dict -> when dict is Empty -> # New nodes are always red. If it violates the rules, it will be fixed # when balancing. Node Red key value Empty Empty - Node nColor nKey nValue nLeft nRight -> - when Num.compare key nKey is + Node n_color n_key n_value n_left n_right -> + when Num.compare key n_key is LT -> - balance nColor nKey nValue (insertHelp key value nLeft) nRight + balance n_color n_key n_value (insert_help key value n_left) n_right EQ -> - Node nColor nKey value nLeft nRight + Node n_color n_key value n_left n_right GT -> - balance nColor nKey nValue nLeft (insertHelp key value nRight) + balance n_color n_key n_value n_left (insert_help key value n_right) balance : NodeColor, k, v, RedBlackTree k v, RedBlackTree k v -> RedBlackTree k v balance = \color, key, value, left, right -> when right is - Node Red rK rV rLeft rRight -> + Node Red r_k r_v r_left r_right -> when left is - Node Red lK lV lLeft lRight -> + Node Red l_k l_v l_left l_right -> Node Red key value - (Node Black lK lV lLeft lRight) - (Node Black rK rV rLeft rRight) + (Node Black l_k l_v l_left l_right) + (Node Black r_k r_v r_left r_right) _ -> - Node color rK rV (Node Red key value left rLeft) rRight + Node color r_k r_v (Node Red key value left r_left) r_right _ -> when left is - Node Red lK lV (Node Red llK llV llLeft llRight) lRight -> + Node Red l_k l_v (Node Red ll_k ll_v ll_left ll_right) l_right -> Node Red - lK - lV - (Node Black llK llV llLeft llRight) - (Node Black key value lRight right) + l_k + l_v + (Node Black ll_k ll_v ll_left ll_right) + (Node Black key value l_right right) _ -> Node color key value left right @@ -1545,8 +1545,8 @@ fn rbtree_layout_issue() { # balance : NodeColor, k, v, RedBlackTree k v -> RedBlackTree k v balance = \color, key, value, right -> when right is - Node Red _ _ rLeft rRight -> - Node color key value rLeft rRight + Node Red _ _ r_left r_right -> + Node color key value r_left r_right _ -> @@ -1579,7 +1579,7 @@ fn rbtree_balance_mono_problem() { // constraint generation where the specialization required by `main` does not fix the // problem. As a result, the first argument is dropped and we run into issues down the line // - // concretely, the `rRight` symbol will not be defined + // concretely, the `r_right` symbol will not be defined assert_evals_to!( indoc!( r#" @@ -1592,18 +1592,18 @@ fn rbtree_balance_mono_problem() { # balance : NodeColor, k, v, RedBlackTree k v, RedBlackTree k v -> RedBlackTree k v balance = \color, key, value, left, right -> when right is - Node Red rK rV rLeft rRight -> + Node Red r_k r_v r_left r_right -> when left is - Node Red lK lV lLeft lRight -> + Node Red l_k l_v l_left l_right -> Node Red key value - (Node Black lK lV lLeft lRight) - (Node Black rK rV rLeft rRight) + (Node Black l_k l_v l_left l_right) + (Node Black r_k r_v r_left r_right) _ -> - Node color rK rV (Node Red key value left rLeft) rRight + Node color r_k r_v (Node Red key value left r_left) r_right _ -> Empty @@ -1639,28 +1639,28 @@ fn rbtree_balance_full() { balance : NodeColor, k, v, RedBlackTree k v, RedBlackTree k v -> RedBlackTree k v balance = \color, key, value, left, right -> when right is - Node Red rK rV rLeft rRight -> + Node Red r_k r_v r_left r_right -> when left is - Node Red lK lV lLeft lRight -> + Node Red l_k l_v l_left l_right -> Node Red key value - (Node Black lK lV lLeft lRight) - (Node Black rK rV rLeft rRight) + (Node Black l_k l_v l_left l_right) + (Node Black r_k r_v r_left r_right) _ -> - Node color rK rV (Node Red key value left rLeft) rRight + Node color r_k r_v (Node Red key value left r_left) r_right _ -> when left is - Node Red lK lV (Node Red llK llV llLeft llRight) lRight -> + Node Red l_k l_v (Node Red ll_k ll_v ll_left ll_right) l_right -> Node Red - lK - lV - (Node Black llK llV llLeft llRight) - (Node Black key value lRight right) + l_k + l_v + (Node Black ll_k ll_v ll_left ll_right) + (Node Black key value l_right right) _ -> Node color key value left right @@ -1876,26 +1876,26 @@ fn task_always_twice() { Effect a := {} -> a - effectAlways : a -> Effect a - effectAlways = \x -> + effect_always : a -> Effect a + effect_always = \x -> inner = \{} -> x @Effect inner - effectAfter : Effect a, (a -> Effect b) -> Effect b - effectAfter = \(@Effect thunk), transform -> transform (thunk {}) + effect_after : Effect a, (a -> Effect b) -> Effect b + effect_after = \(@Effect thunk), transform -> transform (thunk {}) MyTask a err : Effect (Result a err) always : a -> MyTask a * - always = \x -> effectAlways (Ok x) + always = \x -> effect_always (Ok x) fail : err -> MyTask * err - fail = \x -> effectAlways (Err x) + fail = \x -> effect_always (Err x) after : MyTask a err, (a -> MyTask b err) -> MyTask b err after = \task, transform -> - effectAfter task \res -> + effect_after task \res -> when res is Ok x -> transform x Err e -> fail e @@ -1980,27 +1980,27 @@ fn todo_bad_error_message() { Effect a := {} -> a - effectAlways : a -> Effect a - effectAlways = \x -> + effect_always : a -> Effect a + effect_always = \x -> inner = \{} -> x @Effect inner - effectAfter : Effect a, (a -> Effect b) -> Effect b - effectAfter = \(@Effect thunk), transform -> transform (thunk {}) + effect_after : Effect a, (a -> Effect b) -> Effect b + effect_after = \(@Effect thunk), transform -> transform (thunk {}) MyTask a err : Effect (Result a err) always : a -> MyTask a (Frac *) - always = \x -> effectAlways (Ok x) + always = \x -> effect_always (Ok x) # the problem is that this restricts to `MyTask {} *` fail : err -> MyTask {} err - fail = \x -> effectAlways (Err x) + fail = \x -> effect_always (Err x) after : MyTask a err, (a -> MyTask b err) -> MyTask b err after = \task, transform -> - effectAfter task \res -> + effect_after task \res -> when res is Ok x -> transform x # but here it must be `forall b. MyTask b {}` @@ -2024,9 +2024,9 @@ fn hof_conditional() { assert_evals_to!( indoc!( r" - passTrue = \f -> f Bool.true + pass_true = \f -> f Bool.true - passTrue (\trueVal -> if trueVal then Bool.false else Bool.true) + pass_true (\true_val -> if true_val then Bool.false else Bool.true) " ), 0, @@ -2097,10 +2097,10 @@ fn fingertree_basic() { when some is One y -> More (Two x y) q u Two y z -> More (Three x y z) q u - Three y z w -> More (Two x y) (consTuple (Pair z w) q) u + Three y z w -> More (Two x y) (cons_tuple (Pair z w) q) u - consTuple : Tuple a, Seq (Tuple a) -> Seq (Tuple a) - consTuple = \a, b -> cons a b + cons_tuple : Tuple a, Seq (Tuple a) -> Seq (Tuple a) + cons_tuple = \a, b -> cons a b main : Bool main = @@ -2201,11 +2201,11 @@ fn nullable_eval_cfold() { Expr : [Var, Val I64, Add Expr Expr, Mul Expr Expr] - mkExpr : I64, I64 -> Expr - mkExpr = \n , v -> + mk_expr : I64, I64 -> Expr + mk_expr = \n , v -> when n is 0 -> if v == 0 then Var else Val v - _ -> Add (mkExpr (n-1) (v+1)) (mkExpr (n-1) (max (v-1) 0)) + _ -> Add (mk_expr (n-1) (v+1)) (mk_expr (n-1) (max (v-1) 0)) max : I64, I64 -> I64 max = \a, b -> if a > b then a else b @@ -2219,7 +2219,7 @@ fn nullable_eval_cfold() { Mul l r -> eval l * eval r main : I64 - main = eval (mkExpr 3 1) + main = eval (mk_expr 3 1) "# ), 11, @@ -2247,8 +2247,8 @@ fn nested_switch() { Val v -> v ZAdd l r -> eval l + eval r - constFolding : Expr -> Expr - constFolding = \e -> + const_folding : Expr -> Expr + const_folding = \e -> when e is ZAdd e1 e2 -> when Pair e1 e2 is @@ -2263,7 +2263,7 @@ fn nested_switch() { expr = ZAdd (Val 3) (ZAdd (Val 4) (Val 5)) main : I64 - main = eval (constFolding expr) + main = eval (const_folding expr) "# ), 12, @@ -2653,7 +2653,7 @@ fn mirror_llvm_alignment_padding() { p1 = {name : "test1", test: 1 == 1 } List.map [p1, p1] (\{ test } -> if test then "pass" else "fail") - |> Str.joinWith "\n" + |> Str.join_with "\n" "# ), @@ -2675,9 +2675,9 @@ fn lambda_set_bool() { main : I64 main = - oneOfResult = List.map [p1, p2] (\p -> p 42) + one_of_result = List.map [p1, p2] (\p -> p 42) - when oneOfResult is + when one_of_result is _ -> 32 "# @@ -2701,9 +2701,9 @@ fn lambda_set_byte() { main : I64 main = - oneOfResult = List.map [p1, p2, p3] (\p -> p 42) + one_of_result = List.map [p1, p2, p3] (\p -> p 42) - when oneOfResult is + when one_of_result is _ -> 32 "# @@ -2729,9 +2729,9 @@ fn lambda_set_struct_byte() { p1 = (\u -> r == u) foobarbaz = (\p -> p Green) - oneOfResult = List.map [p1, p1] foobarbaz + one_of_result = List.map [p1, p1] foobarbaz - when oneOfResult is + when one_of_result is _ -> 32 "# @@ -2760,9 +2760,9 @@ fn lambda_set_enum_byte_byte() { p1 = (\u -> r == u) p2 = (\u -> g == u) - oneOfResult = List.map [p1, p2] (\p -> p Green) + one_of_result = List.map [p1, p2] (\p -> p Green) - when oneOfResult is + when one_of_result is _ -> 32 "# @@ -2782,14 +2782,14 @@ fn list_walk_until() { app "test" provides [main] to "./platform" - satisfyA : {} -> List {} - satisfyA = \_ -> [] + satisfy_a : {} -> List {} + satisfy_a = \_ -> [] - oneOfResult = - List.walkUntil [satisfyA] [] \_, _ -> Break [] + one_of_result = + List.walk_until [satisfy_a] [] \_, _ -> Break [] main = - when oneOfResult is + when one_of_result is _ -> 32 "# ), @@ -2811,11 +2811,11 @@ fn int_literal_not_specialized_with_annotation() { satisfy : (U8 -> Str) -> Str satisfy = \_ -> "foo" - myEq : a, a -> Str - myEq = \_, _ -> "bar" + my_eq : a, a -> Str + my_eq = \_, _ -> "bar" p1 : Num * -> Str - p1 = (\u -> myEq u 64) + p1 = (\u -> my_eq u 64) when satisfy p1 is _ -> 32 @@ -2839,10 +2839,10 @@ fn int_literal_not_specialized_no_annotation() { satisfy : (U8 -> Str) -> Str satisfy = \_ -> "foo" - myEq : a, a -> Str - myEq = \_, _ -> "bar" + my_eq : a, a -> Str + my_eq = \_, _ -> "bar" - p1 = (\u -> myEq u 64) + p1 = (\u -> my_eq u 64) when satisfy p1 is _ -> 32 @@ -2868,9 +2868,9 @@ fn unresolved_tvar_when_capture_is_unused() { r = 1 p1 = (\_ -> r == 1) - oneOfResult = List.map [p1] (\p -> p Green) + one_of_result = List.map [p1] (\p -> p Green) - when oneOfResult is + when one_of_result is _ -> 32 "# @@ -2891,7 +2891,7 @@ fn value_not_exposed_hits_panic() { main : I64 main = - Str.toInt 32 + Str.to_int 32 "# ), 32, @@ -2974,7 +2974,7 @@ fn do_pass_bool_byte_closure_layout() { any: Parser U8 any = \inp -> when List.first inp is - Ok u -> [Pair u (List.dropFirst inp 1)] + Ok u -> [Pair u (List.drop_first inp 1)] _ -> [] @@ -2991,12 +2991,12 @@ fn do_pass_bool_byte_closure_layout() { else Break accum - List.walkUntil (any input) [] walker + List.walk_until (any input) [] walker - oneOf : List (Parser a) -> Parser a - oneOf = \parserList -> + one_of : List (Parser a) -> Parser a + one_of = \parserList -> \input -> walker = \accum, p -> output = p input @@ -3006,20 +3006,20 @@ fn do_pass_bool_byte_closure_layout() { else Continue accum - List.walkUntil parserList [] walker + List.walk_until parserList [] walker - satisfyA = satisfy (\u -> u == 97) # recognize 97 - satisfyB = satisfy (\u -> u == 98) # recognize 98 + satisfy_a = satisfy (\u -> u == 97) # recognize 97 + satisfy_b = satisfy (\u -> u == 98) # recognize 98 - test1 = if List.len ((oneOf [satisfyA, satisfyB]) [97, 98, 99, 100] ) == 1 then "PASS" else "FAIL" - test2 = if List.len ((oneOf [satisfyA, satisfyB]) [98, 99, 100, 97] ) == 1 then "PASS" else "FAIL" - test3 = if List.len ((oneOf [satisfyB , satisfyA]) [98, 99, 100, 97] ) == 1 then "PASS" else "FAIL" - test4 = if List.len ((oneOf [satisfyA, satisfyB]) [99, 100, 101] ) == 0 then "PASS" else "FAIL" + test1 = if List.len ((one_of [satisfy_a, satisfy_b]) [97, 98, 99, 100] ) == 1 then "PASS" else "FAIL" + test2 = if List.len ((one_of [satisfy_a, satisfy_b]) [98, 99, 100, 97] ) == 1 then "PASS" else "FAIL" + test3 = if List.len ((one_of [satisfy_b , satisfy_a]) [98, 99, 100, 97] ) == 1 then "PASS" else "FAIL" + test4 = if List.len ((one_of [satisfy_a, satisfy_b]) [99, 100, 101] ) == 0 then "PASS" else "FAIL" main : Str - main = [test1, test2, test3, test4] |> Str.joinWith ", " + main = [test1, test2, test3, test4] |> Str.join_with ", " "# ), RocStr::from("PASS, PASS, PASS, PASS"), @@ -3108,23 +3108,23 @@ fn nested_rigid_tag_union() { #[cfg(any(feature = "gen-llvm", feature = "gen-wasm", feature = "gen-dev"))] fn call_that_needs_closure_parameter() { // here both p2 is lifted to the top-level, which means that `list` must be - // passed to it from `manyAux`. + // passed to it from `many_aux`. assert_evals_to!( indoc!( r#" Step state a : [Loop state, Done a] - manyAux : List a -> [Pair (Step (List a) (List a))] - manyAux = \list -> + many_aux : List a -> [Pair (Step (List a) (List a))] + many_aux = \list -> p2 = \_ -> Pair (Done list) p2 "foo" - manyAuxTest = (manyAux []) == Pair (Loop [97]) + many_aux_test = (many_aux []) == Pair (Loop [97]) - runTest = \t -> if t then "PASS" else "FAIL" + run_test = \t -> if t then "PASS" else "FAIL" - runTest manyAuxTest + run_test many_aux_test "# ), RocStr::from("FAIL"), @@ -3168,17 +3168,17 @@ fn recursively_build_effect() { "$(hi), $(name)!" main = - when nestHelp 4 is + when nest_help 4 is _ -> greeting - nestHelp : I64 -> XEffect {} - nestHelp = \m -> + nest_help : I64 -> XEffect {} + nest_help = \m -> when m is 0 -> always {} _ -> - always {} |> after \_ -> nestHelp (m - 1) + always {} |> after \_ -> nest_help (m - 1) XEffect a := {} -> a @@ -3208,13 +3208,13 @@ fn polymophic_expression_captured_inside_closure() { r#" app "test" provides [main] to "./platform" - asU8 : U8 -> U8 - asU8 = \_ -> 30 + as_u8 : U8 -> U8 + as_u8 = \_ -> 30 main = a = 15 f = \{} -> - asU8 a + as_u8 a f {} "# @@ -3231,9 +3231,9 @@ fn issue_2322() { indoc!( r" double = \x -> x * 2 - doubleBind = \x -> (\_ -> double x) - doubleThree = doubleBind 3 - doubleThree {} + double_bind = \x -> (\_ -> double x) + double_three = double_bind 3 + double_three {} " ), 6, @@ -3458,10 +3458,10 @@ fn closure_called_in_its_defining_scope() { g : Str g = "hello world" - getG : {} -> Str - getG = \{} -> g + get_g : {} -> Str + get_g = \{} -> g - getG {} + get_g {} "# ), RocStr::from("hello world"), @@ -3483,11 +3483,11 @@ fn issue_2894() { g : { x : U32 } g = { x: 1u32 } - getG : {} -> { x : U32 } - getG = \{} -> g + get_g : {} -> { x : U32 } + get_g = \{} -> g h : {} -> U32 - h = \{} -> (getG {}).x + h = \{} -> (get_g {}).x h {} "# @@ -3548,7 +3548,7 @@ fn polymorphic_lambda_set_multiple_specializations() { f = if Bool.true then id1 else id2 f z - (id 9u8) + Num.toU8 (id 16u16) + (id 9u8) + Num.to_u8 (id 16u16) " ), 25, @@ -3585,19 +3585,19 @@ fn mutual_recursion_top_level_defs() { r#" app "test" provides [ main ] to "./platform" - isEven = \n -> + is_even = \n -> when n is 0 -> Bool.true 1 -> Bool.false - _ -> isOdd (n - 1) + _ -> is_odd (n - 1) - isOdd = \n -> + is_odd = \n -> when n is 0 -> Bool.false 1 -> Bool.true - _ -> isEven (n - 1) + _ -> is_even (n - 1) - main = isOdd 11 + main = is_odd 11 "# ), true, @@ -3633,7 +3633,7 @@ fn lambda_capture_niche_u64_vs_u8_capture() { capture : _ -> ({} -> Str) capture = \val -> \{} -> - Num.toStr val + Num.to_str val x : Bool x = Bool.true @@ -3661,7 +3661,7 @@ fn lambda_capture_niches_with_other_lambda_capture() { capture : _ -> ({} -> Str) capture = \val -> \{} -> - Num.toStr val + Num.to_str val capture2 = \val -> \{} -> val @@ -3694,7 +3694,7 @@ fn lambda_capture_niches_with_non_capturing_function() { capture : _ -> ({} -> Str) capture = \val -> \{} -> - Num.toStr val + Num.to_str val triv = \{} -> "triv" @@ -4058,9 +4058,9 @@ fn transient_captures() { r#" x = "abc" - getX = \{} -> x + get_x = \{} -> x - h = \{} -> getX {} + h = \{} -> get_x {} h {} "# @@ -4076,9 +4076,9 @@ fn transient_captures_after_def_ordering() { assert_evals_to!( indoc!( r#" - h = \{} -> getX {} + h = \{} -> get_x {} - getX = \{} -> x + get_x = \{} -> x x = "abc" @@ -4098,11 +4098,11 @@ fn deep_transient_capture_chain() { r#" z = "abc" - getX = \{} -> getY {} - getY = \{} -> getZ {} - getZ = \{} -> z + get_x = \{} -> get_y {} + get_y = \{} -> get_z {} + get_z = \{} -> z - h = \{} -> getX {} + h = \{} -> get_x {} h {} "# @@ -4123,13 +4123,13 @@ fn deep_transient_capture_chain_with_multiple_captures() { y = "y" z = "z" - getX = \{} -> Str.concat x (getY {}) - getY = \{} -> Str.concat y (getZ {}) - getZ = \{} -> z + get_x = \{} -> Str.concat x (get_y {}) + get_y = \{} -> Str.concat y (get_z {}) + get_z = \{} -> z - getH = \{} -> Str.concat h (getX {}) + get_h = \{} -> Str.concat h (get_x {}) - getH {} + get_h {} "# ), RocStr::from("hxyz"), @@ -4145,13 +4145,13 @@ fn transient_captures_from_outer_scope() { r#" x = "abc" - getX = \{} -> x + get_x = \{} -> x - innerScope = - h = \{} -> getX {} + inner_scope = + h = \{} -> get_x {} h {} - innerScope + inner_scope "# ), RocStr::from("abc"), @@ -4191,13 +4191,13 @@ fn int_let_generalization() { assert_evals_to!( indoc!( r#" - manyAux : {} -> I32 - manyAux = \_ -> + many_aux : {} -> I32 + many_aux = \_ -> output = \_ -> 42 output {} - when manyAux {} is + when many_aux {} is _ -> "done" "# ), @@ -4281,18 +4281,18 @@ fn issue_4712() { v2 = "cd" apply : Parser (a -> Str), a -> Parser Str - apply = \fnParser, valParser -> + apply = \fn_parser, val_parser -> \{} -> - (fnParser {}) (valParser) + (fn_parser {}) (val_parser) map : a, (a -> Str) -> Parser Str - map = \simpleParser, transform -> - apply (\{} -> transform) simpleParser + map = \simple_parser, transform -> + apply (\{} -> transform) simple_parser gen = \{} -> [ map v1 (\{} -> "ab"), map v2 (\s -> s) ] |> List.map (\f -> f {}) - |> Str.joinWith "," + |> Str.join_with "," main = gen {} "# @@ -4370,11 +4370,11 @@ fn function_specialization_information_in_lambda_set_thunk() { r#" app "test" provides [main] to "./platform" - andThen = \{} -> + and_then = \{} -> x = 10u8 - \newFn -> Num.add (newFn {}) x + \new_fn -> Num.add (new_fn {}) x - between = andThen {} + between = and_then {} main = between \{} -> between \{} -> 10u8 "# @@ -4392,13 +4392,13 @@ fn function_specialization_information_in_lambda_set_thunk_independent_defs() { r#" app "test" provides [main] to "./platform" - andThen = \{} -> + and_then = \{} -> x = 10u8 - \newFn -> Num.add (newFn {}) x + \new_fn -> Num.add (new_fn {}) x - between1 = andThen {} + between1 = and_then {} - between2 = andThen {} + between2 = and_then {} main = between1 \{} -> between2 \{} -> 10u8 "# @@ -4439,14 +4439,14 @@ fn recursive_lambda_set_resolved_only_upon_specialization() { r#" app "test" provides [main] to "./platform" - factCPS = \n, cont -> + fact_cps = \n, cont -> if n == 0 then cont 1 else - factCPS (n - 1) \value -> cont (n * value) + fact_cps (n - 1) \value -> cont (n * value) main = - factCPS 5u64 \x -> x + fact_cps 5u64 \x -> x "# ), 120, @@ -4499,28 +4499,28 @@ fn reset_recursive_type_wraps_in_named_type() { main : Str main = - newList = mapLinkedList (Cons 1 (Cons 2 (Cons 3 Nil))) (\x -> x + 1) - printLinkedList newList Num.toStr + new_list = map_linked_list (Cons 1 (Cons 2 (Cons 3 Nil))) (\x -> x + 1) + print_linked_list new_list Num.to_str LinkedList a : [Cons a (LinkedList a), Nil] - mapLinkedList : LinkedList a, (a -> b) -> LinkedList b - mapLinkedList = \linkedList, f -> when linkedList is + map_linked_list : LinkedList a, (a -> b) -> LinkedList b + map_linked_list = \linked_list, f -> when linked_list is Nil -> Nil Cons x xs -> s = if Bool.true then "true" else "false" expect s == "true" - Cons (f x) (mapLinkedList xs f) + Cons (f x) (map_linked_list xs f) - printLinkedList : LinkedList a, (a -> Str) -> Str - printLinkedList = \linkedList, f -> - when linkedList is + print_linked_list : LinkedList a, (a -> Str) -> Str + print_linked_list = \linked_list, f -> + when linked_list is Nil -> "Nil" Cons x xs -> - strX = f x - strXs = printLinkedList xs f - "Cons $(strX) ($(strXs))" + str_x = f x + str_xs = print_linked_list xs f + "Cons $(str_x) ($(str_xs))" "# ), RocStr::from("Cons 2 (Cons 3 (Cons 4 (Nil)))"), @@ -4643,12 +4643,12 @@ fn issue_6139_contains() { seen else # node = "B" - nextNode = stepNode node + next_node = step_node node # node = "C" - buggy nextNode (List.append seen node) + buggy next_node (List.append seen node) - stepNode = \node -> + step_node = \node -> when node is "A" -> "B" "B" -> "C" @@ -4676,15 +4676,15 @@ fn issue_6139_prefixes() { indoc!( r#" prefixes = \str, soFar -> - if Str.isEmpty str then + if Str.is_empty str then soFar else graphemes = - Str.toUtf8 str - |> List.map \c -> Str.fromUtf8 [c] |> Result.withDefault "" - remaining = List.dropFirst graphemes 1 - next = Str.joinWith remaining "" + Str.to_utf8 str + |> List.map \c -> Str.from_utf8 [c] |> Result.with_default "" + remaining = List.drop_first graphemes 1 + next = Str.join_with remaining "" prefixes next (List.append soFar str) diff --git a/crates/compiler/test_gen/src/gen_records.rs b/crates/compiler/test_gen/src/gen_records.rs index 23552198420..5ba7ca33b82 100644 --- a/crates/compiler/test_gen/src/gen_records.rs +++ b/crates/compiler/test_gen/src/gen_records.rs @@ -113,9 +113,9 @@ fn fn_record() { assert_evals_to!( indoc!( r#" - getRec = \x -> { y: "foo", x, z: 19 } + get_rec = \x -> { y: "foo", x, z: 19 } - (getRec 15).x + (get_rec 15).x "# ), 15, @@ -1005,10 +1005,10 @@ fn update_the_only_field() { foo = 4 - newModel : Model - newModel = { model & foo } + new_model : Model + new_model = { model & foo } - newModel.foo + new_model.foo " ), 4, @@ -1095,9 +1095,9 @@ fn generalized_accessor() { assert_evals_to!( indoc!( r#" - returnFoo = .foo + return_foo = .foo - returnFoo { foo: "foo" } + return_foo { foo: "foo" } "# ), RocStr::from("foo"), @@ -1113,11 +1113,11 @@ fn update_record_that_is_a_thunk() { r#" app "test" provides [main] to "./platform" - main = Num.toStr fromOriginal.birds + main = Num.to_str from_original.birds original = { birds: 5, iguanas: 7, zebras: 2, goats: 1 } - fromOriginal = { original & birds: 4, iguanas: 3 } + from_original = { original & birds: 4, iguanas: 3 } "# ), RocStr::from("4"), @@ -1133,11 +1133,11 @@ fn update_record_that_is_a_thunk_single_field() { r#" app "test" provides [main] to "./platform" - main = Num.toStr fromOriginal.birds + main = Num.to_str from_original.birds original = { birds: 5 } - fromOriginal = { original & birds: 4 } + from_original = { original & birds: 4 } "# ), RocStr::from("4"), diff --git a/crates/compiler/test_gen/src/gen_refcount.rs b/crates/compiler/test_gen/src/gen_refcount.rs index 0e50e1b2ca4..66b2249dbf6 100644 --- a/crates/compiler/test_gen/src/gen_refcount.rs +++ b/crates/compiler/test_gen/src/gen_refcount.rs @@ -39,7 +39,7 @@ fn str_dealloc() { r#" s = Str.concat "A long enough string " "to be heap-allocated" - Str.isEmpty s + Str.is_empty s "# ), bool, @@ -55,7 +55,7 @@ fn str_to_utf8() { r#" s = Str.concat "A long enough string " "to be heap-allocated" - Str.toUtf8 s + Str.to_utf8 s "# ), RocStr, @@ -73,8 +73,8 @@ fn str_from_utf8() { r#" s = Str.concat "A long enough string " "to be heap-allocated" - Str.toUtf8 s - |> Str.fromUtf8 + Str.to_utf8 s + |> Str.from_utf8 "# ), RocStr, @@ -92,7 +92,7 @@ fn str_to_utf8_dealloc() { r#" s = Str.concat "A long enough string " "to be heap-allocated" - Str.toUtf8 s + Str.to_utf8 s |> List.len "# ), @@ -185,7 +185,7 @@ fn list_str_drop_first() { r#" s = Str.concat "A long enough string " "to be heap-allocated" list = [s, s, s] - List.dropFirst list 1 + List.drop_first list 1 "# ), RocList>, @@ -206,7 +206,7 @@ fn list_str_take_first() { r#" s = Str.concat "A long enough string " "to be heap-allocated" list = [s, s, s] - List.takeFirst list 1 + List.take_first list 1 "# ), RocList>, @@ -226,7 +226,7 @@ fn list_str_split_on() { r#" s = Str.concat "A long enough string " "to be heap-allocated" list = [s, s, s] - List.splitAt list 1 + List.split_at list 1 "# ), (RocList, RocList), @@ -245,7 +245,7 @@ fn list_str_split_on_zero() { r#" s = Str.concat "A long enough string " "to be heap-allocated" list = [s, s, s] - List.splitAt list 0 + List.split_at list 0 "# ), (RocList, RocList), @@ -265,7 +265,7 @@ fn list_get() { s = Str.concat "A long enough string " "to be heap-allocated" i1 = [s, s, s] List.get i1 1 - |> Result.withDefault "" + |> Result.with_default "" "# ), RocStr, @@ -284,7 +284,7 @@ fn list_map() { r#" s = Str.concat "A long enough string " "to be heap-allocated" i1 = [s, s, s] - List.map i1 Str.toUtf8 + List.map i1 Str.to_utf8 "# ), RocList, @@ -304,7 +304,7 @@ fn list_map_dealloc() { r#" s = Str.concat "A long enough string " "to be heap-allocated" i1 = [s, s, s] - List.map i1 Str.toUtf8 + List.map i1 Str.to_utf8 |> List.len "# ), @@ -689,17 +689,17 @@ fn union_linked_list_long_dec() { LinkedList a : [Nil, Cons a (LinkedList a)] - prependOnes = \n, tail -> + prepend_ones = \n, tail -> if n == 0 then tail else - prependOnes (n-1) (Cons 1 tail) + prepend_ones (n-1) (Cons 1 tail) main = n = 1_000 linked : LinkedList I64 - linked = prependOnes n Nil + linked = prepend_ones n Nil when linked is Cons x _ -> x @@ -801,8 +801,8 @@ fn reset_reuse_alignment_8() { Val v -> v ZAdd l r -> eval l + eval r - constFolding : Expr -> Expr - constFolding = \e -> + const_folding : Expr -> Expr + const_folding = \e -> when e is ZAdd e1 e2 -> when Pair e1 e2 is @@ -817,7 +817,7 @@ fn reset_reuse_alignment_8() { expr = ZAdd (Val 4) (Val 5) main : I64 - main = eval (constFolding expr) + main = eval (const_folding expr) "# ), i64, @@ -837,8 +837,8 @@ fn basic_cli_parser() { r#" in = "d" - |> Str.toUtf8 - |> List.keepOks \c -> Str.fromUtf8 [c] + |> Str.to_utf8 + |> List.keep_oks \c -> Str.from_utf8 [c] out = when in is diff --git a/crates/compiler/test_gen/src/gen_result.rs b/crates/compiler/test_gen/src/gen_result.rs index f9160a73a09..e46045dff6f 100644 --- a/crates/compiler/test_gen/src/gen_result.rs +++ b/crates/compiler/test_gen/src/gen_result.rs @@ -21,7 +21,7 @@ fn with_default_ok() { result : Result I64 {} result = Ok 12345 - Result.withDefault result 0 + Result.with_default result 0 " ), 12345, @@ -38,7 +38,7 @@ fn with_default_err() { result : Result I64 {} result = Err {} - Result.withDefault result 0 + Result.with_default result 0 " ), 0, @@ -57,7 +57,7 @@ fn result_map() { result |> Result.map (\x -> x + 1) - |> Result.withDefault 0 + |> Result.with_default 0 " ), 3, @@ -72,7 +72,7 @@ fn result_map() { result |> Result.map (\x -> x + 1) - |> Result.withDefault 0 + |> Result.with_default 0 " ), 0, @@ -89,7 +89,7 @@ fn result_map_err() { result : Result {} I64 result = Err 2 - when Result.mapErr result (\x -> x + 1) is + when Result.map_err result (\x -> x + 1) is Err n -> n Ok _ -> 0 " @@ -104,7 +104,7 @@ fn result_map_err() { result : Result {} I64 result = Ok {} - when Result.mapErr result (\x -> x + 1) is + when Result.map_err result (\x -> x + 1) is Err n -> n Ok _ -> 0 " @@ -121,7 +121,7 @@ fn err_type_var() { indoc!( r" Result.map (Ok 3) (\x -> x + 1) - |> Result.withDefault -1 + |> Result.with_default -1 " ), 4, @@ -139,7 +139,7 @@ fn err_type_var_annotation() { ok = Ok 3 Result.map ok (\x -> x + 1) - |> Result.withDefault -1 + |> Result.with_default -1 " ), 4, @@ -157,7 +157,7 @@ fn err_empty_tag_union() { ok = Ok 3 Result.map ok (\x -> x + 1) - |> Result.withDefault -1 + |> Result.with_default -1 " ), 4, @@ -174,7 +174,7 @@ fn is_ok() { result : Result I64 {} result = Ok 2 - Result.isOk result + Result.is_ok result " ), true, @@ -187,7 +187,7 @@ fn is_ok() { result : Result I64 {} result = Err {} - Result.isOk result + Result.is_ok result " ), false, @@ -204,7 +204,7 @@ fn is_err() { result : Result I64 {} result = Ok 2 - Result.isErr result + Result.is_err result " ), false, @@ -217,7 +217,7 @@ fn is_err() { result : Result I64 {} result = Err {} - Result.isErr result + Result.is_err result " ), true, @@ -284,7 +284,7 @@ fn roc_result_err() { fn issue_2583_specialize_errors_behind_unified_branches() { assert_evals_to!( r#" - if Bool.true then List.first [15] else Str.toI64 "" + if Bool.true then List.first [15] else Str.to_i64 "" "#, RocResult::ok(15i64), RocResult @@ -331,7 +331,7 @@ fn roc_result_after_err() { r#" result : Result Str I64 result = - Result.onErr (Ok "already a string") \num -> + Result.on_err (Ok "already a string") \num -> if num < 0 then Ok "negative!" else Err -num result @@ -345,7 +345,7 @@ fn roc_result_after_err() { r#" result : Result Str I64 result = - Result.onErr (Err 100) \num -> + Result.on_err (Err 100) \num -> if num < 0 then Ok "negative!" else Err -num result @@ -364,7 +364,7 @@ fn roc_result_map_both() { result : Result I64 I64 result = Ok 42 - result |> Result.mapBoth Num.toStr Num.toStr + result |> Result.map_both Num.to_str Num.to_str "# ), RocResult::ok(RocStr::from("42")), @@ -377,7 +377,7 @@ fn roc_result_map_both() { result : Result I64 I64 result = Err 24 - result |> Result.mapBoth Num.toStr Num.toStr + result |> Result.map_both Num.to_str Num.to_str "# ), RocResult::err(RocStr::from("24")), diff --git a/crates/compiler/test_gen/src/gen_return.rs b/crates/compiler/test_gen/src/gen_return.rs index b35ac895a47..9b62fa45e2d 100644 --- a/crates/compiler/test_gen/src/gen_return.rs +++ b/crates/compiler/test_gen/src/gen_return.rs @@ -25,13 +25,13 @@ fn early_return_nested_ifs() { r#" app "test" provides [main] to "./platform" - displayN = \n -> - first = Num.toStr n + display_n = \n -> + first = Num.to_str n second = if n == 1 then return "early 1" else - third = Num.toStr (n + 1) + third = Num.to_str (n + 1) if n == 2 then return "early 2" else @@ -40,7 +40,7 @@ fn early_return_nested_ifs() { "$(first), $(second)" main : List Str - main = List.map [1, 2, 3] displayN + main = List.map [1, 2, 3] display_n "# ), RocList::from_slice(&[ @@ -60,15 +60,15 @@ fn early_return_nested_whens() { r#" app "test" provides [main] to "./platform" - displayN = \n -> - first = Num.toStr n + display_n = \n -> + first = Num.to_str n second = when n is 1 -> return "early 1" _ -> - third = Num.toStr (n + 1) + third = Num.to_str (n + 1) when n is 2 -> return "early 2" @@ -79,7 +79,7 @@ fn early_return_nested_whens() { "$(first), $(second)" main : List Str - main = List.map [1, 2, 3] displayN + main = List.map [1, 2, 3] display_n "# ), RocList::from_slice(&[ @@ -134,18 +134,18 @@ fn early_return_annotated_function() { r#" app "test" provides [main] to "./platform" - failIfLessThanFive : U64 -> Result {} [LessThanFive] - failIfLessThanFive = \n -> + fail_if_less_than_five : U64 -> Result {} [LessThanFive] + fail_if_less_than_five = \n -> if n < 5 then Err LessThanFive else Ok {} - validateInput : Str -> Result U64 [InvalidNumStr, LessThanFive] - validateInput = \str -> - num = try Str.toU64 str + validate_input : Str -> Result U64 [InvalidNumStr, LessThanFive] + validate_input = \str -> + num = try Str.to_u64 str - when failIfLessThanFive num is + when fail_if_less_than_five num is Err err -> return Err err @@ -155,8 +155,8 @@ fn early_return_annotated_function() { main : List Str main = ["abc", "3", "7"] - |> List.map validateInput - |> List.map Inspect.toStr + |> List.map validate_input + |> List.map Inspect.to_str "# ), RocList::from_slice(&[ @@ -176,18 +176,18 @@ fn early_return_nested_annotated_function() { r#" app "test" provides [main] to "./platform" - validateInput : Str -> Result U64 [InvalidNumStr, LessThanFive] - validateInput = \str -> - failIfLessThanFive : U64 -> Result {} [LessThanFive] - failIfLessThanFive = \n -> + validate_input : Str -> Result U64 [InvalidNumStr, LessThanFive] + validate_input = \str -> + fail_if_less_than_five : U64 -> Result {} [LessThanFive] + fail_if_less_than_five = \n -> if n < 5 then Err LessThanFive else Ok {} - num = try Str.toU64 str + num = try Str.to_u64 str - when failIfLessThanFive num is + when fail_if_less_than_five num is Err err -> return Err err @@ -197,8 +197,8 @@ fn early_return_nested_annotated_function() { main : List Str main = ["abc", "3", "7"] - |> List.map validateInput - |> List.map Inspect.toStr + |> List.map validate_input + |> List.map Inspect.to_str "# ), RocList::from_slice(&[ @@ -218,39 +218,39 @@ fn early_return_annotated_recursive_function() { r#" app "test" provides [main] to "./platform" - mightCallSecond : U64 -> Result U64 _ - mightCallSecond = \num -> - nextNum = + might_call_second : U64 -> Result U64 _ + might_call_second = \num -> + next_num = if num < 5 then return Err LessThanFive else num - 1 - mightCallFirst nextNum + might_call_first next_num - mightCallFirst : U64 -> Result U64 _ - mightCallFirst = \num -> - nextNum = + might_call_first : U64 -> Result U64 _ + might_call_first = \num -> + next_num = if num < 10 then return Err LessThanTen else num * 2 - if nextNum > 25 then - Ok nextNum + if next_num > 25 then + Ok next_num else - mightCallSecond nextNum + might_call_second next_num main : List Str main = [ - mightCallSecond 3, - mightCallSecond 7, - mightCallSecond 20, - mightCallFirst 7, - mightCallFirst 15, + might_call_second 3, + might_call_second 7, + might_call_second 20, + might_call_first 7, + might_call_first 15, ] - |> List.map Inspect.toStr + |> List.map Inspect.to_str "# ), RocList::from_slice(&[ diff --git a/crates/compiler/test_gen/src/gen_set.rs b/crates/compiler/test_gen/src/gen_set.rs index d3571ad965f..dd500f3384c 100644 --- a/crates/compiler/test_gen/src/gen_set.rs +++ b/crates/compiler/test_gen/src/gen_set.rs @@ -49,7 +49,7 @@ fn single_to_list() { assert_evals_to!( indoc!( r" - Set.toList (Set.single 42) + Set.to_list (Set.single 42) " ), RocList::from_slice(&[42]), @@ -59,7 +59,7 @@ fn single_to_list() { assert_evals_to!( indoc!( r" - Set.toList (Set.single 1) + Set.to_list (Set.single 1) " ), RocList::from_slice(&[1]), @@ -77,7 +77,7 @@ fn insert() { |> Set.insert 0 |> Set.insert 1 |> Set.insert 2 - |> Set.toList + |> Set.to_list " ), RocList::from_slice(&[0, 1, 2]), @@ -96,7 +96,7 @@ fn remove() { |> Set.insert 1 |> Set.remove 1 |> Set.remove 2 - |> Set.toList + |> Set.to_list " ), RocList::from_slice(&[0]), @@ -111,13 +111,13 @@ fn union() { indoc!( r" set1 : Set.Set I64 - set1 = Set.fromList [1,2] + set1 = Set.from_list [1,2] set2 : Set.Set I64 - set2 = Set.fromList [1,3,4] + set2 = Set.from_list [1,3,4] Set.union set1 set2 - |> Set.toList + |> Set.to_list " ), RocList::from_slice(&[1, 3, 4, 2]), @@ -132,13 +132,13 @@ fn difference() { indoc!( r" set1 : Set.Set I64 - set1 = Set.fromList [1,2] + set1 = Set.from_list [1,2] set2 : Set.Set I64 - set2 = Set.fromList [1,3,4] + set2 = Set.from_list [1,3,4] Set.difference set1 set2 - |> Set.toList + |> Set.to_list " ), RocList::from_slice(&[2]), @@ -153,13 +153,13 @@ fn intersection() { indoc!( r" set1 : Set.Set I64 - set1 = Set.fromList [1,2] + set1 = Set.from_list [1,2] set2 : Set.Set I64 - set2 = Set.fromList [1,3,4] + set2 = Set.from_list [1,3,4] Set.intersection set1 set2 - |> Set.toList + |> Set.to_list " ), RocList::from_slice(&[1]), @@ -173,7 +173,7 @@ fn walk_sum() { assert_evals_to!( indoc!( r" - Set.walk (Set.fromList [1,2,3]) 0 (\x, y -> x + y) + Set.walk (Set.from_list [1,2,3]) 0 (\x, y -> x + y) " ), 6, @@ -187,7 +187,7 @@ fn contains() { assert_evals_to!( indoc!( r" - Set.contains (Set.fromList [1,3,4]) 4 + Set.contains (Set.from_list [1,3,4]) 4 " ), true, @@ -197,7 +197,7 @@ fn contains() { assert_evals_to!( indoc!( r" - Set.contains (Set.fromList [1,3,4]) 2 + Set.contains (Set.from_list [1,3,4]) 2 " ), false, @@ -212,8 +212,8 @@ fn from_list() { indoc!( r" [1,2,2,3,1,4] - |> Set.fromList - |> Set.toList + |> Set.from_list + |> Set.to_list " ), RocList::from_slice(&[1, 2, 3, 4]), @@ -227,8 +227,8 @@ fn from_list() { empty = [] empty - |> Set.fromList - |> Set.toList + |> Set.from_list + |> Set.to_list " ), RocList::::default(), @@ -244,8 +244,8 @@ fn from_list_void() { indoc!( r" [] - |> Set.fromList - |> Set.toList + |> Set.from_list + |> Set.to_list " ), RocList::::default(), @@ -259,7 +259,7 @@ fn to_list_empty() { assert_evals_to!( indoc!( r" - Set.toList (Set.empty {}) + Set.to_list (Set.empty {}) " ), RocList::::default(), @@ -277,10 +277,10 @@ fn from_list_result() { x = Ok "foo" [x] - |> Set.fromList - |> Set.toList + |> Set.from_list + |> Set.to_list |> List.len - |> Num.toI64 + |> Num.to_i64 "# ), 1, @@ -298,10 +298,10 @@ fn resolve_set_eq_issue_4671() { main = s1 : Set U8 - s1 = Set.fromList [1, 2, 3] + s1 = Set.from_list [1, 2, 3] s2 : Set U8 - s2 = Set.fromList [3, 2, 1] + s2 = Set.from_list [3, 2, 1] s1 == s2 "# diff --git a/crates/compiler/test_gen/src/gen_str.rs b/crates/compiler/test_gen/src/gen_str.rs index f50e72104c5..1533bcf3128 100644 --- a/crates/compiler/test_gen/src/gen_str.rs +++ b/crates/compiler/test_gen/src/gen_str.rs @@ -55,7 +55,7 @@ fn str_split_on_empty_delimiter() { assert_evals_to!( indoc!( r#" - List.len (Str.splitOn "hello" "") + List.len (Str.split_on "hello" "") "# ), 1, @@ -65,9 +65,9 @@ fn str_split_on_empty_delimiter() { assert_evals_to!( indoc!( r#" - when List.first (Str.splitOn "JJJ" "") is + when List.first (Str.split_on "JJJ" "") is Ok str -> - Str.countUtf8Bytes str + Str.count_utf8_bytes str _ -> 1729 @@ -85,7 +85,7 @@ fn str_split_on_bigger_delimiter_small_str() { assert_evals_to!( indoc!( r#" - List.len (Str.splitOn "hello" "JJJJ there") + List.len (Str.split_on "hello" "JJJJ there") "# ), 1, @@ -95,9 +95,9 @@ fn str_split_on_bigger_delimiter_small_str() { assert_evals_to!( indoc!( r#" - when List.first (Str.splitOn "JJJ" "JJJJ there") is + when List.first (Str.split_on "JJJ" "JJJJ there") is Ok str -> - Str.countUtf8Bytes str + Str.count_utf8_bytes str _ -> 1729 @@ -115,7 +115,7 @@ fn str_split_on_str_concat_repeated() { assert_evals_to!( indoc!( r#" - when List.first (Str.splitOn "JJJJJ" "JJJJ there") is + when List.first (Str.split_on "JJJJJ" "JJJJ there") is Ok str -> str |> Str.concat str @@ -137,7 +137,7 @@ fn str_split_on_str_concat_repeated() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_split_on_small_str_bigger_delimiter() { assert_evals_to!( - indoc!(r#"Str.splitOn "JJJ" "0123456789abcdefghi""#), + indoc!(r#"Str.split_on "JJJ" "0123456789abcdefghi""#), RocList::from_slice(&[RocStr::from("JJJ")]), RocList ); @@ -149,7 +149,7 @@ fn str_split_on_big_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "01234567789abcdefghi?01234567789abcdefghi" "?" + Str.split_on "01234567789abcdefghi?01234567789abcdefghi" "?" "# ), RocList::from_slice(&[ @@ -162,7 +162,7 @@ fn str_split_on_big_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "01234567789abcdefghi 3ch 01234567789abcdefghi" "3ch" + Str.split_on "01234567789abcdefghi 3ch 01234567789abcdefghi" "3ch" "# ), RocList::from_slice(&[ @@ -179,7 +179,7 @@ fn str_split_on_small_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "J!J!J" "!" + Str.split_on "J!J!J" "!" "# ), RocList::from_slice(&[RocStr::from("J"), RocStr::from("J"), RocStr::from("J")]), @@ -193,7 +193,7 @@ fn str_split_on_bigger_delimiter_big_strs() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "string to split is shorter" "than the delimiter which happens to be very very long" "# @@ -209,7 +209,7 @@ fn str_split_on_empty_strs() { assert_evals_to!( indoc!( r#" - Str.splitOn "" "" + Str.split_on "" "" "# ), RocList::from_slice(&[RocStr::from("")]), @@ -223,7 +223,7 @@ fn str_split_on_minimal_example() { assert_evals_to!( indoc!( r#" - Str.splitOn "a," "," + Str.split_on "a," "," "# ), RocList::from_slice(&[RocStr::from("a"), RocStr::from("")]), @@ -237,7 +237,7 @@ fn str_split_on_small_str_big_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "1---- ---- ---- ---- ----2---- ---- ---- ---- ----" "---- ---- ---- ---- ----" |> List.len @@ -250,7 +250,7 @@ fn str_split_on_small_str_big_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "1---- ---- ---- ---- ----2---- ---- ---- ---- ----" "---- ---- ---- ---- ----" "# @@ -266,7 +266,7 @@ fn str_split_on_small_str_20_char_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "3|-- -- -- -- -- -- |4|-- -- -- -- -- -- |" "|-- -- -- -- -- -- |" "# @@ -499,14 +499,14 @@ fn str_concat_empty() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn small_str_is_empty() { - assert_evals_to!(r#"Str.isEmpty "abc""#, false, bool); + assert_evals_to!(r#"Str.is_empty "abc""#, false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn big_str_is_empty() { assert_evals_to!( - r#"Str.isEmpty "this is more than 23 chars long""#, + r#"Str.is_empty "this is more than 23 chars long""#, false, bool ); @@ -515,32 +515,32 @@ fn big_str_is_empty() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn empty_str_is_empty() { - assert_evals_to!(r#"Str.isEmpty """#, true, bool); + assert_evals_to!(r#"Str.is_empty """#, true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with() { - assert_evals_to!(r#"Str.startsWith "hello world" "hell""#, true, bool); - assert_evals_to!(r#"Str.startsWith "hello world" """#, true, bool); - assert_evals_to!(r#"Str.startsWith "nope" "hello world""#, false, bool); - assert_evals_to!(r#"Str.startsWith "hell" "hello world""#, false, bool); - assert_evals_to!(r#"Str.startsWith "" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "hello world" "hell""#, true, bool); + assert_evals_to!(r#"Str.starts_with "hello world" """#, true, bool); + assert_evals_to!(r#"Str.starts_with "nope" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "hell" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "" "hello world""#, false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_ends_with() { - assert_evals_to!(r#"Str.endsWith "hello world" "world""#, true, bool); - assert_evals_to!(r#"Str.endsWith "nope" "hello world""#, false, bool); - assert_evals_to!(r#"Str.endsWith "" "hello world""#, false, bool); + assert_evals_to!(r#"Str.ends_with "hello world" "world""#, true, bool); + assert_evals_to!(r#"Str.ends_with "nope" "hello world""#, false, bool); + assert_evals_to!(r#"Str.ends_with "" "hello world""#, false, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with_same_big_str() { assert_evals_to!( - r#"Str.startsWith "123456789123456789" "123456789123456789""#, + r#"Str.starts_with "123456789123456789" "123456789123456789""#, true, bool ); @@ -550,7 +550,7 @@ fn str_starts_with_same_big_str() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with_different_big_str() { assert_evals_to!( - r#"Str.startsWith "12345678912345678910" "123456789123456789""#, + r#"Str.starts_with "12345678912345678910" "123456789123456789""#, true, bool ); @@ -559,18 +559,18 @@ fn str_starts_with_different_big_str() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with_same_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "1234""#, true, bool); + assert_evals_to!(r#"Str.starts_with "1234" "1234""#, true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with_different_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "12""#, true, bool); + assert_evals_to!(r#"Str.starts_with "1234" "12""#, true, bool); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_starts_with_false_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "23""#, false, bool); + assert_evals_to!(r#"Str.starts_with "1234" "23""#, false, bool); } #[test] @@ -579,7 +579,7 @@ fn str_from_utf8_pass_single_ascii() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97] is + when Str.from_utf8 [97] is Ok val -> val Err _ -> "" "# @@ -595,7 +595,7 @@ fn str_from_utf8_pass_many_ascii() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0x7E] is + when Str.from_utf8 [97, 98, 99, 0x7E] is Ok val -> val Err _ -> "" "# @@ -611,7 +611,7 @@ fn str_from_utf8_pass_single_unicode() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xE2, 0x88, 0x86] is + when Str.from_utf8 [0xE2, 0x88, 0x86] is Ok val -> val Err _ -> "" "# @@ -627,7 +627,7 @@ fn str_from_utf8_pass_many_unicode() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xE2, 0x88, 0x86, 0xC5, 0x93, 0xC2, 0xAC] is + when Str.from_utf8 [0xE2, 0x88, 0x86, 0xC5, 0x93, 0xC2, 0xAC] is Ok val -> val Err _ -> "" "# @@ -643,7 +643,7 @@ fn str_from_utf8_pass_single_grapheme() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96] is Ok val -> val Err _ -> "" "# @@ -659,7 +659,7 @@ fn str_from_utf8_pass_many_grapheme() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96, 0xF0, 0x9F, 0xA4, 0xA0, 0xF0, 0x9F, 0x9A, 0x80] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96, 0xF0, 0x9F, 0xA4, 0xA0, 0xF0, 0x9F, 0x9A, 0x80] is Ok val -> val Err _ -> "" "# @@ -675,7 +675,7 @@ fn str_from_utf8_pass_all() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96, 98, 0xE2, 0x88, 0x86] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96, 98, 0xE2, 0x88, 0x86] is Ok val -> val Err _ -> "" "# @@ -691,9 +691,9 @@ fn str_from_utf8_fail_invalid_start_byte() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 0x80, 99] is - Err (BadUtf8 InvalidStartByte byteIndex) -> - if byteIndex == 2 then + when Str.from_utf8 [97, 98, 0x80, 99] is + Err (BadUtf8 InvalidStartByte byte_index) -> + if byte_index == 2 then "a" else "b" @@ -711,9 +711,9 @@ fn str_from_utf8_fail_unexpected_end_of_sequence() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0xC2] is - Err (BadUtf8 UnexpectedEndOfSequence byteIndex) -> - if byteIndex == 3 then + when Str.from_utf8 [97, 98, 99, 0xC2] is + Err (BadUtf8 UnexpectedEndOfSequence byte_index) -> + if byte_index == 3 then "a" else "b" @@ -731,9 +731,9 @@ fn str_from_utf8_fail_expected_continuation() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0xC2, 0x00] is - Err (BadUtf8 ExpectedContinuation byteIndex) -> - if byteIndex == 3 then + when Str.from_utf8 [97, 98, 99, 0xC2, 0x00] is + Err (BadUtf8 ExpectedContinuation byte_index) -> + if byte_index == 3 then "a" else "b" @@ -751,9 +751,9 @@ fn str_from_utf8_fail_overlong_encoding() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 0xF0, 0x80, 0x80, 0x80] is - Err (BadUtf8 OverlongEncoding byteIndex) -> - if byteIndex == 1 then + when Str.from_utf8 [97, 0xF0, 0x80, 0x80, 0x80] is + Err (BadUtf8 OverlongEncoding byte_index) -> + if byte_index == 1 then "a" else "b" @@ -771,9 +771,9 @@ fn str_from_utf8_fail_codepoint_too_large() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 0xF4, 0x90, 0x80, 0x80] is - Err (BadUtf8 CodepointTooLarge byteIndex) -> - if byteIndex == 1 then + when Str.from_utf8 [97, 0xF4, 0x90, 0x80, 0x80] is + Err (BadUtf8 CodepointTooLarge byte_index) -> + if byte_index == 1 then "a" else "b" @@ -791,9 +791,9 @@ fn str_from_utf8_fail_surrogate_half() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 0xED, 0xA0, 0x80] is - Err (BadUtf8 EncodesSurrogateHalf byteIndex) -> - if byteIndex == 2 then + when Str.from_utf8 [97, 98, 0xED, 0xA0, 0x80] is + Err (BadUtf8 EncodesSurrogateHalf byte_index) -> + if byte_index == 2 then "a" else "b" @@ -841,19 +841,19 @@ fn nested_recursive_literal() { expr : Expr expr = Add (Add (Val 3) (Val 1)) (Add (Val 1) (Var 1)) - printExpr : Expr -> Str - printExpr = \e -> + print_expr : Expr -> Str + print_expr = \e -> when e is Add a b -> "Add (" - |> Str.concat (printExpr a) + |> Str.concat (print_expr a) |> Str.concat ") (" - |> Str.concat (printExpr b) + |> Str.concat (print_expr b) |> Str.concat ")" - Val v -> "Val " |> Str.concat (Num.toStr v) - Var v -> "Var " |> Str.concat (Num.toStr v) + Val v -> "Val " |> Str.concat (Num.to_str v) + Var v -> "Var " |> Str.concat (Num.to_str v) - printExpr expr + print_expr expr "# ), RocStr::from("Add (Add (Val 3) (Val 1)) (Add (Val 1) (Var 1))"), @@ -865,7 +865,7 @@ fn nested_recursive_literal() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_join_comma_small() { assert_evals_to!( - r#"Str.joinWith ["1", "2"] ", " "#, + r#"Str.join_with ["1", "2"] ", " "#, RocStr::from("1, 2"), RocStr ); @@ -875,7 +875,7 @@ fn str_join_comma_small() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_join_comma_big() { assert_evals_to!( - r#"Str.joinWith ["10000000", "2000000", "30000000"] ", " "#, + r#"Str.join_with ["10000000", "2000000", "30000000"] ", " "#, RocStr::from("10000000, 2000000, 30000000"), RocStr ); @@ -884,19 +884,19 @@ fn str_join_comma_big() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_join_comma_single() { - assert_evals_to!(r#"Str.joinWith ["1"] ", " "#, RocStr::from("1"), RocStr); + assert_evals_to!(r#"Str.join_with ["1"] ", " "#, RocStr::from("1"), RocStr); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_to_utf8() { assert_evals_to!( - r#"Str.toUtf8 "hello""#, + r#"Str.to_utf8 "hello""#, RocList::from_slice(&[104, 101, 108, 108, 111]), RocList ); assert_evals_to!( - r#"Str.toUtf8 "this is a long string""#, + r#"Str.to_utf8 "this is a long string""#, RocList::from_slice(&[ 116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 108, 111, 110, 103, 32, 115, 116, 114, 105, 110, 103 @@ -912,10 +912,10 @@ fn str_from_utf8() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -931,11 +931,11 @@ fn str_from_utf8_slice() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 4 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -951,11 +951,11 @@ fn str_from_utf8_slice_not_end() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 3 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -971,12 +971,12 @@ fn str_from_utf8_order_does_not_matter() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 3 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String - Err _ -> "Str.fromUtf8 returned Err instead of Ok!" + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string + Err _ -> "Str.from_utf8 returned Err instead of Ok!" "# ), RocStr::from("ell"), @@ -1139,14 +1139,14 @@ fn str_trim_small_to_small_shared() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_start_small_blank_string() { - assert_evals_to!(indoc!(r#"Str.trimStart " ""#), RocStr::from(""), RocStr); + assert_evals_to!(indoc!(r#"Str.trim_start " ""#), RocStr::from(""), RocStr); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_start_small_to_small() { assert_evals_to!( - indoc!(r#"Str.trimStart " hello world ""#), + indoc!(r#"Str.trim_start " hello world ""#), RocStr::from("hello world "), RocStr ); @@ -1156,7 +1156,7 @@ fn str_trim_start_small_to_small() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_start_large_to_large_unique() { assert_evals_to!( - indoc!(r#"Str.trimStart (Str.concat " " "hello world from a large string ")"#), + indoc!(r#"Str.trim_start (Str.concat " " "hello world from a large string ")"#), RocStr::from("hello world from a large string "), RocStr ); @@ -1166,7 +1166,7 @@ fn str_trim_start_large_to_large_unique() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_start_large_to_small_unique() { assert_evals_to!( - indoc!(r#"Str.trimStart (Str.concat " " "hello world ")"#), + indoc!(r#"Str.trim_start (Str.concat " " "hello world ")"#), RocStr::from("hello world "), RocStr ); @@ -1181,7 +1181,7 @@ fn str_trim_start_large_to_large_shared() { original : Str original = " hello world world " - { trimmed: Str.trimStart original, original: original } + { trimmed: Str.trim_start original, original: original } "# ), ( @@ -1201,7 +1201,7 @@ fn str_trim_start_large_to_small_shared() { original : Str original = " hello world " - { trimmed: Str.trimStart original, original: original } + { trimmed: Str.trim_start original, original: original } "# ), ( @@ -1221,7 +1221,7 @@ fn str_trim_start_small_to_small_shared() { original : Str original = " hello world " - { trimmed: Str.trimStart original, original: original } + { trimmed: Str.trim_start original, original: original } "# ), (RocStr::from(" hello world "), RocStr::from("hello world "),), @@ -1232,14 +1232,14 @@ fn str_trim_start_small_to_small_shared() { #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_end_small_blank_string() { - assert_evals_to!(indoc!(r#"Str.trimEnd " ""#), RocStr::from(""), RocStr); + assert_evals_to!(indoc!(r#"Str.trim_end " ""#), RocStr::from(""), RocStr); } #[test] #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_end_small_to_small() { assert_evals_to!( - indoc!(r#"Str.trimEnd " hello world ""#), + indoc!(r#"Str.trim_end " hello world ""#), RocStr::from(" hello world"), RocStr ); @@ -1249,7 +1249,7 @@ fn str_trim_end_small_to_small() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_end_large_to_large_unique() { assert_evals_to!( - indoc!(r#"Str.trimEnd (Str.concat " hello world from a large string" " ")"#), + indoc!(r#"Str.trim_end (Str.concat " hello world from a large string" " ")"#), RocStr::from(" hello world from a large string"), RocStr ); @@ -1259,7 +1259,7 @@ fn str_trim_end_large_to_large_unique() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_trim_end_large_to_small_unique() { assert_evals_to!( - indoc!(r#"Str.trimEnd (Str.concat " hello world" " ")"#), + indoc!(r#"Str.trim_end (Str.concat " hello world" " ")"#), RocStr::from(" hello world"), RocStr ); @@ -1274,7 +1274,7 @@ fn str_trim_end_large_to_large_shared() { original : Str original = " hello world world " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), ( @@ -1294,7 +1294,7 @@ fn str_trim_end_large_to_small_shared() { original : Str original = " hello world " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), ( @@ -1314,7 +1314,7 @@ fn str_trim_end_small_to_small_shared() { original : Str original = " hello world " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), (RocStr::from(" hello world "), RocStr::from(" hello world"),), @@ -1328,7 +1328,7 @@ fn str_to_nat() { assert_evals_to!( indoc!( r#" - Str.toU64 "1" + Str.to_u64 "1" "# ), RocResult::ok(1), @@ -1342,7 +1342,7 @@ fn str_to_i128() { assert_evals_to!( indoc!( r#" - Str.toI128 "1" + Str.to_i128 "1" "# ), RocResult::ok(I128::from(1)), @@ -1356,7 +1356,7 @@ fn str_to_u128() { assert_evals_to!( indoc!( r#" - Str.toU128 "1" + Str.to_u128 "1" "# ), RocResult::ok(U128::from(1)), @@ -1371,7 +1371,7 @@ fn str_to_i64() { assert_evals_to!( indoc!( r#" - Str.toI64 "1" + Str.to_i64 "1" "# ), RocResult::ok(1), @@ -1385,7 +1385,7 @@ fn str_to_u64() { assert_evals_to!( indoc!( r#" - Str.toU64 "1" + Str.to_u64 "1" "# ), RocResult::ok(1), @@ -1399,7 +1399,7 @@ fn str_to_i32() { assert_evals_to!( indoc!( r#" - Str.toI32 "1" + Str.to_i32 "1" "# ), RocResult::ok(1), @@ -1413,7 +1413,7 @@ fn str_to_u32() { assert_evals_to!( indoc!( r#" - Str.toU32 "1" + Str.to_u32 "1" "# ), RocResult::ok(1), @@ -1427,7 +1427,7 @@ fn str_to_i16() { assert_evals_to!( indoc!( r#" - Str.toI16 "1" + Str.to_i16 "1" "# ), RocResult::ok(1), @@ -1441,7 +1441,7 @@ fn str_to_u16() { assert_evals_to!( indoc!( r#" - Str.toU16 "1" + Str.to_u16 "1" "# ), RocResult::ok(1), @@ -1455,7 +1455,7 @@ fn str_to_i8() { assert_evals_to!( indoc!( r#" - Str.toI8 "1" + Str.to_i8 "1" "# ), RocResult::ok(1), @@ -1469,7 +1469,7 @@ fn str_to_u8() { assert_evals_to!( indoc!( r#" - Str.toU8 "1" + Str.to_u8 "1" "# ), RocResult::ok(1), @@ -1483,7 +1483,7 @@ fn str_to_f64() { assert_evals_to!( indoc!( r#" - when Str.toF64 "1.0" is + when Str.to_f64 "1.0" is Ok n -> n Err _ -> 0 @@ -1500,7 +1500,7 @@ fn str_to_f32() { assert_evals_to!( indoc!( r#" - when Str.toF32 "1.0" is + when Str.to_f32 "1.0" is Ok n -> n Err _ -> 0 @@ -1519,7 +1519,7 @@ fn str_to_dec() { assert_evals_to!( indoc!( r#" - when Str.toDec "1.0" is + when Str.to_dec "1.0" is Ok n -> n Err _ -> 0 @@ -1552,7 +1552,7 @@ fn str_split_on_first_one_char() { assert_evals_to!( indoc!( r#" - Str.splitFirst "foo/bar/baz" "/" + Str.split_first "foo/bar/baz" "/" "# ), // the result is a { before, after } record, and because of @@ -1568,7 +1568,7 @@ fn str_split_on_first_multiple_chars() { assert_evals_to!( indoc!( r#" - Str.splitFirst "foo//bar//baz" "//" + Str.split_first "foo//bar//baz" "//" "# ), RocResult::ok((RocStr::from("bar//baz"), RocStr::from("foo"))), @@ -1582,7 +1582,7 @@ fn str_split_on_first_entire_input() { assert_evals_to!( indoc!( r#" - Str.splitFirst "foo" "foo" + Str.split_first "foo" "foo" "# ), RocResult::ok((RocStr::from(""), RocStr::from(""))), @@ -1596,7 +1596,7 @@ fn str_split_on_first_not_found() { assert_evals_to!( indoc!( r#" - Str.splitFirst "foo" "bar" + Str.split_first "foo" "bar" "# ), RocResult::err(()), @@ -1610,7 +1610,7 @@ fn str_split_on_last_one_char() { assert_evals_to!( indoc!( r#" - Str.splitLast"foo/bar/baz" "/" + Str.split_last "foo/bar/baz" "/" "# ), RocResult::ok((RocStr::from("baz"), RocStr::from("foo/bar"))), @@ -1624,7 +1624,7 @@ fn str_split_on_last_multiple_chars() { assert_evals_to!( indoc!( r#" - Str.splitLast "foo//bar//baz" "//" + Str.split_last "foo//bar//baz" "//" "# ), RocResult::ok((RocStr::from("baz"), RocStr::from("foo//bar"))), @@ -1638,7 +1638,7 @@ fn str_split_on_last_entire_input() { assert_evals_to!( indoc!( r#" - Str.splitLast "foo" "foo" + Str.split_last "foo" "foo" "# ), RocResult::ok((RocStr::from(""), RocStr::from(""))), @@ -1652,7 +1652,7 @@ fn str_split_on_last_not_found() { assert_evals_to!( indoc!( r#" - Str.splitLast "foo" "bar" + Str.split_last "foo" "bar" "# ), RocResult::err(()), @@ -1664,7 +1664,7 @@ fn str_split_on_last_not_found() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_split_on_overlapping_substring_1() { assert_evals_to!( - r#"Str.splitOn "aaa" "aa""#, + r#"Str.split_on "aaa" "aa""#, RocList::from_slice(&[RocStr::from(""), RocStr::from("a")]), RocList ); @@ -1674,7 +1674,7 @@ fn str_split_on_overlapping_substring_1() { #[cfg(any(feature = "gen-llvm", feature = "gen-dev"))] fn str_split_on_overlapping_substring_2() { assert_evals_to!( - r#"Str.splitOn "aaaa" "aa""#, + r#"Str.split_on "aaaa" "aa""#, RocList::from_slice(&[RocStr::from(""), RocStr::from(""), RocStr::from("")]), RocList ); @@ -1688,7 +1688,7 @@ fn str_walk_utf8() { // Reverse the bytes indoc!( r#" - Str.walkUtf8 "abcd" [] (\list, byte -> List.prepend list byte) + Str.walk_utf8 "abcd" [] (\list, byte -> List.prepend list byte) "# ), RocList::from_slice(&[b'd', b'c', b'b', b'a']), @@ -1699,7 +1699,7 @@ fn str_walk_utf8() { assert_evals_to!( indoc!( r#" - Str.walkUtf8 "abcd" [] (\list, byte -> List.prepend list byte) + Str.walk_utf8 "abcd" [] (\list, byte -> List.prepend list byte) "# ), RocList::from_slice(&[b'd', b'c', b'b', b'a']), @@ -1713,7 +1713,7 @@ fn str_walk_utf8_with_index() { assert_evals_to!( indoc!( r#" - Str.walkUtf8WithIndex "abcd" [] (\list, byte, index -> List.append list (Pair index byte)) + Str.walk_utf8_with_index "abcd" [] (\list, byte, index -> List.append list (Pair index byte)) "# ), RocList::from_slice(&[(0, b'a'), (1, b'b'), (2, b'c'), (3, b'd')]), @@ -1792,7 +1792,7 @@ fn with_capacity() { assert_evals_to!( indoc!( r#" - Str.withCapacity 10 + Str.with_capacity 10 "# ), RocStr::from(""), @@ -1806,7 +1806,7 @@ fn with_capacity_concat() { assert_evals_to!( indoc!( r#" - Str.withCapacity 10 |> Str.concat "Forty-two" + Str.with_capacity 10 |> Str.concat "Forty-two" "# ), RocStr::from("Forty-two"), @@ -1820,7 +1820,7 @@ fn str_with_prefix() { assert_evals_to!( indoc!( r#" - Str.withPrefix "world!" "Hello " + Str.with_prefix "world!" "Hello " "# ), RocStr::from("Hello world!"), @@ -1830,7 +1830,7 @@ fn str_with_prefix() { assert_evals_to!( indoc!( r#" - "two" |> Str.withPrefix "Forty " + "two" |> Str.with_prefix "Forty " "# ), RocStr::from("Forty two"), @@ -1888,7 +1888,7 @@ fn release_excess_capacity() { indoc!( r#" Str.reserve "" 50 - |> Str.releaseExcessCapacity + |> Str.release_excess_capacity "# ), (RocStr::empty().capacity(), RocStr::empty()), @@ -1905,7 +1905,7 @@ fn release_excess_capacity_with_len() { r#" "123456789012345678901234567890" |> Str.reserve 50 - |> Str.releaseExcessCapacity + |> Str.release_excess_capacity "# ), (30, "123456789012345678901234567890".into()), @@ -1920,7 +1920,7 @@ fn release_excess_capacity_empty() { assert_evals_to!( indoc!( r#" - Str.releaseExcessCapacity "" + Str.release_excess_capacity "" "# ), (RocStr::empty().capacity(), RocStr::empty()), @@ -1994,7 +1994,7 @@ fn str_contains_self() { fn str_drop_prefix() { assert_evals_to!( r#" - Str.dropPrefix "" "foo" + Str.drop_prefix "" "foo" "#, RocStr::from(""), RocStr @@ -2002,7 +2002,7 @@ fn str_drop_prefix() { assert_evals_to!( r#" - Str.dropPrefix "bar" "foo" + Str.drop_prefix "bar" "foo" "#, RocStr::from("bar"), RocStr @@ -2010,7 +2010,7 @@ fn str_drop_prefix() { assert_evals_to!( r#" - Str.dropPrefix "foobar" "foo" + Str.drop_prefix "foobar" "foo" "#, RocStr::from("bar"), RocStr @@ -2018,7 +2018,7 @@ fn str_drop_prefix() { assert_evals_to!( r#" - Str.dropPrefix "fooBarThisIsDefinitelyAReallyLongAndNotaShortString" "foo" + Str.drop_prefix "fooBarThisIsDefinitelyAReallyLongAndNotaShortString" "foo" "#, RocStr::from("BarThisIsDefinitelyAReallyLongAndNotaShortString"), RocStr @@ -2030,7 +2030,7 @@ fn str_drop_prefix() { fn str_drop_suffix() { assert_evals_to!( r#" - Str.dropSuffix "" "foo" + Str.drop_suffix "" "foo" "#, RocStr::from(""), RocStr @@ -2038,7 +2038,7 @@ fn str_drop_suffix() { assert_evals_to!( r#" - Str.dropSuffix "bar" "foo" + Str.drop_suffix "bar" "foo" "#, RocStr::from("bar"), RocStr @@ -2046,7 +2046,7 @@ fn str_drop_suffix() { assert_evals_to!( r#" - Str.dropSuffix "barfoo" "foo" + Str.drop_suffix "barfoo" "foo" "#, RocStr::from("bar"), RocStr @@ -2054,7 +2054,7 @@ fn str_drop_suffix() { assert_evals_to!( r#" - Str.dropSuffix "BarThisIsDefinitelyAReallyLongAndNotaShortStringfoo" "foo" + Str.drop_suffix "BarThisIsDefinitelyAReallyLongAndNotaShortStringfoo" "foo" "#, RocStr::from("BarThisIsDefinitelyAReallyLongAndNotaShortString"), RocStr diff --git a/crates/compiler/test_gen/src/gen_tags.rs b/crates/compiler/test_gen/src/gen_tags.rs index df25fae4460..71611fb1df9 100644 --- a/crates/compiler/test_gen/src/gen_tags.rs +++ b/crates/compiler/test_gen/src/gen_tags.rs @@ -349,14 +349,14 @@ fn maybe_is_just_not_nested() { Maybe a : [Just a, Nothing] - isJust : Maybe a -> Bool - isJust = \list -> + is_just : Maybe a -> Bool + is_just = \list -> when list is Nothing -> Bool.false Just _ -> Bool.true main = - isJust (Just 42) + is_just (Just 42) "# ), true, @@ -372,13 +372,13 @@ fn maybe_is_just_nested() { r" Maybe a : [Just a, Nothing] - isJust : Maybe a -> Bool - isJust = \list -> + is_just : Maybe a -> Bool + is_just = \list -> when list is Nothing -> Bool.false Just _ -> Bool.true - isJust (Just 42) + is_just (Just 42) " ), true, @@ -415,7 +415,7 @@ fn if_guard_vanilla() { r#" when "fooz" is s if s == "foo" -> [] - s -> Str.toUtf8 s + s -> Str.to_utf8 s "# ), RocList::from_slice(b"fooz"), @@ -1078,7 +1078,7 @@ fn applied_tag_function_result() { x : List (Result Str *) x = List.map ["a", "b"] Ok - List.keepOks x (\y -> y) + List.keep_oks x (\y -> y) "# ), RocList::from_slice(&[(RocStr::from("a")), (RocStr::from("b"))]), @@ -1217,19 +1217,19 @@ fn monomorphized_tag_with_polymorphic_arg() { a = \{} -> A wrap = \{} -> Wrapped (a {}) - useWrap1 : [Wrapped [A], Other] -> U8 - useWrap1 = + use_wrap1 : [Wrapped [A], Other] -> U8 + use_wrap1 = \w -> when w is Wrapped A -> 2 Other -> 3 - useWrap2 : [Wrapped [A, B]] -> U8 - useWrap2 = + use_wrap2 : [Wrapped [A, B]] -> U8 + use_wrap2 = \w -> when w is Wrapped A -> 5 Wrapped B -> 7 - if Bool.true then useWrap1 (wrap {}) else useWrap2 (wrap {}) + if Bool.true then use_wrap1 (wrap {}) else use_wrap2 (wrap {}) "# ), 2, @@ -1251,19 +1251,19 @@ fn monomorphized_tag_with_polymorphic_and_monomorphic_arg() { poly = \{} -> A wrap = \{} -> Wrapped (poly {}) mono - useWrap1 : [Wrapped [A] U8, Other] -> U8 - useWrap1 = + use_wrap1 : [Wrapped [A] U8, Other] -> U8 + use_wrap1 = \w -> when w is Wrapped A n -> n Other -> 0 - useWrap2 : [Wrapped [A, B] U8] -> U8 - useWrap2 = + use_wrap2 : [Wrapped [A, B] U8] -> U8 + use_wrap2 = \w -> when w is Wrapped A n -> n Wrapped B _ -> 0 - useWrap1 (wrap {}) * useWrap2 (wrap {}) + use_wrap1 (wrap {}) * use_wrap2 (wrap {}) "# ), 225, @@ -1443,8 +1443,8 @@ fn issue_1162() { balance : a, RBTree a -> RBTree a balance = \key, left -> when left is - Node _ _ lRight -> - Node key lRight Empty + Node _ _ l_right -> + Node key l_right Empty _ -> Empty @@ -1489,8 +1489,8 @@ fn issue_2725_alias_polymorphic_lambda() { indoc!( r" wrap = \value -> Tag value - wrapIt = wrap - wrapIt 42 + wrap_it = wrap + wrap_it 42 " ), 42, // Tag is a newtype, it gets unwrapped @@ -1508,12 +1508,12 @@ fn opaque_assign_to_symbol() { Variable := U8 - fromUtf8 : U8 -> Result Variable [InvalidVariableUtf8] - fromUtf8 = \char -> + from_utf8 : U8 -> Result Variable [InvalidVariableUtf8] + from_utf8 = \char -> Ok (@Variable char) out = - when fromUtf8 98 is + when from_utf8 98 is Ok (@Variable n) -> n _ -> 1 "# @@ -1616,9 +1616,9 @@ fn issue_3261_non_nullable_unwrapped_recursive_union_at_index() { foo : Named foo = Named "outer" [Named "inner" []] - Named name outerList = foo + Named name outer_list = foo - {name, outerList}.name + {name, outer_list}.name "# ), RocStr::from("outer"), @@ -1888,7 +1888,7 @@ fn issue_2165_recursive_tag_destructure() { x = Ctor { rec: [] } when x is - Ctor { rec } -> Num.toStr (List.len rec) + Ctor { rec } -> Num.to_str (List.len rec) " ), RocStr::from("0"), @@ -1902,13 +1902,13 @@ fn tag_union_let_generalization() { assert_evals_to!( indoc!( r#" - manyAux : {} -> [ Loop, Done ] - manyAux = \_ -> + many_aux : {} -> [ Loop, Done ] + many_aux = \_ -> output = Done output - when manyAux {} is + when many_aux {} is Loop -> "loop" Done -> "done" "# @@ -1929,13 +1929,13 @@ fn fit_recursive_union_in_struct_into_recursive_pointer() { Next { item: Str, rest: NonEmpty }, ] - nonEmpty = + non_empty = a = "abcdefgh" b = @NonEmpty (First "ijkl") c = Next { item: a, rest: b } @NonEmpty c - when nonEmpty is + when non_empty is @NonEmpty (Next r) -> r.item _ -> "" "# @@ -2026,15 +2026,15 @@ fn unify_types_with_fixed_fixpoints_outside_fixing_region() { job = \inputs -> @Job (Job inputs) - helloWorld : Job - helloWorld = + hello_world : Job + hello_world = @Job ( Job [ @Input (FromJob greeting []) ] ) greeting : Job greeting = job [] - main = (\_ -> "OKAY") helloWorld + main = (\_ -> "OKAY") hello_world "# ), RocStr::from("OKAY"), @@ -2137,17 +2137,17 @@ fn nullable_wrapped_with_nullable_not_last_index() { OneOrMore Parser, ] - toIdParser : Parser -> Str - toIdParser = \parser -> + to_id_parser : Parser -> Str + to_id_parser = \parser -> when parser is OneOrMore _ -> "a" Keyword _ -> "b" CharLiteral -> "c" main = - toIdParser (OneOrMore CharLiteral) - |> Str.concat (toIdParser (Keyword "try")) - |> Str.concat (toIdParser CharLiteral) + to_id_parser (OneOrMore CharLiteral) + |> Str.concat (to_id_parser (Keyword "try")) + |> Str.concat (to_id_parser CharLiteral) "# ), RocStr::from("abc"), @@ -2165,9 +2165,9 @@ fn refcount_nullable_unwrapped_needing_no_refcount_issue_5027() { Effect : {} -> Str - after = \effect, buildNext -> + after = \effect, build_next -> \{} -> - when buildNext (effect {}) is + when build_next (effect {}) is thunk -> thunk {} line : Effect diff --git a/crates/compiler/test_gen/src/gen_tuples.rs b/crates/compiler/test_gen/src/gen_tuples.rs index 1cef7ff7052..7ff0c17b265 100644 --- a/crates/compiler/test_gen/src/gen_tuples.rs +++ b/crates/compiler/test_gen/src/gen_tuples.rs @@ -93,9 +93,9 @@ fn fn_tuple() { assert_evals_to!( indoc!( r#" - getRec = \x -> ("foo", x, 19) + get_rec = \x -> ("foo", x, 19) - (getRec 15).1 + (get_rec 15).1 "# ), 15, diff --git a/crates/compiler/test_gen/src/helpers/debug-wasm-test.html b/crates/compiler/test_gen/src/helpers/debug-wasm-test.html index 47b25a0a1bf..6b42a5f491c 100644 --- a/crates/compiler/test_gen/src/helpers/debug-wasm-test.html +++ b/crates/compiler/test_gen/src/helpers/debug-wasm-test.html @@ -174,7 +174,7 @@

Steps

const rc_encoded = rc_pointers.map((ptr) => ptr && deref(ptr)); const rc_encoded_hex = rc_encoded.map((x) => - x ? x.toString(16) : "(deallocated)" + x ? x.to_string(16) : "(deallocated)" ); const rc_values = rc_encoded.map((x) => x && x - 0x80000000 + 1); diff --git a/crates/compiler/test_gen/src/wasm_str.rs b/crates/compiler/test_gen/src/wasm_str.rs index 37fe5512387..5e6cd674fdf 100644 --- a/crates/compiler/test_gen/src/wasm_str.rs +++ b/crates/compiler/test_gen/src/wasm_str.rs @@ -19,7 +19,7 @@ fn str_split_on_empty_delimiter() { assert_evals_to!( indoc!( r#" - List.len (Str.splitOn "hello" "") + List.len (Str.split_on "hello" "") "# ), 1, @@ -32,7 +32,7 @@ fn str_split_on_bigger_delimiter_small_str() { assert_evals_to!( indoc!( r#" - List.len (Str.splitOn "hello" "JJJJ there") + List.len (Str.split_on "hello" "JJJJ there") "# ), 1, @@ -45,7 +45,7 @@ fn str_split_on_str_concat_repeated() { assert_evals_to!( indoc!( r#" - when List.first (Str.splitOn "JJJJJ" "JJJJ there") is + when List.first (Str.split_on "JJJJJ" "JJJJ there") is Ok str -> str |> Str.concat str @@ -70,7 +70,7 @@ fn str_split_on_small_str_bigger_delimiter() { r#" when List.first - (Str.splitOn "JJJ" "0123456789abcdefghi") + (Str.split_on "JJJ" "0123456789abcdefghi") is Ok str -> str _ -> "" @@ -86,7 +86,7 @@ fn str_split_on_big_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "01234567789abcdefghi?01234567789abcdefghi" "?" + Str.split_on "01234567789abcdefghi?01234567789abcdefghi" "?" "# ), RocList::from_slice(&[ @@ -99,7 +99,7 @@ fn str_split_on_big_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "01234567789abcdefghi 3ch 01234567789abcdefghi" "3ch" + Str.split_on "01234567789abcdefghi 3ch 01234567789abcdefghi" "3ch" "# ), RocList::from_slice(&[ @@ -115,7 +115,7 @@ fn str_split_on_small_str_small_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn "J!J!J" "!" + Str.split_on "J!J!J" "!" "# ), RocList::from_slice(&[RocStr::from("J"), RocStr::from("J"), RocStr::from("J")]), @@ -128,7 +128,7 @@ fn str_split_on_bigger_delimiter_big_strs() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "string to split is shorter" "than the delimiter which happens to be very very long" "# @@ -143,7 +143,7 @@ fn str_split_on_empty_strs() { assert_evals_to!( indoc!( r#" - Str.splitOn "" "" + Str.split_on "" "" "# ), RocList::from_slice(&[RocStr::from("")]), @@ -156,7 +156,7 @@ fn str_split_on_minimal_example() { assert_evals_to!( indoc!( r#" - Str.splitOn "a," "," + Str.split_on "a," "," "# ), RocList::from_slice(&[RocStr::from("a"), RocStr::from("")]), @@ -169,7 +169,7 @@ fn str_split_on_small_str_big_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "1---- ---- ---- ---- ----2---- ---- ---- ---- ----" "---- ---- ---- ---- ----" |> List.len @@ -182,7 +182,7 @@ fn str_split_on_small_str_big_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "1---- ---- ---- ---- ----2---- ---- ---- ---- ----" "---- ---- ---- ---- ----" "# @@ -197,7 +197,7 @@ fn str_split_on_small_str_20_char_delimiter() { assert_evals_to!( indoc!( r#" - Str.splitOn + Str.split_on "3|-- -- -- -- -- -- |4|-- -- -- -- -- -- |" "|-- -- -- -- -- -- |" "# @@ -245,26 +245,26 @@ fn small_str_zeroed_literal() { r#" app "test" provides [main] to "./platform" - createStr = \isForRealThisTime -> - if isForRealThisTime then + create_str = \is_for_real_this_time -> + if is_for_real_this_time then "J" else "xxxxxxx" - functionWithReusedSpace = \isForRealThisTime -> + function_with_reused_space = \is_for_real_this_time -> # Different string value on each call, at the same memory location - # (Can't inline createStr without refcounting, which isn't implemented) - reusedSpace = createStr isForRealThisTime + # (Can't inline create_str without refcounting, which isn't implemented) + reused_space = create_str is_for_real_this_time # Unoptimised 'if' ensures that we don't just allocate in the caller's frame if Bool.true then - reusedSpace + reused_space else - reusedSpace + reused_space main = - garbage = functionWithReusedSpace Bool.false - functionWithReusedSpace Bool.true + garbage = function_with_reused_space Bool.false + function_with_reused_space Bool.true "# ), [ @@ -346,13 +346,13 @@ fn str_concat_empty() { #[test] fn small_str_is_empty() { - assert_evals_to!(r#"Str.isEmpty "abc""#, false, bool); + assert_evals_to!(r#"Str.is_empty "abc""#, false, bool); } #[test] fn big_str_is_empty() { assert_evals_to!( - r#"Str.isEmpty "this is more than 15 chars long""#, + r#"Str.is_empty "this is more than 15 chars long""#, false, bool ); @@ -360,29 +360,29 @@ fn big_str_is_empty() { #[test] fn empty_str_is_empty() { - assert_evals_to!(r#"Str.isEmpty """#, true, bool); + assert_evals_to!(r#"Str.is_empty """#, true, bool); } #[test] fn str_starts_with() { - assert_evals_to!(r#"Str.startsWith "hello world" "hell""#, true, bool); - assert_evals_to!(r#"Str.startsWith "hello world" """#, true, bool); - assert_evals_to!(r#"Str.startsWith "nope" "hello world""#, false, bool); - assert_evals_to!(r#"Str.startsWith "hell" "hello world""#, false, bool); - assert_evals_to!(r#"Str.startsWith "" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "hello world" "hell""#, true, bool); + assert_evals_to!(r#"Str.starts_with "hello world" """#, true, bool); + assert_evals_to!(r#"Str.starts_with "nope" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "hell" "hello world""#, false, bool); + assert_evals_to!(r#"Str.starts_with "" "hello world""#, false, bool); } #[test] fn str_ends_with() { - assert_evals_to!(r#"Str.endsWith "hello world" "world""#, true, bool); - assert_evals_to!(r#"Str.endsWith "nope" "hello world""#, false, bool); - assert_evals_to!(r#"Str.endsWith "" "hello world""#, false, bool); + assert_evals_to!(r#"Str.ends_with "hello world" "world""#, true, bool); + assert_evals_to!(r#"Str.ends_with "nope" "hello world""#, false, bool); + assert_evals_to!(r#"Str.ends_with "" "hello world""#, false, bool); } #[test] fn str_starts_with_same_big_str() { assert_evals_to!( - r#"Str.startsWith "123456789123456789" "123456789123456789""#, + r#"Str.starts_with "123456789123456789" "123456789123456789""#, true, bool ); @@ -391,7 +391,7 @@ fn str_starts_with_same_big_str() { #[test] fn str_starts_with_different_big_str() { assert_evals_to!( - r#"Str.startsWith "12345678912345678910" "123456789123456789""#, + r#"Str.starts_with "12345678912345678910" "123456789123456789""#, true, bool ); @@ -399,16 +399,16 @@ fn str_starts_with_different_big_str() { #[test] fn str_starts_with_same_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "1234""#, true, bool); + assert_evals_to!(r#"Str.starts_with "1234" "1234""#, true, bool); } #[test] fn str_starts_with_different_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "12""#, true, bool); + assert_evals_to!(r#"Str.starts_with "1234" "12""#, true, bool); } #[test] fn str_starts_with_false_small_str() { - assert_evals_to!(r#"Str.startsWith "1234" "23""#, false, bool); + assert_evals_to!(r#"Str.starts_with "1234" "23""#, false, bool); } #[test] @@ -416,7 +416,7 @@ fn str_from_utf8_pass_single_ascii() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97] is + when Str.from_utf8 [97] is Ok val -> val Err _ -> "" "# @@ -431,7 +431,7 @@ fn str_from_utf8_pass_many_ascii() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0x7E] is + when Str.from_utf8 [97, 98, 99, 0x7E] is Ok val -> val Err _ -> "" "# @@ -446,7 +446,7 @@ fn str_from_utf8_pass_single_unicode() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xE2, 0x88, 0x86] is + when Str.from_utf8 [0xE2, 0x88, 0x86] is Ok val -> val Err _ -> "" "# @@ -461,7 +461,7 @@ fn str_from_utf8_pass_many_unicode() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xE2, 0x88, 0x86, 0xC5, 0x93, 0xC2, 0xAC] is + when Str.from_utf8 [0xE2, 0x88, 0x86, 0xC5, 0x93, 0xC2, 0xAC] is Ok val -> val Err _ -> "" "# @@ -476,7 +476,7 @@ fn str_from_utf8_pass_single_grapheme() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96] is Ok val -> val Err _ -> "" "# @@ -491,7 +491,7 @@ fn str_from_utf8_pass_many_grapheme() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96, 0xF0, 0x9F, 0xA4, 0xA0, 0xF0, 0x9F, 0x9A, 0x80] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96, 0xF0, 0x9F, 0xA4, 0xA0, 0xF0, 0x9F, 0x9A, 0x80] is Ok val -> val Err _ -> "" "# @@ -506,7 +506,7 @@ fn str_from_utf8_pass_all() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [0xF0, 0x9F, 0x92, 0x96, 98, 0xE2, 0x88, 0x86] is + when Str.from_utf8 [0xF0, 0x9F, 0x92, 0x96, 98, 0xE2, 0x88, 0x86] is Ok val -> val Err _ -> "" "# @@ -521,9 +521,9 @@ fn str_from_utf8_fail_invalid_start_byte() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 0x80, 99] is - Err (BadUtf8 InvalidStartByte byteIndex) -> - if byteIndex == 2 then + when Str.from_utf8 [97, 98, 0x80, 99] is + Err (BadUtf8 InvalidStartByte byte_index) -> + if byte_index == 2 then "a" else "b" @@ -540,9 +540,9 @@ fn str_from_utf8_fail_unexpected_end_of_sequence() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0xC2] is - Err (BadUtf8 UnexpectedEndOfSequence byteIndex) -> - if byteIndex == 3 then + when Str.from_utf8 [97, 98, 99, 0xC2] is + Err (BadUtf8 UnexpectedEndOfSequence byte_index) -> + if byte_index == 3 then "a" else "b" @@ -559,9 +559,9 @@ fn str_from_utf8_fail_expected_continuation() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 99, 0xC2, 0x00] is - Err (BadUtf8 ExpectedContinuation byteIndex) -> - if byteIndex == 3 then + when Str.from_utf8 [97, 98, 99, 0xC2, 0x00] is + Err (BadUtf8 ExpectedContinuation byte_index) -> + if byte_index == 3 then "a" else "b" @@ -578,9 +578,9 @@ fn str_from_utf8_fail_overlong_encoding() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 0xF0, 0x80, 0x80, 0x80] is - Err (BadUtf8 OverlongEncoding byteIndex) -> - if byteIndex == 1 then + when Str.from_utf8 [97, 0xF0, 0x80, 0x80, 0x80] is + Err (BadUtf8 OverlongEncoding byte_index) -> + if byte_index == 1 then "a" else "b" @@ -597,9 +597,9 @@ fn str_from_utf8_fail_codepoint_too_large() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 0xF4, 0x90, 0x80, 0x80] is - Err (BadUtf8 CodepointTooLarge byteIndex) -> - if byteIndex == 1 then + when Str.from_utf8 [97, 0xF4, 0x90, 0x80, 0x80] is + Err (BadUtf8 CodepointTooLarge byte_index) -> + if byte_index == 1 then "a" else "b" @@ -616,9 +616,9 @@ fn str_from_utf8_fail_surrogate_half() { assert_evals_to!( indoc!( r#" - when Str.fromUtf8 [97, 98, 0xED, 0xA0, 0x80] is - Err (BadUtf8 EncodesSurrogateHalf byteIndex) -> - if byteIndex == 2 then + when Str.from_utf8 [97, 98, 0xED, 0xA0, 0x80] is + Err (BadUtf8 EncodesSurrogateHalf byte_index) -> + if byte_index == 2 then "a" else "b" @@ -645,7 +645,7 @@ fn str_equality() { #[test] fn str_join_comma_small() { assert_evals_to!( - r#"Str.joinWith ["1", "2"] ", " "#, + r#"Str.join_with ["1", "2"] ", " "#, RocStr::from("1, 2"), RocStr ); @@ -654,7 +654,7 @@ fn str_join_comma_small() { #[test] fn str_join_comma_big() { assert_evals_to!( - r#"Str.joinWith ["10000000", "2000000", "30000000"] ", " "#, + r#"Str.join_with ["10000000", "2000000", "30000000"] ", " "#, RocStr::from("10000000, 2000000, 30000000"), RocStr ); @@ -662,18 +662,18 @@ fn str_join_comma_big() { #[test] fn str_join_comma_single() { - assert_evals_to!(r#"Str.joinWith ["1"] ", " "#, RocStr::from("1"), RocStr); + assert_evals_to!(r#"Str.join_with ["1"] ", " "#, RocStr::from("1"), RocStr); } #[test] fn str_to_utf8() { assert_evals_to!( - r#"Str.toUtf8 "hello""#, + r#"Str.to_utf8 "hello""#, RocList::from_slice(&[104, 101, 108, 108, 111]), RocList ); assert_evals_to!( - r#"Str.toUtf8 "this is a long string""#, + r#"Str.to_utf8 "this is a long string""#, RocList::from_slice(&[ 116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 108, 111, 110, 103, 32, 115, 116, 114, 105, 110, 103 @@ -688,10 +688,10 @@ fn str_from_utf8() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -706,11 +706,11 @@ fn str_from_utf8_slice() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 4 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -725,11 +725,11 @@ fn str_from_utf8_slice_not_end() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 3 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -744,11 +744,11 @@ fn str_from_utf8_order_does_not_matter() { indoc!( r#" bytes = - Str.toUtf8 "hello" + Str.to_utf8 "hello" |> List.sublist { start: 1, len: 3 } - when Str.fromUtf8 bytes is - Ok utf8String -> utf8String + when Str.from_utf8 bytes is + Ok utf8_string -> utf8_string _ -> "" "# ), @@ -875,13 +875,13 @@ fn str_trim_small_to_small_shared() { #[test] fn str_trim_start_small_blank_string() { - assert_evals_to!(indoc!(r#"Str.trimStart " ""#), RocStr::from(""), RocStr); + assert_evals_to!(indoc!(r#"Str.trim_start " ""#), RocStr::from(""), RocStr); } #[test] fn str_trim_start_small_to_small() { assert_evals_to!( - indoc!(r#"Str.trimStart " hello ""#), + indoc!(r#"Str.trim_start " hello ""#), RocStr::from("hello "), RocStr ); @@ -890,7 +890,7 @@ fn str_trim_start_small_to_small() { #[test] fn str_trim_start_large_to_large_unique() { assert_evals_to!( - indoc!(r#"Str.trimStart (Str.concat " " "hello world from a large string ")"#), + indoc!(r#"Str.trim_start (Str.concat " " "hello world from a large string ")"#), RocStr::from("hello world from a large string "), RocStr ); @@ -899,7 +899,7 @@ fn str_trim_start_large_to_large_unique() { #[test] fn str_trim_start_large_to_small_unique() { assert_evals_to!( - indoc!(r#"Str.trimStart (Str.concat " " "hello ")"#), + indoc!(r#"Str.trim_start (Str.concat " " "hello ")"#), RocStr::from("hello "), RocStr ); @@ -907,13 +907,13 @@ fn str_trim_start_large_to_small_unique() { #[test] fn str_trim_end_small_blank_string() { - assert_evals_to!(indoc!(r#"Str.trimEnd " ""#), RocStr::from(""), RocStr); + assert_evals_to!(indoc!(r#"Str.trim_end " ""#), RocStr::from(""), RocStr); } #[test] fn str_trim_end_small_to_small() { assert_evals_to!( - indoc!(r#"Str.trimEnd " hello ""#), + indoc!(r#"Str.trim_end " hello ""#), RocStr::from(" hello"), RocStr ); @@ -922,7 +922,7 @@ fn str_trim_end_small_to_small() { #[test] fn str_trim_end_large_to_large_unique() { assert_evals_to!( - indoc!(r#"Str.trimEnd (Str.concat " hello world from a large string" " ")"#), + indoc!(r#"Str.trim_end (Str.concat " hello world from a large string" " ")"#), RocStr::from(" hello world from a large string"), RocStr ); @@ -931,7 +931,7 @@ fn str_trim_end_large_to_large_unique() { #[test] fn str_trim_end_large_to_small_unique() { assert_evals_to!( - indoc!(r#"Str.trimEnd (Str.concat " hello" " ")"#), + indoc!(r#"Str.trim_end (Str.concat " hello" " ")"#), RocStr::from(" hello"), RocStr ); @@ -945,7 +945,7 @@ fn str_trim_end_large_to_large_shared() { original : Str original = " hello world world " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), ( @@ -964,7 +964,7 @@ fn str_trim_end_large_to_small_shared() { original : Str original = " hello " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), (RocStr::from(" hello "), RocStr::from(" hello"),), @@ -980,7 +980,7 @@ fn str_trim_end_small_to_small_shared() { original : Str original = " hello " - { trimmed: Str.trimEnd original, original: original } + { trimmed: Str.trim_end original, original: original } "# ), (RocStr::from(" hello "), RocStr::from(" hello"),), @@ -993,7 +993,7 @@ fn str_to_i128() { assert_evals_to!( indoc!( r#" - when Str.toI128 "1" is + when Str.to_i128 "1" is Ok n -> n Err _ -> 0 "# @@ -1008,7 +1008,7 @@ fn str_to_u128() { assert_evals_to!( indoc!( r#" - when Str.toU128 "1" is + when Str.to_u128 "1" is Ok n -> n Err _ -> 0 "# @@ -1023,7 +1023,7 @@ fn str_to_i64() { assert_evals_to!( indoc!( r#" - when Str.toI64 "1" is + when Str.to_i64 "1" is Ok n -> n Err _ -> 0 "# @@ -1038,7 +1038,7 @@ fn str_to_u64() { assert_evals_to!( indoc!( r#" - when Str.toU64 "1" is + when Str.to_u64 "1" is Ok n -> n Err _ -> 0 "# @@ -1053,7 +1053,7 @@ fn str_to_i32() { assert_evals_to!( indoc!( r#" - when Str.toI32 "1" is + when Str.to_i32 "1" is Ok n -> n Err _ -> 0 "# @@ -1068,7 +1068,7 @@ fn str_to_u32() { assert_evals_to!( indoc!( r#" - when Str.toU32 "1" is + when Str.to_u32 "1" is Ok n -> n Err _ -> 0 "# @@ -1083,7 +1083,7 @@ fn str_to_i16() { assert_evals_to!( indoc!( r#" - when Str.toI16 "1" is + when Str.to_i16 "1" is Ok n -> n Err _ -> 0 "# @@ -1098,7 +1098,7 @@ fn str_to_u16() { assert_evals_to!( indoc!( r#" - when Str.toU16 "1" is + when Str.to_u16 "1" is Ok n -> n Err _ -> 0 "# @@ -1113,7 +1113,7 @@ fn str_to_i8() { assert_evals_to!( indoc!( r#" - when Str.toI8 "1" is + when Str.to_i8 "1" is Ok n -> n Err _ -> 0 "# @@ -1128,7 +1128,7 @@ fn str_to_u8() { assert_evals_to!( indoc!( r#" - when Str.toU8 "1" is + when Str.to_u8 "1" is Ok n -> n Err _ -> 0 "# @@ -1143,7 +1143,7 @@ fn str_to_f64() { assert_evals_to!( indoc!( r#" - when Str.toF64 "1.0" is + when Str.to_f64 "1.0" is Ok n -> n Err _ -> 0 "# @@ -1158,7 +1158,7 @@ fn str_to_f32() { assert_evals_to!( indoc!( r#" - when Str.toF32 "1.0" is + when Str.to_f32 "1.0" is Ok n -> n Err _ -> 0 "# @@ -1175,7 +1175,7 @@ fn str_to_dec() { assert_evals_to!( indoc!( r#" - when Str.toDec "1.0" is + when Str.to_dec "1.0" is Ok n -> n Err _ -> 0 "# diff --git a/crates/compiler/test_mono/generated/as_pattern_in_closure_arg.txt b/crates/compiler/test_mono/generated/as_pattern_in_closure_arg.txt deleted file mode 100644 index 5d25c983bf3..00000000000 --- a/crates/compiler/test_mono/generated/as_pattern_in_closure_arg.txt +++ /dev/null @@ -1,31 +0,0 @@ -procedure Num.19 (#Attr.2, #Attr.3): - let Num.282 : I64 = lowlevel NumAdd #Attr.2 #Attr.3; - ret Num.282; - -procedure Test.1 (Test.12): - let Test.6 : I64 = StructAtIndex 0 Test.12; - let Test.5 : I64 = StructAtIndex 1 Test.12; - let Test.3 : I64 = StructAtIndex 2 Test.12; - let Test.4 : I64 = StructAtIndex 3 Test.12; - let Test.18 : I64 = CallByName Num.19 Test.3 Test.5; - let Test.19 : I64 = CallByName Num.19 Test.4 Test.6; - let Test.17 : {I64, I64} = Struct {Test.18, Test.19}; - ret Test.17; - -procedure Test.2 (Test.9): - let Test.7 : I64 = StructAtIndex 2 Test.9; - let Test.8 : I64 = StructAtIndex 3 Test.9; - let Test.16 : {I64, I64} = CallByName Test.1 Test.9; - let Test.10 : I64 = StructAtIndex 0 Test.16; - let Test.11 : I64 = StructAtIndex 1 Test.16; - let Test.15 : {I64, I64, I64, I64} = Struct {Test.7, Test.8, Test.10, Test.11}; - ret Test.15; - -procedure Test.0 (): - let Test.20 : I64 = 4i64; - let Test.21 : I64 = 3i64; - let Test.22 : I64 = 1i64; - let Test.23 : I64 = 2i64; - let Test.14 : {I64, I64, I64, I64} = Struct {Test.20, Test.21, Test.22, Test.23}; - let Test.13 : {I64, I64, I64, I64} = CallByName Test.2 Test.14; - ret Test.13; diff --git a/crates/compiler/test_mono/generated/choose_correct_recursion_var_under_record.txt b/crates/compiler/test_mono/generated/choose_correct_recursion_var_under_record.txt index 4ff2c76757e..d7f2dcc7143 100644 --- a/crates/compiler/test_mono/generated/choose_correct_recursion_var_under_record.txt +++ b/crates/compiler/test_mono/generated/choose_correct_recursion_var_under_record.txt @@ -1,131 +1,14 @@ procedure Bool.1 (): - let Bool.24 : Int1 = false; - ret Bool.24; - -procedure List.100 (#Derived_gen.0, #Derived_gen.1, #Derived_gen.2, #Derived_gen.3, #Derived_gen.4): - joinpoint List.687 List.174 List.175 List.176 List.177 List.178: - let List.689 : Int1 = CallByName Num.22 List.177 List.178; - if List.689 then - let List.693 : [C List [C List *self, C *self], C [C List *self, C *self]] = CallByName List.66 List.174 List.177; - inc List.693; - let List.179 : List Str = CallByName List.283 List.175 List.693 List.176; - let List.692 : U64 = 1i64; - let List.691 : U64 = CallByName Num.51 List.177 List.692; - jump List.687 List.174 List.179 List.176 List.691 List.178; - else - dec List.174; - ret List.175; - in - inc #Derived_gen.0; - jump List.687 #Derived_gen.0 #Derived_gen.1 #Derived_gen.2 #Derived_gen.3 #Derived_gen.4; - -procedure List.18 (List.171, List.172, List.173): - let List.685 : U64 = 0i64; - let List.686 : U64 = CallByName List.6 List.171; - let List.684 : List Str = CallByName List.100 List.171 List.172 List.173 List.685 List.686; - ret List.684; - -procedure List.2 (List.119, List.120): - let List.679 : U64 = CallByName List.6 List.119; - let List.675 : Int1 = CallByName Num.22 List.120 List.679; - if List.675 then - let List.677 : Str = CallByName List.66 List.119 List.120; - inc List.677; - let List.676 : [C {}, C Str] = TagId(1) List.677; - ret List.676; - else - let List.674 : {} = Struct {}; - let List.673 : [C {}, C Str] = TagId(0) List.674; - ret List.673; - -procedure List.283 (List.284, List.285, List.281): - let List.698 : Str = CallByName Test.10 List.285; - let List.697 : List Str = CallByName List.71 List.284 List.698; - ret List.697; - -procedure List.5 (List.280, List.281): - let List.282 : U64 = CallByName List.6 List.280; - let List.682 : List Str = CallByName List.68 List.282; - let List.681 : List Str = CallByName List.18 List.280 List.682 List.281; - ret List.681; - -procedure List.6 (#Attr.2): - let List.680 : U64 = lowlevel ListLenU64 #Attr.2; - ret List.680; - -procedure List.6 (#Attr.2): - let List.695 : U64 = lowlevel ListLenU64 #Attr.2; - ret List.695; - -procedure List.66 (#Attr.2, #Attr.3): - let List.678 : Str = lowlevel ListGetUnsafe #Attr.2 #Attr.3; - ret List.678; - -procedure List.66 (#Attr.2, #Attr.3): - let List.694 : [C List [C List *self, C *self], C [C List *self, C *self]] = lowlevel ListGetUnsafe #Attr.2 #Attr.3; - ret List.694; - -procedure List.68 (#Attr.2): - let List.700 : List Str = lowlevel ListWithCapacity #Attr.2; - ret List.700; - -procedure List.71 (#Attr.2, #Attr.3): - let List.699 : List Str = lowlevel ListAppendUnsafe #Attr.2 #Attr.3; - ret List.699; - -procedure List.9 (List.391): - let List.672 : U64 = 0i64; - let List.665 : [C {}, C Str] = CallByName List.2 List.391 List.672; - let List.669 : U8 = 1i64; - let List.670 : U8 = GetTagId List.665; - let List.671 : Int1 = lowlevel Eq List.669 List.670; - if List.671 then - let List.392 : Str = UnionAtIndex (Id 1) (Index 0) List.665; - let List.666 : [C {}, C Str] = TagId(1) List.392; - ret List.666; - else - dec List.665; - let List.668 : {} = Struct {}; - let List.667 : [C {}, C Str] = TagId(0) List.668; - ret List.667; - -procedure Num.22 (#Attr.2, #Attr.3): - let Num.284 : Int1 = lowlevel NumLt #Attr.2 #Attr.3; - ret Num.284; - -procedure Num.51 (#Attr.2, #Attr.3): - let Num.285 : U64 = lowlevel NumAddWrap #Attr.2 #Attr.3; - ret Num.285; - -procedure Result.5 (Result.14, Result.15): - let Result.63 : U8 = 1i64; - let Result.64 : U8 = GetTagId Result.14; - let Result.65 : Int1 = lowlevel Eq Result.63 Result.64; - if Result.65 then - dec Result.15; - let Result.16 : Str = UnionAtIndex (Id 1) (Index 0) Result.14; - ret Result.16; - else - dec Result.14; - ret Result.15; - -procedure Test.10 (Test.11): - let Test.12 : Str = CallByName Test.2 Test.11; - let Test.26 : Int1 = CallByName Bool.1; - if Test.26 then - ret Test.12; - else - dec Test.12; - let Test.25 : Str = "foo"; - ret Test.25; + let Bool.23 : Int1 = false; + ret Bool.23; procedure Test.2 (Test.6): - let Test.29 : U8 = 1i64; - let Test.30 : U8 = GetTagId Test.6; - let Test.31 : Int1 = lowlevel Eq Test.29 Test.30; - if Test.31 then + let Test.22 : U8 = 1i64; + let Test.23 : U8 = GetTagId Test.6; + let Test.24 : Int1 = lowlevel Eq Test.22 Test.23; + if Test.24 then let Test.7 : [C List *self, C *self] = UnionAtIndex (Id 1) (Index 0) Test.6; - joinpoint #Derived_gen.9: + joinpoint #Derived_gen.1: let Test.8 : Str = CallByName Test.2 Test.7; let Test.18 : Int1 = CallByName Bool.1; if Test.18 then @@ -135,37 +18,32 @@ procedure Test.2 (Test.6): let Test.17 : Str = "foo"; ret Test.17; in - let #Derived_gen.10 : Int1 = lowlevel RefCountIsUnique Test.6; - if #Derived_gen.10 then + let #Derived_gen.2 : Int1 = lowlevel RefCountIsUnique Test.6; + if #Derived_gen.2 then free Test.6; - jump #Derived_gen.9; + jump #Derived_gen.1; else inc Test.7; decref Test.6; - jump #Derived_gen.9; + jump #Derived_gen.1; else let Test.9 : List [C List [C List *self, C *self], C [C List *self, C *self]] = UnionAtIndex (Id 0) (Index 0) Test.6; - joinpoint #Derived_gen.11: - let Test.24 : {} = Struct {}; - let Test.23 : List Str = CallByName List.5 Test.9 Test.24; + joinpoint #Derived_gen.3: dec Test.9; - let Test.21 : [C {}, C Str] = CallByName List.9 Test.23; - dec Test.23; - let Test.22 : Str = "foo"; - let Test.20 : Str = CallByName Result.5 Test.21 Test.22; - ret Test.20; + let Test.21 : Str = "ValueNotExposed { module_name: ModuleName(IdentStr { string: \"Result\" }), ident: Ident(IdentStr { string: \"withDefault\" }), region: @662-680, exposed_values: ['is_err', 'on_err', 'map', 'map_err', 'with_default', 'try', 'is_ok', 'map_both', 'map2', 'on_err!'] }"; + Crash Test.21 in - let #Derived_gen.12 : Int1 = lowlevel RefCountIsUnique Test.6; - if #Derived_gen.12 then + let #Derived_gen.4 : Int1 = lowlevel RefCountIsUnique Test.6; + if #Derived_gen.4 then free Test.6; - jump #Derived_gen.11; + jump #Derived_gen.3; else inc Test.9; decref Test.6; - jump #Derived_gen.11; + jump #Derived_gen.3; procedure Test.0 (): - let Test.32 : List [C List [C List *self, C *self], C [C List *self, C *self]] = Array []; - let Test.15 : [C List *self, C *self] = TagId(0) Test.32; + let Test.25 : List [C List [C List *self, C *self], C [C List *self, C *self]] = Array []; + let Test.15 : [C List *self, C *self] = TagId(0) Test.25; let Test.14 : Str = CallByName Test.2 Test.15; ret Test.14; diff --git a/crates/compiler/test_mono/generated/dbg_expr.txt b/crates/compiler/test_mono/generated/dbg_expr.txt index e9f1f9b8b2f..9474ef8d86a 100644 --- a/crates/compiler/test_mono/generated/dbg_expr.txt +++ b/crates/compiler/test_mono/generated/dbg_expr.txt @@ -1,38 +1,38 @@ -procedure Inspect.278 (Inspect.279, Inspect.277): - let Inspect.318 : Str = CallByName Num.96 Inspect.277; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.279 Inspect.318; - dec Inspect.318; - ret Inspect.317; +procedure Inspect.277 (Inspect.278, Inspect.276): + let Inspect.317 : Str = CallByName Num.96 Inspect.276; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.278 Inspect.317; + dec Inspect.317; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.5 (Inspect.150): - let Inspect.312 : I64 = CallByName Inspect.57 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.278 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.57 (Inspect.277): - let Inspect.313 : I64 = CallByName Inspect.30 Inspect.277; - ret Inspect.313; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.320 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.320; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : I64 = CallByName Inspect.57 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.277 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.57 (Inspect.276): + let Inspect.312 : I64 = CallByName Inspect.30 Inspect.276; + ret Inspect.312; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.319 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.319; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Num.19 (#Attr.2, #Attr.3): let Num.283 : I64 = lowlevel NumAdd #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/generated/dbg_in_expect.txt b/crates/compiler/test_mono/generated/dbg_in_expect.txt index 15af7a2b6b3..15a86f212be 100644 --- a/crates/compiler/test_mono/generated/dbg_in_expect.txt +++ b/crates/compiler/test_mono/generated/dbg_in_expect.txt @@ -2,46 +2,46 @@ procedure Bool.2 (): let Bool.23 : Int1 = true; ret Bool.23; -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.323 : Str = "\""; - let Inspect.322 : Str = CallByName Inspect.63 Inspect.251 Inspect.323; - dec Inspect.323; - let Inspect.318 : Str = CallByName Inspect.63 Inspect.322 Inspect.249; - let Inspect.319 : Str = "\""; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.318 Inspect.319; - dec Inspect.319; - ret Inspect.317; +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.322 : Str = "\""; + let Inspect.321 : Str = CallByName Inspect.63 Inspect.250 Inspect.322; + dec Inspect.322; + let Inspect.317 : Str = CallByName Inspect.63 Inspect.321 Inspect.248; + let Inspect.318 : Str = "\""; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.317 Inspect.318; + dec Inspect.318; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; -procedure Inspect.47 (Inspect.249): - let Inspect.313 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.313; +procedure Inspect.47 (Inspect.248): + let Inspect.312 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.312; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName Inspect.47 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.250 Inspect.308 Inspect.312; - dec Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.321 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.321; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : Str = CallByName Inspect.47 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.249 Inspect.307 Inspect.311; + dec Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.320 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.320; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Str.3 (#Attr.2, #Attr.3): let Str.246 : Str = lowlevel StrConcat #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/generated/dbg_inside_string.txt b/crates/compiler/test_mono/generated/dbg_inside_string.txt index 434f6ccb11d..692ae812af9 100644 --- a/crates/compiler/test_mono/generated/dbg_inside_string.txt +++ b/crates/compiler/test_mono/generated/dbg_inside_string.txt @@ -1,43 +1,43 @@ -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.323 : Str = "\""; - let Inspect.322 : Str = CallByName Inspect.63 Inspect.251 Inspect.323; - dec Inspect.323; - let Inspect.318 : Str = CallByName Inspect.63 Inspect.322 Inspect.249; - let Inspect.319 : Str = "\""; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.318 Inspect.319; - dec Inspect.319; - ret Inspect.317; +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.322 : Str = "\""; + let Inspect.321 : Str = CallByName Inspect.63 Inspect.250 Inspect.322; + dec Inspect.322; + let Inspect.317 : Str = CallByName Inspect.63 Inspect.321 Inspect.248; + let Inspect.318 : Str = "\""; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.317 Inspect.318; + dec Inspect.318; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; -procedure Inspect.47 (Inspect.249): - let Inspect.313 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.313; +procedure Inspect.47 (Inspect.248): + let Inspect.312 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.312; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName Inspect.47 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.250 Inspect.308 Inspect.312; - dec Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.321 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.321; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : Str = CallByName Inspect.47 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.249 Inspect.307 Inspect.311; + dec Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.320 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.320; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Str.3 (#Attr.2, #Attr.3): let Str.248 : Str = lowlevel StrConcat #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/generated/dbg_nested_expr.txt b/crates/compiler/test_mono/generated/dbg_nested_expr.txt index fd7ac484d68..f2e346a440e 100644 --- a/crates/compiler/test_mono/generated/dbg_nested_expr.txt +++ b/crates/compiler/test_mono/generated/dbg_nested_expr.txt @@ -1,38 +1,38 @@ -procedure Inspect.278 (Inspect.279, Inspect.277): - let Inspect.318 : Str = CallByName Num.96 Inspect.277; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.279 Inspect.318; - dec Inspect.318; - ret Inspect.317; +procedure Inspect.277 (Inspect.278, Inspect.276): + let Inspect.317 : Str = CallByName Num.96 Inspect.276; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.278 Inspect.317; + dec Inspect.317; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.324 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.323 : Str = CallByName Inspect.64 Inspect.324; - ret Inspect.323; + let Inspect.323 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.322 : Str = CallByName Inspect.64 Inspect.323; + ret Inspect.322; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.5 (Inspect.150): - let Inspect.312 : I64 = CallByName Inspect.57 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.278 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.57 (Inspect.277): - let Inspect.313 : I64 = CallByName Inspect.30 Inspect.277; - ret Inspect.313; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.320 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.320; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : I64 = CallByName Inspect.57 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.277 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.57 (Inspect.276): + let Inspect.312 : I64 = CallByName Inspect.30 Inspect.276; + ret Inspect.312; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.319 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.319; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Num.96 (#Attr.2): let Num.283 : Str = lowlevel NumToStr #Attr.2; diff --git a/crates/compiler/test_mono/generated/dbg_str_followed_by_number.txt b/crates/compiler/test_mono/generated/dbg_str_followed_by_number.txt index 25267016f68..67ebad8e0cf 100644 --- a/crates/compiler/test_mono/generated/dbg_str_followed_by_number.txt +++ b/crates/compiler/test_mono/generated/dbg_str_followed_by_number.txt @@ -1,43 +1,43 @@ -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.323 : Str = "\""; - let Inspect.322 : Str = CallByName Inspect.63 Inspect.251 Inspect.323; - dec Inspect.323; - let Inspect.318 : Str = CallByName Inspect.63 Inspect.322 Inspect.249; - let Inspect.319 : Str = "\""; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.318 Inspect.319; - dec Inspect.319; - ret Inspect.317; +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.322 : Str = "\""; + let Inspect.321 : Str = CallByName Inspect.63 Inspect.250 Inspect.322; + dec Inspect.322; + let Inspect.317 : Str = CallByName Inspect.63 Inspect.321 Inspect.248; + let Inspect.318 : Str = "\""; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.317 Inspect.318; + dec Inspect.318; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; -procedure Inspect.47 (Inspect.249): - let Inspect.313 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.313; +procedure Inspect.47 (Inspect.248): + let Inspect.312 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.312; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName Inspect.47 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.250 Inspect.308 Inspect.312; - dec Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.321 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.321; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : Str = CallByName Inspect.47 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.249 Inspect.307 Inspect.311; + dec Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.320 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.320; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Str.3 (#Attr.2, #Attr.3): let Str.246 : Str = lowlevel StrConcat #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/generated/dict.txt b/crates/compiler/test_mono/generated/dict.txt index b788c1cac07..67d35d20149 100644 --- a/crates/compiler/test_mono/generated/dict.txt +++ b/crates/compiler/test_mono/generated/dict.txt @@ -1,29 +1,29 @@ -procedure Dict.1 (Dict.731): - let Dict.740 : List {U32, U32} = Array []; - let Dict.741 : List {[], []} = Array []; - let Dict.742 : U64 = 0i64; +procedure Dict.1 (Dict.732): + let Dict.741 : List {U32, U32} = Array []; + let Dict.742 : List {[], []} = Array []; + let Dict.743 : U64 = 0i64; let Dict.51 : Float32 = CallByName Dict.51; let Dict.52 : U8 = CallByName Dict.52; - let Dict.739 : {List {U32, U32}, List {[], []}, U64, Float32, U8} = Struct {Dict.740, Dict.741, Dict.742, Dict.51, Dict.52}; - ret Dict.739; + let Dict.740 : {List {U32, U32}, List {[], []}, U64, Float32, U8} = Struct {Dict.741, Dict.742, Dict.743, Dict.51, Dict.52}; + ret Dict.740; -procedure Dict.4 (Dict.737): - let Dict.163 : List {[], []} = StructAtIndex 1 Dict.737; - let #Derived_gen.0 : List {U32, U32} = StructAtIndex 0 Dict.737; +procedure Dict.4 (Dict.738): + let Dict.163 : List {[], []} = StructAtIndex 1 Dict.738; + let #Derived_gen.0 : List {U32, U32} = StructAtIndex 0 Dict.738; dec #Derived_gen.0; - let Dict.738 : U64 = CallByName List.6 Dict.163; + let Dict.739 : U64 = CallByName List.6 Dict.163; dec Dict.163; - ret Dict.738; + ret Dict.739; procedure Dict.51 (): - let Dict.746 : Float32 = 0.8f64; - ret Dict.746; + let Dict.747 : Float32 = 0.8f64; + ret Dict.747; procedure Dict.52 (): - let Dict.744 : U8 = 64i64; - let Dict.745 : U8 = 3i64; - let Dict.743 : U8 = CallByName Num.75 Dict.744 Dict.745; - ret Dict.743; + let Dict.745 : U8 = 64i64; + let Dict.746 : U8 = 3i64; + let Dict.744 : U8 = CallByName Num.75 Dict.745 Dict.746; + ret Dict.744; procedure List.6 (#Attr.2): let List.665 : U64 = lowlevel ListLenU64 #Attr.2; diff --git a/crates/compiler/test_mono/generated/inspect_derived_dict.txt b/crates/compiler/test_mono/generated/inspect_derived_dict.txt index 2a287b8b8b9..db622b9f79b 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_dict.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_dict.txt @@ -34,705 +34,705 @@ procedure Bool.7 (Bool.19, Bool.20): let Bool.27 : Int1 = CallByName Bool.12 Bool.19 Bool.20; ret Bool.27; -procedure Dict.1 (Dict.731): - let Dict.893 : List {U32, U32} = Array []; - let Dict.894 : List {Str, I64} = Array []; - let Dict.895 : U64 = 0i64; +procedure Dict.1 (Dict.732): + let Dict.894 : List {U32, U32} = Array []; + let Dict.895 : List {Str, I64} = Array []; + let Dict.896 : U64 = 0i64; let Dict.51 : Float32 = CallByName Dict.51; let Dict.52 : U8 = CallByName Dict.52; - let Dict.892 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.893, Dict.894, Dict.895, Dict.51, Dict.52}; - ret Dict.892; + let Dict.893 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.894, Dict.895, Dict.896, Dict.51, Dict.52}; + ret Dict.893; -procedure Dict.10 (Dict.732, Dict.186, Dict.187): - let Dict.185 : List {Str, I64} = StructAtIndex 1 Dict.732; - let #Derived_gen.67 : List {U32, U32} = StructAtIndex 0 Dict.732; +procedure Dict.10 (Dict.733, Dict.186, Dict.187): + let Dict.185 : List {Str, I64} = StructAtIndex 1 Dict.733; + let #Derived_gen.67 : List {U32, U32} = StructAtIndex 0 Dict.733; dec #Derived_gen.67; - let Dict.1109 : {Str, Int1} = CallByName List.18 Dict.185 Dict.186 Dict.187; + let Dict.1110 : {Str, Int1} = CallByName List.18 Dict.185 Dict.186 Dict.187; dec Dict.185; - ret Dict.1109; - -procedure Dict.100 (Dict.545, Dict.546, Dict.547): - let Dict.1062 : U8 = CallByName Dict.22 Dict.545 Dict.546; - let Dict.548 : U64 = CallByName Num.133 Dict.1062; - let Dict.1061 : U8 = 1i64; - let Dict.1060 : U64 = CallByName Num.74 Dict.547 Dict.1061; - let Dict.1059 : U64 = CallByName Num.51 Dict.1060 Dict.546; - let Dict.1058 : U8 = CallByName Dict.22 Dict.545 Dict.1059; - let Dict.549 : U64 = CallByName Num.133 Dict.1058; - let Dict.1057 : U64 = 1i64; - let Dict.1056 : U64 = CallByName Num.75 Dict.547 Dict.1057; - let Dict.1055 : U64 = CallByName Num.51 Dict.1056 Dict.546; - let Dict.1054 : U8 = CallByName Dict.22 Dict.545 Dict.1055; - let Dict.550 : U64 = CallByName Num.133 Dict.1054; - let Dict.1053 : U8 = 16i64; - let Dict.1050 : U64 = CallByName Num.72 Dict.548 Dict.1053; - let Dict.1052 : U8 = 8i64; - let Dict.1051 : U64 = CallByName Num.72 Dict.549 Dict.1052; - let Dict.551 : U64 = CallByName Num.71 Dict.1050 Dict.1051; - let Dict.1049 : U64 = CallByName Num.71 Dict.551 Dict.550; - ret Dict.1049; + ret Dict.1110; + +procedure Dict.100 (Dict.546, Dict.547, Dict.548): + let Dict.1063 : U8 = CallByName Dict.22 Dict.546 Dict.547; + let Dict.549 : U64 = CallByName Num.133 Dict.1063; + let Dict.1062 : U8 = 1i64; + let Dict.1061 : U64 = CallByName Num.74 Dict.548 Dict.1062; + let Dict.1060 : U64 = CallByName Num.51 Dict.1061 Dict.547; + let Dict.1059 : U8 = CallByName Dict.22 Dict.546 Dict.1060; + let Dict.550 : U64 = CallByName Num.133 Dict.1059; + let Dict.1058 : U64 = 1i64; + let Dict.1057 : U64 = CallByName Num.75 Dict.548 Dict.1058; + let Dict.1056 : U64 = CallByName Num.51 Dict.1057 Dict.547; + let Dict.1055 : U8 = CallByName Dict.22 Dict.546 Dict.1056; + let Dict.551 : U64 = CallByName Num.133 Dict.1055; + let Dict.1054 : U8 = 16i64; + let Dict.1051 : U64 = CallByName Num.72 Dict.549 Dict.1054; + let Dict.1053 : U8 = 8i64; + let Dict.1052 : U64 = CallByName Num.72 Dict.550 Dict.1053; + let Dict.552 : U64 = CallByName Num.71 Dict.1051 Dict.1052; + let Dict.1050 : U64 = CallByName Num.71 Dict.552 Dict.551; + ret Dict.1050; procedure Dict.12 (Dict.158): - let Dict.891 : {} = Struct {}; - let Dict.739 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.1 Dict.891; - let Dict.740 : {} = Struct {}; - let Dict.738 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName List.18 Dict.158 Dict.739 Dict.740; - ret Dict.738; + let Dict.892 : {} = Struct {}; + let Dict.740 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.1 Dict.892; + let Dict.741 : {} = Struct {}; + let Dict.739 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName List.18 Dict.158 Dict.740 Dict.741; + ret Dict.739; procedure Dict.127 (Dict.128, Dict.126): - let Dict.1106 : {} = Struct {}; let Dict.1107 : {} = Struct {}; let Dict.1108 : {} = Struct {}; - let Dict.1105 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = CallByName Inspect.42 Dict.126 Dict.1106 Dict.1107 Dict.1108; - let Dict.1104 : Str = CallByName Inspect.31 Dict.1105 Dict.128; - ret Dict.1104; - -procedure Dict.159 (Dict.160, Dict.741): - let Dict.161 : Str = StructAtIndex 0 Dict.741; - let Dict.162 : I64 = StructAtIndex 1 Dict.741; - let Dict.742 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.8 Dict.160 Dict.161 Dict.162; - ret Dict.742; - -procedure Dict.188 (Dict.189, Dict.1111, Dict.187): - let Dict.190 : Str = StructAtIndex 0 Dict.1111; - let Dict.191 : I64 = StructAtIndex 1 Dict.1111; - let Dict.1113 : {Str, Int1} = CallByName Inspect.191 Dict.189 Dict.190 Dict.191 Dict.187; - ret Dict.1113; - -procedure Dict.20 (Dict.728): - let Dict.155 : U64 = StructAtIndex 2 Dict.728; - let #Derived_gen.70 : List {U32, U32} = StructAtIndex 0 Dict.728; + let Dict.1109 : {} = Struct {}; + let Dict.1106 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = CallByName Inspect.42 Dict.126 Dict.1107 Dict.1108 Dict.1109; + let Dict.1105 : Str = CallByName Inspect.31 Dict.1106 Dict.128; + ret Dict.1105; + +procedure Dict.159 (Dict.160, Dict.742): + let Dict.161 : Str = StructAtIndex 0 Dict.742; + let Dict.162 : I64 = StructAtIndex 1 Dict.742; + let Dict.743 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.8 Dict.160 Dict.161 Dict.162; + ret Dict.743; + +procedure Dict.188 (Dict.189, Dict.1112, Dict.187): + let Dict.190 : Str = StructAtIndex 0 Dict.1112; + let Dict.191 : I64 = StructAtIndex 1 Dict.1112; + let Dict.1114 : {Str, Int1} = CallByName Inspect.191 Dict.189 Dict.190 Dict.191 Dict.187; + ret Dict.1114; + +procedure Dict.20 (Dict.729): + let Dict.155 : U64 = StructAtIndex 2 Dict.729; + let #Derived_gen.70 : List {U32, U32} = StructAtIndex 0 Dict.729; dec #Derived_gen.70; - let #Derived_gen.69 : List {Str, I64} = StructAtIndex 1 Dict.728; + let #Derived_gen.69 : List {Str, I64} = StructAtIndex 1 Dict.729; dec #Derived_gen.69; ret Dict.155; procedure Dict.22 (#Attr.2, #Attr.3): - let Dict.773 : {U32, U32} = lowlevel ListGetUnsafe #Attr.2 #Attr.3; - ret Dict.773; + let Dict.774 : {U32, U32} = lowlevel ListGetUnsafe #Attr.2 #Attr.3; + ret Dict.774; procedure Dict.22 (#Attr.2, #Attr.3): - let Dict.789 : {Str, I64} = lowlevel ListGetUnsafe #Attr.2 #Attr.3; - ret Dict.789; + let Dict.790 : {Str, I64} = lowlevel ListGetUnsafe #Attr.2 #Attr.3; + ret Dict.790; procedure Dict.22 (#Attr.2, #Attr.3): - let Dict.952 : U8 = lowlevel ListGetUnsafe #Attr.2 #Attr.3; - ret Dict.952; + let Dict.953 : U8 = lowlevel ListGetUnsafe #Attr.2 #Attr.3; + ret Dict.953; procedure Dict.23 (#Attr.2): - let Dict.825 : U64 = lowlevel DictPseudoSeed #Attr.2; - ret Dict.825; + let Dict.826 : U64 = lowlevel DictPseudoSeed #Attr.2; + ret Dict.826; -procedure Dict.4 (Dict.737): - let Dict.163 : List {Str, I64} = StructAtIndex 1 Dict.737; - let #Derived_gen.66 : List {U32, U32} = StructAtIndex 0 Dict.737; +procedure Dict.4 (Dict.738): + let Dict.163 : List {Str, I64} = StructAtIndex 1 Dict.738; + let #Derived_gen.66 : List {U32, U32} = StructAtIndex 0 Dict.738; dec #Derived_gen.66; - let Dict.890 : U64 = CallByName List.6 Dict.163; + let Dict.891 : U64 = CallByName List.6 Dict.163; dec Dict.163; - ret Dict.890; - -procedure Dict.406 (Dict.407, Dict.848, Dict.409, Dict.405): - let Dict.408 : Str = StructAtIndex 0 Dict.848; - let Dict.853 : {U64, U32} = CallByName Dict.72 Dict.407 Dict.408 Dict.405; - let Dict.410 : U64 = StructAtIndex 0 Dict.853; - let Dict.411 : U32 = StructAtIndex 1 Dict.853; - let Dict.852 : U32 = CallByName Num.131 Dict.409; - let Dict.851 : {U32, U32} = Struct {Dict.852, Dict.411}; - let Dict.850 : List {U32, U32} = CallByName Dict.74 Dict.407 Dict.851 Dict.410; - ret Dict.850; + ret Dict.891; + +procedure Dict.407 (Dict.408, Dict.849, Dict.410, Dict.406): + let Dict.409 : Str = StructAtIndex 0 Dict.849; + let Dict.854 : {U64, U32} = CallByName Dict.72 Dict.408 Dict.409 Dict.406; + let Dict.411 : U64 = StructAtIndex 0 Dict.854; + let Dict.412 : U32 = StructAtIndex 1 Dict.854; + let Dict.853 : U32 = CallByName Num.131 Dict.410; + let Dict.852 : {U32, U32} = Struct {Dict.853, Dict.412}; + let Dict.851 : List {U32, U32} = CallByName Dict.74 Dict.408 Dict.852 Dict.411; + ret Dict.851; procedure Dict.43 (Dict.126): - let Dict.1101 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Inspect.30 Dict.126; - ret Dict.1101; + let Dict.1102 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Inspect.30 Dict.126; + ret Dict.1102; -procedure Dict.45 (#Derived_gen.45, #Derived_gen.46, #Derived_gen.47, #Derived_gen.48, #Derived_gen.49, #Derived_gen.50, #Derived_gen.51, #Derived_gen.52, #Derived_gen.53): - joinpoint Dict.744 Dict.228 Dict.229 Dict.230 Dict.231 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236: +procedure Dict.45 (#Derived_gen.41, #Derived_gen.42, #Derived_gen.43, #Derived_gen.44, #Derived_gen.45, #Derived_gen.46, #Derived_gen.47, #Derived_gen.48, #Derived_gen.49): + joinpoint Dict.745 Dict.228 Dict.229 Dict.230 Dict.231 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236: let Dict.237 : {U32, U32} = CallByName Dict.22 Dict.228 Dict.230; - let Dict.791 : U32 = StructAtIndex 1 Dict.237; - let Dict.779 : Int1 = CallByName Bool.11 Dict.231 Dict.791; - if Dict.779 then - let Dict.790 : U32 = StructAtIndex 0 Dict.237; - let Dict.788 : U64 = CallByName Num.133 Dict.790; - let Dict.787 : {Str, I64} = CallByName Dict.22 Dict.229 Dict.788; - let Dict.238 : Str = StructAtIndex 0 Dict.787; - let Dict.782 : Int1 = CallByName Bool.11 Dict.238 Dict.232; - if Dict.782 then - let Dict.786 : U32 = StructAtIndex 0 Dict.237; - let Dict.784 : U64 = CallByName Num.133 Dict.786; - let Dict.785 : {Str, I64} = Struct {Dict.232, Dict.233}; - let Dict.239 : List {Str, I64} = CallByName List.3 Dict.229 Dict.784 Dict.785; - let Dict.783 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.228, Dict.239, Dict.234, Dict.235, Dict.236}; - ret Dict.783; + let Dict.792 : U32 = StructAtIndex 1 Dict.237; + let Dict.780 : Int1 = CallByName Bool.11 Dict.231 Dict.792; + if Dict.780 then + let Dict.791 : U32 = StructAtIndex 0 Dict.237; + let Dict.789 : U64 = CallByName Num.133 Dict.791; + let Dict.788 : {Str, I64} = CallByName Dict.22 Dict.229 Dict.789; + let Dict.238 : Str = StructAtIndex 0 Dict.788; + let Dict.783 : Int1 = CallByName Bool.11 Dict.238 Dict.232; + if Dict.783 then + let Dict.787 : U32 = StructAtIndex 0 Dict.237; + let Dict.785 : U64 = CallByName Num.133 Dict.787; + let Dict.786 : {Str, I64} = Struct {Dict.232, Dict.233}; + let Dict.239 : List {Str, I64} = CallByName List.3 Dict.229 Dict.785 Dict.786; + let Dict.784 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.228, Dict.239, Dict.234, Dict.235, Dict.236}; + ret Dict.784; else - let Dict.781 : U64 = CallByName List.6 Dict.228; - let Dict.240 : U64 = CallByName Dict.75 Dict.230 Dict.781; + let Dict.782 : U64 = CallByName List.6 Dict.228; + let Dict.240 : U64 = CallByName Dict.75 Dict.230 Dict.782; let Dict.241 : U32 = CallByName Dict.55 Dict.231; - jump Dict.744 Dict.228 Dict.229 Dict.240 Dict.241 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236; + jump Dict.745 Dict.228 Dict.229 Dict.240 Dict.241 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236; else - let Dict.778 : U32 = StructAtIndex 1 Dict.237; - let Dict.758 : Int1 = CallByName Num.24 Dict.231 Dict.778; - if Dict.758 then - let Dict.777 : {Str, I64} = Struct {Dict.232, Dict.233}; - let Dict.242 : List {Str, I64} = CallByName List.4 Dict.229 Dict.777; - let Dict.775 : U64 = CallByName List.6 Dict.242; - let Dict.776 : U64 = 1i64; - let Dict.243 : U64 = CallByName Num.75 Dict.775 Dict.776; - let Dict.774 : U32 = CallByName Num.131 Dict.243; - let Dict.760 : {U32, U32} = Struct {Dict.774, Dict.231}; - let Dict.244 : List {U32, U32} = CallByName Dict.74 Dict.228 Dict.760 Dict.230; - let Dict.759 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.244, Dict.242, Dict.234, Dict.235, Dict.236}; - ret Dict.759; + let Dict.779 : U32 = StructAtIndex 1 Dict.237; + let Dict.759 : Int1 = CallByName Num.24 Dict.231 Dict.779; + if Dict.759 then + let Dict.778 : {Str, I64} = Struct {Dict.232, Dict.233}; + let Dict.242 : List {Str, I64} = CallByName List.4 Dict.229 Dict.778; + let Dict.776 : U64 = CallByName List.6 Dict.242; + let Dict.777 : U64 = 1i64; + let Dict.243 : U64 = CallByName Num.75 Dict.776 Dict.777; + let Dict.775 : U32 = CallByName Num.131 Dict.243; + let Dict.761 : {U32, U32} = Struct {Dict.775, Dict.231}; + let Dict.244 : List {U32, U32} = CallByName Dict.74 Dict.228 Dict.761 Dict.230; + let Dict.760 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.244, Dict.242, Dict.234, Dict.235, Dict.236}; + ret Dict.760; else - let Dict.751 : U64 = CallByName List.6 Dict.228; - let Dict.245 : U64 = CallByName Dict.75 Dict.230 Dict.751; + let Dict.752 : U64 = CallByName List.6 Dict.228; + let Dict.245 : U64 = CallByName Dict.75 Dict.230 Dict.752; let Dict.246 : U32 = CallByName Dict.55 Dict.231; - jump Dict.744 Dict.228 Dict.229 Dict.245 Dict.246 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236; + jump Dict.745 Dict.228 Dict.229 Dict.245 Dict.246 Dict.232 Dict.233 Dict.234 Dict.235 Dict.236; in - inc #Derived_gen.49; - jump Dict.744 #Derived_gen.45 #Derived_gen.46 #Derived_gen.47 #Derived_gen.48 #Derived_gen.49 #Derived_gen.50 #Derived_gen.51 #Derived_gen.52 #Derived_gen.53; + inc #Derived_gen.45; + jump Dict.745 #Derived_gen.41 #Derived_gen.42 #Derived_gen.43 #Derived_gen.44 #Derived_gen.45 #Derived_gen.46 #Derived_gen.47 #Derived_gen.48 #Derived_gen.49; procedure Dict.48 (): - let Dict.868 : U32 = 0i64; let Dict.869 : U32 = 0i64; - let Dict.867 : {U32, U32} = Struct {Dict.868, Dict.869}; - ret Dict.867; + let Dict.870 : U32 = 0i64; + let Dict.868 : {U32, U32} = Struct {Dict.869, Dict.870}; + ret Dict.868; procedure Dict.49 (): - let Dict.749 : U32 = 1i64; - let Dict.750 : U8 = 8i64; - let Dict.748 : U32 = CallByName Num.72 Dict.749 Dict.750; - ret Dict.748; + let Dict.750 : U32 = 1i64; + let Dict.751 : U8 = 8i64; + let Dict.749 : U32 = CallByName Num.72 Dict.750 Dict.751; + ret Dict.749; procedure Dict.50 (): - let Dict.799 : U32 = CallByName Dict.49; - let Dict.800 : U32 = 1i64; - let Dict.798 : U32 = CallByName Num.75 Dict.799 Dict.800; - ret Dict.798; + let Dict.800 : U32 = CallByName Dict.49; + let Dict.801 : U32 = 1i64; + let Dict.799 : U32 = CallByName Num.75 Dict.800 Dict.801; + ret Dict.799; procedure Dict.51 (): - let Dict.899 : Float32 = 0.8f64; - ret Dict.899; + let Dict.900 : Float32 = 0.8f64; + ret Dict.900; procedure Dict.52 (): - let Dict.897 : U8 = 64i64; - let Dict.898 : U8 = 3i64; - let Dict.896 : U8 = CallByName Num.75 Dict.897 Dict.898; - ret Dict.896; + let Dict.898 : U8 = 64i64; + let Dict.899 : U8 = 3i64; + let Dict.897 : U8 = CallByName Num.75 Dict.898 Dict.899; + ret Dict.897; procedure Dict.53 (): - let Dict.842 : U64 = 1i64; - let Dict.843 : U8 = 32i64; - let Dict.841 : U64 = CallByName Num.72 Dict.842 Dict.843; - ret Dict.841; + let Dict.843 : U64 = 1i64; + let Dict.844 : U8 = 32i64; + let Dict.842 : U64 = CallByName Num.72 Dict.843 Dict.844; + ret Dict.842; procedure Dict.54 (): - let Dict.840 : U64 = CallByName Dict.53; - ret Dict.840; + let Dict.841 : U64 = CallByName Dict.53; + ret Dict.841; procedure Dict.55 (Dict.314): - let Dict.747 : U32 = CallByName Dict.49; - let Dict.746 : U32 = CallByName Num.51 Dict.314 Dict.747; - ret Dict.746; - -procedure Dict.66 (Dict.727): - let Dict.384 : List {Str, I64} = StructAtIndex 1 Dict.727; - let Dict.385 : U64 = StructAtIndex 2 Dict.727; - let Dict.386 : Float32 = StructAtIndex 3 Dict.727; - let Dict.387 : U8 = StructAtIndex 4 Dict.727; - let #Derived_gen.68 : List {U32, U32} = StructAtIndex 0 Dict.727; + let Dict.748 : U32 = CallByName Dict.49; + let Dict.747 : U32 = CallByName Num.51 Dict.314 Dict.748; + ret Dict.747; + +procedure Dict.66 (Dict.728): + let Dict.385 : List {Str, I64} = StructAtIndex 1 Dict.728; + let Dict.386 : U64 = StructAtIndex 2 Dict.728; + let Dict.387 : Float32 = StructAtIndex 3 Dict.728; + let Dict.388 : U8 = StructAtIndex 4 Dict.728; + let #Derived_gen.68 : List {U32, U32} = StructAtIndex 0 Dict.728; dec #Derived_gen.68; - let Dict.885 : U64 = CallByName Dict.54; - let Dict.844 : Int1 = CallByName Bool.7 Dict.385 Dict.885; - if Dict.844 then - let Dict.884 : U8 = 1i64; - let Dict.388 : U8 = CallByName Num.75 Dict.387 Dict.884; - let Dict.863 : {List {U32, U32}, U64} = CallByName Dict.67 Dict.388 Dict.386; - let Dict.389 : List {U32, U32} = StructAtIndex 0 Dict.863; - let Dict.390 : U64 = StructAtIndex 1 Dict.863; - let Dict.391 : List {U32, U32} = CallByName Dict.71 Dict.389 Dict.384 Dict.388; - let Dict.845 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.391, Dict.384, Dict.390, Dict.386, Dict.388}; - ret Dict.845; + let Dict.886 : U64 = CallByName Dict.54; + let Dict.845 : Int1 = CallByName Bool.7 Dict.386 Dict.886; + if Dict.845 then + let Dict.885 : U8 = 1i64; + let Dict.389 : U8 = CallByName Num.75 Dict.388 Dict.885; + let Dict.864 : {List {U32, U32}, U64} = CallByName Dict.67 Dict.389 Dict.387; + let Dict.390 : List {U32, U32} = StructAtIndex 0 Dict.864; + let Dict.391 : U64 = StructAtIndex 1 Dict.864; + let Dict.392 : List {U32, U32} = CallByName Dict.71 Dict.390 Dict.385 Dict.389; + let Dict.846 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = Struct {Dict.392, Dict.385, Dict.391, Dict.387, Dict.389}; + ret Dict.846; else - dec Dict.384; - let Dict.835 : Str = "Dict hit limit of "; - let Dict.839 : U64 = CallByName Dict.54; - let Dict.837 : Str = CallByName Num.96 Dict.839; - let Dict.838 : Str = " elements. Unable to grow more."; - let Dict.836 : Str = CallByName Str.3 Dict.837 Dict.838; - dec Dict.838; - let Dict.834 : Str = CallByName Str.3 Dict.835 Dict.836; - dec Dict.836; - Crash Dict.834 - -procedure Dict.67 (Dict.392, Dict.393): - let Dict.394 : U64 = CallByName Dict.70 Dict.392; - let Dict.877 : U64 = CallByName Dict.54; - let Dict.872 : Int1 = CallByName Bool.11 Dict.394 Dict.877; - if Dict.872 then - let Dict.875 : {U32, U32} = CallByName Dict.48; - let Dict.876 : U64 = CallByName Dict.54; - let Dict.874 : List {U32, U32} = CallByName List.11 Dict.875 Dict.876; + dec Dict.385; + let Dict.836 : Str = "Dict hit limit of "; + let Dict.840 : U64 = CallByName Dict.54; + let Dict.838 : Str = CallByName Num.96 Dict.840; + let Dict.839 : Str = " elements. Unable to grow more."; + let Dict.837 : Str = CallByName Str.3 Dict.838 Dict.839; + dec Dict.839; + let Dict.835 : Str = CallByName Str.3 Dict.836 Dict.837; + dec Dict.837; + Crash Dict.835 + +procedure Dict.67 (Dict.393, Dict.394): + let Dict.395 : U64 = CallByName Dict.70 Dict.393; + let Dict.878 : U64 = CallByName Dict.54; + let Dict.873 : Int1 = CallByName Bool.11 Dict.395 Dict.878; + if Dict.873 then + let Dict.876 : {U32, U32} = CallByName Dict.48; + let Dict.877 : U64 = CallByName Dict.54; + let Dict.875 : List {U32, U32} = CallByName List.11 Dict.876 Dict.877; let Dict.54 : U64 = CallByName Dict.54; - let Dict.873 : {List {U32, U32}, U64} = Struct {Dict.874, Dict.54}; - ret Dict.873; + let Dict.874 : {List {U32, U32}, U64} = Struct {Dict.875, Dict.54}; + ret Dict.874; else - let Dict.871 : Float32 = CallByName Num.139 Dict.394; - let Dict.870 : Float32 = CallByName Num.21 Dict.871 Dict.393; - let Dict.395 : U64 = CallByName Num.50 Dict.870; - let Dict.866 : {U32, U32} = CallByName Dict.48; - let Dict.865 : List {U32, U32} = CallByName List.11 Dict.866 Dict.394; - let Dict.864 : {List {U32, U32}, U64} = Struct {Dict.865, Dict.395}; - ret Dict.864; - -procedure Dict.70 (Dict.402): - let Dict.881 : U64 = 1i64; - let Dict.883 : U8 = 64i64; - let Dict.882 : U8 = CallByName Num.75 Dict.883 Dict.402; - let Dict.879 : U64 = CallByName Num.72 Dict.881 Dict.882; - let Dict.880 : U64 = CallByName Dict.54; - let Dict.878 : U64 = CallByName Num.148 Dict.879 Dict.880; - ret Dict.878; - -procedure Dict.71 (Dict.403, Dict.404, Dict.405): - let Dict.846 : List {U32, U32} = CallByName List.83 Dict.404 Dict.403 Dict.405; - ret Dict.846; - -procedure Dict.72 (Dict.412, Dict.413, Dict.414): - let Dict.415 : U64 = CallByName Dict.76 Dict.413; - let Dict.416 : U32 = CallByName Dict.77 Dict.415; - let Dict.417 : U64 = CallByName Dict.78 Dict.415 Dict.414; - let Dict.854 : {U64, U32} = CallByName Dict.73 Dict.412 Dict.417 Dict.416; - ret Dict.854; + let Dict.872 : Float32 = CallByName Num.139 Dict.395; + let Dict.871 : Float32 = CallByName Num.21 Dict.872 Dict.394; + let Dict.396 : U64 = CallByName Num.50 Dict.871; + let Dict.867 : {U32, U32} = CallByName Dict.48; + let Dict.866 : List {U32, U32} = CallByName List.11 Dict.867 Dict.395; + let Dict.865 : {List {U32, U32}, U64} = Struct {Dict.866, Dict.396}; + ret Dict.865; + +procedure Dict.70 (Dict.403): + let Dict.882 : U64 = 1i64; + let Dict.884 : U8 = 64i64; + let Dict.883 : U8 = CallByName Num.75 Dict.884 Dict.403; + let Dict.880 : U64 = CallByName Num.72 Dict.882 Dict.883; + let Dict.881 : U64 = CallByName Dict.54; + let Dict.879 : U64 = CallByName Num.148 Dict.880 Dict.881; + ret Dict.879; + +procedure Dict.71 (Dict.404, Dict.405, Dict.406): + let Dict.847 : List {U32, U32} = CallByName List.83 Dict.405 Dict.404 Dict.406; + ret Dict.847; + +procedure Dict.72 (Dict.413, Dict.414, Dict.415): + let Dict.416 : U64 = CallByName Dict.76 Dict.414; + let Dict.417 : U32 = CallByName Dict.77 Dict.416; + let Dict.418 : U64 = CallByName Dict.78 Dict.416 Dict.415; + let Dict.855 : {U64, U32} = CallByName Dict.73 Dict.413 Dict.418 Dict.417; + ret Dict.855; procedure Dict.73 (#Derived_gen.16, #Derived_gen.17, #Derived_gen.18): - joinpoint Dict.855 Dict.418 Dict.419 Dict.420: - let Dict.421 : {U32, U32} = CallByName Dict.22 Dict.418 Dict.419; - let Dict.862 : U32 = StructAtIndex 1 Dict.421; - let Dict.857 : Int1 = CallByName Num.22 Dict.420 Dict.862; - if Dict.857 then - let Dict.861 : U64 = CallByName List.6 Dict.418; - let Dict.859 : U64 = CallByName Dict.75 Dict.419 Dict.861; - let Dict.860 : U32 = CallByName Dict.55 Dict.420; - jump Dict.855 Dict.418 Dict.859 Dict.860; + joinpoint Dict.856 Dict.419 Dict.420 Dict.421: + let Dict.422 : {U32, U32} = CallByName Dict.22 Dict.419 Dict.420; + let Dict.863 : U32 = StructAtIndex 1 Dict.422; + let Dict.858 : Int1 = CallByName Num.22 Dict.421 Dict.863; + if Dict.858 then + let Dict.862 : U64 = CallByName List.6 Dict.419; + let Dict.860 : U64 = CallByName Dict.75 Dict.420 Dict.862; + let Dict.861 : U32 = CallByName Dict.55 Dict.421; + jump Dict.856 Dict.419 Dict.860 Dict.861; else - dec Dict.418; - let Dict.856 : {U64, U32} = Struct {Dict.419, Dict.420}; - ret Dict.856; + dec Dict.419; + let Dict.857 : {U64, U32} = Struct {Dict.420, Dict.421}; + ret Dict.857; in inc #Derived_gen.16; - jump Dict.855 #Derived_gen.16 #Derived_gen.17 #Derived_gen.18; - -procedure Dict.74 (#Derived_gen.54, #Derived_gen.55, #Derived_gen.56): - joinpoint Dict.761 Dict.422 Dict.423 Dict.424: - let Dict.425 : {U32, U32} = CallByName Dict.22 Dict.422 Dict.424; - let Dict.771 : U32 = StructAtIndex 1 Dict.425; - let Dict.772 : U32 = 0i64; - let Dict.763 : Int1 = CallByName Bool.7 Dict.771 Dict.772; - if Dict.763 then - let Dict.426 : List {U32, U32} = CallByName List.3 Dict.422 Dict.424 Dict.423; - let Dict.768 : U32 = StructAtIndex 0 Dict.425; - let Dict.769 : U32 = StructAtIndex 1 Dict.425; - let Dict.770 : U32 = CallByName Dict.55 Dict.769; - let Dict.765 : {U32, U32} = Struct {Dict.768, Dict.770}; - let Dict.767 : U64 = CallByName List.6 Dict.426; - let Dict.766 : U64 = CallByName Dict.75 Dict.424 Dict.767; - jump Dict.761 Dict.426 Dict.765 Dict.766; + jump Dict.856 #Derived_gen.16 #Derived_gen.17 #Derived_gen.18; + +procedure Dict.74 (#Derived_gen.50, #Derived_gen.51, #Derived_gen.52): + joinpoint Dict.762 Dict.423 Dict.424 Dict.425: + let Dict.426 : {U32, U32} = CallByName Dict.22 Dict.423 Dict.425; + let Dict.772 : U32 = StructAtIndex 1 Dict.426; + let Dict.773 : U32 = 0i64; + let Dict.764 : Int1 = CallByName Bool.7 Dict.772 Dict.773; + if Dict.764 then + let Dict.427 : List {U32, U32} = CallByName List.3 Dict.423 Dict.425 Dict.424; + let Dict.769 : U32 = StructAtIndex 0 Dict.426; + let Dict.770 : U32 = StructAtIndex 1 Dict.426; + let Dict.771 : U32 = CallByName Dict.55 Dict.770; + let Dict.766 : {U32, U32} = Struct {Dict.769, Dict.771}; + let Dict.768 : U64 = CallByName List.6 Dict.427; + let Dict.767 : U64 = CallByName Dict.75 Dict.425 Dict.768; + jump Dict.762 Dict.427 Dict.766 Dict.767; else - let Dict.762 : List {U32, U32} = CallByName List.3 Dict.422 Dict.424 Dict.423; - ret Dict.762; + let Dict.763 : List {U32, U32} = CallByName List.3 Dict.423 Dict.425 Dict.424; + ret Dict.763; in - jump Dict.761 #Derived_gen.54 #Derived_gen.55 #Derived_gen.56; - -procedure Dict.75 (Dict.427, Dict.428): - let Dict.757 : U64 = 1i64; - let Dict.756 : U64 = CallByName Num.51 Dict.427 Dict.757; - let Dict.753 : Int1 = CallByName Bool.7 Dict.756 Dict.428; - if Dict.753 then - let Dict.755 : U64 = 1i64; - let Dict.754 : U64 = CallByName Num.51 Dict.427 Dict.755; - ret Dict.754; + jump Dict.762 #Derived_gen.50 #Derived_gen.51 #Derived_gen.52; + +procedure Dict.75 (Dict.428, Dict.429): + let Dict.758 : U64 = 1i64; + let Dict.757 : U64 = CallByName Num.51 Dict.428 Dict.758; + let Dict.754 : Int1 = CallByName Bool.7 Dict.757 Dict.429; + if Dict.754 then + let Dict.756 : U64 = 1i64; + let Dict.755 : U64 = CallByName Num.51 Dict.428 Dict.756; + ret Dict.755; else - let Dict.752 : U64 = 0i64; - ret Dict.752; - -procedure Dict.76 (Dict.429): - let Dict.805 : [C , C U64] = TagId(0) ; - let Dict.804 : {U64, U64} = CallByName Dict.80 Dict.805; - let Dict.802 : {U64, U64} = CallByName Hash.19 Dict.804 Dict.429; - let Dict.801 : U64 = CallByName Dict.83 Dict.802; - ret Dict.801; - -procedure Dict.77 (Dict.431): - let Dict.796 : U32 = CallByName Num.131 Dict.431; - let Dict.797 : U32 = CallByName Dict.50; - let Dict.794 : U32 = CallByName Num.69 Dict.796 Dict.797; - let Dict.795 : U32 = CallByName Dict.49; - let Dict.793 : U32 = CallByName Num.71 Dict.794 Dict.795; + let Dict.753 : U64 = 0i64; + ret Dict.753; + +procedure Dict.76 (Dict.430): + let Dict.806 : [C , C U64] = TagId(0) ; + let Dict.805 : {U64, U64} = CallByName Dict.80 Dict.806; + let Dict.803 : {U64, U64} = CallByName Hash.19 Dict.805 Dict.430; + let Dict.802 : U64 = CallByName Dict.83 Dict.803; + ret Dict.802; + +procedure Dict.77 (Dict.432): + let Dict.797 : U32 = CallByName Num.131 Dict.432; + let Dict.798 : U32 = CallByName Dict.50; + let Dict.795 : U32 = CallByName Num.69 Dict.797 Dict.798; + let Dict.796 : U32 = CallByName Dict.49; + let Dict.794 : U32 = CallByName Num.71 Dict.795 Dict.796; + ret Dict.794; + +procedure Dict.78 (Dict.433, Dict.434): + let Dict.793 : U64 = CallByName Num.74 Dict.433 Dict.434; ret Dict.793; -procedure Dict.78 (Dict.432, Dict.433): - let Dict.792 : U64 = CallByName Num.74 Dict.432 Dict.433; - ret Dict.792; - procedure Dict.8 (Dict.217, Dict.218, Dict.219): - joinpoint Dict.832 Dict.830: - let Dict.220 : List {U32, U32} = StructAtIndex 0 Dict.830; - let Dict.221 : List {Str, I64} = StructAtIndex 1 Dict.830; - let Dict.222 : U64 = StructAtIndex 2 Dict.830; - let Dict.223 : Float32 = StructAtIndex 3 Dict.830; - let Dict.224 : U8 = StructAtIndex 4 Dict.830; + joinpoint Dict.833 Dict.831: + let Dict.220 : List {U32, U32} = StructAtIndex 0 Dict.831; + let Dict.221 : List {Str, I64} = StructAtIndex 1 Dict.831; + let Dict.222 : U64 = StructAtIndex 2 Dict.831; + let Dict.223 : Float32 = StructAtIndex 3 Dict.831; + let Dict.224 : U8 = StructAtIndex 4 Dict.831; inc Dict.218; let Dict.225 : U64 = CallByName Dict.76 Dict.218; let Dict.226 : U32 = CallByName Dict.77 Dict.225; let Dict.227 : U64 = CallByName Dict.78 Dict.225 Dict.224; - let Dict.743 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.45 Dict.220 Dict.221 Dict.227 Dict.226 Dict.218 Dict.219 Dict.222 Dict.223 Dict.224; + let Dict.744 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.45 Dict.220 Dict.221 Dict.227 Dict.226 Dict.218 Dict.219 Dict.222 Dict.223 Dict.224; dec Dict.218; - ret Dict.743; + ret Dict.744; in inc 2 Dict.217; - let Dict.887 : U64 = CallByName Dict.4 Dict.217; - let Dict.888 : U64 = CallByName Dict.20 Dict.217; - let Dict.886 : Int1 = CallByName Num.22 Dict.887 Dict.888; - if Dict.886 then - jump Dict.832 Dict.217; + let Dict.888 : U64 = CallByName Dict.4 Dict.217; + let Dict.889 : U64 = CallByName Dict.20 Dict.217; + let Dict.887 : Int1 = CallByName Num.22 Dict.888 Dict.889; + if Dict.887 then + jump Dict.833 Dict.217; else - let Dict.831 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.66 Dict.217; - jump Dict.832 Dict.831; - -procedure Dict.80 (Dict.435): - joinpoint Dict.822 Dict.436: - let Dict.807 : U64 = CallByName Dict.82 Dict.436; - let Dict.806 : {U64, U64} = Struct {Dict.807, Dict.436}; - ret Dict.806; + let Dict.832 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.66 Dict.217; + jump Dict.833 Dict.832; + +procedure Dict.80 (Dict.436): + joinpoint Dict.823 Dict.437: + let Dict.808 : U64 = CallByName Dict.82 Dict.437; + let Dict.807 : {U64, U64} = Struct {Dict.808, Dict.437}; + ret Dict.807; in - let Dict.827 : U8 = 0i64; - let Dict.828 : U8 = GetTagId Dict.435; - let Dict.829 : Int1 = lowlevel Eq Dict.827 Dict.828; - if Dict.829 then - let Dict.824 : {} = Struct {}; - let Dict.823 : U64 = CallByName Dict.23 Dict.824; - jump Dict.822 Dict.823; + let Dict.828 : U8 = 0i64; + let Dict.829 : U8 = GetTagId Dict.436; + let Dict.830 : Int1 = lowlevel Eq Dict.828 Dict.829; + if Dict.830 then + let Dict.825 : {} = Struct {}; + let Dict.824 : U64 = CallByName Dict.23 Dict.825; + jump Dict.823 Dict.824; else - let Dict.437 : U64 = UnionAtIndex (Id 1) (Index 0) Dict.435; - jump Dict.822 Dict.437; - -procedure Dict.81 (Dict.716, Dict.717): - let Dict.440 : U64 = StructAtIndex 0 Dict.717; - let Dict.441 : U64 = StructAtIndex 1 Dict.717; - let Dict.443 : U64 = StructAtIndex 2 Dict.717; - let Dict.442 : U64 = StructAtIndex 3 Dict.717; - let Dict.438 : U64 = StructAtIndex 0 Dict.716; - let Dict.439 : U64 = StructAtIndex 1 Dict.716; - let Dict.921 : U64 = CallByName Dict.93; - let Dict.919 : U64 = CallByName Num.70 Dict.440 Dict.921; - let Dict.920 : U64 = CallByName Num.70 Dict.441 Dict.442; - let Dict.444 : {U64, U64} = CallByName Dict.97 Dict.919 Dict.920; - let Dict.916 : U64 = StructAtIndex 0 Dict.444; - let Dict.917 : U64 = CallByName Dict.92; - let Dict.915 : U64 = CallByName Num.70 Dict.916 Dict.917; - let Dict.445 : U64 = CallByName Num.70 Dict.915 Dict.443; - let Dict.912 : U64 = StructAtIndex 1 Dict.444; - let Dict.913 : U64 = CallByName Dict.93; - let Dict.446 : U64 = CallByName Num.70 Dict.912 Dict.913; - let Dict.447 : U64 = CallByName Dict.96 Dict.445 Dict.446; - let Dict.904 : U64 = CallByName Dict.96 Dict.439 Dict.447; - let Dict.903 : {U64, U64} = Struct {Dict.438, Dict.904}; - ret Dict.903; - -procedure Dict.82 (Dict.448): - let Dict.820 : U64 = CallByName Dict.92; - let Dict.810 : U64 = CallByName Num.70 Dict.448 Dict.820; - let Dict.811 : U64 = CallByName Dict.93; - let Dict.809 : U64 = CallByName Dict.96 Dict.810 Dict.811; - let Dict.808 : U64 = CallByName Num.70 Dict.809 Dict.448; - ret Dict.808; - -procedure Dict.83 (Dict.735): - let Dict.449 : U64 = StructAtIndex 1 Dict.735; - ret Dict.449; - -procedure Dict.89 (Dict.710, Dict.488): - let Dict.486 : U64 = StructAtIndex 0 Dict.710; - let Dict.487 : U64 = StructAtIndex 1 Dict.710; - let Dict.489 : U64 = CallByName List.6 Dict.488; - joinpoint Dict.926 Dict.490: - let Dict.901 : {U64, U64} = Struct {Dict.486, Dict.487}; - let Dict.922 : U64 = StructAtIndex 0 Dict.490; - let Dict.923 : U64 = StructAtIndex 1 Dict.490; - let Dict.924 : U64 = StructAtIndex 2 Dict.490; - let Dict.902 : {U64, U64, U64, U64} = Struct {Dict.922, Dict.923, Dict.489, Dict.924}; - let Dict.900 : {U64, U64} = CallByName Dict.81 Dict.901 Dict.902; - ret Dict.900; + let Dict.438 : U64 = UnionAtIndex (Id 1) (Index 0) Dict.436; + jump Dict.823 Dict.438; + +procedure Dict.81 (Dict.717, Dict.718): + let Dict.441 : U64 = StructAtIndex 0 Dict.718; + let Dict.442 : U64 = StructAtIndex 1 Dict.718; + let Dict.444 : U64 = StructAtIndex 2 Dict.718; + let Dict.443 : U64 = StructAtIndex 3 Dict.718; + let Dict.439 : U64 = StructAtIndex 0 Dict.717; + let Dict.440 : U64 = StructAtIndex 1 Dict.717; + let Dict.922 : U64 = CallByName Dict.93; + let Dict.920 : U64 = CallByName Num.70 Dict.441 Dict.922; + let Dict.921 : U64 = CallByName Num.70 Dict.442 Dict.443; + let Dict.445 : {U64, U64} = CallByName Dict.97 Dict.920 Dict.921; + let Dict.917 : U64 = StructAtIndex 0 Dict.445; + let Dict.918 : U64 = CallByName Dict.92; + let Dict.916 : U64 = CallByName Num.70 Dict.917 Dict.918; + let Dict.446 : U64 = CallByName Num.70 Dict.916 Dict.444; + let Dict.913 : U64 = StructAtIndex 1 Dict.445; + let Dict.914 : U64 = CallByName Dict.93; + let Dict.447 : U64 = CallByName Num.70 Dict.913 Dict.914; + let Dict.448 : U64 = CallByName Dict.96 Dict.446 Dict.447; + let Dict.905 : U64 = CallByName Dict.96 Dict.440 Dict.448; + let Dict.904 : {U64, U64} = Struct {Dict.439, Dict.905}; + ret Dict.904; + +procedure Dict.82 (Dict.449): + let Dict.821 : U64 = CallByName Dict.92; + let Dict.811 : U64 = CallByName Num.70 Dict.449 Dict.821; + let Dict.812 : U64 = CallByName Dict.93; + let Dict.810 : U64 = CallByName Dict.96 Dict.811 Dict.812; + let Dict.809 : U64 = CallByName Num.70 Dict.810 Dict.449; + ret Dict.809; + +procedure Dict.83 (Dict.736): + let Dict.450 : U64 = StructAtIndex 1 Dict.736; + ret Dict.450; + +procedure Dict.89 (Dict.711, Dict.489): + let Dict.487 : U64 = StructAtIndex 0 Dict.711; + let Dict.488 : U64 = StructAtIndex 1 Dict.711; + let Dict.490 : U64 = CallByName List.6 Dict.489; + joinpoint Dict.927 Dict.491: + let Dict.902 : {U64, U64} = Struct {Dict.487, Dict.488}; + let Dict.923 : U64 = StructAtIndex 0 Dict.491; + let Dict.924 : U64 = StructAtIndex 1 Dict.491; + let Dict.925 : U64 = StructAtIndex 2 Dict.491; + let Dict.903 : {U64, U64, U64, U64} = Struct {Dict.923, Dict.924, Dict.490, Dict.925}; + let Dict.901 : {U64, U64} = CallByName Dict.81 Dict.902 Dict.903; + ret Dict.901; in - let Dict.1100 : U64 = 16i64; - let Dict.1040 : Int1 = CallByName Num.23 Dict.489 Dict.1100; - if Dict.1040 then - joinpoint Dict.1042 Dict.925: - jump Dict.926 Dict.925; + let Dict.1101 : U64 = 16i64; + let Dict.1041 : Int1 = CallByName Num.23 Dict.490 Dict.1101; + if Dict.1041 then + joinpoint Dict.1043 Dict.926: + jump Dict.927 Dict.926; in - let Dict.1099 : U64 = 4i64; - let Dict.1064 : Int1 = CallByName Num.25 Dict.489 Dict.1099; - if Dict.1064 then - let Dict.1098 : U8 = 3i64; - let Dict.1096 : U64 = CallByName Num.74 Dict.489 Dict.1098; - let Dict.1097 : U8 = 2i64; - let Dict.491 : U64 = CallByName Num.72 Dict.1096 Dict.1097; - let Dict.1095 : U64 = 0i64; - let Dict.1093 : U64 = CallByName Dict.99 Dict.488 Dict.1095; - let Dict.1094 : U8 = 32i64; - let Dict.1091 : U64 = CallByName Num.72 Dict.1093 Dict.1094; - let Dict.1092 : U64 = CallByName Dict.99 Dict.488 Dict.491; - let Dict.492 : U64 = CallByName Num.71 Dict.1091 Dict.1092; - let Dict.1090 : U64 = 4i64; - let Dict.1089 : U64 = CallByName Num.75 Dict.489 Dict.1090; - let Dict.1087 : U64 = CallByName Dict.99 Dict.488 Dict.1089; - let Dict.1088 : U8 = 32i64; - let Dict.1065 : U64 = CallByName Num.72 Dict.1087 Dict.1088; - let Dict.1086 : U64 = 4i64; - let Dict.1085 : U64 = CallByName Num.75 Dict.489 Dict.1086; - let Dict.1067 : U64 = CallByName Num.75 Dict.1085 Dict.491; - let Dict.1066 : U64 = CallByName Dict.99 Dict.488 Dict.1067; - let Dict.493 : U64 = CallByName Num.71 Dict.1065 Dict.1066; - let Dict.1041 : {U64, U64, U64} = Struct {Dict.492, Dict.493, Dict.486}; - jump Dict.1042 Dict.1041; + let Dict.1100 : U64 = 4i64; + let Dict.1065 : Int1 = CallByName Num.25 Dict.490 Dict.1100; + if Dict.1065 then + let Dict.1099 : U8 = 3i64; + let Dict.1097 : U64 = CallByName Num.74 Dict.490 Dict.1099; + let Dict.1098 : U8 = 2i64; + let Dict.492 : U64 = CallByName Num.72 Dict.1097 Dict.1098; + let Dict.1096 : U64 = 0i64; + let Dict.1094 : U64 = CallByName Dict.99 Dict.489 Dict.1096; + let Dict.1095 : U8 = 32i64; + let Dict.1092 : U64 = CallByName Num.72 Dict.1094 Dict.1095; + let Dict.1093 : U64 = CallByName Dict.99 Dict.489 Dict.492; + let Dict.493 : U64 = CallByName Num.71 Dict.1092 Dict.1093; + let Dict.1091 : U64 = 4i64; + let Dict.1090 : U64 = CallByName Num.75 Dict.490 Dict.1091; + let Dict.1088 : U64 = CallByName Dict.99 Dict.489 Dict.1090; + let Dict.1089 : U8 = 32i64; + let Dict.1066 : U64 = CallByName Num.72 Dict.1088 Dict.1089; + let Dict.1087 : U64 = 4i64; + let Dict.1086 : U64 = CallByName Num.75 Dict.490 Dict.1087; + let Dict.1068 : U64 = CallByName Num.75 Dict.1086 Dict.492; + let Dict.1067 : U64 = CallByName Dict.99 Dict.489 Dict.1068; + let Dict.494 : U64 = CallByName Num.71 Dict.1066 Dict.1067; + let Dict.1042 : {U64, U64, U64} = Struct {Dict.493, Dict.494, Dict.487}; + jump Dict.1043 Dict.1042; else - let Dict.1063 : U64 = 0i64; - let Dict.1045 : Int1 = CallByName Num.24 Dict.489 Dict.1063; - if Dict.1045 then + let Dict.1064 : U64 = 0i64; + let Dict.1046 : Int1 = CallByName Num.24 Dict.490 Dict.1064; + if Dict.1046 then + let Dict.1049 : U64 = 0i64; + let Dict.1047 : U64 = CallByName Dict.100 Dict.489 Dict.1049 Dict.490; let Dict.1048 : U64 = 0i64; - let Dict.1046 : U64 = CallByName Dict.100 Dict.488 Dict.1048 Dict.489; - let Dict.1047 : U64 = 0i64; - let Dict.1041 : {U64, U64, U64} = Struct {Dict.1046, Dict.1047, Dict.486}; - jump Dict.1042 Dict.1041; + let Dict.1042 : {U64, U64, U64} = Struct {Dict.1047, Dict.1048, Dict.487}; + jump Dict.1043 Dict.1042; else - let Dict.1043 : U64 = 0i64; let Dict.1044 : U64 = 0i64; - let Dict.1041 : {U64, U64, U64} = Struct {Dict.1043, Dict.1044, Dict.486}; - jump Dict.1042 Dict.1041; + let Dict.1045 : U64 = 0i64; + let Dict.1042 : {U64, U64, U64} = Struct {Dict.1044, Dict.1045, Dict.487}; + jump Dict.1043 Dict.1042; else - let Dict.1039 : U64 = 48i64; - let Dict.1037 : Int1 = CallByName Num.23 Dict.489 Dict.1039; - if Dict.1037 then - let Dict.1038 : U64 = 0i64; - let Dict.925 : {U64, U64, U64} = CallByName Dict.91 Dict.486 Dict.488 Dict.1038 Dict.489; - jump Dict.926 Dict.925; + let Dict.1040 : U64 = 48i64; + let Dict.1038 : Int1 = CallByName Num.23 Dict.490 Dict.1040; + if Dict.1038 then + let Dict.1039 : U64 = 0i64; + let Dict.926 : {U64, U64, U64} = CallByName Dict.91 Dict.487 Dict.489 Dict.1039 Dict.490; + jump Dict.927 Dict.926; else - let Dict.927 : U64 = 0i64; - let Dict.925 : {U64, U64, U64} = CallByName Dict.90 Dict.486 Dict.486 Dict.486 Dict.488 Dict.927 Dict.489; - jump Dict.926 Dict.925; + let Dict.928 : U64 = 0i64; + let Dict.926 : {U64, U64, U64} = CallByName Dict.90 Dict.487 Dict.487 Dict.487 Dict.489 Dict.928 Dict.490; + jump Dict.927 Dict.926; procedure Dict.90 (#Derived_gen.6, #Derived_gen.7, #Derived_gen.8, #Derived_gen.9, #Derived_gen.10, #Derived_gen.11): - joinpoint Dict.928 Dict.494 Dict.495 Dict.496 Dict.497 Dict.498 Dict.499: - let Dict.1035 : U64 = CallByName Dict.98 Dict.497 Dict.498; - let Dict.1036 : U64 = CallByName Dict.93; - let Dict.1030 : U64 = CallByName Num.70 Dict.1035 Dict.1036; - let Dict.1034 : U64 = 8i64; - let Dict.1033 : U64 = CallByName Num.51 Dict.498 Dict.1034; - let Dict.1032 : U64 = CallByName Dict.98 Dict.497 Dict.1033; - let Dict.1031 : U64 = CallByName Num.70 Dict.1032 Dict.494; - let Dict.500 : U64 = CallByName Dict.96 Dict.1030 Dict.1031; - let Dict.1029 : U64 = 16i64; - let Dict.1028 : U64 = CallByName Num.51 Dict.498 Dict.1029; - let Dict.1025 : U64 = CallByName Dict.98 Dict.497 Dict.1028; - let Dict.1026 : U64 = CallByName Dict.94; - let Dict.1020 : U64 = CallByName Num.70 Dict.1025 Dict.1026; - let Dict.1024 : U64 = 24i64; - let Dict.1023 : U64 = CallByName Num.51 Dict.498 Dict.1024; - let Dict.1022 : U64 = CallByName Dict.98 Dict.497 Dict.1023; - let Dict.1021 : U64 = CallByName Num.70 Dict.1022 Dict.495; - let Dict.501 : U64 = CallByName Dict.96 Dict.1020 Dict.1021; - let Dict.1019 : U64 = 32i64; - let Dict.1018 : U64 = CallByName Num.51 Dict.498 Dict.1019; - let Dict.1015 : U64 = CallByName Dict.98 Dict.497 Dict.1018; - let Dict.1016 : U64 = CallByName Dict.95; - let Dict.1010 : U64 = CallByName Num.70 Dict.1015 Dict.1016; - let Dict.1014 : U64 = 40i64; - let Dict.1013 : U64 = CallByName Num.51 Dict.498 Dict.1014; - let Dict.1012 : U64 = CallByName Dict.98 Dict.497 Dict.1013; - let Dict.1011 : U64 = CallByName Num.70 Dict.1012 Dict.496; - let Dict.502 : U64 = CallByName Dict.96 Dict.1010 Dict.1011; + joinpoint Dict.929 Dict.495 Dict.496 Dict.497 Dict.498 Dict.499 Dict.500: + let Dict.1036 : U64 = CallByName Dict.98 Dict.498 Dict.499; + let Dict.1037 : U64 = CallByName Dict.93; + let Dict.1031 : U64 = CallByName Num.70 Dict.1036 Dict.1037; + let Dict.1035 : U64 = 8i64; + let Dict.1034 : U64 = CallByName Num.51 Dict.499 Dict.1035; + let Dict.1033 : U64 = CallByName Dict.98 Dict.498 Dict.1034; + let Dict.1032 : U64 = CallByName Num.70 Dict.1033 Dict.495; + let Dict.501 : U64 = CallByName Dict.96 Dict.1031 Dict.1032; + let Dict.1030 : U64 = 16i64; + let Dict.1029 : U64 = CallByName Num.51 Dict.499 Dict.1030; + let Dict.1026 : U64 = CallByName Dict.98 Dict.498 Dict.1029; + let Dict.1027 : U64 = CallByName Dict.94; + let Dict.1021 : U64 = CallByName Num.70 Dict.1026 Dict.1027; + let Dict.1025 : U64 = 24i64; + let Dict.1024 : U64 = CallByName Num.51 Dict.499 Dict.1025; + let Dict.1023 : U64 = CallByName Dict.98 Dict.498 Dict.1024; + let Dict.1022 : U64 = CallByName Num.70 Dict.1023 Dict.496; + let Dict.502 : U64 = CallByName Dict.96 Dict.1021 Dict.1022; + let Dict.1020 : U64 = 32i64; + let Dict.1019 : U64 = CallByName Num.51 Dict.499 Dict.1020; + let Dict.1016 : U64 = CallByName Dict.98 Dict.498 Dict.1019; + let Dict.1017 : U64 = CallByName Dict.95; + let Dict.1011 : U64 = CallByName Num.70 Dict.1016 Dict.1017; + let Dict.1015 : U64 = 40i64; + let Dict.1014 : U64 = CallByName Num.51 Dict.499 Dict.1015; + let Dict.1013 : U64 = CallByName Dict.98 Dict.498 Dict.1014; + let Dict.1012 : U64 = CallByName Num.70 Dict.1013 Dict.497; + let Dict.503 : U64 = CallByName Dict.96 Dict.1011 Dict.1012; + let Dict.1010 : U64 = 48i64; + let Dict.504 : U64 = CallByName Num.75 Dict.500 Dict.1010; let Dict.1009 : U64 = 48i64; - let Dict.503 : U64 = CallByName Num.75 Dict.499 Dict.1009; + let Dict.505 : U64 = CallByName Num.51 Dict.499 Dict.1009; let Dict.1008 : U64 = 48i64; - let Dict.504 : U64 = CallByName Num.51 Dict.498 Dict.1008; - let Dict.1007 : U64 = 48i64; - let Dict.1005 : Int1 = CallByName Num.24 Dict.503 Dict.1007; - if Dict.1005 then - jump Dict.928 Dict.500 Dict.501 Dict.502 Dict.497 Dict.504 Dict.503; + let Dict.1006 : Int1 = CallByName Num.24 Dict.504 Dict.1008; + if Dict.1006 then + jump Dict.929 Dict.501 Dict.502 Dict.503 Dict.498 Dict.505 Dict.504; else - let Dict.1004 : U64 = 16i64; - let Dict.979 : Int1 = CallByName Num.24 Dict.503 Dict.1004; - if Dict.979 then - let Dict.1003 : U64 = CallByName Num.70 Dict.501 Dict.500; - let Dict.505 : U64 = CallByName Num.70 Dict.502 Dict.1003; - let Dict.980 : {U64, U64, U64} = CallByName Dict.91 Dict.505 Dict.497 Dict.504 Dict.503; - dec Dict.497; - ret Dict.980; + let Dict.1005 : U64 = 16i64; + let Dict.980 : Int1 = CallByName Num.24 Dict.504 Dict.1005; + if Dict.980 then + let Dict.1004 : U64 = CallByName Num.70 Dict.502 Dict.501; + let Dict.506 : U64 = CallByName Num.70 Dict.503 Dict.1004; + let Dict.981 : {U64, U64, U64} = CallByName Dict.91 Dict.506 Dict.498 Dict.505 Dict.504; + dec Dict.498; + ret Dict.981; else - let Dict.978 : U64 = CallByName Num.70 Dict.501 Dict.500; - let Dict.506 : U64 = CallByName Num.70 Dict.502 Dict.978; - let Dict.977 : U64 = 16i64; - let Dict.976 : U64 = CallByName Num.75 Dict.503 Dict.977; - let Dict.975 : U64 = CallByName Num.51 Dict.976 Dict.504; - let Dict.930 : U64 = CallByName Dict.98 Dict.497 Dict.975; - let Dict.974 : U64 = 8i64; - let Dict.973 : U64 = CallByName Num.75 Dict.503 Dict.974; - let Dict.932 : U64 = CallByName Num.51 Dict.973 Dict.504; - let Dict.931 : U64 = CallByName Dict.98 Dict.497 Dict.932; - dec Dict.497; - let Dict.929 : {U64, U64, U64} = Struct {Dict.930, Dict.931, Dict.506}; - ret Dict.929; + let Dict.979 : U64 = CallByName Num.70 Dict.502 Dict.501; + let Dict.507 : U64 = CallByName Num.70 Dict.503 Dict.979; + let Dict.978 : U64 = 16i64; + let Dict.977 : U64 = CallByName Num.75 Dict.504 Dict.978; + let Dict.976 : U64 = CallByName Num.51 Dict.977 Dict.505; + let Dict.931 : U64 = CallByName Dict.98 Dict.498 Dict.976; + let Dict.975 : U64 = 8i64; + let Dict.974 : U64 = CallByName Num.75 Dict.504 Dict.975; + let Dict.933 : U64 = CallByName Num.51 Dict.974 Dict.505; + let Dict.932 : U64 = CallByName Dict.98 Dict.498 Dict.933; + dec Dict.498; + let Dict.930 : {U64, U64, U64} = Struct {Dict.931, Dict.932, Dict.507}; + ret Dict.930; in inc #Derived_gen.9; - jump Dict.928 #Derived_gen.6 #Derived_gen.7 #Derived_gen.8 #Derived_gen.9 #Derived_gen.10 #Derived_gen.11; + jump Dict.929 #Derived_gen.6 #Derived_gen.7 #Derived_gen.8 #Derived_gen.9 #Derived_gen.10 #Derived_gen.11; procedure Dict.91 (#Derived_gen.0, #Derived_gen.1, #Derived_gen.2, #Derived_gen.3): - joinpoint Dict.981 Dict.507 Dict.508 Dict.509 Dict.510: - let Dict.1001 : U64 = CallByName Dict.98 Dict.508 Dict.509; - let Dict.1002 : U64 = CallByName Dict.93; - let Dict.996 : U64 = CallByName Num.70 Dict.1001 Dict.1002; - let Dict.1000 : U64 = 8i64; - let Dict.999 : U64 = CallByName Num.51 Dict.509 Dict.1000; - let Dict.998 : U64 = CallByName Dict.98 Dict.508 Dict.999; - let Dict.997 : U64 = CallByName Num.70 Dict.998 Dict.507; - let Dict.511 : U64 = CallByName Dict.96 Dict.996 Dict.997; + joinpoint Dict.982 Dict.508 Dict.509 Dict.510 Dict.511: + let Dict.1002 : U64 = CallByName Dict.98 Dict.509 Dict.510; + let Dict.1003 : U64 = CallByName Dict.93; + let Dict.997 : U64 = CallByName Num.70 Dict.1002 Dict.1003; + let Dict.1001 : U64 = 8i64; + let Dict.1000 : U64 = CallByName Num.51 Dict.510 Dict.1001; + let Dict.999 : U64 = CallByName Dict.98 Dict.509 Dict.1000; + let Dict.998 : U64 = CallByName Num.70 Dict.999 Dict.508; + let Dict.512 : U64 = CallByName Dict.96 Dict.997 Dict.998; + let Dict.996 : U64 = 16i64; + let Dict.513 : U64 = CallByName Num.75 Dict.511 Dict.996; let Dict.995 : U64 = 16i64; - let Dict.512 : U64 = CallByName Num.75 Dict.510 Dict.995; + let Dict.514 : U64 = CallByName Num.51 Dict.510 Dict.995; let Dict.994 : U64 = 16i64; - let Dict.513 : U64 = CallByName Num.51 Dict.509 Dict.994; - let Dict.993 : U64 = 16i64; - let Dict.983 : Int1 = CallByName Num.23 Dict.512 Dict.993; - if Dict.983 then - let Dict.992 : U64 = 16i64; - let Dict.991 : U64 = CallByName Num.75 Dict.512 Dict.992; - let Dict.990 : U64 = CallByName Num.51 Dict.991 Dict.513; - let Dict.985 : U64 = CallByName Dict.98 Dict.508 Dict.990; - let Dict.989 : U64 = 8i64; - let Dict.988 : U64 = CallByName Num.75 Dict.512 Dict.989; - let Dict.987 : U64 = CallByName Num.51 Dict.988 Dict.513; - let Dict.986 : U64 = CallByName Dict.98 Dict.508 Dict.987; - dec Dict.508; - let Dict.984 : {U64, U64, U64} = Struct {Dict.985, Dict.986, Dict.511}; - ret Dict.984; + let Dict.984 : Int1 = CallByName Num.23 Dict.513 Dict.994; + if Dict.984 then + let Dict.993 : U64 = 16i64; + let Dict.992 : U64 = CallByName Num.75 Dict.513 Dict.993; + let Dict.991 : U64 = CallByName Num.51 Dict.992 Dict.514; + let Dict.986 : U64 = CallByName Dict.98 Dict.509 Dict.991; + let Dict.990 : U64 = 8i64; + let Dict.989 : U64 = CallByName Num.75 Dict.513 Dict.990; + let Dict.988 : U64 = CallByName Num.51 Dict.989 Dict.514; + let Dict.987 : U64 = CallByName Dict.98 Dict.509 Dict.988; + dec Dict.509; + let Dict.985 : {U64, U64, U64} = Struct {Dict.986, Dict.987, Dict.512}; + ret Dict.985; else - jump Dict.981 Dict.511 Dict.508 Dict.513 Dict.512; + jump Dict.982 Dict.512 Dict.509 Dict.514 Dict.513; in inc #Derived_gen.1; - jump Dict.981 #Derived_gen.0 #Derived_gen.1 #Derived_gen.2 #Derived_gen.3; + jump Dict.982 #Derived_gen.0 #Derived_gen.1 #Derived_gen.2 #Derived_gen.3; procedure Dict.92 (): - let Dict.918 : U64 = 11562461410679940143i64; - ret Dict.918; + let Dict.919 : U64 = 11562461410679940143i64; + ret Dict.919; procedure Dict.93 (): - let Dict.914 : U64 = 16646288086500911323i64; - ret Dict.914; + let Dict.915 : U64 = 16646288086500911323i64; + ret Dict.915; procedure Dict.94 (): - let Dict.1027 : U64 = 10285213230658275043i64; - ret Dict.1027; + let Dict.1028 : U64 = 10285213230658275043i64; + ret Dict.1028; procedure Dict.95 (): - let Dict.1017 : U64 = 6384245875588680899i64; - ret Dict.1017; - -procedure Dict.96 (Dict.514, Dict.515): - let Dict.906 : {U64, U64} = CallByName Dict.97 Dict.514 Dict.515; - let Dict.516 : U64 = StructAtIndex 0 Dict.906; - let Dict.517 : U64 = StructAtIndex 1 Dict.906; - let Dict.905 : U64 = CallByName Num.70 Dict.516 Dict.517; - ret Dict.905; - -procedure Dict.97 (Dict.518, Dict.519): - let Dict.910 : U128 = CallByName Num.135 Dict.518; + let Dict.1018 : U64 = 6384245875588680899i64; + ret Dict.1018; + +procedure Dict.96 (Dict.515, Dict.516): + let Dict.907 : {U64, U64} = CallByName Dict.97 Dict.515 Dict.516; + let Dict.517 : U64 = StructAtIndex 0 Dict.907; + let Dict.518 : U64 = StructAtIndex 1 Dict.907; + let Dict.906 : U64 = CallByName Num.70 Dict.517 Dict.518; + ret Dict.906; + +procedure Dict.97 (Dict.519, Dict.520): let Dict.911 : U128 = CallByName Num.135 Dict.519; - let Dict.520 : U128 = CallByName Num.78 Dict.910 Dict.911; - let Dict.521 : U64 = CallByName Num.133 Dict.520; - let Dict.909 : U8 = 64i64; - let Dict.908 : U128 = CallByName Num.74 Dict.520 Dict.909; - let Dict.522 : U64 = CallByName Num.133 Dict.908; - let Dict.907 : {U64, U64} = Struct {Dict.521, Dict.522}; - ret Dict.907; - -procedure Dict.98 (Dict.523, Dict.524): - let Dict.972 : U8 = CallByName Dict.22 Dict.523 Dict.524; - let Dict.525 : U64 = CallByName Num.133 Dict.972; - let Dict.971 : U64 = 1i64; - let Dict.970 : U64 = CallByName Num.51 Dict.524 Dict.971; - let Dict.969 : U8 = CallByName Dict.22 Dict.523 Dict.970; - let Dict.526 : U64 = CallByName Num.133 Dict.969; - let Dict.968 : U64 = 2i64; - let Dict.967 : U64 = CallByName Num.51 Dict.524 Dict.968; - let Dict.966 : U8 = CallByName Dict.22 Dict.523 Dict.967; - let Dict.527 : U64 = CallByName Num.133 Dict.966; - let Dict.965 : U64 = 3i64; - let Dict.964 : U64 = CallByName Num.51 Dict.524 Dict.965; - let Dict.963 : U8 = CallByName Dict.22 Dict.523 Dict.964; - let Dict.528 : U64 = CallByName Num.133 Dict.963; - let Dict.962 : U64 = 4i64; - let Dict.961 : U64 = CallByName Num.51 Dict.524 Dict.962; - let Dict.960 : U8 = CallByName Dict.22 Dict.523 Dict.961; - let Dict.529 : U64 = CallByName Num.133 Dict.960; - let Dict.959 : U64 = 5i64; - let Dict.958 : U64 = CallByName Num.51 Dict.524 Dict.959; - let Dict.957 : U8 = CallByName Dict.22 Dict.523 Dict.958; - let Dict.530 : U64 = CallByName Num.133 Dict.957; - let Dict.956 : U64 = 6i64; - let Dict.955 : U64 = CallByName Num.51 Dict.524 Dict.956; - let Dict.954 : U8 = CallByName Dict.22 Dict.523 Dict.955; - let Dict.531 : U64 = CallByName Num.133 Dict.954; - let Dict.953 : U64 = 7i64; - let Dict.951 : U64 = CallByName Num.51 Dict.524 Dict.953; - let Dict.950 : U8 = CallByName Dict.22 Dict.523 Dict.951; - let Dict.532 : U64 = CallByName Num.133 Dict.950; - let Dict.949 : U8 = 8i64; - let Dict.948 : U64 = CallByName Num.72 Dict.526 Dict.949; - let Dict.533 : U64 = CallByName Num.71 Dict.525 Dict.948; - let Dict.947 : U8 = 16i64; - let Dict.944 : U64 = CallByName Num.72 Dict.527 Dict.947; - let Dict.946 : U8 = 24i64; - let Dict.945 : U64 = CallByName Num.72 Dict.528 Dict.946; - let Dict.534 : U64 = CallByName Num.71 Dict.944 Dict.945; - let Dict.943 : U8 = 32i64; - let Dict.940 : U64 = CallByName Num.72 Dict.529 Dict.943; - let Dict.942 : U8 = 40i64; - let Dict.941 : U64 = CallByName Num.72 Dict.530 Dict.942; - let Dict.535 : U64 = CallByName Num.71 Dict.940 Dict.941; - let Dict.939 : U8 = 48i64; - let Dict.936 : U64 = CallByName Num.72 Dict.531 Dict.939; - let Dict.938 : U8 = 56i64; - let Dict.937 : U64 = CallByName Num.72 Dict.532 Dict.938; - let Dict.536 : U64 = CallByName Num.71 Dict.936 Dict.937; - let Dict.934 : U64 = CallByName Num.71 Dict.533 Dict.534; - let Dict.935 : U64 = CallByName Num.71 Dict.535 Dict.536; - let Dict.933 : U64 = CallByName Num.71 Dict.934 Dict.935; - ret Dict.933; - -procedure Dict.99 (Dict.537, Dict.538): - let Dict.1084 : U8 = CallByName Dict.22 Dict.537 Dict.538; - let Dict.539 : U64 = CallByName Num.133 Dict.1084; - let Dict.1083 : U64 = 1i64; - let Dict.1082 : U64 = CallByName Num.51 Dict.538 Dict.1083; - let Dict.1081 : U8 = CallByName Dict.22 Dict.537 Dict.1082; - let Dict.540 : U64 = CallByName Num.133 Dict.1081; - let Dict.1080 : U64 = 2i64; - let Dict.1079 : U64 = CallByName Num.51 Dict.538 Dict.1080; - let Dict.1078 : U8 = CallByName Dict.22 Dict.537 Dict.1079; - let Dict.541 : U64 = CallByName Num.133 Dict.1078; - let Dict.1077 : U64 = 3i64; - let Dict.1076 : U64 = CallByName Num.51 Dict.538 Dict.1077; - let Dict.1075 : U8 = CallByName Dict.22 Dict.537 Dict.1076; - let Dict.542 : U64 = CallByName Num.133 Dict.1075; - let Dict.1074 : U8 = 8i64; - let Dict.1073 : U64 = CallByName Num.72 Dict.540 Dict.1074; - let Dict.543 : U64 = CallByName Num.71 Dict.539 Dict.1073; - let Dict.1072 : U8 = 16i64; - let Dict.1069 : U64 = CallByName Num.72 Dict.541 Dict.1072; - let Dict.1071 : U8 = 24i64; - let Dict.1070 : U64 = CallByName Num.72 Dict.542 Dict.1071; - let Dict.544 : U64 = CallByName Num.71 Dict.1069 Dict.1070; - let Dict.1068 : U64 = CallByName Num.71 Dict.543 Dict.544; - ret Dict.1068; + let Dict.912 : U128 = CallByName Num.135 Dict.520; + let Dict.521 : U128 = CallByName Num.78 Dict.911 Dict.912; + let Dict.522 : U64 = CallByName Num.133 Dict.521; + let Dict.910 : U8 = 64i64; + let Dict.909 : U128 = CallByName Num.74 Dict.521 Dict.910; + let Dict.523 : U64 = CallByName Num.133 Dict.909; + let Dict.908 : {U64, U64} = Struct {Dict.522, Dict.523}; + ret Dict.908; + +procedure Dict.98 (Dict.524, Dict.525): + let Dict.973 : U8 = CallByName Dict.22 Dict.524 Dict.525; + let Dict.526 : U64 = CallByName Num.133 Dict.973; + let Dict.972 : U64 = 1i64; + let Dict.971 : U64 = CallByName Num.51 Dict.525 Dict.972; + let Dict.970 : U8 = CallByName Dict.22 Dict.524 Dict.971; + let Dict.527 : U64 = CallByName Num.133 Dict.970; + let Dict.969 : U64 = 2i64; + let Dict.968 : U64 = CallByName Num.51 Dict.525 Dict.969; + let Dict.967 : U8 = CallByName Dict.22 Dict.524 Dict.968; + let Dict.528 : U64 = CallByName Num.133 Dict.967; + let Dict.966 : U64 = 3i64; + let Dict.965 : U64 = CallByName Num.51 Dict.525 Dict.966; + let Dict.964 : U8 = CallByName Dict.22 Dict.524 Dict.965; + let Dict.529 : U64 = CallByName Num.133 Dict.964; + let Dict.963 : U64 = 4i64; + let Dict.962 : U64 = CallByName Num.51 Dict.525 Dict.963; + let Dict.961 : U8 = CallByName Dict.22 Dict.524 Dict.962; + let Dict.530 : U64 = CallByName Num.133 Dict.961; + let Dict.960 : U64 = 5i64; + let Dict.959 : U64 = CallByName Num.51 Dict.525 Dict.960; + let Dict.958 : U8 = CallByName Dict.22 Dict.524 Dict.959; + let Dict.531 : U64 = CallByName Num.133 Dict.958; + let Dict.957 : U64 = 6i64; + let Dict.956 : U64 = CallByName Num.51 Dict.525 Dict.957; + let Dict.955 : U8 = CallByName Dict.22 Dict.524 Dict.956; + let Dict.532 : U64 = CallByName Num.133 Dict.955; + let Dict.954 : U64 = 7i64; + let Dict.952 : U64 = CallByName Num.51 Dict.525 Dict.954; + let Dict.951 : U8 = CallByName Dict.22 Dict.524 Dict.952; + let Dict.533 : U64 = CallByName Num.133 Dict.951; + let Dict.950 : U8 = 8i64; + let Dict.949 : U64 = CallByName Num.72 Dict.527 Dict.950; + let Dict.534 : U64 = CallByName Num.71 Dict.526 Dict.949; + let Dict.948 : U8 = 16i64; + let Dict.945 : U64 = CallByName Num.72 Dict.528 Dict.948; + let Dict.947 : U8 = 24i64; + let Dict.946 : U64 = CallByName Num.72 Dict.529 Dict.947; + let Dict.535 : U64 = CallByName Num.71 Dict.945 Dict.946; + let Dict.944 : U8 = 32i64; + let Dict.941 : U64 = CallByName Num.72 Dict.530 Dict.944; + let Dict.943 : U8 = 40i64; + let Dict.942 : U64 = CallByName Num.72 Dict.531 Dict.943; + let Dict.536 : U64 = CallByName Num.71 Dict.941 Dict.942; + let Dict.940 : U8 = 48i64; + let Dict.937 : U64 = CallByName Num.72 Dict.532 Dict.940; + let Dict.939 : U8 = 56i64; + let Dict.938 : U64 = CallByName Num.72 Dict.533 Dict.939; + let Dict.537 : U64 = CallByName Num.71 Dict.937 Dict.938; + let Dict.935 : U64 = CallByName Num.71 Dict.534 Dict.535; + let Dict.936 : U64 = CallByName Num.71 Dict.536 Dict.537; + let Dict.934 : U64 = CallByName Num.71 Dict.935 Dict.936; + ret Dict.934; + +procedure Dict.99 (Dict.538, Dict.539): + let Dict.1085 : U8 = CallByName Dict.22 Dict.538 Dict.539; + let Dict.540 : U64 = CallByName Num.133 Dict.1085; + let Dict.1084 : U64 = 1i64; + let Dict.1083 : U64 = CallByName Num.51 Dict.539 Dict.1084; + let Dict.1082 : U8 = CallByName Dict.22 Dict.538 Dict.1083; + let Dict.541 : U64 = CallByName Num.133 Dict.1082; + let Dict.1081 : U64 = 2i64; + let Dict.1080 : U64 = CallByName Num.51 Dict.539 Dict.1081; + let Dict.1079 : U8 = CallByName Dict.22 Dict.538 Dict.1080; + let Dict.542 : U64 = CallByName Num.133 Dict.1079; + let Dict.1078 : U64 = 3i64; + let Dict.1077 : U64 = CallByName Num.51 Dict.539 Dict.1078; + let Dict.1076 : U8 = CallByName Dict.22 Dict.538 Dict.1077; + let Dict.543 : U64 = CallByName Num.133 Dict.1076; + let Dict.1075 : U8 = 8i64; + let Dict.1074 : U64 = CallByName Num.72 Dict.541 Dict.1075; + let Dict.544 : U64 = CallByName Num.71 Dict.540 Dict.1074; + let Dict.1073 : U8 = 16i64; + let Dict.1070 : U64 = CallByName Num.72 Dict.542 Dict.1073; + let Dict.1072 : U8 = 24i64; + let Dict.1071 : U64 = CallByName Num.72 Dict.543 Dict.1072; + let Dict.545 : U64 = CallByName Num.71 Dict.1070 Dict.1071; + let Dict.1069 : U64 = CallByName Num.71 Dict.544 Dict.545; + ret Dict.1069; procedure Hash.19 (Hash.42, Hash.43): let Hash.75 : List U8 = CallByName Str.12 Hash.43; @@ -745,90 +745,90 @@ procedure Inspect.187 (Inspect.188, #Attr.12): let Inspect.185 : {} = StructAtIndex 2 #Attr.12; let Inspect.184 : {} = StructAtIndex 1 #Attr.12; let Inspect.183 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = StructAtIndex 0 #Attr.12; - let Inspect.355 : Str = "{"; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.188 Inspect.355; - dec Inspect.355; - let Inspect.329 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = Struct {Inspect.183, Inspect.184, Inspect.185, Inspect.186}; - let Inspect.324 : {Str, Int1} = CallByName Inspect.189 Inspect.328 Inspect.329; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.201 Inspect.324; - let Inspect.321 : Str = "}"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.354 : Str = "{"; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.188 Inspect.354; + dec Inspect.354; + let Inspect.328 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = Struct {Inspect.183, Inspect.184, Inspect.185, Inspect.186}; + let Inspect.323 : {Str, Int1} = CallByName Inspect.189 Inspect.327 Inspect.328; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.201 Inspect.323; + let Inspect.320 : Str = "}"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.189 (Inspect.190, #Attr.12): let Inspect.186 : {} = StructAtIndex 3 #Attr.12; let Inspect.185 : {} = StructAtIndex 2 #Attr.12; let Inspect.184 : {} = StructAtIndex 1 #Attr.12; let Inspect.183 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = StructAtIndex 0 #Attr.12; - let Inspect.354 : Int1 = CallByName Bool.1; + let Inspect.353 : Int1 = CallByName Bool.1; inc Inspect.190; - let Inspect.332 : {Str, Int1} = Struct {Inspect.190, Inspect.354}; - let Inspect.333 : {{}, {}} = Struct {Inspect.185, Inspect.186}; - let Inspect.331 : {Str, Int1} = CallByName Dict.10 Inspect.183 Inspect.332 Inspect.333; - ret Inspect.331; + let Inspect.331 : {Str, Int1} = Struct {Inspect.190, Inspect.353}; + let Inspect.332 : {{}, {}} = Struct {Inspect.185, Inspect.186}; + let Inspect.330 : {Str, Int1} = CallByName Dict.10 Inspect.183 Inspect.331 Inspect.332; + ret Inspect.330; -procedure Inspect.191 (Inspect.334, Inspect.194, Inspect.195, #Attr.12): +procedure Inspect.191 (Inspect.333, Inspect.194, Inspect.195, #Attr.12): let Inspect.186 : {} = StructAtIndex 1 #Attr.12; let Inspect.185 : {} = StructAtIndex 0 #Attr.12; - let Inspect.192 : Str = StructAtIndex 0 Inspect.334; - let Inspect.193 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.352 Inspect.196: - let Inspect.349 : Str = CallByName Inspect.47 Inspect.194; - let Inspect.347 : Str = CallByName Inspect.31 Inspect.349 Inspect.196; - dec Inspect.349; - let Inspect.348 : Str = ": "; - let Inspect.341 : Str = CallByName Inspect.63 Inspect.347 Inspect.348; + let Inspect.192 : Str = StructAtIndex 0 Inspect.333; + let Inspect.193 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.351 Inspect.196: + let Inspect.348 : Str = CallByName Inspect.47 Inspect.194; + let Inspect.346 : Str = CallByName Inspect.31 Inspect.348 Inspect.196; dec Inspect.348; - let Inspect.342 : {I64, {}} = Struct {Inspect.195, Inspect.186}; - let Inspect.337 : Str = CallByName Inspect.197 Inspect.341 Inspect.342; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.199 Inspect.337; - dec Inspect.337; - ret Inspect.336; + let Inspect.347 : Str = ": "; + let Inspect.340 : Str = CallByName Inspect.63 Inspect.346 Inspect.347; + dec Inspect.347; + let Inspect.341 : {I64, {}} = Struct {Inspect.195, Inspect.186}; + let Inspect.336 : Str = CallByName Inspect.197 Inspect.340 Inspect.341; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.199 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.193 then - let Inspect.353 : Str = ", "; - let Inspect.351 : Str = CallByName Inspect.63 Inspect.192 Inspect.353; - dec Inspect.353; - jump Inspect.352 Inspect.351; + let Inspect.352 : Str = ", "; + let Inspect.350 : Str = CallByName Inspect.63 Inspect.192 Inspect.352; + dec Inspect.352; + jump Inspect.351 Inspect.350; else - jump Inspect.352 Inspect.192; + jump Inspect.351 Inspect.192; procedure Inspect.197 (Inspect.198, #Attr.12): let Inspect.186 : {} = StructAtIndex 1 #Attr.12; let Inspect.195 : I64 = StructAtIndex 0 #Attr.12; - let Inspect.345 : I64 = CallByName Inspect.57 Inspect.195; - let Inspect.344 : Str = CallByName Inspect.31 Inspect.345 Inspect.198; - ret Inspect.344; + let Inspect.344 : I64 = CallByName Inspect.57 Inspect.195; + let Inspect.343 : Str = CallByName Inspect.31 Inspect.344 Inspect.198; + ret Inspect.343; procedure Inspect.199 (Inspect.200): - let Inspect.340 : Int1 = CallByName Bool.2; + let Inspect.339 : Int1 = CallByName Bool.2; inc Inspect.200; - let Inspect.339 : {Str, Int1} = Struct {Inspect.200, Inspect.340}; - ret Inspect.339; - -procedure Inspect.201 (Inspect.326): - let Inspect.327 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.327; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.370 : Str = "\""; - let Inspect.369 : Str = CallByName Inspect.63 Inspect.251 Inspect.370; - dec Inspect.370; - let Inspect.367 : Str = CallByName Inspect.63 Inspect.369 Inspect.249; - let Inspect.368 : Str = "\""; - let Inspect.366 : Str = CallByName Inspect.63 Inspect.367 Inspect.368; - dec Inspect.368; - ret Inspect.366; - -procedure Inspect.278 (Inspect.279, Inspect.277): - let Inspect.361 : Str = CallByName Num.96 Inspect.277; - let Inspect.360 : Str = CallByName Inspect.63 Inspect.279 Inspect.361; - dec Inspect.361; - ret Inspect.360; + let Inspect.338 : {Str, Int1} = Struct {Inspect.200, Inspect.339}; + ret Inspect.338; + +procedure Inspect.201 (Inspect.325): + let Inspect.326 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.326; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.369 : Str = "\""; + let Inspect.368 : Str = CallByName Inspect.63 Inspect.250 Inspect.369; + dec Inspect.369; + let Inspect.366 : Str = CallByName Inspect.63 Inspect.368 Inspect.248; + let Inspect.367 : Str = "\""; + let Inspect.365 : Str = CallByName Inspect.63 Inspect.366 Inspect.367; + dec Inspect.367; + ret Inspect.365; + +procedure Inspect.277 (Inspect.278, Inspect.276): + let Inspect.360 : Str = CallByName Num.96 Inspect.276; + let Inspect.359 : Str = CallByName Inspect.63 Inspect.278 Inspect.360; + dec Inspect.360; + ret Inspect.359; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -842,55 +842,55 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.187 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.187 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.346 : Str = CallByName Inspect.278 Inspect.149 Inspect.303; - ret Inspect.346; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.345 : Str = CallByName Inspect.277 Inspect.149 Inspect.302; + ret Inspect.345; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.350 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.350; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.349 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.349; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.42 (Inspect.183, Inspect.184, Inspect.185, Inspect.186): - let Inspect.316 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = Struct {Inspect.183, Inspect.184, Inspect.185, Inspect.186}; - let Inspect.315 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = CallByName Inspect.30 Inspect.316; - ret Inspect.315; + let Inspect.315 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = Struct {Inspect.183, Inspect.184, Inspect.185, Inspect.186}; + let Inspect.314 : {{List {U32, U32}, List {Str, I64}, U64, Float32, U8}, {}, {}, {}} = CallByName Inspect.30 Inspect.315; + ret Inspect.314; -procedure Inspect.47 (Inspect.249): - let Inspect.362 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.362; +procedure Inspect.47 (Inspect.248): + let Inspect.361 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.361; procedure Inspect.5 (Inspect.150): - let Inspect.312 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.43 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Dict.127 Inspect.308 Inspect.312; - ret Inspect.307; + let Inspect.311 : {List {U32, U32}, List {Str, I64}, U64, Float32, U8} = CallByName Dict.43 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Dict.127 Inspect.307 Inspect.311; + ret Inspect.306; -procedure Inspect.57 (Inspect.277): - let Inspect.356 : I64 = CallByName Inspect.30 Inspect.277; - ret Inspect.356; +procedure Inspect.57 (Inspect.276): + let Inspect.355 : I64 = CallByName Inspect.30 Inspect.276; + ret Inspect.355; -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.323 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.323; +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.322 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.322; -procedure Inspect.64 (Inspect.302): - ret Inspect.302; +procedure Inspect.64 (Inspect.301): + ret Inspect.301; -procedure List.100 (#Derived_gen.40, #Derived_gen.41, #Derived_gen.42, #Derived_gen.43, #Derived_gen.44): +procedure List.100 (#Derived_gen.34, #Derived_gen.35, #Derived_gen.36, #Derived_gen.37, #Derived_gen.38): joinpoint List.732 List.174 List.175 List.176 List.177 List.178: let List.734 : Int1 = CallByName Num.22 List.177 List.178; if List.734 then @@ -904,10 +904,10 @@ procedure List.100 (#Derived_gen.40, #Derived_gen.41, #Derived_gen.42, #Derived_ dec List.174; ret List.175; in - inc #Derived_gen.40; - jump List.732 #Derived_gen.40 #Derived_gen.41 #Derived_gen.42 #Derived_gen.43 #Derived_gen.44; + inc #Derived_gen.34; + jump List.732 #Derived_gen.34 #Derived_gen.35 #Derived_gen.36 #Derived_gen.37 #Derived_gen.38; -procedure List.100 (#Derived_gen.61, #Derived_gen.62, #Derived_gen.63, #Derived_gen.64, #Derived_gen.65): +procedure List.100 (#Derived_gen.57, #Derived_gen.58, #Derived_gen.59, #Derived_gen.60, #Derived_gen.61): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: let List.670 : Int1 = CallByName Num.22 List.177 List.178; if List.670 then @@ -921,8 +921,8 @@ procedure List.100 (#Derived_gen.61, #Derived_gen.62, #Derived_gen.63, #Derived_ dec List.174; ret List.175; in - inc #Derived_gen.61; - jump List.668 #Derived_gen.61 #Derived_gen.62 #Derived_gen.63 #Derived_gen.64 #Derived_gen.65; + inc #Derived_gen.57; + jump List.668 #Derived_gen.57 #Derived_gen.58 #Derived_gen.59 #Derived_gen.60 #Derived_gen.61; procedure List.101 (#Derived_gen.21, #Derived_gen.22, #Derived_gen.23, #Derived_gen.24, #Derived_gen.25): joinpoint List.707 List.183 List.184 List.185 List.186 List.187: @@ -930,7 +930,7 @@ procedure List.101 (#Derived_gen.21, #Derived_gen.22, #Derived_gen.23, #Derived_ if List.709 then let List.713 : {Str, I64} = CallByName List.66 List.183 List.186; inc List.713; - let List.188 : List {U32, U32} = CallByName Dict.406 List.184 List.713 List.186 List.185; + let List.188 : List {U32, U32} = CallByName Dict.407 List.184 List.713 List.186 List.185; let List.712 : U64 = 1i64; let List.711 : U64 = CallByName Num.51 List.186 List.712; jump List.707 List.183 List.188 List.185 List.711 List.187; @@ -1042,7 +1042,7 @@ procedure List.83 (List.180, List.181, List.182): let List.704 : List {U32, U32} = CallByName List.101 List.180 List.181 List.182 List.705 List.706; ret List.704; -procedure List.98 (#Derived_gen.28, #Derived_gen.29, #Derived_gen.30): +procedure List.98 (#Derived_gen.26, #Derived_gen.27, #Derived_gen.28): joinpoint List.716 List.151 List.152 List.153: let List.724 : U64 = 0i64; let List.718 : Int1 = CallByName Num.24 List.152 List.724; @@ -1054,7 +1054,7 @@ procedure List.98 (#Derived_gen.28, #Derived_gen.29, #Derived_gen.30): else ret List.153; in - jump List.716 #Derived_gen.28 #Derived_gen.29 #Derived_gen.30; + jump List.716 #Derived_gen.26 #Derived_gen.27 #Derived_gen.28; procedure Num.131 (#Attr.2): let Num.291 : U32 = lowlevel NumIntCast #Attr.2; diff --git a/crates/compiler/test_mono/generated/inspect_derived_list.txt b/crates/compiler/test_mono/generated/inspect_derived_list.txt index fcdffbea8e4..afd706f1788 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_list.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_list.txt @@ -25,64 +25,64 @@ procedure Inspect.156 (Inspect.157, #Attr.12): let Inspect.155 : {} = StructAtIndex 2 #Attr.12; let Inspect.154 : {} = StructAtIndex 1 #Attr.12; let Inspect.153 : List I64 = StructAtIndex 0 #Attr.12; - let Inspect.347 : Str = "["; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.157 Inspect.347; - dec Inspect.347; - let Inspect.329 : {List I64, {}, {}} = Struct {Inspect.153, Inspect.154, Inspect.155}; - let Inspect.324 : {Str, Int1} = CallByName Inspect.158 Inspect.328 Inspect.329; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.167 Inspect.324; - let Inspect.321 : Str = "]"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.346 : Str = "["; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.157 Inspect.346; + dec Inspect.346; + let Inspect.328 : {List I64, {}, {}} = Struct {Inspect.153, Inspect.154, Inspect.155}; + let Inspect.323 : {Str, Int1} = CallByName Inspect.158 Inspect.327 Inspect.328; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.167 Inspect.323; + let Inspect.320 : Str = "]"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.158 (Inspect.159, #Attr.12): let Inspect.155 : {} = StructAtIndex 2 #Attr.12; let Inspect.154 : {} = StructAtIndex 1 #Attr.12; let Inspect.153 : List I64 = StructAtIndex 0 #Attr.12; - let Inspect.346 : Int1 = CallByName Bool.1; + let Inspect.345 : Int1 = CallByName Bool.1; inc Inspect.159; - let Inspect.332 : {Str, Int1} = Struct {Inspect.159, Inspect.346}; - let Inspect.331 : {Str, Int1} = CallByName List.18 Inspect.153 Inspect.332 Inspect.155; + let Inspect.331 : {Str, Int1} = Struct {Inspect.159, Inspect.345}; + let Inspect.330 : {Str, Int1} = CallByName List.18 Inspect.153 Inspect.331 Inspect.155; dec Inspect.153; - ret Inspect.331; - -procedure Inspect.160 (Inspect.334, Inspect.163, Inspect.155): - let Inspect.161 : Str = StructAtIndex 0 Inspect.334; - let Inspect.162 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.344 Inspect.164: - let Inspect.341 : I64 = CallByName #Derived.3 Inspect.163; - let Inspect.337 : Str = CallByName Inspect.31 Inspect.341 Inspect.164; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.165 Inspect.337; - dec Inspect.337; - ret Inspect.336; + ret Inspect.330; + +procedure Inspect.160 (Inspect.333, Inspect.163, Inspect.155): + let Inspect.161 : Str = StructAtIndex 0 Inspect.333; + let Inspect.162 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.343 Inspect.164: + let Inspect.340 : I64 = CallByName #Derived.3 Inspect.163; + let Inspect.336 : Str = CallByName Inspect.31 Inspect.340 Inspect.164; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.165 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.162 then - let Inspect.345 : Str = ", "; - let Inspect.343 : Str = CallByName Inspect.63 Inspect.161 Inspect.345; - dec Inspect.345; - jump Inspect.344 Inspect.343; + let Inspect.344 : Str = ", "; + let Inspect.342 : Str = CallByName Inspect.63 Inspect.161 Inspect.344; + dec Inspect.344; + jump Inspect.343 Inspect.342; else - jump Inspect.344 Inspect.161; + jump Inspect.343 Inspect.161; procedure Inspect.165 (Inspect.166): - let Inspect.340 : Int1 = CallByName Bool.2; + let Inspect.339 : Int1 = CallByName Bool.2; inc Inspect.166; - let Inspect.339 : {Str, Int1} = Struct {Inspect.166, Inspect.340}; - ret Inspect.339; + let Inspect.338 : {Str, Int1} = Struct {Inspect.166, Inspect.339}; + ret Inspect.338; -procedure Inspect.167 (Inspect.326): - let Inspect.327 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.327; +procedure Inspect.167 (Inspect.325): + let Inspect.326 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.326; -procedure Inspect.278 (Inspect.279, Inspect.277): - let Inspect.353 : Str = CallByName Num.96 Inspect.277; - let Inspect.352 : Str = CallByName Inspect.63 Inspect.279 Inspect.353; - dec Inspect.353; - ret Inspect.352; +procedure Inspect.277 (Inspect.278, Inspect.276): + let Inspect.352 : Str = CallByName Num.96 Inspect.276; + let Inspect.351 : Str = CallByName Inspect.63 Inspect.278 Inspect.352; + dec Inspect.352; + ret Inspect.351; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -93,47 +93,47 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.156 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.156 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.342 : Str = CallByName Inspect.278 Inspect.149 Inspect.303; - ret Inspect.342; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.341 : Str = CallByName Inspect.277 Inspect.149 Inspect.302; + ret Inspect.341; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.40 (Inspect.153, Inspect.154, Inspect.155): inc Inspect.153; - let Inspect.316 : {List I64, {}, {}} = Struct {Inspect.153, Inspect.154, Inspect.155}; - let Inspect.315 : {List I64, {}, {}} = CallByName Inspect.30 Inspect.316; - ret Inspect.315; + let Inspect.315 : {List I64, {}, {}} = Struct {Inspect.153, Inspect.154, Inspect.155}; + let Inspect.314 : {List I64, {}, {}} = CallByName Inspect.30 Inspect.315; + ret Inspect.314; procedure Inspect.5 (Inspect.150): - let Inspect.312 : List I64 = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.4 Inspect.308 Inspect.312; - dec Inspect.312; - ret Inspect.307; - -procedure Inspect.57 (Inspect.277): - let Inspect.348 : I64 = CallByName Inspect.30 Inspect.277; - ret Inspect.348; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.323 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.323; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : List I64 = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.4 Inspect.307 Inspect.311; + dec Inspect.311; + ret Inspect.306; + +procedure Inspect.57 (Inspect.276): + let Inspect.347 : I64 = CallByName Inspect.30 Inspect.276; + ret Inspect.347; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.322 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.322; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure List.100 (#Derived_gen.8, #Derived_gen.9, #Derived_gen.10, #Derived_gen.11, #Derived_gen.12): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: diff --git a/crates/compiler/test_mono/generated/inspect_derived_nested_record_string.txt b/crates/compiler/test_mono/generated/inspect_derived_nested_record_string.txt index 41a69e36ab9..83c897de991 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_nested_record_string.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_nested_record_string.txt @@ -35,125 +35,125 @@ procedure Bool.2 (): ret Bool.25; procedure Inspect.229 (Inspect.230, Inspect.228): - let Inspect.352 : Str = "{"; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.230 Inspect.352; - dec Inspect.352; - let Inspect.324 : {Str, Int1} = CallByName Inspect.231 Inspect.328 Inspect.228; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.243 Inspect.324; - let Inspect.321 : Str = "}"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.351 : Str = "{"; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.230 Inspect.351; + dec Inspect.351; + let Inspect.323 : {Str, Int1} = CallByName Inspect.231 Inspect.327 Inspect.228; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.243 Inspect.323; + let Inspect.320 : Str = "}"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.229 (Inspect.230, Inspect.228): - let Inspect.392 : Str = "{"; - let Inspect.368 : Str = CallByName Inspect.63 Inspect.230 Inspect.392; - dec Inspect.392; - let Inspect.364 : {Str, Int1} = CallByName Inspect.231 Inspect.368 Inspect.228; - dec Inspect.368; - let Inspect.365 : {} = Struct {}; - let Inspect.360 : Str = CallByName Inspect.243 Inspect.364; - let Inspect.361 : Str = "}"; - let Inspect.359 : Str = CallByName Inspect.63 Inspect.360 Inspect.361; - dec Inspect.361; - ret Inspect.359; + let Inspect.391 : Str = "{"; + let Inspect.367 : Str = CallByName Inspect.63 Inspect.230 Inspect.391; + dec Inspect.391; + let Inspect.363 : {Str, Int1} = CallByName Inspect.231 Inspect.367 Inspect.228; + dec Inspect.367; + let Inspect.364 : {} = Struct {}; + let Inspect.359 : Str = CallByName Inspect.243 Inspect.363; + let Inspect.360 : Str = "}"; + let Inspect.358 : Str = CallByName Inspect.63 Inspect.359 Inspect.360; + dec Inspect.360; + ret Inspect.358; procedure Inspect.231 (Inspect.232, Inspect.228): - let Inspect.351 : Int1 = CallByName Bool.1; + let Inspect.350 : Int1 = CallByName Bool.1; inc Inspect.232; - let Inspect.332 : {Str, Int1} = Struct {Inspect.232, Inspect.351}; - let Inspect.333 : {} = Struct {}; - let Inspect.331 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.332 Inspect.333; - ret Inspect.331; + let Inspect.331 : {Str, Int1} = Struct {Inspect.232, Inspect.350}; + let Inspect.332 : {} = Struct {}; + let Inspect.330 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.331 Inspect.332; + ret Inspect.330; procedure Inspect.231 (Inspect.232, Inspect.228): - let Inspect.391 : Int1 = CallByName Bool.1; + let Inspect.390 : Int1 = CallByName Bool.1; inc Inspect.232; - let Inspect.372 : {Str, Int1} = Struct {Inspect.232, Inspect.391}; - let Inspect.373 : {} = Struct {}; - let Inspect.371 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.372 Inspect.373; - ret Inspect.371; - -procedure Inspect.233 (Inspect.334, Inspect.335): - let Inspect.236 : Str = StructAtIndex 0 Inspect.335; - let Inspect.237 : Str = StructAtIndex 1 Inspect.335; - let Inspect.234 : Str = StructAtIndex 0 Inspect.334; - let Inspect.235 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.349 Inspect.238: - let Inspect.346 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; + let Inspect.371 : {Str, Int1} = Struct {Inspect.232, Inspect.390}; + let Inspect.372 : {} = Struct {}; + let Inspect.370 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.371 Inspect.372; + ret Inspect.370; + +procedure Inspect.233 (Inspect.333, Inspect.334): + let Inspect.236 : Str = StructAtIndex 0 Inspect.334; + let Inspect.237 : Str = StructAtIndex 1 Inspect.334; + let Inspect.234 : Str = StructAtIndex 0 Inspect.333; + let Inspect.235 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.348 Inspect.238: + let Inspect.345 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; dec Inspect.236; - let Inspect.347 : Str = ": "; - let Inspect.341 : Str = CallByName Inspect.63 Inspect.346 Inspect.347; - dec Inspect.347; - let Inspect.337 : Str = CallByName Inspect.239 Inspect.341 Inspect.237; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.241 Inspect.337; - dec Inspect.337; - ret Inspect.336; + let Inspect.346 : Str = ": "; + let Inspect.340 : Str = CallByName Inspect.63 Inspect.345 Inspect.346; + dec Inspect.346; + let Inspect.336 : Str = CallByName Inspect.239 Inspect.340 Inspect.237; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.241 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.235 then - let Inspect.350 : Str = ", "; - let Inspect.348 : Str = CallByName Inspect.63 Inspect.234 Inspect.350; - dec Inspect.350; - jump Inspect.349 Inspect.348; + let Inspect.349 : Str = ", "; + let Inspect.347 : Str = CallByName Inspect.63 Inspect.234 Inspect.349; + dec Inspect.349; + jump Inspect.348 Inspect.347; else - jump Inspect.349 Inspect.234; - -procedure Inspect.233 (Inspect.334, Inspect.335): - let Inspect.236 : Str = StructAtIndex 0 Inspect.335; - let Inspect.237 : Str = StructAtIndex 1 Inspect.335; - let Inspect.234 : Str = StructAtIndex 0 Inspect.334; - let Inspect.235 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.389 Inspect.238: - let Inspect.386 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; + jump Inspect.348 Inspect.234; + +procedure Inspect.233 (Inspect.333, Inspect.334): + let Inspect.236 : Str = StructAtIndex 0 Inspect.334; + let Inspect.237 : Str = StructAtIndex 1 Inspect.334; + let Inspect.234 : Str = StructAtIndex 0 Inspect.333; + let Inspect.235 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.388 Inspect.238: + let Inspect.385 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; dec Inspect.236; - let Inspect.387 : Str = ": "; - let Inspect.381 : Str = CallByName Inspect.63 Inspect.386 Inspect.387; - dec Inspect.387; - let Inspect.377 : Str = CallByName Inspect.239 Inspect.381 Inspect.237; + let Inspect.386 : Str = ": "; + let Inspect.380 : Str = CallByName Inspect.63 Inspect.385 Inspect.386; + dec Inspect.386; + let Inspect.376 : Str = CallByName Inspect.239 Inspect.380 Inspect.237; dec Inspect.237; - let Inspect.378 : {} = Struct {}; - let Inspect.376 : {Str, Int1} = CallByName Inspect.241 Inspect.377; - dec Inspect.377; - ret Inspect.376; + let Inspect.377 : {} = Struct {}; + let Inspect.375 : {Str, Int1} = CallByName Inspect.241 Inspect.376; + dec Inspect.376; + ret Inspect.375; in if Inspect.235 then - let Inspect.390 : Str = ", "; - let Inspect.388 : Str = CallByName Inspect.63 Inspect.234 Inspect.390; - dec Inspect.390; - jump Inspect.389 Inspect.388; + let Inspect.389 : Str = ", "; + let Inspect.387 : Str = CallByName Inspect.63 Inspect.234 Inspect.389; + dec Inspect.389; + jump Inspect.388 Inspect.387; else - jump Inspect.389 Inspect.234; + jump Inspect.388 Inspect.234; procedure Inspect.239 (Inspect.240, Inspect.237): - let Inspect.344 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; - ret Inspect.344; + let Inspect.343 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; + ret Inspect.343; procedure Inspect.239 (Inspect.240, Inspect.237): - let Inspect.384 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; - ret Inspect.384; + let Inspect.383 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; + ret Inspect.383; procedure Inspect.241 (Inspect.242): - let Inspect.380 : Int1 = CallByName Bool.2; + let Inspect.379 : Int1 = CallByName Bool.2; inc Inspect.242; - let Inspect.379 : {Str, Int1} = Struct {Inspect.242, Inspect.380}; - ret Inspect.379; - -procedure Inspect.243 (Inspect.326): - let Inspect.367 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.367; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.401 : Str = "\""; - let Inspect.400 : Str = CallByName Inspect.63 Inspect.251 Inspect.401; - dec Inspect.401; - let Inspect.398 : Str = CallByName Inspect.63 Inspect.400 Inspect.249; - let Inspect.399 : Str = "\""; - let Inspect.397 : Str = CallByName Inspect.63 Inspect.398 Inspect.399; - dec Inspect.399; - ret Inspect.397; + let Inspect.378 : {Str, Int1} = Struct {Inspect.242, Inspect.379}; + ret Inspect.378; + +procedure Inspect.243 (Inspect.325): + let Inspect.366 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.366; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.400 : Str = "\""; + let Inspect.399 : Str = CallByName Inspect.63 Inspect.250 Inspect.400; + dec Inspect.400; + let Inspect.397 : Str = CallByName Inspect.63 Inspect.399 Inspect.248; + let Inspect.398 : Str = "\""; + let Inspect.396 : Str = CallByName Inspect.63 Inspect.397 Inspect.398; + dec Inspect.398; + ret Inspect.396; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -170,58 +170,58 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.229 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.229 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.345 : Str = CallByName #Derived.6 Inspect.149 Inspect.303; - ret Inspect.345; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.344 : Str = CallByName #Derived.6 Inspect.149 Inspect.302; + ret Inspect.344; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.354 : Str = CallByName Inspect.229 Inspect.149 Inspect.303; - ret Inspect.354; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.353 : Str = CallByName Inspect.229 Inspect.149 Inspect.302; + ret Inspect.353; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.385 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.385; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.384 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.384; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.45 (Inspect.228): - let Inspect.315 : List {Str, Str} = CallByName Inspect.30 Inspect.228; - ret Inspect.315; + let Inspect.314 : List {Str, Str} = CallByName Inspect.30 Inspect.228; + ret Inspect.314; procedure Inspect.45 (Inspect.228): - let Inspect.355 : List {Str, Str} = CallByName Inspect.30 Inspect.228; - ret Inspect.355; + let Inspect.354 : List {Str, Str} = CallByName Inspect.30 Inspect.228; + ret Inspect.354; -procedure Inspect.47 (Inspect.249): - let Inspect.393 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.393; +procedure Inspect.47 (Inspect.248): + let Inspect.392 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.392; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.2 Inspect.308 Inspect.312; - ret Inspect.307; + let Inspect.311 : Str = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.2 Inspect.307 Inspect.311; + ret Inspect.306; -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.363 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.363; +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.362 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.362; -procedure Inspect.64 (Inspect.302): - ret Inspect.302; +procedure Inspect.64 (Inspect.301): + ret Inspect.301; -procedure List.100 (#Derived_gen.30, #Derived_gen.31, #Derived_gen.32, #Derived_gen.33, #Derived_gen.34): +procedure List.100 (#Derived_gen.32, #Derived_gen.33, #Derived_gen.34, #Derived_gen.35, #Derived_gen.36): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: let List.670 : Int1 = CallByName Num.22 List.177 List.178; if List.670 then @@ -235,8 +235,8 @@ procedure List.100 (#Derived_gen.30, #Derived_gen.31, #Derived_gen.32, #Derived_ dec List.174; ret List.175; in - inc #Derived_gen.30; - jump List.668 #Derived_gen.30 #Derived_gen.31 #Derived_gen.32 #Derived_gen.33 #Derived_gen.34; + inc #Derived_gen.32; + jump List.668 #Derived_gen.32 #Derived_gen.33 #Derived_gen.34 #Derived_gen.35 #Derived_gen.36; procedure List.100 (#Derived_gen.43, #Derived_gen.44, #Derived_gen.45, #Derived_gen.46, #Derived_gen.47): joinpoint List.680 List.174 List.175 List.176 List.177 List.178: diff --git a/crates/compiler/test_mono/generated/inspect_derived_record.txt b/crates/compiler/test_mono/generated/inspect_derived_record.txt index 47fe7368293..e1c5b176a08 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_record.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_record.txt @@ -26,78 +26,78 @@ procedure Bool.2 (): ret Bool.23; procedure Inspect.229 (Inspect.230, Inspect.228): - let Inspect.353 : Str = "{"; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.230 Inspect.353; - dec Inspect.353; - let Inspect.324 : {Str, Int1} = CallByName Inspect.231 Inspect.328 Inspect.228; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.243 Inspect.324; - let Inspect.321 : Str = "}"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.352 : Str = "{"; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.230 Inspect.352; + dec Inspect.352; + let Inspect.323 : {Str, Int1} = CallByName Inspect.231 Inspect.327 Inspect.228; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.243 Inspect.323; + let Inspect.320 : Str = "}"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.231 (Inspect.232, Inspect.228): - let Inspect.352 : Int1 = CallByName Bool.1; + let Inspect.351 : Int1 = CallByName Bool.1; inc Inspect.232; - let Inspect.332 : {Str, Int1} = Struct {Inspect.232, Inspect.352}; - let Inspect.333 : {} = Struct {}; - let Inspect.331 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.332 Inspect.333; - ret Inspect.331; - -procedure Inspect.233 (Inspect.334, Inspect.335): - let Inspect.237 : [C I64, C Decimal] = StructAtIndex 0 Inspect.335; - let Inspect.236 : Str = StructAtIndex 1 Inspect.335; - let Inspect.234 : Str = StructAtIndex 0 Inspect.334; - let Inspect.235 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.350 Inspect.238: - let Inspect.347 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; + let Inspect.331 : {Str, Int1} = Struct {Inspect.232, Inspect.351}; + let Inspect.332 : {} = Struct {}; + let Inspect.330 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.331 Inspect.332; + ret Inspect.330; + +procedure Inspect.233 (Inspect.333, Inspect.334): + let Inspect.237 : [C I64, C Decimal] = StructAtIndex 0 Inspect.334; + let Inspect.236 : Str = StructAtIndex 1 Inspect.334; + let Inspect.234 : Str = StructAtIndex 0 Inspect.333; + let Inspect.235 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.349 Inspect.238: + let Inspect.346 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; dec Inspect.236; - let Inspect.348 : Str = ": "; - let Inspect.341 : Str = CallByName Inspect.63 Inspect.347 Inspect.348; - dec Inspect.348; - let Inspect.337 : Str = CallByName Inspect.239 Inspect.341 Inspect.237; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.241 Inspect.337; - dec Inspect.337; - ret Inspect.336; + let Inspect.347 : Str = ": "; + let Inspect.340 : Str = CallByName Inspect.63 Inspect.346 Inspect.347; + dec Inspect.347; + let Inspect.336 : Str = CallByName Inspect.239 Inspect.340 Inspect.237; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.241 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.235 then - let Inspect.351 : Str = ", "; - let Inspect.349 : Str = CallByName Inspect.63 Inspect.234 Inspect.351; - dec Inspect.351; - jump Inspect.350 Inspect.349; + let Inspect.350 : Str = ", "; + let Inspect.348 : Str = CallByName Inspect.63 Inspect.234 Inspect.350; + dec Inspect.350; + jump Inspect.349 Inspect.348; else - jump Inspect.350 Inspect.234; + jump Inspect.349 Inspect.234; procedure Inspect.239 (Inspect.240, Inspect.237): - let Inspect.344 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; - ret Inspect.344; + let Inspect.343 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; + ret Inspect.343; procedure Inspect.241 (Inspect.242): - let Inspect.340 : Int1 = CallByName Bool.2; + let Inspect.339 : Int1 = CallByName Bool.2; inc Inspect.242; - let Inspect.339 : {Str, Int1} = Struct {Inspect.242, Inspect.340}; - ret Inspect.339; - -procedure Inspect.243 (Inspect.326): - let Inspect.327 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.327; - -procedure Inspect.278 (Inspect.279, #Attr.12): - let Inspect.366 : I64 = UnionAtIndex (Id 0) (Index 0) #Attr.12; - let Inspect.365 : Str = CallByName Num.96 Inspect.366; - let Inspect.364 : Str = CallByName Inspect.63 Inspect.279 Inspect.365; - dec Inspect.365; - ret Inspect.364; - -procedure Inspect.293 (Inspect.294, #Attr.12): - let Inspect.360 : Decimal = UnionAtIndex (Id 1) (Index 0) #Attr.12; - let Inspect.359 : Str = CallByName Num.96 Inspect.360; - let Inspect.358 : Str = CallByName Inspect.63 Inspect.294 Inspect.359; - dec Inspect.359; - ret Inspect.358; + let Inspect.338 : {Str, Int1} = Struct {Inspect.242, Inspect.339}; + ret Inspect.338; + +procedure Inspect.243 (Inspect.325): + let Inspect.326 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.326; + +procedure Inspect.277 (Inspect.278, #Attr.12): + let Inspect.365 : I64 = UnionAtIndex (Id 0) (Index 0) #Attr.12; + let Inspect.364 : Str = CallByName Num.96 Inspect.365; + let Inspect.363 : Str = CallByName Inspect.63 Inspect.278 Inspect.364; + dec Inspect.364; + ret Inspect.363; + +procedure Inspect.292 (Inspect.293, #Attr.12): + let Inspect.359 : Decimal = UnionAtIndex (Id 1) (Index 0) #Attr.12; + let Inspect.358 : Str = CallByName Num.96 Inspect.359; + let Inspect.357 : Str = CallByName Inspect.63 Inspect.293 Inspect.358; + dec Inspect.358; + ret Inspect.357; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -108,60 +108,60 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.229 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.229 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.346 : U8 = GetTagId Inspect.303; - switch Inspect.346: +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.345 : U8 = GetTagId Inspect.302; + switch Inspect.345: case 0: - let Inspect.345 : Str = CallByName Inspect.278 Inspect.149 Inspect.303; - ret Inspect.345; + let Inspect.344 : Str = CallByName Inspect.277 Inspect.149 Inspect.302; + ret Inspect.344; default: - let Inspect.345 : Str = CallByName Inspect.293 Inspect.149 Inspect.303; - ret Inspect.345; + let Inspect.344 : Str = CallByName Inspect.292 Inspect.149 Inspect.302; + ret Inspect.344; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.45 (Inspect.228): - let Inspect.315 : List {[C I64, C Decimal], Str} = CallByName Inspect.30 Inspect.228; - ret Inspect.315; + let Inspect.314 : List {[C I64, C Decimal], Str} = CallByName Inspect.30 Inspect.228; + ret Inspect.314; procedure Inspect.5 (Inspect.150): - let Inspect.312 : {Decimal, I64} = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.2 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.57 (Inspect.277): - let Inspect.362 : [C I64, C Decimal] = TagId(0) Inspect.277; - let Inspect.361 : [C I64, C Decimal] = CallByName Inspect.30 Inspect.362; - ret Inspect.361; - -procedure Inspect.62 (Inspect.292): - let Inspect.355 : [C I64, C Decimal] = TagId(1) Inspect.292; - let Inspect.354 : [C I64, C Decimal] = CallByName Inspect.30 Inspect.355; - ret Inspect.354; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.323 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.323; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; - -procedure List.100 (#Derived_gen.22, #Derived_gen.23, #Derived_gen.24, #Derived_gen.25, #Derived_gen.26): + let Inspect.311 : {Decimal, I64} = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.2 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.57 (Inspect.276): + let Inspect.361 : [C I64, C Decimal] = TagId(0) Inspect.276; + let Inspect.360 : [C I64, C Decimal] = CallByName Inspect.30 Inspect.361; + ret Inspect.360; + +procedure Inspect.62 (Inspect.291): + let Inspect.354 : [C I64, C Decimal] = TagId(1) Inspect.291; + let Inspect.353 : [C I64, C Decimal] = CallByName Inspect.30 Inspect.354; + ret Inspect.353; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.322 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.322; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; + +procedure List.100 (#Derived_gen.20, #Derived_gen.21, #Derived_gen.22, #Derived_gen.23, #Derived_gen.24): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: let List.670 : Int1 = CallByName Num.22 List.177 List.178; if List.670 then @@ -175,8 +175,8 @@ procedure List.100 (#Derived_gen.22, #Derived_gen.23, #Derived_gen.24, #Derived_ dec List.174; ret List.175; in - inc #Derived_gen.22; - jump List.668 #Derived_gen.22 #Derived_gen.23 #Derived_gen.24 #Derived_gen.25 #Derived_gen.26; + inc #Derived_gen.20; + jump List.668 #Derived_gen.20 #Derived_gen.21 #Derived_gen.22 #Derived_gen.23 #Derived_gen.24; procedure List.18 (List.171, List.172, List.173): let List.666 : U64 = 0i64; diff --git a/crates/compiler/test_mono/generated/inspect_derived_record_one_field_string.txt b/crates/compiler/test_mono/generated/inspect_derived_record_one_field_string.txt index 3cc1aefd2be..ef946672577 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_record_one_field_string.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_record_one_field_string.txt @@ -21,75 +21,75 @@ procedure Bool.2 (): ret Bool.23; procedure Inspect.229 (Inspect.230, Inspect.228): - let Inspect.352 : Str = "{"; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.230 Inspect.352; - dec Inspect.352; - let Inspect.324 : {Str, Int1} = CallByName Inspect.231 Inspect.328 Inspect.228; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.243 Inspect.324; - let Inspect.321 : Str = "}"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.351 : Str = "{"; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.230 Inspect.351; + dec Inspect.351; + let Inspect.323 : {Str, Int1} = CallByName Inspect.231 Inspect.327 Inspect.228; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.243 Inspect.323; + let Inspect.320 : Str = "}"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.231 (Inspect.232, Inspect.228): - let Inspect.351 : Int1 = CallByName Bool.1; + let Inspect.350 : Int1 = CallByName Bool.1; inc Inspect.232; - let Inspect.332 : {Str, Int1} = Struct {Inspect.232, Inspect.351}; - let Inspect.333 : {} = Struct {}; - let Inspect.331 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.332 Inspect.333; - ret Inspect.331; - -procedure Inspect.233 (Inspect.334, Inspect.335): - let Inspect.236 : Str = StructAtIndex 0 Inspect.335; - let Inspect.237 : Str = StructAtIndex 1 Inspect.335; - let Inspect.234 : Str = StructAtIndex 0 Inspect.334; - let Inspect.235 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.349 Inspect.238: - let Inspect.346 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; + let Inspect.331 : {Str, Int1} = Struct {Inspect.232, Inspect.350}; + let Inspect.332 : {} = Struct {}; + let Inspect.330 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.331 Inspect.332; + ret Inspect.330; + +procedure Inspect.233 (Inspect.333, Inspect.334): + let Inspect.236 : Str = StructAtIndex 0 Inspect.334; + let Inspect.237 : Str = StructAtIndex 1 Inspect.334; + let Inspect.234 : Str = StructAtIndex 0 Inspect.333; + let Inspect.235 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.348 Inspect.238: + let Inspect.345 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; dec Inspect.236; - let Inspect.347 : Str = ": "; - let Inspect.341 : Str = CallByName Inspect.63 Inspect.346 Inspect.347; - dec Inspect.347; - let Inspect.337 : Str = CallByName Inspect.239 Inspect.341 Inspect.237; + let Inspect.346 : Str = ": "; + let Inspect.340 : Str = CallByName Inspect.63 Inspect.345 Inspect.346; + dec Inspect.346; + let Inspect.336 : Str = CallByName Inspect.239 Inspect.340 Inspect.237; dec Inspect.237; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.241 Inspect.337; - dec Inspect.337; - ret Inspect.336; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.241 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.235 then - let Inspect.350 : Str = ", "; - let Inspect.348 : Str = CallByName Inspect.63 Inspect.234 Inspect.350; - dec Inspect.350; - jump Inspect.349 Inspect.348; + let Inspect.349 : Str = ", "; + let Inspect.347 : Str = CallByName Inspect.63 Inspect.234 Inspect.349; + dec Inspect.349; + jump Inspect.348 Inspect.347; else - jump Inspect.349 Inspect.234; + jump Inspect.348 Inspect.234; procedure Inspect.239 (Inspect.240, Inspect.237): - let Inspect.344 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; - ret Inspect.344; + let Inspect.343 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; + ret Inspect.343; procedure Inspect.241 (Inspect.242): - let Inspect.340 : Int1 = CallByName Bool.2; + let Inspect.339 : Int1 = CallByName Bool.2; inc Inspect.242; - let Inspect.339 : {Str, Int1} = Struct {Inspect.242, Inspect.340}; - ret Inspect.339; - -procedure Inspect.243 (Inspect.326): - let Inspect.327 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.327; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.361 : Str = "\""; - let Inspect.360 : Str = CallByName Inspect.63 Inspect.251 Inspect.361; - dec Inspect.361; - let Inspect.358 : Str = CallByName Inspect.63 Inspect.360 Inspect.249; - let Inspect.359 : Str = "\""; - let Inspect.357 : Str = CallByName Inspect.63 Inspect.358 Inspect.359; - dec Inspect.359; - ret Inspect.357; + let Inspect.338 : {Str, Int1} = Struct {Inspect.242, Inspect.339}; + ret Inspect.338; + +procedure Inspect.243 (Inspect.325): + let Inspect.326 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.326; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.360 : Str = "\""; + let Inspect.359 : Str = CallByName Inspect.63 Inspect.250 Inspect.360; + dec Inspect.360; + let Inspect.357 : Str = CallByName Inspect.63 Inspect.359 Inspect.248; + let Inspect.358 : Str = "\""; + let Inspect.356 : Str = CallByName Inspect.63 Inspect.357 Inspect.358; + dec Inspect.358; + ret Inspect.356; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -100,44 +100,44 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.229 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.229 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.345 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.345; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.344 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.344; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.45 (Inspect.228): - let Inspect.315 : List {Str, Str} = CallByName Inspect.30 Inspect.228; - ret Inspect.315; + let Inspect.314 : List {Str, Str} = CallByName Inspect.30 Inspect.228; + ret Inspect.314; -procedure Inspect.47 (Inspect.249): - let Inspect.353 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.353; +procedure Inspect.47 (Inspect.248): + let Inspect.352 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.352; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.2 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.323 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.323; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : Str = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.2 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.322 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.322; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure List.100 (#Derived_gen.12, #Derived_gen.13, #Derived_gen.14, #Derived_gen.15, #Derived_gen.16): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: diff --git a/crates/compiler/test_mono/generated/inspect_derived_record_two_field_strings.txt b/crates/compiler/test_mono/generated/inspect_derived_record_two_field_strings.txt index a6ae504494e..9ac717cbc43 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_record_two_field_strings.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_record_two_field_strings.txt @@ -28,75 +28,75 @@ procedure Bool.2 (): ret Bool.23; procedure Inspect.229 (Inspect.230, Inspect.228): - let Inspect.352 : Str = "{"; - let Inspect.328 : Str = CallByName Inspect.63 Inspect.230 Inspect.352; - dec Inspect.352; - let Inspect.324 : {Str, Int1} = CallByName Inspect.231 Inspect.328 Inspect.228; - dec Inspect.328; - let Inspect.325 : {} = Struct {}; - let Inspect.320 : Str = CallByName Inspect.243 Inspect.324; - let Inspect.321 : Str = "}"; - let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; - dec Inspect.321; - ret Inspect.319; + let Inspect.351 : Str = "{"; + let Inspect.327 : Str = CallByName Inspect.63 Inspect.230 Inspect.351; + dec Inspect.351; + let Inspect.323 : {Str, Int1} = CallByName Inspect.231 Inspect.327 Inspect.228; + dec Inspect.327; + let Inspect.324 : {} = Struct {}; + let Inspect.319 : Str = CallByName Inspect.243 Inspect.323; + let Inspect.320 : Str = "}"; + let Inspect.318 : Str = CallByName Inspect.63 Inspect.319 Inspect.320; + dec Inspect.320; + ret Inspect.318; procedure Inspect.231 (Inspect.232, Inspect.228): - let Inspect.351 : Int1 = CallByName Bool.1; + let Inspect.350 : Int1 = CallByName Bool.1; inc Inspect.232; - let Inspect.332 : {Str, Int1} = Struct {Inspect.232, Inspect.351}; - let Inspect.333 : {} = Struct {}; - let Inspect.331 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.332 Inspect.333; - ret Inspect.331; - -procedure Inspect.233 (Inspect.334, Inspect.335): - let Inspect.236 : Str = StructAtIndex 0 Inspect.335; - let Inspect.237 : Str = StructAtIndex 1 Inspect.335; - let Inspect.234 : Str = StructAtIndex 0 Inspect.334; - let Inspect.235 : Int1 = StructAtIndex 1 Inspect.334; - joinpoint Inspect.349 Inspect.238: - let Inspect.346 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; + let Inspect.331 : {Str, Int1} = Struct {Inspect.232, Inspect.350}; + let Inspect.332 : {} = Struct {}; + let Inspect.330 : {Str, Int1} = CallByName List.18 Inspect.228 Inspect.331 Inspect.332; + ret Inspect.330; + +procedure Inspect.233 (Inspect.333, Inspect.334): + let Inspect.236 : Str = StructAtIndex 0 Inspect.334; + let Inspect.237 : Str = StructAtIndex 1 Inspect.334; + let Inspect.234 : Str = StructAtIndex 0 Inspect.333; + let Inspect.235 : Int1 = StructAtIndex 1 Inspect.333; + joinpoint Inspect.348 Inspect.238: + let Inspect.345 : Str = CallByName Inspect.63 Inspect.238 Inspect.236; dec Inspect.236; - let Inspect.347 : Str = ": "; - let Inspect.341 : Str = CallByName Inspect.63 Inspect.346 Inspect.347; - dec Inspect.347; - let Inspect.337 : Str = CallByName Inspect.239 Inspect.341 Inspect.237; + let Inspect.346 : Str = ": "; + let Inspect.340 : Str = CallByName Inspect.63 Inspect.345 Inspect.346; + dec Inspect.346; + let Inspect.336 : Str = CallByName Inspect.239 Inspect.340 Inspect.237; dec Inspect.237; - let Inspect.338 : {} = Struct {}; - let Inspect.336 : {Str, Int1} = CallByName Inspect.241 Inspect.337; - dec Inspect.337; - ret Inspect.336; + let Inspect.337 : {} = Struct {}; + let Inspect.335 : {Str, Int1} = CallByName Inspect.241 Inspect.336; + dec Inspect.336; + ret Inspect.335; in if Inspect.235 then - let Inspect.350 : Str = ", "; - let Inspect.348 : Str = CallByName Inspect.63 Inspect.234 Inspect.350; - dec Inspect.350; - jump Inspect.349 Inspect.348; + let Inspect.349 : Str = ", "; + let Inspect.347 : Str = CallByName Inspect.63 Inspect.234 Inspect.349; + dec Inspect.349; + jump Inspect.348 Inspect.347; else - jump Inspect.349 Inspect.234; + jump Inspect.348 Inspect.234; procedure Inspect.239 (Inspect.240, Inspect.237): - let Inspect.344 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; - ret Inspect.344; + let Inspect.343 : Str = CallByName Inspect.31 Inspect.237 Inspect.240; + ret Inspect.343; procedure Inspect.241 (Inspect.242): - let Inspect.340 : Int1 = CallByName Bool.2; + let Inspect.339 : Int1 = CallByName Bool.2; inc Inspect.242; - let Inspect.339 : {Str, Int1} = Struct {Inspect.242, Inspect.340}; - ret Inspect.339; - -procedure Inspect.243 (Inspect.326): - let Inspect.327 : Str = StructAtIndex 0 Inspect.326; - ret Inspect.327; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.361 : Str = "\""; - let Inspect.360 : Str = CallByName Inspect.63 Inspect.251 Inspect.361; - dec Inspect.361; - let Inspect.358 : Str = CallByName Inspect.63 Inspect.360 Inspect.249; - let Inspect.359 : Str = "\""; - let Inspect.357 : Str = CallByName Inspect.63 Inspect.358 Inspect.359; - dec Inspect.359; - ret Inspect.357; + let Inspect.338 : {Str, Int1} = Struct {Inspect.242, Inspect.339}; + ret Inspect.338; + +procedure Inspect.243 (Inspect.325): + let Inspect.326 : Str = StructAtIndex 0 Inspect.325; + ret Inspect.326; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.360 : Str = "\""; + let Inspect.359 : Str = CallByName Inspect.63 Inspect.250 Inspect.360; + dec Inspect.360; + let Inspect.357 : Str = CallByName Inspect.63 Inspect.359 Inspect.248; + let Inspect.358 : Str = "\""; + let Inspect.356 : Str = CallByName Inspect.63 Inspect.357 Inspect.358; + dec Inspect.358; + ret Inspect.356; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -107,44 +107,44 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.314 : Str = CallByName Inspect.229 Inspect.149 Inspect.303; - ret Inspect.314; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.313 : Str = CallByName Inspect.229 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.345 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.345; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.344 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.344; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.45 (Inspect.228): - let Inspect.315 : List {Str, Str} = CallByName Inspect.30 Inspect.228; - ret Inspect.315; + let Inspect.314 : List {Str, Str} = CallByName Inspect.30 Inspect.228; + ret Inspect.314; -procedure Inspect.47 (Inspect.249): - let Inspect.362 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.362; +procedure Inspect.47 (Inspect.248): + let Inspect.361 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.361; procedure Inspect.5 (Inspect.150): - let Inspect.312 : {Str, Str} = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.2 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.323 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.323; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : {Str, Str} = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.2 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.322 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.322; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure List.100 (#Derived_gen.16, #Derived_gen.17, #Derived_gen.18, #Derived_gen.19, #Derived_gen.20): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: diff --git a/crates/compiler/test_mono/generated/inspect_derived_string.txt b/crates/compiler/test_mono/generated/inspect_derived_string.txt index d7501b230b0..e1b0bb21b15 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_string.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_string.txt @@ -1,43 +1,43 @@ -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.323 : Str = "\""; - let Inspect.322 : Str = CallByName Inspect.63 Inspect.251 Inspect.323; - dec Inspect.323; - let Inspect.318 : Str = CallByName Inspect.63 Inspect.322 Inspect.249; - let Inspect.319 : Str = "\""; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.318 Inspect.319; - dec Inspect.319; - ret Inspect.317; +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.322 : Str = "\""; + let Inspect.321 : Str = CallByName Inspect.63 Inspect.250 Inspect.322; + dec Inspect.322; + let Inspect.317 : Str = CallByName Inspect.63 Inspect.321 Inspect.248; + let Inspect.318 : Str = "\""; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.317 Inspect.318; + dec Inspect.318; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; -procedure Inspect.47 (Inspect.249): - let Inspect.313 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.313; +procedure Inspect.47 (Inspect.248): + let Inspect.312 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.312; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName Inspect.47 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.250 Inspect.308 Inspect.312; - dec Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.321 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.321; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : Str = CallByName Inspect.47 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.249 Inspect.307 Inspect.311; + dec Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.320 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.320; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Str.3 (#Attr.2, #Attr.3): let Str.246 : Str = lowlevel StrConcat #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/generated/inspect_derived_tag_one_field_string.txt b/crates/compiler/test_mono/generated/inspect_derived_tag_one_field_string.txt index 8756198db09..1414f97b313 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_tag_one_field_string.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_tag_one_field_string.txt @@ -20,51 +20,51 @@ procedure Bool.11 (#Attr.2, #Attr.3): ret Bool.23; procedure Inspect.204 (Inspect.205, #Attr.12): - let Inspect.346 : Str = UnionAtIndex (Id 0) (Index 0) #Attr.12; - let Inspect.345 : Str = CallByName Inspect.63 Inspect.205 Inspect.346; - dec Inspect.346; - ret Inspect.345; + let Inspect.345 : Str = UnionAtIndex (Id 0) (Index 0) #Attr.12; + let Inspect.344 : Str = CallByName Inspect.63 Inspect.205 Inspect.345; + dec Inspect.345; + ret Inspect.344; procedure Inspect.206 (Inspect.207, #Attr.12): - let Inspect.340 : List Str = UnionAtIndex (Id 1) (Index 1) #Attr.12; - let Inspect.339 : Str = UnionAtIndex (Id 1) (Index 0) #Attr.12; - let Inspect.338 : Str = "("; - let Inspect.337 : Str = CallByName Inspect.63 Inspect.207 Inspect.338; + let Inspect.339 : List Str = UnionAtIndex (Id 1) (Index 1) #Attr.12; + let Inspect.338 : Str = UnionAtIndex (Id 1) (Index 0) #Attr.12; + let Inspect.337 : Str = "("; + let Inspect.336 : Str = CallByName Inspect.63 Inspect.207 Inspect.337; + dec Inspect.337; + let Inspect.324 : Str = CallByName Inspect.63 Inspect.336 Inspect.338; dec Inspect.338; - let Inspect.325 : Str = CallByName Inspect.63 Inspect.337 Inspect.339; + let Inspect.320 : Str = CallByName Inspect.208 Inspect.324 Inspect.339; dec Inspect.339; - let Inspect.321 : Str = CallByName Inspect.208 Inspect.325 Inspect.340; - dec Inspect.340; - let Inspect.322 : Str = ")"; - let Inspect.320 : Str = CallByName Inspect.63 Inspect.321 Inspect.322; - dec Inspect.322; - ret Inspect.320; + let Inspect.321 : Str = ")"; + let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; + dec Inspect.321; + ret Inspect.319; procedure Inspect.208 (Inspect.209, Inspect.203): - let Inspect.329 : {} = Struct {}; - let Inspect.328 : Str = CallByName List.18 Inspect.203 Inspect.209 Inspect.329; - ret Inspect.328; + let Inspect.328 : {} = Struct {}; + let Inspect.327 : Str = CallByName List.18 Inspect.203 Inspect.209 Inspect.328; + ret Inspect.327; procedure Inspect.210 (Inspect.211, Inspect.212): - let Inspect.336 : Str = " "; - let Inspect.331 : Str = CallByName Inspect.63 Inspect.211 Inspect.336; - dec Inspect.336; - let Inspect.330 : Str = CallByName Inspect.213 Inspect.331 Inspect.212; - ret Inspect.330; + let Inspect.335 : Str = " "; + let Inspect.330 : Str = CallByName Inspect.63 Inspect.211 Inspect.335; + dec Inspect.335; + let Inspect.329 : Str = CallByName Inspect.213 Inspect.330 Inspect.212; + ret Inspect.329; procedure Inspect.213 (Inspect.214, Inspect.212): - let Inspect.334 : Str = CallByName Inspect.31 Inspect.212 Inspect.214; - ret Inspect.334; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.355 : Str = "\""; - let Inspect.354 : Str = CallByName Inspect.63 Inspect.251 Inspect.355; - dec Inspect.355; - let Inspect.352 : Str = CallByName Inspect.63 Inspect.354 Inspect.249; - let Inspect.353 : Str = "\""; - let Inspect.351 : Str = CallByName Inspect.63 Inspect.352 Inspect.353; - dec Inspect.353; - ret Inspect.351; + let Inspect.333 : Str = CallByName Inspect.31 Inspect.212 Inspect.214; + ret Inspect.333; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.354 : Str = "\""; + let Inspect.353 : Str = CallByName Inspect.63 Inspect.250 Inspect.354; + dec Inspect.354; + let Inspect.351 : Str = CallByName Inspect.63 Inspect.353 Inspect.248; + let Inspect.352 : Str = "\""; + let Inspect.350 : Str = CallByName Inspect.63 Inspect.351 Inspect.352; + dec Inspect.352; + ret Inspect.350; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -75,62 +75,62 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.315 : U8 = GetTagId Inspect.303; - switch Inspect.315: +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.314 : U8 = GetTagId Inspect.302; + switch Inspect.314: case 0: - let Inspect.314 : Str = CallByName Inspect.204 Inspect.149 Inspect.303; - ret Inspect.314; + let Inspect.313 : Str = CallByName Inspect.204 Inspect.149 Inspect.302; + ret Inspect.313; default: - let Inspect.314 : Str = CallByName Inspect.206 Inspect.149 Inspect.303; - ret Inspect.314; + let Inspect.313 : Str = CallByName Inspect.206 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.335 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.335; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.334 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.334; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.43 (Inspect.202, Inspect.203): - let Inspect.341 : Int1 = CallByName List.1 Inspect.203; - if Inspect.341 then + let Inspect.340 : Int1 = CallByName List.1 Inspect.203; + if Inspect.340 then inc Inspect.202; - let Inspect.343 : [C Str, C Str List Str] = TagId(0) Inspect.202; - let Inspect.342 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.343; - ret Inspect.342; + let Inspect.342 : [C Str, C Str List Str] = TagId(0) Inspect.202; + let Inspect.341 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.342; + ret Inspect.341; else inc Inspect.203; inc Inspect.202; - let Inspect.317 : [C Str, C Str List Str] = TagId(1) Inspect.202 Inspect.203; - let Inspect.316 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.317; - ret Inspect.316; + let Inspect.316 : [C Str, C Str List Str] = TagId(1) Inspect.202 Inspect.203; + let Inspect.315 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.316; + ret Inspect.315; -procedure Inspect.47 (Inspect.249): - let Inspect.347 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.347; +procedure Inspect.47 (Inspect.248): + let Inspect.346 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.346; procedure Inspect.5 (Inspect.150): - let Inspect.312 : Str = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.3 Inspect.308 Inspect.312; - ret Inspect.307; + let Inspect.311 : Str = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.3 Inspect.307 Inspect.311; + ret Inspect.306; -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.324 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.324; +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.323 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.323; -procedure Inspect.64 (Inspect.302): - ret Inspect.302; +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure List.1 (List.118): let List.678 : U64 = CallByName List.6 List.118; @@ -138,7 +138,7 @@ procedure List.1 (List.118): let List.677 : Int1 = CallByName Bool.11 List.678 List.679; ret List.677; -procedure List.100 (#Derived_gen.14, #Derived_gen.15, #Derived_gen.16, #Derived_gen.17, #Derived_gen.18): +procedure List.100 (#Derived_gen.12, #Derived_gen.13, #Derived_gen.14, #Derived_gen.15, #Derived_gen.16): joinpoint List.668 List.174 List.175 List.176 List.177 List.178: let List.670 : Int1 = CallByName Num.22 List.177 List.178; if List.670 then @@ -153,8 +153,8 @@ procedure List.100 (#Derived_gen.14, #Derived_gen.15, #Derived_gen.16, #Derived_ dec List.174; ret List.175; in - inc #Derived_gen.14; - jump List.668 #Derived_gen.14 #Derived_gen.15 #Derived_gen.16 #Derived_gen.17 #Derived_gen.18; + inc #Derived_gen.12; + jump List.668 #Derived_gen.12 #Derived_gen.13 #Derived_gen.14 #Derived_gen.15 #Derived_gen.16; procedure List.18 (List.171, List.172, List.173): let List.666 : U64 = 0i64; diff --git a/crates/compiler/test_mono/generated/inspect_derived_tag_two_payloads_string.txt b/crates/compiler/test_mono/generated/inspect_derived_tag_two_payloads_string.txt index 1183f3a7415..add16ae62f4 100644 --- a/crates/compiler/test_mono/generated/inspect_derived_tag_two_payloads_string.txt +++ b/crates/compiler/test_mono/generated/inspect_derived_tag_two_payloads_string.txt @@ -23,51 +23,51 @@ procedure Bool.11 (#Attr.2, #Attr.3): ret Bool.23; procedure Inspect.204 (Inspect.205, #Attr.12): - let Inspect.346 : Str = UnionAtIndex (Id 0) (Index 0) #Attr.12; - let Inspect.345 : Str = CallByName Inspect.63 Inspect.205 Inspect.346; - dec Inspect.346; - ret Inspect.345; + let Inspect.345 : Str = UnionAtIndex (Id 0) (Index 0) #Attr.12; + let Inspect.344 : Str = CallByName Inspect.63 Inspect.205 Inspect.345; + dec Inspect.345; + ret Inspect.344; procedure Inspect.206 (Inspect.207, #Attr.12): - let Inspect.340 : List Str = UnionAtIndex (Id 1) (Index 1) #Attr.12; - let Inspect.339 : Str = UnionAtIndex (Id 1) (Index 0) #Attr.12; - let Inspect.338 : Str = "("; - let Inspect.337 : Str = CallByName Inspect.63 Inspect.207 Inspect.338; + let Inspect.339 : List Str = UnionAtIndex (Id 1) (Index 1) #Attr.12; + let Inspect.338 : Str = UnionAtIndex (Id 1) (Index 0) #Attr.12; + let Inspect.337 : Str = "("; + let Inspect.336 : Str = CallByName Inspect.63 Inspect.207 Inspect.337; + dec Inspect.337; + let Inspect.324 : Str = CallByName Inspect.63 Inspect.336 Inspect.338; dec Inspect.338; - let Inspect.325 : Str = CallByName Inspect.63 Inspect.337 Inspect.339; + let Inspect.320 : Str = CallByName Inspect.208 Inspect.324 Inspect.339; dec Inspect.339; - let Inspect.321 : Str = CallByName Inspect.208 Inspect.325 Inspect.340; - dec Inspect.340; - let Inspect.322 : Str = ")"; - let Inspect.320 : Str = CallByName Inspect.63 Inspect.321 Inspect.322; - dec Inspect.322; - ret Inspect.320; + let Inspect.321 : Str = ")"; + let Inspect.319 : Str = CallByName Inspect.63 Inspect.320 Inspect.321; + dec Inspect.321; + ret Inspect.319; procedure Inspect.208 (Inspect.209, Inspect.203): - let Inspect.329 : {} = Struct {}; - let Inspect.328 : Str = CallByName List.18 Inspect.203 Inspect.209 Inspect.329; - ret Inspect.328; + let Inspect.328 : {} = Struct {}; + let Inspect.327 : Str = CallByName List.18 Inspect.203 Inspect.209 Inspect.328; + ret Inspect.327; procedure Inspect.210 (Inspect.211, Inspect.212): - let Inspect.336 : Str = " "; - let Inspect.331 : Str = CallByName Inspect.63 Inspect.211 Inspect.336; - dec Inspect.336; - let Inspect.330 : Str = CallByName Inspect.213 Inspect.331 Inspect.212; - ret Inspect.330; + let Inspect.335 : Str = " "; + let Inspect.330 : Str = CallByName Inspect.63 Inspect.211 Inspect.335; + dec Inspect.335; + let Inspect.329 : Str = CallByName Inspect.213 Inspect.330 Inspect.212; + ret Inspect.329; procedure Inspect.213 (Inspect.214, Inspect.212): - let Inspect.334 : Str = CallByName Inspect.31 Inspect.212 Inspect.214; - ret Inspect.334; - -procedure Inspect.250 (Inspect.251, Inspect.249): - let Inspect.355 : Str = "\""; - let Inspect.354 : Str = CallByName Inspect.63 Inspect.251 Inspect.355; - dec Inspect.355; - let Inspect.352 : Str = CallByName Inspect.63 Inspect.354 Inspect.249; - let Inspect.353 : Str = "\""; - let Inspect.351 : Str = CallByName Inspect.63 Inspect.352 Inspect.353; - dec Inspect.353; - ret Inspect.351; + let Inspect.333 : Str = CallByName Inspect.31 Inspect.212 Inspect.214; + ret Inspect.333; + +procedure Inspect.249 (Inspect.250, Inspect.248): + let Inspect.354 : Str = "\""; + let Inspect.353 : Str = CallByName Inspect.63 Inspect.250 Inspect.354; + dec Inspect.354; + let Inspect.351 : Str = CallByName Inspect.63 Inspect.353 Inspect.248; + let Inspect.352 : Str = "\""; + let Inspect.350 : Str = CallByName Inspect.63 Inspect.351 Inspect.352; + dec Inspect.352; + ret Inspect.350; procedure Inspect.30 (Inspect.147): ret Inspect.147; @@ -78,62 +78,62 @@ procedure Inspect.30 (Inspect.147): procedure Inspect.30 (Inspect.147): ret Inspect.147; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.315 : U8 = GetTagId Inspect.303; - switch Inspect.315: +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.314 : U8 = GetTagId Inspect.302; + switch Inspect.314: case 0: - let Inspect.314 : Str = CallByName Inspect.204 Inspect.149 Inspect.303; - ret Inspect.314; + let Inspect.313 : Str = CallByName Inspect.204 Inspect.149 Inspect.302; + ret Inspect.313; default: - let Inspect.314 : Str = CallByName Inspect.206 Inspect.149 Inspect.303; - ret Inspect.314; + let Inspect.313 : Str = CallByName Inspect.206 Inspect.149 Inspect.302; + ret Inspect.313; -procedure Inspect.31 (Inspect.303, Inspect.149): - let Inspect.335 : Str = CallByName Inspect.250 Inspect.149 Inspect.303; - ret Inspect.335; +procedure Inspect.31 (Inspect.302, Inspect.149): + let Inspect.334 : Str = CallByName Inspect.249 Inspect.149 Inspect.302; + ret Inspect.334; procedure Inspect.33 (Inspect.152): - let Inspect.305 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.304 : Str = CallByName Inspect.64 Inspect.305; - ret Inspect.304; + let Inspect.304 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.303 : Str = CallByName Inspect.64 Inspect.304; + ret Inspect.303; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.43 (Inspect.202, Inspect.203): - let Inspect.341 : Int1 = CallByName List.1 Inspect.203; - if Inspect.341 then + let Inspect.340 : Int1 = CallByName List.1 Inspect.203; + if Inspect.340 then inc Inspect.202; - let Inspect.343 : [C Str, C Str List Str] = TagId(0) Inspect.202; - let Inspect.342 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.343; - ret Inspect.342; + let Inspect.342 : [C Str, C Str List Str] = TagId(0) Inspect.202; + let Inspect.341 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.342; + ret Inspect.341; else inc Inspect.203; inc Inspect.202; - let Inspect.317 : [C Str, C Str List Str] = TagId(1) Inspect.202 Inspect.203; - let Inspect.316 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.317; - ret Inspect.316; + let Inspect.316 : [C Str, C Str List Str] = TagId(1) Inspect.202 Inspect.203; + let Inspect.315 : [C Str, C Str List Str] = CallByName Inspect.30 Inspect.316; + ret Inspect.315; -procedure Inspect.47 (Inspect.249): - let Inspect.356 : Str = CallByName Inspect.30 Inspect.249; - ret Inspect.356; +procedure Inspect.47 (Inspect.248): + let Inspect.355 : Str = CallByName Inspect.30 Inspect.248; + ret Inspect.355; procedure Inspect.5 (Inspect.150): - let Inspect.312 : {Str, Str} = CallByName #Derived.0 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName #Derived.4 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.324 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.324; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : {Str, Str} = CallByName #Derived.0 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName #Derived.4 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.323 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.323; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure List.1 (List.118): let List.678 : U64 = CallByName List.6 List.118; diff --git a/crates/compiler/test_mono/generated/linked_list_filter.txt b/crates/compiler/test_mono/generated/linked_list_filter.txt index 659ccd01420..8d48bbf5b7d 100644 --- a/crates/compiler/test_mono/generated/linked_list_filter.txt +++ b/crates/compiler/test_mono/generated/linked_list_filter.txt @@ -1,56 +1,42 @@ -procedure Num.31 (Num.220): - let Num.284 : I64 = 2i64; - let Num.283 : Int1 = CallByName Num.86 Num.220 Num.284; - ret Num.283; - -procedure Num.86 (#Attr.2, #Attr.3): - let Num.285 : Int1 = lowlevel NumIsMultipleOf #Attr.2 #Attr.3; - ret Num.285; - -procedure Test.2 (#Derived_gen.0, #Derived_gen.1): - let #Derived_gen.3 : [, C I64 *self] = NullPointer; - let #Derived_gen.2 : Ptr([, C I64 *self]) = Alloca #Derived_gen.3; - joinpoint #Derived_gen.4 Test.4 Test.5 #Derived_gen.5 #Derived_gen.6: - let Test.22 : U8 = 1i64; - let Test.23 : U8 = GetTagId Test.4; - let Test.24 : Int1 = lowlevel Eq Test.22 Test.23; - if Test.24 then - let Test.17 : [, C I64 *self] = TagId(1) ; - let #Derived_gen.8 : {} = lowlevel PtrStore #Derived_gen.5 Test.17; - let #Derived_gen.7 : [, C I64 *self] = lowlevel PtrLoad #Derived_gen.6; - ret #Derived_gen.7; +procedure Test.2 (Test.4, Test.5): + let Test.23 : U8 = 1i64; + let Test.24 : U8 = GetTagId Test.4; + let Test.25 : Int1 = lowlevel Eq Test.23 Test.24; + if Test.25 then + let Test.17 : [, C I64 *self] = TagId(1) ; + ret Test.17; + else + let Test.7 : I64 = UnionAtIndex (Id 0) (Index 0) Test.4; + let Test.8 : [, C I64 *self] = UnionAtIndex (Id 0) (Index 1) Test.4; + joinpoint #Derived_gen.2: + dec Test.8; + let Test.22 : Str = "a Lambda Set is empty. Most likely there is a type error in your program."; + Crash Test.22 + in + let #Derived_gen.3 : Int1 = lowlevel RefCountIsUnique Test.4; + if #Derived_gen.3 then + free Test.4; + jump #Derived_gen.2; else - let Test.7 : I64 = UnionAtIndex (Id 0) (Index 0) Test.4; - let Test.8 : [, C I64 *self] = UnionAtIndex (Id 0) (Index 1) Test.4; - joinpoint #Derived_gen.12 #Derived_gen.14: - let Test.19 : Int1 = CallByName Num.31 Test.7; - if Test.19 then - let #Derived_gen.9 : [, C I64 *self] = NullPointer; - let Test.20 : [, C I64 *self] = Reuse #Derived_gen.14 UpdateModeId { id: 1 } TagId(0) Test.7 #Derived_gen.9; - let #Derived_gen.10 : Ptr([, C I64 *self]) = GetElementPointer (Indices [0, 1]) Test.20; - let #Derived_gen.11 : {} = lowlevel PtrStore #Derived_gen.5 Test.20; - jump #Derived_gen.4 Test.8 Test.5 #Derived_gen.10 #Derived_gen.6; - else - decref #Derived_gen.14; - jump #Derived_gen.4 Test.8 Test.5 #Derived_gen.5 #Derived_gen.6; - in - let #Derived_gen.13 : Int1 = lowlevel RefCountIsUnique Test.4; - if #Derived_gen.13 then - jump #Derived_gen.12 Test.4; - else - inc Test.8; - decref Test.4; - let #Derived_gen.15 : [, C I64 *self] = NullPointer; - jump #Derived_gen.12 #Derived_gen.15; - in - jump #Derived_gen.4 #Derived_gen.0 #Derived_gen.1 #Derived_gen.2 #Derived_gen.2; + inc Test.8; + decref Test.4; + jump #Derived_gen.2; procedure Test.0 (): - let Test.25 : I64 = 1i64; - let Test.27 : I64 = 2i64; - let Test.28 : [, C I64 *self] = TagId(1) ; - let Test.26 : [, C I64 *self] = TagId(0) Test.27 Test.28; - let Test.14 : [, C I64 *self] = TagId(0) Test.25 Test.26; - let Test.15 : {} = Struct {}; - let Test.13 : [, C I64 *self] = CallByName Test.2 Test.14 Test.15; - ret Test.13; + let Test.27 : I64 = 1i64; + let Test.29 : I64 = 2i64; + let Test.30 : [, C I64 *self] = TagId(1) ; + let Test.28 : [, C I64 *self] = TagId(0) Test.29 Test.30; + let Test.14 : [, C I64 *self] = TagId(0) Test.27 Test.28; + joinpoint #Derived_gen.4: + let Test.26 : Str = "ValueNotExposed { module_name: ModuleName(IdentStr { string: \"Num\" }), ident: Ident(IdentStr { string: \"isEven\" }), region: @416-426, exposed_values: ['max_f32', 'min_f32', 'abs', 'neg', 'add', 'sub', 'mul', 'is_lt', 'is_lte', 'is_gt', 'is_gte', 'to_frac', 'sin', 'cos', 'tan', 'is_zero', 'is_even', 'is_odd', 'is_positive', 'is_negative', 'rem', 'rem_checked', 'div', 'div_checked', 'div_trunc', 'div_trunc_checked', 'sqrt', 'sqrt_checked', 'log', 'log_checked', 'round', 'compare', 'pow', 'ceiling', 'pow_int', 'floor', 'add_wrap', 'add_checked', 'add_saturated', 'atan', 'acos', 'asin', 'bitwise_and', 'bitwise_xor', 'bitwise_or', 'shift_left_by', 'shift_right_by', 'shift_right_zf_by', 'sub_wrap', 'sub_checked', 'sub_saturated', 'mul_wrap', 'mul_checked', 'mul_saturated', 'e', 'pi', 'tau', 'is_multiple_of', 'count_one_bits', 'abs_diff', 'is_nan', 'is_infinite', 'is_finite', 'count_leading_zero_bits', 'count_trailing_zero_bits', 'to_str', 'min_i8', 'max_i8', 'min_u8', 'max_u8', 'min_i16', 'max_i16', 'min_u16', 'max_u16', 'min_i32', 'max_i32', 'min_u32', 'max_u32', 'min_i64', 'max_i64', 'min_u64', 'max_u64', 'min_i128', 'max_i128', 'min_u128', 'max_u128', 'to_i8', 'to_i8_checked', 'to_i16', 'to_i16_checked', 'to_i32', 'to_i32_checked', 'to_i64', 'to_i64_checked', 'to_i128', 'to_i128_checked', 'to_u8', 'to_u8_checked', 'to_u16', 'to_u16_checked', 'to_u32', 'to_u32_checked', 'to_u64', 'to_u64_checked', 'to_u128', 'to_u128_checked', 'div_ceil', 'div_ceil_checked', 'to_f32', 'to_f32_checked', 'to_f64', 'to_f64_checked', 'max_f64', 'min_f64', 'add_checked_lowlevel', 'sub_checked_lowlevel', 'mul_checked_lowlevel', 'min', 'max', 'bitwise_not', 'int_cast', 'is_approx_eq', 'bytes_to_u16_owlevel', 'bytes_to_u32_lowlevel', 'bytes_to_u64_lowlevel', 'bytes_to_u128_lowlevel', 'div_trunc_unchecked', 'rem_unchecked', 'without_decimal_point', 'with_decimal_point', 'f32_to_parts', 'f64_to_parts', 'f32_from_parts', 'f64_from_parts', 'nan_f32', 'nan_f64', 'infinity_f32', 'infinity_f64', 'from_bool'] }"; + Crash Test.26 + in + let #Derived_gen.5 : Int1 = lowlevel RefCountIsUnique Test.14; + if #Derived_gen.5 then + dec Test.28; + free Test.14; + jump #Derived_gen.4; + else + decref Test.14; + jump #Derived_gen.4; diff --git a/crates/compiler/test_mono/generated/pizza_dbg.txt b/crates/compiler/test_mono/generated/pizza_dbg.txt index f5c2314062c..7d51995ff84 100644 --- a/crates/compiler/test_mono/generated/pizza_dbg.txt +++ b/crates/compiler/test_mono/generated/pizza_dbg.txt @@ -1,38 +1,38 @@ -procedure Inspect.278 (Inspect.279, Inspect.277): - let Inspect.318 : Str = CallByName Num.96 Inspect.277; - let Inspect.317 : Str = CallByName Inspect.63 Inspect.279 Inspect.318; - dec Inspect.318; - ret Inspect.317; +procedure Inspect.277 (Inspect.278, Inspect.276): + let Inspect.317 : Str = CallByName Num.96 Inspect.276; + let Inspect.316 : Str = CallByName Inspect.63 Inspect.278 Inspect.317; + dec Inspect.317; + ret Inspect.316; procedure Inspect.30 (Inspect.147): ret Inspect.147; procedure Inspect.33 (Inspect.152): - let Inspect.322 : Str = CallByName Inspect.5 Inspect.152; - let Inspect.321 : Str = CallByName Inspect.64 Inspect.322; - ret Inspect.321; + let Inspect.321 : Str = CallByName Inspect.5 Inspect.152; + let Inspect.320 : Str = CallByName Inspect.64 Inspect.321; + ret Inspect.320; -procedure Inspect.39 (Inspect.301): - let Inspect.311 : Str = ""; - ret Inspect.311; +procedure Inspect.39 (Inspect.300): + let Inspect.310 : Str = ""; + ret Inspect.310; procedure Inspect.5 (Inspect.150): - let Inspect.312 : I64 = CallByName Inspect.57 Inspect.150; - let Inspect.309 : {} = Struct {}; - let Inspect.308 : Str = CallByName Inspect.39 Inspect.309; - let Inspect.307 : Str = CallByName Inspect.278 Inspect.308 Inspect.312; - ret Inspect.307; - -procedure Inspect.57 (Inspect.277): - let Inspect.313 : I64 = CallByName Inspect.30 Inspect.277; - ret Inspect.313; - -procedure Inspect.63 (Inspect.300, Inspect.296): - let Inspect.320 : Str = CallByName Str.3 Inspect.300 Inspect.296; - ret Inspect.320; - -procedure Inspect.64 (Inspect.302): - ret Inspect.302; + let Inspect.311 : I64 = CallByName Inspect.57 Inspect.150; + let Inspect.308 : {} = Struct {}; + let Inspect.307 : Str = CallByName Inspect.39 Inspect.308; + let Inspect.306 : Str = CallByName Inspect.277 Inspect.307 Inspect.311; + ret Inspect.306; + +procedure Inspect.57 (Inspect.276): + let Inspect.312 : I64 = CallByName Inspect.30 Inspect.276; + ret Inspect.312; + +procedure Inspect.63 (Inspect.299, Inspect.295): + let Inspect.319 : Str = CallByName Str.3 Inspect.299 Inspect.295; + ret Inspect.319; + +procedure Inspect.64 (Inspect.301): + ret Inspect.301; procedure Num.19 (#Attr.2, #Attr.3): let Num.283 : I64 = lowlevel NumAdd #Attr.2 #Attr.3; diff --git a/crates/compiler/test_mono/src/tests.rs b/crates/compiler/test_mono/src/tests.rs index e13833aab82..c59eddaff0d 100644 --- a/crates/compiler/test_mono/src/tests.rs +++ b/crates/compiler/test_mono/src/tests.rs @@ -33,47 +33,47 @@ const TARGET: roc_target::Target = roc_target::Target::LinuxX64; pub const ERR_DECODER_FMT: &str = r#" ErrDecoder := {} implements [ DecoderFormatting { - u8: decodeU8, - u16: decodeU16, - u32: decodeU32, - u64: decodeU64, - u128: decodeU128, - i8: decodeI8, - i16: decodeI16, - i32: decodeI32, - i64: decodeI64, - i128: decodeI128, - f32: decodeF32, - f64: decodeF64, - dec: decodeDec, - bool: decodeBool, - string: decodeString, - list: decodeList, - record: decodeRecord, - tuple: decodeTuple, + u8: decode_u8, + u16: decode_u16, + u32: decode_u32, + u64: decode_u64, + u128: decode_u128, + i8: decode_i8, + i16: decode_i16, + i32: decode_i32, + i64: decode_i64, + i128: decode_i128, + f32: decode_f32, + f64: decode_f64, + dec: decode_dec, + bool: decode_bool, + string: decode_string, + list: decode_list, + record: decode_record, + tuple: decode_tuple, }, ] -decodeU8 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeU16 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeU32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeU64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeU128 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeI8 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeI16 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeI32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeI64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeI128 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeF32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeF64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeDec = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeBool = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeString = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeList : Decoder elem ErrDecoder -> Decoder (List elem) ErrDecoder -decodeList = \_ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeRecord : state, (state, Str -> [Keep (Decoder state ErrDecoder), Skip]), (state, ErrDecoder -> Result val DecodeError) -> Decoder val ErrDecoder -decodeRecord = \_, _, _ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } -decodeTuple : state, (state, U64 -> [Next (Decoder state ErrDecoder), TooLong]), (state -> Result val DecodeError) -> Decoder val ErrDecoder -decodeTuple = \_, _, _ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_u8 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_u16 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_u32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_u64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_u128 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_i8 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_i16 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_i32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_i64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_i128 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_f32 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_f64 = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_dec = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_bool = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_string = Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_list : Decoder elem ErrDecoder -> Decoder (List elem) ErrDecoder +decode_list = \_ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_record : state, (state, Str -> [Keep (Decoder state ErrDecoder), Skip]), (state, ErrDecoder -> Result val DecodeError) -> Decoder val ErrDecoder +decode_record = \_, _, _ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } +decode_tuple : state, (state, U64 -> [Next (Decoder state ErrDecoder), TooLong]), (state -> Result val DecodeError) -> Decoder val ErrDecoder +decode_tuple = \_, _, _ -> Decode.custom \rest, @ErrDecoder {} -> { result: Err TooShort, rest } "#; /// Without this, some tests pass in `cargo test --release` but fail without @@ -367,7 +367,7 @@ fn ir_round() { #[mono_test] fn ir_when_idiv() { r" - when Num.divTruncChecked 1000 10 is + when Num.div_trunc_checked 1000 10 is Ok val -> val Err _ -> -1 " @@ -458,9 +458,9 @@ fn dict() { #[mono_test] fn list_append_closure() { r" - myFunction = \l -> List.append l 42 + my_function = \l -> List.append l 42 - myFunction [1, 2] + my_function [1, 2] " } @@ -687,18 +687,18 @@ fn opaque_as_pattern_in_closure_arg() { fn quicksort_help() { // do we still need with_larger_debug_stack? r" - quicksortHelp : List (Num a), I64, I64 -> List (Num a) - quicksortHelp = \list, low, high -> + quicksort_help : List (Num a), I64, I64 -> List (Num a) + quicksort_help = \list, low, high -> if low < high then - (Pair partitionIndex partitioned) = Pair 0 [] + (Pair partition_index partitioned) = Pair 0 [] partitioned - |> quicksortHelp low (partitionIndex - 1) - |> quicksortHelp (partitionIndex + 1) high + |> quicksort_help low (partition_index - 1) + |> quicksort_help (partition_index + 1) high else list - quicksortHelp [] 0 0 + quicksort_help [] 0 0 " } @@ -710,10 +710,10 @@ fn quicksort_swap() { swap = \list -> when Pair (List.get list 0) (List.get list 0) is - Pair (Ok atI) (Ok atJ) -> + Pair (Ok at_i) (Ok at_j) -> list - |> List.set 0 atJ - |> List.set 0 atI + |> List.set 0 at_j + |> List.set 0 at_i _ -> [] @@ -731,15 +731,15 @@ fn quicksort_swap() { // r#" // app "test" provides [main] to "./platform" -// partitionHelp : I64, I64, List (Num a), I64, (Num a) -> [Pair I64 (List (Num a))] -// partitionHelp = \i, j, list, high, pivot -> +// partition_help : I64, I64, List (Num a), I64, (Num a) -> [Pair I64 (List (Num a))] +// partition_help = \i, j, list, high, pivot -> // if j < high then // when List.get list j is // Ok value -> // if value <= pivot then -// partitionHelp (i + 1) (j + 1) (swap (i + 1) j list) high pivot +// partition_help (i + 1) (j + 1) (swap (i + 1) j list) high pivot // else -// partitionHelp i (j + 1) list high pivot +// partition_help i (j + 1) list high pivot // Err _ -> // Pair i list @@ -747,7 +747,7 @@ fn quicksort_swap() { // Pair i list // main = -// partitionHelp 0 0 [] 0 0 +// partition_help 0 0 [] 0 0 // "# // ) // } @@ -759,57 +759,57 @@ fn quicksort_swap() { // r#" // app "test" provides [main] to "./platform" -// quicksortHelp : List (Num a), I64, I64 -> List (Num a) -// quicksortHelp = \list, low, high -> +// quicksort_help : List (Num a), I64, I64 -> List (Num a) +// quicksort_help = \list, low, high -> // if low < high then -// (Pair partitionIndex partitioned) = partition low high list +// (Pair partition_index partitioned) = partition low high list // partitioned -// |> quicksortHelp low (partitionIndex - 1) -// |> quicksortHelp (partitionIndex + 1) high +// |> quicksort_help low (partition_index - 1) +// |> quicksort_help (partition_index + 1) high // else // list // swap : I64, I64, List a -> List a // swap = \i, j, list -> // when Pair (List.get list i) (List.get list j) is -// Pair (Ok atI) (Ok atJ) -> +// Pair (Ok at_i) (Ok at_j) -> // list -// |> List.set i atJ -// |> List.set j atI +// |> List.set i at_j +// |> List.set j at_i // _ -> // [] // partition : I64, I64, List (Num a) -> [Pair I64 (List (Num a))] -// partition = \low, high, initialList -> -// when List.get initialList high is +// partition = \low, high, initial_list -> +// when List.get initial_list high is // Ok pivot -> -// when partitionHelp (low - 1) low initialList high pivot is -// Pair newI newList -> -// Pair (newI + 1) (swap (newI + 1) high newList) +// when partition_help (low - 1) low initial_list high pivot is +// Pair new_i newList -> +// Pair (new_i + 1) (swap (new_i + 1) high newList) // Err _ -> -// Pair (low - 1) initialList +// Pair (low - 1) initial_list -// partitionHelp : I64, I64, List (Num a), I64, (Num a) -> [Pair I64 (List (Num a))] -// partitionHelp = \i, j, list, high, pivot -> +// partition_help : I64, I64, List (Num a), I64, (Num a) -> [Pair I64 (List (Num a))] +// partition_help = \i, j, list, high, pivot -> // if j < high then // when List.get list j is // Ok value -> // if value <= pivot then -// partitionHelp (i + 1) (j + 1) (swap (i + 1) j list) high pivot +// partition_help (i + 1) (j + 1) (swap (i + 1) j list) high pivot // else -// partitionHelp i (j + 1) list high pivot +// partition_help i (j + 1) list high pivot // Err _ -> // Pair i list // else // Pair i list -// quicksort = \originalList -> -// n = List.len originalList -// quicksortHelp originalList 0 (n - 1) +// quicksort = \original_list -> +// n = List.len original_list +// quicksort_help original_list 0 (n - 1) // main = // quicksort [1,2,3] @@ -837,13 +837,13 @@ fn is_nil() { r" ConsList a : [Cons a (ConsList a), Nil] - isNil : ConsList a -> Bool - isNil = \list -> + is_nil : ConsList a -> Bool + is_nil = \list -> when list is Nil -> Bool.true Cons _ _ -> Bool.false - isNil (Cons 0x2 Nil) + is_nil (Cons 0x2 Nil) " } @@ -854,14 +854,14 @@ fn has_none() { Maybe a : [Just a, Nothing] ConsList a : [Cons a (ConsList a), Nil] - hasNone : ConsList (Maybe a) -> Bool - hasNone = \list -> + has_none : ConsList (Maybe a) -> Bool + has_none = \list -> when list is Nil -> Bool.false Cons Nothing _ -> Bool.true - Cons (Just _) xs -> hasNone xs + Cons (Just _) xs -> has_none xs - hasNone (Cons (Just 3) Nil) + has_none (Cons (Just 3) Nil) " } @@ -871,10 +871,10 @@ fn mk_pair_of() { r#" app "test" provides [main] to "./platform" - mkPairOf = \x -> Pair x x + mk_pair_of = \x -> Pair x x main = - mkPairOf [1,2,3] + mk_pair_of [1,2,3] "# ) } @@ -1052,12 +1052,12 @@ fn rigids() { swap : U64, U64, List a -> List a swap = \i, j, list -> when Pair (List.get list i) (List.get list j) is - Pair (Ok atI) (Ok atJ) -> - foo = atJ + Pair (Ok at_i) (Ok at_j) -> + foo = at_j list |> List.set i foo - |> List.set j atI + |> List.set j at_i _ -> [] @@ -1236,17 +1236,17 @@ fn empty_list_of_function_type() { app "test" provides [main] to "./platform" main = - myList : List (Str -> Str) - myList = [] + my_list : List (Str -> Str) + my_list = [] - myClosure : Str -> Str - myClosure = \_ -> "bar" + my_closure : Str -> Str + my_closure = \_ -> "bar" choose = if Bool.false then - myList + my_list else - [myClosure] + [my_closure] when List.get choose 0 is Ok f -> f "foo" @@ -1417,8 +1417,8 @@ fn issue_2725_alias_polymorphic_lambda() { indoc!( r" wrap = \value -> Tag value - wrapIt = wrap - wrapIt 42 + wrap_it = wrap + wrap_it 42 " ) } @@ -1427,7 +1427,7 @@ fn issue_2725_alias_polymorphic_lambda() { fn issue_2583_specialize_errors_behind_unified_branches() { indoc!( r#" - if Bool.true then List.first [] else Str.toI64 "" + if Bool.true then List.first [] else Str.to_i64 "" "# ) } @@ -1487,11 +1487,11 @@ fn opaque_assign_to_symbol() { Variable := U8 - fromUtf8 : U8 -> Result Variable [InvalidVariableUtf8] - fromUtf8 = \char -> + from_utf8 : U8 -> Result Variable [InvalidVariableUtf8] + from_utf8 = \char -> Ok (@Variable char) - out = fromUtf8 98 + out = from_utf8 98 "# ) } @@ -1500,12 +1500,12 @@ fn opaque_assign_to_symbol() { fn encode() { indoc!( r#" - app "test" provides [myU8Bytes] to "./platform" + app "test" provides [my_u8_bytes] to "./platform" MEncoder fmt := List U8, fmt -> List U8 where fmt implements Format MEncoding implements - toEncoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format + to_encoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format Format implements u8 : U8 -> MEncoder fmt where fmt implements Format @@ -1515,13 +1515,13 @@ fn encode() { u8 = \n -> @MEncoder (\lst, @Linear {} -> List.append lst n) - MyU8 := U8 implements [MEncoding {toEncoder}] + MyU8 := U8 implements [MEncoding {to_encoder}] - toEncoder = \@MyU8 n -> u8 n + to_encoder = \@MyU8 n -> u8 n - myU8Bytes = - when toEncoder (@MyU8 15) is - @MEncoder doEncode -> doEncode [] (@Linear {}) + my_u8_bytes = + when to_encoder (@MyU8 15) is + @MEncoder do_encode -> do_encode [] (@Linear {}) "# ) } @@ -1587,7 +1587,7 @@ fn list_sort_asc() { r#" app "test" provides [out] to "./platform" - out = List.sortAsc [4, 3, 2, 1] + out = List.sort_asc [4, 3, 2, 1] "# ) } @@ -1598,19 +1598,19 @@ fn encode_custom_type() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} HelloWorld := {{}} - toEncoder = \@HelloWorld {{}} -> + to_encoder = \@HelloWorld {{}} -> Encode.custom \bytes, fmt -> bytes - |> Encode.appendWith (Encode.string "Hello, World!\n") fmt + |> Encode.append_with (Encode.string "Hello, World!\n") fmt main = - result = Str.fromUtf8 (Encode.toBytes (@HelloWorld {{}}) tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes (@HelloWorld {{}}) tag_len_fmt) when result is Ok s -> s _ -> "" @@ -1623,13 +1623,13 @@ fn encode_derived_string() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes "abc" tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes "abc" tag_len_fmt) when result is Ok s -> s _ -> "" @@ -1643,13 +1643,13 @@ fn encode_derived_record() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes {{a: "a"}} tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes {{a: "a"}} tag_len_fmt) when result is Ok s -> s _ -> "" @@ -1666,21 +1666,21 @@ fn choose_correct_recursion_var_under_record() { Record (List {parser: Parser}), ] - printCombinatorParser : Parser -> Str - printCombinatorParser = \parser -> + print_combinator_parser : Parser -> Str + print_combinator_parser = \parser -> when parser is Specialize p -> - printed = printCombinatorParser p + printed = print_combinator_parser p if Bool.false then printed else "foo" Record fields -> fields |> List.map \f -> - printed = printCombinatorParser f.parser + printed = print_combinator_parser f.parser if Bool.false then printed else "foo" |> List.first |> Result.withDefault ("foo") - printCombinatorParser (Record []) + print_combinator_parser (Record []) "# ) } @@ -1703,9 +1703,9 @@ fn tail_call_elimination() { fn tail_call_with_same_layout_different_lambda_sets() { indoc!( r#" - chain = \in, buildLazy -> + chain = \in, build_lazy -> \{} -> - thunk = buildLazy in + thunk = build_lazy in thunk {} chain 1u8 \_ -> chain 1u8 \_ -> (\{} -> "") @@ -1717,9 +1717,9 @@ fn tail_call_with_same_layout_different_lambda_sets() { fn tail_call_with_different_layout() { indoc!( r#" - chain = \in, buildLazy -> + chain = \in, build_lazy -> \{} -> - thunk = buildLazy in + thunk = build_lazy in thunk {} chain 1u8 \_ -> chain 1u16 \_ -> (\{} -> "") @@ -1734,7 +1734,7 @@ fn lambda_capture_niche_u8_vs_u64() { capture : _ -> ({} -> Str) capture = \val -> \{} -> - Num.toStr val + Num.to_str val x : [True, False] x = True @@ -1987,13 +1987,13 @@ fn encode_derived_record_one_field_string() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes {{a: "foo"}} tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes {{a: "foo"}} tag_len_fmt) when result is Ok s -> s _ -> "" @@ -2006,13 +2006,13 @@ fn encode_derived_record_two_field_strings() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes {{a: "foo", b: "bar"}} tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes {{a: "foo", b: "bar"}} tag_len_fmt) when result is Ok s -> s _ -> "" @@ -2025,13 +2025,13 @@ fn encode_derived_nested_record_string() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} main = - result = Str.fromUtf8 (Encode.toBytes {{a: {{b: "bar"}}}} tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes {{a: {{b: "bar"}}}} tag_len_fmt) when result is Ok s -> s _ -> "" @@ -2044,7 +2044,7 @@ fn encode_derived_tag_one_field_string() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} @@ -2052,7 +2052,7 @@ fn encode_derived_tag_one_field_string() { main = x : [A Str] x = A "foo" - result = Str.fromUtf8 (Encode.toBytes x tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes x tag_len_fmt) when result is Ok s -> s _ -> "" @@ -2070,12 +2070,12 @@ fn polymorphic_expression_unification() { Text Str, Indent (List RenderTree), ] - parseFunction : Str -> RenderTree - parseFunction = \name -> + parse_function : Str -> RenderTree + parse_function = \name -> last = Indent [Text ".trace(\"$(name)\")" ] Indent [last] - values = parseFunction "interface_header" + values = parse_function "interface_header" main = values == Text "" "# @@ -2087,7 +2087,7 @@ fn encode_derived_tag_two_payloads_string() { &formatdoc!( r#" app "test" - imports [Encode.{{ toEncoder }}] + imports [Encode.{{ to_encoder }}] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} @@ -2095,7 +2095,7 @@ fn encode_derived_tag_two_payloads_string() { main = x : [A Str Str] x = A "foo" "foo" - result = Str.fromUtf8 (Encode.toBytes x tagLenFmt) + result = Str.from_utf8 (Encode.to_bytes x tag_len_fmt) when result is Ok s -> s _ -> "" @@ -2176,7 +2176,7 @@ fn unreachable_branch_is_eliminated_but_produces_lambda_specializations() { r#" app "test" provides [main] to "./platform" - provideThunk = \x -> + provide_thunk = \x -> when x is Ok _ -> t1 = \{} -> "t1" @@ -2201,7 +2201,7 @@ fn unreachable_branch_is_eliminated_but_produces_lambda_specializations() { x : Result Str [] x = Ok "abc" - thunk = provideThunk x + thunk = provide_thunk x thunk {} "# @@ -2234,15 +2234,15 @@ fn recursive_function_and_union_with_inference_hole() { Element (List (Html state)), ] - translateStatic : Html _ -> Html _ - translateStatic = \node -> + translate_static : Html _ -> Html _ + translate_static = \node -> when node is Element children -> - newChildren = List.map children translateStatic + new_children = List.map children translate_static - Element newChildren + Element new_children - main = when translateStatic (Element []) is + main = when translate_static (Element []) is _ -> "" "# ) @@ -2254,14 +2254,14 @@ fn crash() { r#" app "test" provides [main] to "./platform" - getInfallible = \result -> when result is + get_infallible = \result -> when result is Ok x -> x _ -> crash "turns out this was fallible" main = x : [Ok U64, Err Str] x = Ok 78 - getInfallible x + get_infallible x "# ) } @@ -2415,16 +2415,16 @@ fn anonymous_closure_in_polymorphic_expression_issue_4717() { r#" app "test" provides [main] to "platform" - chompWhile : (List U8) -> (List U8) - chompWhile = \input -> - index = List.walkUntil input 0 \i, _ -> Break i + chomp_while : (List U8) -> (List U8) + chomp_while = \input -> + index = List.walk_until input 0 \i, _ -> Break i if index == 0 then input else - List.dropFirst input index + List.drop_first input index - main = chompWhile [1u8, 2u8, 3u8] + main = chomp_while [1u8, 2u8, 3u8] "# ) } @@ -2459,10 +2459,10 @@ fn issue_4557() { r#" app "test" provides [main] to "./platform" - isEqQ = \q1, q2 -> when T q1 q2 is - T (U f1) (U f2) -> Bool.or (isEqQ (U f2) (U f1)) (f1 {} == f2 {}) + is_eq_q = \q1, q2 -> when T q1 q2 is + T (U f1) (U f2) -> Bool.or (is_eq_q (U f2) (U f1)) (f1 {} == f2 {}) - main = isEqQ (U \{} -> "a") (U \{} -> "a") + main = is_eq_q (U \{} -> "a") (U \{} -> "a") "# ) } @@ -2479,14 +2479,14 @@ fn nullable_wrapped_with_nullable_not_last_index() { CharLiteral, ] - toIdParser : Parser -> Str - toIdParser = \parser -> + to_id_parser : Parser -> Str + to_id_parser = \parser -> when parser is OneOrMore _ -> "a" Keyword _ -> "b" CharLiteral -> "c" - main = toIdParser CharLiteral == "c" + main = to_id_parser CharLiteral == "c" "# ) } @@ -2544,11 +2544,11 @@ fn function_specialization_information_in_lambda_set_thunk() { r#" app "test" provides [main] to "./platform" - andThen = \{} -> + and_then = \{} -> x = 10 - \newFn -> Num.add (newFn {}) x + \new_fn -> Num.add (new_fn {}) x - between = andThen {} + between = and_then {} main = between \{} -> between \{} -> 10 "# @@ -2563,13 +2563,13 @@ fn function_specialization_information_in_lambda_set_thunk_independent_defs() { r#" app "test" provides [main] to "./platform" - andThen = \{} -> + and_then = \{} -> x = 10u8 - \newFn -> Num.add (newFn {}) x + \new_fn -> Num.add (new_fn {}) x - between1 = andThen {} + between1 = and_then {} - between2 = andThen {} + between2 = and_then {} main = between1 \{} -> between2 \{} -> 10u8 "# @@ -2584,12 +2584,12 @@ fn issue_4772_weakened_monomorphic_destructure() { {ERR_DECODER_FMT} - getNumber = - {{ result, rest }} = Decode.fromBytesPartial (Str.toUtf8 "-1234") (@ErrDecoder {{}}) + get_number = + {{ result, rest }} = Decode.from_bytes_partial (Str.to_utf8 "-1234") (@ErrDecoder {{}}) when result is Ok val -> - when Str.toI64 val is + when Str.to_i64 val is Ok number -> Ok {{val : number, input : rest}} Err InvalidNumStr -> @@ -2599,7 +2599,7 @@ fn issue_4772_weakened_monomorphic_destructure() { Err (ParsingFailure "not a number") expect - result = getNumber + result = get_number result == Ok {{val : -1234i64, input : []}} "# ) @@ -2616,12 +2616,12 @@ fn weakening_avoids_overspecialization() { main : (List U8) -> (List U8) main = \input -> - index = List.walkUntil input 0 \i, _ -> Break i + index = List.walk_until input 0 \i, _ -> Break i if index == 0 then input else - List.dropFirst input index + List.drop_first input index "# ) } @@ -2639,17 +2639,17 @@ fn recursively_build_effect() { "$(hi), $(name)!" main = - when nestHelp 4 is + when nest_help 4 is _ -> greeting - nestHelp : I64 -> XEffect {} - nestHelp = \m -> + nest_help : I64 -> XEffect {} + nest_help = \m -> when m is 0 -> always {} _ -> - always {} |> after \_ -> nestHelp (m - 1) + always {} |> after \_ -> nest_help (m - 1) XEffect a := {} -> a @@ -2675,9 +2675,9 @@ fn recursive_lambda_set_has_nested_non_recursive_lambda_sets_issue_5026() { Effect : {} -> Str - after = \buildNext -> - afterInner = \{} -> (buildNext "foobar") {} - afterInner + after = \build_next -> + after_inner = \{} -> (build_next "foobar") {} + after_inner await : (Str -> Effect) -> Effect await = \cont -> after (\result -> cont result) @@ -2691,28 +2691,28 @@ fn recursive_lambda_set_has_nested_non_recursive_lambda_sets_issue_5026() { fn unspecialized_lambda_set_unification_keeps_all_concrete_types_without_unification() { // This is a regression test for the ambient lambda set specialization algorithm. // - // In the program below, monomorphization of `toEncoderQ` with the `Q` in `main` induces the + // In the program below, monomorphization of `to_encoder_q` with the `Q` in `main` induces the // resolution of `t.a` and `t.b`, and the unification of their pending unspecialization lambda // sets, when `t.a` and `t.b` have been resolved to concrete types, but before the // specialization procedure steps in to resolve the lambda sets concretely. That's because - // monomorphization unifies the general type of `toEncoderQ` with the concrete type, forcing + // monomorphization unifies the general type of `to_encoder_q` with the concrete type, forcing // concretization of `t`, but the specialization procedure runs only after the unification is // complete. // - // In this case, it's imperative that the unspecialized lambda sets of `toEncoder t.a` and - // `toEncoder t.b` wind up in the same lambda set, that is in + // In this case, it's imperative that the unspecialized lambda sets of `to_encoder t.a` and + // `to_encoder t.b` wind up in the same lambda set, that is in // - // tag : @MEncoder (Bytes, Linear -[[] + @MU8:toEncoder:1 + @MStr:toEncoder+1] -> Bytes) + // tag : @MEncoder (Bytes, Linear -[[] + @MU8:to_encoder:1 + @MStr:to_encoder+1] -> Bytes) // -[lTag]-> - // @MEncoder (Bytes, Linear -[[Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MU8:toEncoder:1 + @MStr:toEncoder:1] -> Bytes) }]] -> Bytes) + // @MEncoder (Bytes, Linear -[[Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MU8:to_encoder:1 + @MStr:to_encoder:1] -> Bytes) }]] -> Bytes) // // rather than forcing the lambda set inside to `tag` to become disjoint, as e.g. // - // tag : @MEncoder (Bytes, Linear -[[] + @MU8:toEncoder:1 + @MStr:toEncoder+1] -> Bytes) + // tag : @MEncoder (Bytes, Linear -[[] + @MU8:to_encoder:1 + @MStr:to_encoder+1] -> Bytes) // -[lTag]-> // @MEncoder (Bytes, Linear -[[ - // Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MU8:toEncoder:1] -> Bytes) }, - // Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MStr:toEncoder:1] -> Bytes) }, + // Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MU8:to_encoder:1] -> Bytes) }, + // Linear:lTag:3 { @MEncoder (Bytes, Linear -[[] + @MStr:to_encoder:1] -> Bytes) }, // ]] -> Bytes) indoc!( r#" @@ -2721,7 +2721,7 @@ fn unspecialized_lambda_set_unification_keeps_all_concrete_types_without_unifica MEncoder fmt := List U8, fmt -> List U8 where fmt implements Format MEncoding implements - toEncoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format + to_encoder : val -> MEncoder fmt where val implements MEncoding, fmt implements Format Format implements u8 : {} -> MEncoder fmt where fmt implements Format @@ -2730,8 +2730,8 @@ fn unspecialized_lambda_set_unification_keeps_all_concrete_types_without_unifica Linear := {} implements [Format {u8: lU8, str: lStr, tag: lTag}] - MU8 := U8 implements [MEncoding {toEncoder: toEncoderU8}] - MStr := Str implements [MEncoding {toEncoder: toEncoderStr}] + MU8 := U8 implements [MEncoding {to_encoder: to_encoder_u8}] + MStr := Str implements [MEncoding {to_encoder: to_encoder_str}] Q a b := { a: a, b: b } @@ -2742,20 +2742,20 @@ fn unspecialized_lambda_set_unification_keeps_all_concrete_types_without_unifica doFormat lst (@Linear {}) ) - toEncoderU8 = \@MU8 _ -> u8 {} + to_encoder_u8 = \@MU8 _ -> u8 {} - toEncoderStr = \@MStr _ -> str {} + to_encoder_str = \@MStr _ -> str {} - toEncoderQ = + to_encoder_q = \@Q t -> \fmt -> @MEncoder doit = if Bool.true - then tag (toEncoder t.a) - else tag (toEncoder t.b) + then tag (to_encoder t.a) + else tag (to_encoder t.b) doit [] fmt main = - fmt = toEncoderQ (@Q {a : @MStr "", b: @MU8 7}) + fmt = to_encoder_q (@Q {a : @MStr "", b: @MU8 7}) fmt (@Linear {}) "# ) @@ -2773,30 +2773,30 @@ fn unspecialized_lambda_set_unification_keeps_all_concrete_types_without_unifica // `EncoderFormatting`). // // In this test, the payload types `[A]*` and `[B]*` of the encoded type `Q` are unifiable in - // their unspecialized lambda set representations under `toEncoderQ`; however, they must not + // their unspecialized lambda set representations under `to_encoder_q`; however, they must not // be, because they in fact represent to different specializations of needed encoders. In - // particular, the lambda set `[[] + [A]:toEncoder:1 + [B]:toEncoder:1]` must be preserved, - // rather than collapsing to `[[] + [A, B]:toEncoder:1]`. + // particular, the lambda set `[[] + [A]:to_encoder:1 + [B]:to_encoder:1]` must be preserved, + // rather than collapsing to `[[] + [A, B]:to_encoder:1]`. &formatdoc!( r#" app "test" imports [] provides [main] to "./platform" {TAG_LEN_ENCODER_FMT} - Q a b := {{ a: a, b: b }} implements [Encoding {{toEncoder: toEncoderQ}}] + Q a b := {{ a: a, b: b }} implements [Encoding {{to_encoder: to_encoder_q}}] - toEncoderQ = + to_encoder_q = \@Q t -> Encode.custom \bytes, fmt -> f = if Bool.true - then Encode.tag "A" [Encode.toEncoder t.a] - else Encode.tag "B" [Encode.toEncoder t.b] + then Encode.tag "A" [Encode.to_encoder t.a] + else Encode.tag "B" [Encode.to_encoder t.b] - Encode.appendWith bytes f fmt + Encode.append_with bytes f fmt accessor = @Q {{a : A, b: B}} main = - Encode.toBytes accessor tagLenFmt + Encode.to_bytes accessor tag_len_fmt "# ) } @@ -2812,10 +2812,10 @@ fn unspecialized_lambda_set_unification_does_not_duplicate_identical_concrete_ty // `EncoderFormatting`). // // In this test, the payload types `Str` and `Str` of the encoded type `Q` are unifiable in - // their unspecialized lambda set representations under `toEncoderQ`, and moreoever they are + // their unspecialized lambda set representations under `to_encoder_q`, and moreoever they are // equivalent specializations, since they both come from the same root variable `x`. In as - // such, the lambda set `[[] + Str:toEncoder:1]` should be produced during compaction, rather - // than staying as the expanded `[[] + Str:toEncoder:1 + Str:toEncoder:1]` after the types of + // such, the lambda set `[[] + Str:to_encoder:1]` should be produced during compaction, rather + // than staying as the expanded `[[] + Str:to_encoder:1 + Str:to_encoder:1]` after the types of // `t.a` and `t.b` are filled in. &formatdoc!( r#" @@ -2823,22 +2823,22 @@ fn unspecialized_lambda_set_unification_does_not_duplicate_identical_concrete_ty {TAG_LEN_ENCODER_FMT} - Q a b := {{ a: a, b: b }} implements [Encoding {{toEncoder: toEncoderQ}}] + Q a b := {{ a: a, b: b }} implements [Encoding {{to_encoder: to_encoder_q}}] - toEncoderQ = + to_encoder_q = \@Q t -> Encode.custom \bytes, fmt -> f = if Bool.true - then Encode.tag "A" [Encode.toEncoder t.a] - else Encode.tag "B" [Encode.toEncoder t.b] + then Encode.tag "A" [Encode.to_encoder t.a] + else Encode.tag "B" [Encode.to_encoder t.b] - Encode.appendWith bytes f fmt + Encode.append_with bytes f fmt accessor = x = "" @Q {{a : x, b: x}} main = - Encode.toBytes accessor tagLenFmt + Encode.to_bytes accessor tag_len_fmt "# ) } @@ -2894,14 +2894,14 @@ fn recursive_closure_with_transiently_used_capture() { r#" app "test" provides [f] to "./platform" - thenDo = \x, callback -> + then_do = \x, callback -> callback x f = \{} -> code = 10u16 bf = \{} -> - thenDo code \_ -> bf {} + then_do code \_ -> bf {} bf {} "# @@ -2932,14 +2932,14 @@ fn recursive_lambda_set_resolved_only_upon_specialization() { r#" app "test" provides [main] to "./platform" - factCPS = \n, cont -> + fact_cps = \n, cont -> if n == 0u8 then cont 1u8 else - factCPS (n - 1) \value -> cont (n * value) + fact_cps (n - 1) \value -> cont (n * value) main = - factCPS 5 \x -> x + fact_cps 5 \x -> x "# ) } @@ -2956,12 +2956,12 @@ fn compose_recursive_lambda_set_productive_nullable_wrapped() { else \x -> f (g x) identity = \x -> x - exclame = \s -> "$(s)!" + exclaim = \s -> "$(s)!" whisper = \s -> "($(s))" main = res: Str -> Str - res = List.walk [ exclame, whisper ] identity (compose Bool.true) + res = List.walk [ exclaim, whisper ] identity (compose Bool.true) res "hello" "# ) @@ -3018,19 +3018,19 @@ fn issue_4770() { app "test" provides [main] to "./platform" main = - isCorrectOrder { left: IsList [IsInteger 10], right: IsList [IsInteger 20] } + is_correct_order { left: IsList [IsInteger 10], right: IsList [IsInteger 20] } - isCorrectOrder = \pair -> + is_correct_order = \pair -> when pair is { left: IsInteger left, right: IsInteger right } -> left < right { left: IsList l, right: IsList r } -> - if List.map2 l r (\left, right -> { left, right }) |> List.all isCorrectOrder then + if List.map2 l r (\left, right -> { left, right }) |> List.all is_correct_order then List.len l < List.len r else Bool.false - { left: IsList _, right: IsInteger _ } -> isCorrectOrder { left: pair.left, right: IsList [pair.right] } - { left: IsInteger _, right: IsList _ } -> isCorrectOrder { left: IsList [pair.left], right: pair.right } + { left: IsList _, right: IsInteger _ } -> is_correct_order { left: pair.left, right: IsList [pair.right] } + { left: IsInteger _, right: IsList _ } -> is_correct_order { left: IsList [pair.left], right: pair.right } "# ) } @@ -3054,7 +3054,7 @@ fn binary_tree_fbip() { main = tree = Node (Node (Node (Node Tip Tip) Tip) (Node Tip Tip)) (Node Tip Tip) - checkFbip tree + check_fbip tree Tree : [Node Tree Tree, Tip] @@ -3065,14 +3065,14 @@ fn binary_tree_fbip() { Visit : [NodeR Tree Visit, Done] - checkFbip : Tree -> Num a - checkFbip = \t -> checkFbipHelper t Done 0 + check_fbip : Tree -> Num a + check_fbip = \t -> check_fbip_helper t Done 0 - checkFbipHelper : Tree, Visit, Num a-> Num a - checkFbipHelper = \t, v, a -> when t is - Node l r -> checkFbipHelper l (NodeR r v) (a + 1) + check_fbip_helper : Tree, Visit, Num a-> Num a + check_fbip_helper = \t, v, a -> when t is + Node l r -> check_fbip_helper l (NodeR r v) (a + 1) Tip -> when v is - NodeR r v2 -> checkFbipHelper r v2 a + NodeR r v2 -> check_fbip_helper r v2 a Done -> a "# ) @@ -3140,32 +3140,32 @@ fn specialize_after_match() { app "test" provides [main] to "./platform" main = - listA : LinkedList Str - listA = Nil + list_a : LinkedList Str + list_a = Nil - listB : LinkedList Str - listB = Nil + list_b : LinkedList Str + list_b = Nil - longestLinkedList listA listB + longest_linked_list list_a list_b LinkedList a : [Cons a (LinkedList a), Nil] - longestLinkedList : LinkedList a, LinkedList a -> U64 - longestLinkedList = \listA, listB -> when listA is - Nil -> linkedListLength listB - Cons a aa -> when listB is - Nil -> linkedListLength listA + longest_linked_list : LinkedList a, LinkedList a -> U64 + longest_linked_list = \list_a, list_b -> when list_a is + Nil -> linked_list_length list_b + Cons a aa -> when list_b is + Nil -> linked_list_length list_a Cons b bb -> - lengthA = (linkedListLength aa) + 1 - lengthB = linkedListLength listB - if lengthA > lengthB - then lengthA - else lengthB - - linkedListLength : LinkedList a -> U64 - linkedListLength = \list -> when list is + length_a = (linked_list_length aa) + 1 + length_b = linked_list_length list_b + if length_a > length_b + then length_a + else length_b + + linked_list_length : LinkedList a -> U64 + linked_list_length = \list -> when list is Nil -> 0 - Cons _ rest -> 1 + linkedListLength rest + Cons _ rest -> 1 + linked_list_length rest "# ) } @@ -3209,9 +3209,9 @@ fn drop_specialize_after_jump() { main = v = "value" t = { left: { left: v, right: v }, right: v } - tupleItem t + tuple_item t - tupleItem = \t -> + tuple_item = \t -> true = Bool.true l = t.left x = if true then 1 else 0 @@ -3245,9 +3245,9 @@ fn drop_specialize_before_jump() { main = v = "value" t = { left: v, right: v } - tupleItem t + tuple_item t - tupleItem = \t -> + tuple_item = \t -> true = Bool.true l = t.left x = if true then 1 else 0 @@ -3317,13 +3317,13 @@ fn linked_list_reverse() { LinkedList a : [Nil, Cons a (LinkedList a)] reverse : LinkedList a -> LinkedList a - reverse = \list -> reverseHelp Nil list + reverse = \list -> reverse_help Nil list - reverseHelp : LinkedList a, LinkedList a -> LinkedList a - reverseHelp = \accum, list -> + reverse_help : LinkedList a, LinkedList a -> LinkedList a + reverse_help = \accum, list -> when list is Nil -> accum - Cons first rest -> reverseHelp (Cons first accum) rest + Cons first rest -> reverse_help (Cons first accum) rest main : LinkedList I64 main = reverse (Cons 42 Nil) @@ -3390,32 +3390,32 @@ fn capture_void_layout_task() { succeed = \ok -> \{} -> Ok ok after : Fx a, (a -> Fx b) -> Fx b - after = \fx, toNext -> - afterInner = \{} -> - fxOut = fx {} - next = toNext fxOut + after = \fx, to_next -> + after_inner = \{} -> + fx_out = fx {} + next = to_next fx_out next {} - afterInner + after_inner await : OtherTask a err, (a -> OtherTask b err) -> OtherTask b err - await = \fx, toNext -> + await = \fx, to_next -> inner = after fx \result -> when result is Ok a -> - bFx = toNext a - bFx + b_fx = to_next a + b_fx Err e -> (\{} -> Err e) inner - forEach : List a, (a -> OtherTask {} err) -> OtherTask {} err - forEach = \list, fromElem -> + for_each : List a, (a -> OtherTask {} err) -> OtherTask {} err + for_each = \list, from_elem -> List.walk list (succeed {}) \task, elem -> - await task \{} -> fromElem elem + await task \{} -> from_elem elem main : OtherTask {} [] main = - forEach [] \_ -> succeed {} + for_each [] \_ -> succeed {} "# ) } @@ -3450,10 +3450,10 @@ fn inspect_custom_type() { imports [] provides [main] to "./platform" - HelloWorld := {} implements [Inspect { toInspector: myToInspector }] + HelloWorld := {} implements [Inspect { to_inspector: my_to_inspector }] - myToInspector : HelloWorld -> Inspector f where f implements InspectFormatter - myToInspector = \@HellowWorld {} -> + my_to_inspector : HelloWorld -> Inspector f where f implements InspectFormatter + my_to_inspector = \@HellowWorld {} -> Inspect.custom \fmt -> Inspect.apply (Inspect.str "Hello, World!\n") fmt @@ -3471,7 +3471,7 @@ fn inspect_derived_string() { imports [] provides [main] to "./platform" - main = Inspect.toStr "abc" + main = Inspect.to_str "abc" "# ) } @@ -3484,7 +3484,7 @@ fn inspect_derived_record() { imports [] provides [main] to "./platform" - main = Inspect.toStr {a: 7, b: 3dec} + main = Inspect.to_str {a: 7, b: 3dec} "# ) } @@ -3496,7 +3496,7 @@ fn inspect_derived_record_one_field_string() { imports [] provides [main] to "./platform" - main = Inspect.toStr {a: "foo"} + main = Inspect.to_str {a: "foo"} "# ) } @@ -3509,7 +3509,7 @@ fn inspect_derived_record_two_field_strings() { imports [] provides [main] to "./platform" - main = Inspect.toStr {a: "foo", b: "bar"} + main = Inspect.to_str {a: "foo", b: "bar"} "# ) } @@ -3522,7 +3522,7 @@ fn inspect_derived_nested_record_string() { imports [] provides [main] to "./platform" - main = Inspect.toStr {a: {b: "bar"}} + main = Inspect.to_str {a: {b: "bar"}} "# ) } @@ -3538,7 +3538,7 @@ fn inspect_derived_tag_one_field_string() { main = x : [A Str] x = A "foo" - Inspect.toStr x + Inspect.to_str x "# ) } @@ -3554,7 +3554,7 @@ fn inspect_derived_tag_two_payloads_string() { main = x : [A Str Str] x = A "foo" "foo" - Inspect.toStr x + Inspect.to_str x "# ) } @@ -3567,7 +3567,7 @@ fn inspect_derived_list() { imports [] provides [main] to "./platform" - main = Inspect.toStr [1, 2, 3] + main = Inspect.to_str [1, 2, 3] "# ) } @@ -3581,8 +3581,8 @@ fn inspect_derived_dict() { provides [main] to "./platform" main = - Dict.fromList [("a", 1), ("b", 2)] - |> Inspect.toStr + Dict.from_list [("a", 1), ("b", 2)] + |> Inspect.to_str "# ) } @@ -3678,13 +3678,13 @@ fn issue_6606_2() { fn dec_refcount_for_usage_after_early_return_in_if() { indoc!( r#" - displayN = \n -> - first = Num.toStr n + display_n = \n -> + first = Num.to_str n second = if n == 1 then return "early 1" else - third = Num.toStr (n + 1) + third = Num.to_str (n + 1) if n == 2 then return "early 2" else @@ -3692,7 +3692,7 @@ fn dec_refcount_for_usage_after_early_return_in_if() { "$(first), $(second)" - displayN 3 + display_n 3 "# ) } @@ -3701,13 +3701,13 @@ fn dec_refcount_for_usage_after_early_return_in_if() { fn return_annotated() { indoc!( r#" - validateInput : Str -> Result U64 _ - validateInput = \str -> - num = try Str.toU64 str + validate_input : Str -> Result U64 _ + validate_input = \str -> + num = try Str.to_u64 str Ok num - validateInput "123" + validate_input "123" "# ) } diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.formatted.roc index b6d53f2f44a..5cfd7e58c44 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.formatted.roc @@ -3,4 +3,4 @@ platform "cli" exposes [] packages {} imports [Task.{ Task }] - provides [mainForHost] + provides [main_for_host] diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.result-ast index ca4b86646d0..add8393cba0 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.result-ast @@ -91,7 +91,7 @@ SpacesBefore { }, item: [ @141-152 ExposedName( - "mainForHost", + "main_for_host", ), ], }, diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.roc b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.roc index a4ec7c9b78b..0287d20de44 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/function_effect_types.header.roc @@ -3,4 +3,4 @@ platform "cli" exposes [] packages {} imports [ Task.{ Task } ] - provides [ mainForHost ] + provides [ main_for_host ] diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.formatted.roc index 2020be61739..18e9f949b73 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.formatted.roc @@ -3,4 +3,4 @@ platform "foo/barbaz" exposes [] packages { foo: "./foo" } imports [] - provides [mainForHost] + provides [main_for_host] diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.result-ast index fdb021d33dd..ea80123e8fd 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.result-ast @@ -81,7 +81,7 @@ SpacesBefore { }, item: [ @132-143 ExposedName( - "mainForHost", + "main_for_host", ), ], }, diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.roc b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.roc index 789dae30555..ba60974d82f 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/nonempty_platform_header.header.roc @@ -3,4 +3,4 @@ platform "foo/barbaz" exposes [] packages { foo: "./foo" } imports [] - provides [ mainForHost ] + provides [ main_for_host ] diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.result-ast index 521b4e9399d..3dbbe0ebae0 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.result-ast @@ -120,7 +120,7 @@ Defs { @130-145 Apply( @130-139 Var { module_name: "Num", - ident: "toStr", + ident: "to_str", }, [ @140-145 Var { diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.roc b/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.roc index e53dc93f391..646c9f1d805 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/pizza_question.moduledefs.roc @@ -3,5 +3,5 @@ main = |> List.dropFirst 1 |> List.mapTry? Str.toU8 |> List.sum - |> \total -> "Sum of numbers: $(Num.toStr total)" + |> \total -> "Sum of numbers: $(Num.to_str total)" |> Str.toUpper diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.formatted.roc index e52d0bf32c5..abf9f3ab817 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.formatted.roc @@ -3,4 +3,4 @@ platform "test/types" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.result-ast index 789547f199f..9a31230080a 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.result-ast @@ -87,7 +87,7 @@ SpacesBefore { }, item: [ @141-152 ExposedName( - "mainForHost", + "main_for_host", ), ], }, diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.roc b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.roc index 1755f5a0665..0065ddc0aca 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/requires_type.header.roc @@ -3,7 +3,7 @@ platform "test/types" exposes [] packages {} imports [] - provides [ mainForHost ] + provides [ main_for_host ] -mainForHost : App Flags Model -mainForHost = main +main_for_host : App Flags Model +main_for_host = main diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.formatted.roc index 037e118de30..231d12611df 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.formatted.roc @@ -5,6 +5,6 @@ maybeEarlyReturn = \x -> else x + 2 - Num.toStr y + Num.to_str y maybeEarlyReturn 10 \ No newline at end of file diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.result-ast index b526d3c2ea4..e6cdc737e22 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.result-ast @@ -118,7 +118,7 @@ Apply( @116-125 Var { module_name: "Num", - ident: "toStr", + ident: "to_str", }, [ @126-127 Var { diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.roc b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.roc index 18a7c88d61b..d8fccfaa272 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_if.expr.roc @@ -5,6 +5,6 @@ maybeEarlyReturn = \x -> else x + 2 - Num.toStr y + Num.to_str y maybeEarlyReturn 10 diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.formatted.roc index 59d0508f038..bf5a53fb43f 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.formatted.roc @@ -7,6 +7,6 @@ maybeEarlyReturn = \x -> _ -> x + 2 - Num.toStr y + Num.to_str y maybeEarlyRetun 3 \ No newline at end of file diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.result-ast index bcb05f24fdf..77b4f24607c 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.result-ast @@ -127,7 +127,7 @@ Apply( @143-152 Var { module_name: "Num", - ident: "toStr", + ident: "to_str", }, [ @153-154 Var { diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.roc b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.roc index 5f00323c6c1..8a7366edb88 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/return_in_when.expr.roc @@ -8,6 +8,6 @@ maybeEarlyReturn = \x -> _ -> x + 2 - Num.toStr y + Num.to_str y maybeEarlyRetun 3 diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.formatted.roc b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.formatted.roc index bb662215bef..53c8421bb02 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.formatted.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.formatted.roc @@ -1,3 +1,3 @@ -mainForHost : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op -mainForHost = main +main_for_host : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op +main_for_host = main 42 \ No newline at end of file diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.result-ast b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.result-ast index 3718cb6a153..c66e30dd2fc 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.result-ast +++ b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.result-ast @@ -18,7 +18,7 @@ value_defs: [ AnnotatedBody { ann_pattern: @0-11 Identifier { - ident: "mainForHost", + ident: "main_for_host", }, ann_type: @14-0 As( @14-76 TagUnion { @@ -88,7 +88,7 @@ Newline, ], body_pattern: @83-94 Identifier { - ident: "mainForHost", + ident: "main_for_host", }, body_expr: @97-101 Var { module_name: "", diff --git a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.roc b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.roc index 382ce9377df..9bc27a7b13e 100644 --- a/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.roc +++ b/crates/compiler/test_syntax/tests/snapshots/pass/tag_union_functions_as.expr.roc @@ -1,3 +1,3 @@ -mainForHost : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op -mainForHost = main +main_for_host : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op +main_for_host = main 42 diff --git a/crates/compiler/test_syntax/tests/test_fmt.rs b/crates/compiler/test_syntax/tests/test_fmt.rs index 073e3fe91ab..0abef3660d8 100644 --- a/crates/compiler/test_syntax/tests/test_fmt.rs +++ b/crates/compiler/test_syntax/tests/test_fmt.rs @@ -5270,7 +5270,7 @@ mod test_fmt { exposes [] \ packages {} \ imports [] \ - provides [mainForHost]", + provides [main_for_host]", ); } @@ -6233,7 +6233,7 @@ mod test_fmt { exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] "# )); } diff --git a/crates/glue/README.md b/crates/glue/README.md index 332abd69d3c..c4692bf75fb 100644 --- a/crates/glue/README.md +++ b/crates/glue/README.md @@ -21,13 +21,13 @@ platform "glue-types" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] GlueTypes : { a : SomeType, b : AnotherType, } -mainForHost : GlueTypes -mainForHost = main +main_for_host : GlueTypes +main_for_host = main ``` diff --git a/crates/glue/platform/Shape.roc b/crates/glue/platform/Shape.roc index 56ffad8d40e..02b86fb617a 100644 --- a/crates/glue/platform/Shape.roc +++ b/crates/glue/platform/Shape.roc @@ -62,8 +62,8 @@ RocTagUnion : [ { name : Str, tags : List { name : Str, payload : [Some TypeId, None] }, - discriminantSize : U32, - discriminantOffset : U32, + discriminant_size : U32, + discriminant_offset : U32, }, ## A recursive tag union (general case) ## e.g. `Expr : [Sym Str, Add Expr Expr]` @@ -71,8 +71,8 @@ RocTagUnion : [ { name : Str, tags : List { name : Str, payload : [Some TypeId, None] }, - discriminantSize : U32, - discriminantOffset : U32, + discriminant_size : U32, + discriminant_offset : U32, }, ## A recursive tag union that has an empty variant ## Optimization: Represent the empty variant as null pointer => no memory usage & fast comparison @@ -82,17 +82,17 @@ RocTagUnion : [ NullableWrapped { name : Str, - indexOfNullTag : U16, + index_of_null_tag : U16, tags : List { name : Str, payload : [Some TypeId, None] }, - discriminantSize : U32, - discriminantOffset : U32, + discriminant_size : U32, + discriminant_offset : U32, }, ## Optimization: No need to store a tag ID (the payload is "unwrapped") ## e.g. `RoseTree a : [Tree a (List (RoseTree a))]` NonNullableUnwrapped { name : Str, - tagName : Str, + tag_name : Str, payload : TypeId, # These always have a payload. }, ## Optimization: No need to store a tag ID (the payload is "unwrapped") @@ -100,7 +100,7 @@ RocTagUnion : [ SingleTagStruct { name : Str, - tagName : Str, + tag_name : Str, payload : RocSingleTagPayload, }, ## A recursive tag union with only two variants, where one is empty. @@ -109,10 +109,10 @@ RocTagUnion : [ NullableUnwrapped { name : Str, - nullTag : Str, - nonNullTag : Str, - nonNullPayload : TypeId, - whichTagIsNull : [FirstTagIsNull, SecondTagIsNull], + null_tag : Str, + non_null_tag : Str, + non_null_payload : TypeId, + which_tag_is_null : [FirstTagIsNull, SecondTagIsNull], }, ] @@ -127,10 +127,10 @@ RocSingleTagPayload : [ ] RocFn : { - functionName : Str, - externName : Str, + function_name : Str, + extern_name : Str, args : List TypeId, - lambdaSet : TypeId, + lambda_set : TypeId, ret : TypeId, - isToplevel : Bool, + is_toplevel : Bool, } diff --git a/crates/glue/platform/Target.roc b/crates/glue/platform/Target.roc index 92f18cfa8e4..e223d55c796 100644 --- a/crates/glue/platform/Target.roc +++ b/crates/glue/platform/Target.roc @@ -2,7 +2,7 @@ module [Target, Architecture, OperatingSystem] Target : { architecture : Architecture, - operatingSystem : OperatingSystem, + operating_system : OperatingSystem, } Architecture : [ diff --git a/crates/glue/platform/TypeId.roc b/crates/glue/platform/TypeId.roc index dac002a1dc1..6795f587f69 100644 --- a/crates/glue/platform/TypeId.roc +++ b/crates/glue/platform/TypeId.roc @@ -1,11 +1,11 @@ -module [TypeId, typeIDfromU64, typeIDtoU64] +module [TypeId, type_id_from_u64, type_id_to_u64] TypeId := U64 implements [Eq, Hash, Inspect, Encoding] # renamed here so we can import the functions directly as a workaround for # https://github.com/roc-lang/roc/issues/5477 -typeIDtoU64 : TypeId -> U64 -typeIDtoU64 = \@TypeId x -> x +type_id_to_u64 : TypeId -> U64 +type_id_to_u64 = \@TypeId(x) -> x -typeIDfromU64 : U64 -> TypeId -typeIDfromU64 = @TypeId +type_id_from_u64 : U64 -> TypeId +type_id_from_u64 = @TypeId diff --git a/crates/glue/platform/Types.roc b/crates/glue/platform/Types.roc index ff50eb69384..1f7146d74e5 100644 --- a/crates/glue/platform/Types.roc +++ b/crates/glue/platform/Types.roc @@ -1,7 +1,7 @@ -module [Types, shape, size, alignment, target, walkShapes, entryPoints] +module [Types, shape, size, alignment, target, walk_shapes, entry_points] import Shape exposing [Shape] -import TypeId exposing [TypeId, typeIDfromU64, typeIDtoU64] +import TypeId exposing [TypeId, type_id_from_u64, type_id_to_u64] import Target exposing [Target] # TODO: switch AssocList uses to Dict once roc_std is updated. @@ -15,55 +15,55 @@ Types := { aligns : List U32, # Needed to check for duplicates - typesByName : List Tuple1, + types_by_name : List Tuple1, ## Dependencies - that is, which type depends on which other type. ## This is important for declaration order in C; we need to output a ## type declaration earlier in the file than where it gets referenced by another type. deps : List Tuple2, - ## Names and types of the entry points of the program (e.g. mainForHost) + ## Names and types of the entry points of the program (e.g. main_for_host) entrypoints : List Tuple1, target : Target, } implements [Inspect, Encoding] target : Types -> Target -target = \@Types types -> types.target +target = \@Types(types) -> types.target -entryPoints : Types -> List Tuple1 -entryPoints = \@Types { entrypoints } -> entrypoints +entry_points : Types -> List Tuple1 +entry_points = \@Types({ entrypoints }) -> entrypoints -walkShapes : Types, state, (state, Shape, TypeId -> state) -> state -walkShapes = \@Types { types: shapes }, originalState, update -> - List.walkWithIndex shapes originalState \state, elem, index -> - id = typeIDfromU64 index +walk_shapes : Types, state, (state, Shape, TypeId -> state) -> state +walk_shapes = \@Types({ types: shapes }), original_state, update -> + List.walk_with_index(shapes, original_state, \state, elem, index -> + id = type_id_from_u64(index) - update state elem id + update(state, elem, id)) shape : Types, TypeId -> Shape -shape = \@Types types, id -> - when List.get types.types (typeIDtoU64 id) is - Ok answer -> answer - Err OutOfBounds -> - idStr = Num.toStr (typeIDtoU64 id) +shape = \@Types(types), id -> + when List.get(types.types, type_id_to_u64(id)) is + Ok(answer) -> answer + Err(OutOfBounds) -> + id_str = Num.to_str(type_id_to_u64(id)) - crash "TypeId #$(idStr) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at " + crash("TypeId #$(id_str) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at ") alignment : Types, TypeId -> U32 -alignment = \@Types types, id -> - when List.get types.aligns (typeIDtoU64 id) is - Ok answer -> answer - Err OutOfBounds -> - idStr = Num.toStr (typeIDtoU64 id) +alignment = \@Types(types), id -> + when List.get(types.aligns, type_id_to_u64(id)) is + Ok(answer) -> answer + Err(OutOfBounds) -> + id_str = Num.to_str(type_id_to_u64(id)) - crash "TypeId #$(idStr) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at " + crash("TypeId #$(id_str) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at ") size : Types, TypeId -> U32 -size = \@Types types, id -> - when List.get types.sizes (typeIDtoU64 id) is - Ok answer -> answer - Err OutOfBounds -> - idStr = Num.toStr (typeIDtoU64 id) +size = \@Types(types), id -> + when List.get(types.sizes, type_id_to_u64(id)) is + Ok(answer) -> answer + Err(OutOfBounds) -> + id_str = Num.to_str(type_id_to_u64(id)) - crash "TypeId #$(idStr) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at " + crash("TypeId #$(id_str) was not found in Types. This should never happen, and means there was a bug in `roc glue`. If you have time, please open an issue at ") diff --git a/crates/glue/platform/main.roc b/crates/glue/platform/main.roc index 8abd83a981d..fd5d079c896 100644 --- a/crates/glue/platform/main.roc +++ b/crates/glue/platform/main.roc @@ -1,9 +1,9 @@ platform "roc-lang/glue" - requires {} { makeGlue : List Types -> Result (List File) Str } + requires {} { make_glue : List Types -> Result (List File) Str } exposes [Shape, File, Types, TypeId, Target] packages {} imports [Types.{ Types }, File.{ File }] - provides [makeGlueForHost] + provides [make_glue_for_host] -makeGlueForHost : List Types -> Result (List File) Str -makeGlueForHost = \types -> makeGlue types +make_glue_for_host : List Types -> Result (List File) Str +make_glue_for_host = \types -> make_glue(types) diff --git a/crates/glue/src/CGlue.roc b/crates/glue/src/CGlue.roc index cf38922210c..2ed4d99c074 100644 --- a/crates/glue/src/CGlue.roc +++ b/crates/glue/src/CGlue.roc @@ -1,4 +1,4 @@ -app [makeGlue] { pf: platform "../platform/main.roc" } +app [make_glue] { pf: platform "../platform/main.roc" } import pf.Types exposing [Types] # import pf.Shape exposing [Shape, RocFn] @@ -6,24 +6,24 @@ import pf.File exposing [File] # import pf.TypeId exposing [TypeId] ## generate placeholder glue for now that only works for our one C test -makeGlue : List Types -> Result (List File) Str -makeGlue = \_typesByArch -> - Ok ([{ name: "roc_app.h", content: placeholderGlue }]) +make_glue : List Types -> Result (List File) Str +make_glue = \_types_by_arch -> + Ok([{ name: "roc_app.h", content: placeholder_glue }]) -placeholderGlue = +placeholder_glue = """ #ifndef ROC_APP_H #define ROC_APP_H #include - extern void roc__mainForHost_1_exposed_generic(uint8_t *ret); + extern void roc__main_for_host_1_exposed_generic(uint8_t *ret); - uint8_t roc_mainForHost() + uint8_t roc_main_for_host() { uint8_t ret; - roc__mainForHost_1_exposed_generic(&ret); + roc__main_for_host_1_exposed_generic(&ret); return ret; } diff --git a/crates/glue/src/DescribeGlue.roc b/crates/glue/src/DescribeGlue.roc index ea57ddbfee4..886107e8844 100644 --- a/crates/glue/src/DescribeGlue.roc +++ b/crates/glue/src/DescribeGlue.roc @@ -1,13 +1,13 @@ -app [makeGlue] { pf: platform "../platform/main.roc" } +app [make_glue] { pf: platform "../platform/main.roc" } import pf.Types exposing [Types] import pf.File exposing [File] -makeGlue : List Types -> Result (List File) Str -makeGlue = \types -> - Ok [ +make_glue : List Types -> Result (List File) Str +make_glue = \types -> + Ok([ { name: "types.txt", - content: List.map types Inspect.toStr |> Str.joinWith "\n", + content: List.map(types, Inspect.to_str) |> Str.join_with("\n"), }, - ] + ]) diff --git a/crates/glue/src/RustGlue.roc b/crates/glue/src/RustGlue.roc index f8d833203d4..acc4fdd4efd 100644 --- a/crates/glue/src/RustGlue.roc +++ b/crates/glue/src/RustGlue.roc @@ -1,98 +1,99 @@ -app [makeGlue] { pf: platform "../platform/main.roc" } +app [make_glue] { pf: platform "../platform/main.roc" } import pf.Types exposing [Types] import pf.Shape exposing [Shape, RocFn] import pf.File exposing [File] import pf.TypeId exposing [TypeId] -import "../static/Cargo.toml" as rocAppCargoToml : Str -import "../../roc_std/Cargo.toml" as rocStdCargoToml : Str -import "../../roc_std/src/lib.rs" as rocStdLib : Str -import "../../roc_std/src/roc_box.rs" as rocStdBox : Str -import "../../roc_std/src/roc_list.rs" as rocStdList : Str -import "../../roc_std/src/roc_str.rs" as rocStdStr : Str -import "../../roc_std/src/storage.rs" as rocStdStorage : Str - -makeGlue : List Types -> Result (List File) Str -makeGlue = \typesByArch -> - modFileContent = - List.walk typesByArch fileHeader \content, types -> - arch = (Types.target types).architecture - archStr = archName arch - - Str.concat - content +import "../static/Cargo.toml" as roc_app_cargo_toml : Str +import "../../roc_std/Cargo.toml" as roc_std_cargo_toml : Str +import "../../roc_std/src/lib.rs" as roc_std_lib : Str +import "../../roc_std/src/roc_box.rs" as roc_std_box : Str +import "../../roc_std/src/roc_list.rs" as roc_std_list : Str +import "../../roc_std/src/roc_str.rs" as roc_std_str : Str +import "../../roc_std/src/storage.rs" as roc_std_storage : Str + +make_glue : List Types -> Result (List File) Str +make_glue = \types_by_arch -> + mod_file_content = + List.walk(types_by_arch, file_header, \content, types -> + arch = (Types.target(types)).architecture + arch_str = arch_name(arch) + + Str.concat( + content, """ - #[cfg(target_arch = "$(archStr)")] - mod $(archStr); - #[cfg(target_arch = "$(archStr)")] - pub use $(archStr)::*; + #[cfg(target_arch = "$(arch_str)")] + mod $(arch_str); + #[cfg(target_arch = "$(arch_str)")] + pub use $(arch_str)::*; - """ + """, + )) - typesByArch - |> List.map convertTypesToFile - |> List.append { name: "roc_app/src/lib.rs", content: modFileContent } - |> List.concat staticFiles + types_by_arch + |> List.map(convert_types_to_file) + |> List.append({ name: "roc_app/src/lib.rs", content: mod_file_content }) + |> List.concat(static_files) |> Ok ## These are always included, and don't depend on the specifics of the app. -staticFiles : List File -staticFiles = [ - { name: "roc_app/Cargo.toml", content: rocAppCargoToml }, - { name: "roc_std/Cargo.toml", content: rocStdCargoToml }, - { name: "roc_std/src/lib.rs", content: rocStdLib }, - { name: "roc_std/src/roc_box.rs", content: rocStdBox }, - { name: "roc_std/src/roc_list.rs", content: rocStdList }, - { name: "roc_std/src/roc_str.rs", content: rocStdStr }, - { name: "roc_std/src/storage.rs", content: rocStdStorage }, +static_files : List File +static_files = [ + { name: "roc_app/Cargo.toml", content: roc_app_cargo_toml }, + { name: "roc_std/Cargo.toml", content: roc_std_cargo_toml }, + { name: "roc_std/src/lib.rs", content: roc_std_lib }, + { name: "roc_std/src/roc_box.rs", content: roc_std_box }, + { name: "roc_std/src/roc_list.rs", content: roc_std_list }, + { name: "roc_std/src/roc_str.rs", content: roc_std_str }, + { name: "roc_std/src/storage.rs", content: roc_std_storage }, ] -convertTypesToFile : Types -> File -convertTypesToFile = \types -> +convert_types_to_file : Types -> File +convert_types_to_file = \types -> content = - Types.walkShapes types fileHeader \buf, type, id -> + Types.walk_shapes(types, file_header, \buf, type, id -> when type is - Struct { name, fields } -> - generateStruct buf types id name fields Public + Struct({ name, fields }) -> + generate_struct(buf, types, id, name, fields, Public) - TagUnionPayload { name, fields } -> - generateStruct buf types id name (nameTagUnionPayloadFields fields) Public + TagUnionPayload({ name, fields }) -> + generate_struct(buf, types, id, name, name_tag_union_payload_fields(fields), Public) - TagUnion (Enumeration { name, tags, size }) -> - generateEnumeration buf types type name tags size + TagUnion(Enumeration({ name, tags, size })) -> + generate_enumeration(buf, types, type, name, tags, size) - TagUnion (NonRecursive { name, tags, discriminantSize, discriminantOffset }) -> - if !(List.isEmpty tags) then - generateNonRecursiveTagUnion buf types id name tags discriminantSize discriminantOffset + TagUnion(NonRecursive({ name, tags, discriminant_size, discriminant_offset })) -> + if !(List.is_empty(tags)) then + generate_non_recursive_tag_union(buf, types, id, name, tags, discriminant_size, discriminant_offset) else buf - TagUnion (Recursive { name, tags, discriminantSize, discriminantOffset }) -> - if !(List.isEmpty tags) then - generateRecursiveTagUnion buf types id name tags discriminantSize discriminantOffset None + TagUnion(Recursive({ name, tags, discriminant_size, discriminant_offset })) -> + if !(List.is_empty(tags)) then + generate_recursive_tag_union(buf, types, id, name, tags, discriminant_size, discriminant_offset, None) else buf - TagUnion (NullableWrapped { name, indexOfNullTag, tags, discriminantSize, discriminantOffset }) -> + TagUnion(NullableWrapped({ name, index_of_null_tag, tags, discriminant_size, discriminant_offset })) -> # TODO: generate this as `TypeName(*mut u8)` if the payload contains functions / unsized types - generateRecursiveTagUnion buf types id name tags discriminantSize discriminantOffset (Some indexOfNullTag) + generate_recursive_tag_union(buf, types, id, name, tags, discriminant_size, discriminant_offset, Some(index_of_null_tag)) - TagUnion (NullableUnwrapped { name, nullTag, nonNullTag, nonNullPayload, whichTagIsNull }) -> - generateNullableUnwrapped buf types id name nullTag nonNullTag nonNullPayload whichTagIsNull + TagUnion(NullableUnwrapped({ name, null_tag, non_null_tag, non_null_payload, which_tag_is_null })) -> + generate_nullable_unwrapped(buf, types, id, name, null_tag, non_null_tag, non_null_payload, which_tag_is_null) - TagUnion (SingleTagStruct { name, tagName, payload }) -> - generateSingleTagStruct buf types name tagName payload + TagUnion(SingleTagStruct({ name, tag_name, payload })) -> + generate_single_tag_struct(buf, types, name, tag_name, payload) - TagUnion (NonNullableUnwrapped { name, tagName, payload }) -> - generateNonNullableUnwrapped buf types name tagName payload 0 0 None + TagUnion(NonNullableUnwrapped({ name, tag_name, payload })) -> + generate_non_nullable_unwrapped(buf, types, name, tag_name, payload, 0, 0, None) - Function rocFn -> - if rocFn.isToplevel then + Function(roc_fn) -> + if roc_fn.is_toplevel then buf else - generateFunction buf types rocFn + generate_function(buf, types, roc_fn) - RecursivePointer _ -> + RecursivePointer(_) -> # This is recursively pointing to a type that should already have been added, # so no extra work needs to happen. buf @@ -100,107 +101,107 @@ convertTypesToFile = \types -> Unit | Unsized | EmptyTagUnion - | Num _ + | Num(_) | Bool - | RocResult _ _ + | RocResult(_, _) | RocStr - | RocDict _ _ - | RocSet _ - | RocList _ - | RocBox _ -> + | RocDict(_, _) + | RocSet(_) + | RocList(_) + | RocBox(_) -> # These types don't need to be declared in Rust. # TODO: Eventually we want to generate roc_std. So these types will need to be emitted. - buf + buf) - arch = (Types.target types).architecture - archStr = archName arch + arch = (Types.target(types)).architecture + arch_str = arch_name(arch) { - name: "roc_app/src/$(archStr).rs", - content: content |> generateEntryPoints types, + name: "roc_app/src/$(arch_str).rs", + content: content |> generate_entry_points(types), } -generateEntryPoints : Str, Types -> Str -generateEntryPoints = \buf, types -> - List.walk (Types.entryPoints types) buf \accum, T name id -> generateEntryPoint accum types name id +generate_entry_points : Str, Types -> Str +generate_entry_points = \buf, types -> + List.walk(Types.entry_points(types), buf, \accum, T(name, id) -> generate_entry_point(accum, types, name, id)) -generateEntryPoint : Str, Types, Str, TypeId -> Str -generateEntryPoint = \buf, types, name, id -> - publicSignature = - when Types.shape types id is - Function rocFn -> +generate_entry_point : Str, Types, Str, TypeId -> Str +generate_entry_point = \buf, types, name, id -> + public_signature = + when Types.shape(types, id) is + Function(roc_fn) -> arguments = - toArgStr rocFn.args types \argId, _shape, index -> - type = typeName types argId - indexStr = Num.toStr index + to_arg_str(roc_fn.args, types, \arg_id, _shape, index -> + type = type_name(types, arg_id) + index_str = Num.to_str(index) - "arg$(indexStr): $(type)" + "arg$(index_str): $(type)") - ret = typeName types rocFn.ret + ret = type_name(types, roc_fn.ret) "($(arguments)) -> $(ret)" _ -> - ret = typeName types id + ret = type_name(types, id) "() -> $(ret)" - (externSignature, returnTypeName, returnsFn) = - when Types.shape types id is - Function rocFn -> + (extern_signature, return_type_name, returns_fn) = + when Types.shape(types, id) is + Function(roc_fn) -> arguments = - toArgStr rocFn.args types \argId, shape, _index -> - type = typeName types argId + to_arg_str(roc_fn.args, types, \arg_id, shape, _index -> + type = type_name(types, arg_id) - if canDeriveCopy types shape then + if can_derive_copy(types, shape) then "_: $(type)" else - "_: &mut core::mem::ManuallyDrop<$(type)>" + "_: &mut core::mem::ManuallyDrop<$(type)>") - ret = typeName types rocFn.ret - when Types.shape types rocFn.ret is - Function _ -> + ret = type_name(types, roc_fn.ret) + when Types.shape(types, roc_fn.ret) is + Function(_) -> ("(_: *mut u8, $(arguments))", ret, Bool.true) _ -> ("(_: *mut $(ret), $(arguments))", ret, Bool.false) _ -> - ret = typeName types id + ret = type_name(types, id) ("(_: *mut $(ret))", ret, Bool.false) - externArguments = - when Types.shape types id is - Function rocFn -> - toArgStr rocFn.args types \_argId, shape, index -> - indexStr = Num.toStr index + extern_arguments = + when Types.shape(types, id) is + Function(roc_fn) -> + to_arg_str(roc_fn.args, types, \_argId, shape, index -> + index_str = Num.to_str(index) - if canDeriveCopy types shape then - "arg$(indexStr)" + if can_derive_copy(types, shape) then + "arg$(index_str)" else - "&mut core::mem::ManuallyDrop::new(arg$(indexStr))" + "&mut core::mem::ManuallyDrop::new(arg$(index_str))") _ -> "" - if returnsFn then + if returns_fn then """ $(buf) - pub fn $(name)$(publicSignature) { + pub fn $(name)$(public_signature) { extern "C" { - fn roc__$(name)_1_exposed_generic$(externSignature); + fn roc__$(name)_1_exposed_generic$(extern_signature); fn roc__$(name)_1_exposed_size() -> i64; } unsafe { let capacity = roc__$(name)_1_exposed_size() as usize; - let mut ret = $(returnTypeName) { + let mut ret = $(return_type_name) { closure_data: Vec::with_capacity(capacity), }; ret.closure_data.resize(capacity, 0); - roc__$(name)_1_exposed_generic(ret.closure_data.as_mut_ptr(), $(externArguments)); + roc__$(name)_1_exposed_generic(ret.closure_data.as_mut_ptr(), $(extern_arguments)); ret } @@ -210,63 +211,63 @@ generateEntryPoint = \buf, types, name, id -> """ $(buf) - pub fn $(name)$(publicSignature) { + pub fn $(name)$(public_signature) { extern "C" { - fn roc__$(name)_1_exposed_generic$(externSignature); + fn roc__$(name)_1_exposed_generic$(extern_signature); } let mut ret = core::mem::MaybeUninit::uninit(); unsafe { - roc__$(name)_1_exposed_generic(ret.as_mut_ptr(), $(externArguments)); + roc__$(name)_1_exposed_generic(ret.as_mut_ptr(), $(extern_arguments)); ret.assume_init() } } """ -generateFunction : Str, Types, RocFn -> Str -generateFunction = \buf, types, rocFn -> - name = rocFn.functionName - externName = rocFn.externName +generate_function : Str, Types, RocFn -> Str +generate_function = \buf, types, roc_fn -> + name = roc_fn.function_name + extern_name = roc_fn.extern_name - publicArguments = - toArgStr rocFn.args types \argId, _shape, index -> - type = typeName types argId - indexStr = Num.toStr index + public_arguments = + to_arg_str(roc_fn.args, types, \arg_id, _shape, index -> + type = type_name(types, arg_id) + index_str = Num.to_str(index) - "arg$(indexStr): $(type)" + "arg$(index_str): $(type)") - externDefArguments = - withoutUnit = - toArgStr rocFn.args types \argId, _shape, index -> - type = typeName types argId - indexStr = Num.toStr index + extern_def_arguments = + without_unit = + to_arg_str(roc_fn.args, types, \arg_id, _shape, index -> + type = type_name(types, arg_id) + index_str = Num.to_str(index) - "arg$(indexStr): *const $(type)" + "arg$(index_str): *const $(type)") - if Str.isEmpty withoutUnit then + if Str.is_empty(without_unit) then # These always have a first argument that's a pointer, even if it's to nothing. "arg0: *const ()" else - withoutUnit + without_unit - externCallArguments = - withoutUnit = - toArgStr rocFn.args types \_argId, _shape, index -> - indexStr = Num.toStr index + extern_call_arguments = + without_unit = + to_arg_str(roc_fn.args, types, \_argId, _shape, index -> + index_str = Num.to_str(index) - "&arg$(indexStr)" + "&arg$(index_str)") - if Str.isEmpty withoutUnit then + if Str.is_empty(without_unit) then # These always have a first argument that's a pointer, even if it's to nothing. "&()" else - withoutUnit + without_unit - publicComma = if Str.isEmpty publicArguments then "" else ", " + public_comma = if Str.is_empty(public_arguments) then "" else ", " - ret = typeName types rocFn.ret + ret = type_name(types, roc_fn.ret) """ $(buf) @@ -278,31 +279,31 @@ generateFunction = \buf, types, rocFn -> } impl $(name) { - pub fn force_thunk(mut self$(publicComma)$(publicArguments)) -> $(ret) { + pub fn force_thunk(mut self$(public_comma)$(public_arguments)) -> $(ret) { extern "C" { - fn $(externName)($(externDefArguments), closure_data: *mut u8, output: *mut $(ret)); + fn $(extern_name)($(extern_def_arguments), closure_data: *mut u8, output: *mut $(ret)); } let mut output = core::mem::MaybeUninit::uninit(); unsafe { - $(externName)($(externCallArguments), self.closure_data.as_mut_ptr(), output.as_mut_ptr()); + $(extern_name)($(extern_call_arguments), self.closure_data.as_mut_ptr(), output.as_mut_ptr()); output.assume_init() } } } """ - |> generateRocRefcounted types (Function rocFn) name + |> generate_roc_refcounted(types, Function(roc_fn), name) -generateStruct : Str, Types, TypeId, _, _, _ -> Str -generateStruct = \buf, types, id, name, structFields, visibility -> - escapedName = escapeKW name +generate_struct : Str, Types, TypeId, _, _, _ -> Str +generate_struct = \buf, types, id, name, struct_fields, visibility -> + escaped_name = escape_kw(name) repr = length = - when structFields is - HasClosure fields -> List.len fields - HasNoClosure fields -> List.len fields + when struct_fields is + HasClosure(fields) -> List.len(fields) + HasNoClosure(fields) -> List.len(fields) if length <= 1 then "transparent" else @@ -313,97 +314,98 @@ generateStruct = \buf, types, id, name, structFields, visibility -> Public -> "pub " Private -> "" - structType = Types.shape types id + struct_type = Types.shape(types, id) buf - |> generateDeriveStr types structType IncludeDebug - |> Str.concat "#[repr($(repr))]\n$(pub)struct $(escapedName) {\n" - |> generateStructFields types Public structFields - |> Str.concat "}\n\n" - |> generateRocRefcounted types structType escapedName + |> generate_derive_str(types, struct_type, IncludeDebug) + |> Str.concat("#[repr($(repr))]\n$(pub)struct $(escaped_name) {\n") + |> generate_struct_fields(types, Public, struct_fields) + |> Str.concat("}\n\n") + |> generate_roc_refcounted(types, struct_type, escaped_name) -generateStructFields = \buf, types, visibility, structFields -> - when structFields is - HasNoClosure fields -> - List.walk fields buf (generateStructFieldWithoutClosure types visibility) +generate_struct_fields = \buf, types, visibility, struct_fields -> + when struct_fields is + HasNoClosure(fields) -> + List.walk(fields, buf, generate_struct_field_without_closure(types, visibility)) - HasClosure fields -> - List.walk fields buf (generateStructFieldWithoutClosure types visibility) + HasClosure(fields) -> + List.walk(fields, buf, generate_struct_field_without_closure(types, visibility)) -generateStructFieldWithoutClosure = \types, visibility -> - \accum, { name: fieldName, id } -> - typeStr = typeName types id - escapedFieldName = escapeKW fieldName +generate_struct_field_without_closure = \types, visibility -> + \accum, { name: field_name, id } -> + type_str = type_name(types, id) + escaped_field_name = escape_kw(field_name) pub = when visibility is Public -> "pub" Private -> "" - Str.concat accum "$(indent)$(pub) $(escapedFieldName): $(typeStr),\n" + Str.concat(accum, "$(indent)$(pub) $(escaped_field_name): $(type_str),\n") -nameTagUnionPayloadFields = \payloadFields -> +name_tag_union_payload_fields = \payload_fields -> # Tag union payloads have numbered fields, so we prefix them # with an "f" because Rust doesn't allow struct fields to be numbers. - when payloadFields is - HasNoClosure fields -> - renamedFields = List.map fields \{ name, id } -> { name: "f$(name)", id } - HasNoClosure renamedFields + when payload_fields is + HasNoClosure(fields) -> + renamed_fields = List.map(fields, \{ name, id } -> { name: "f$(name)", id }) + HasNoClosure(renamed_fields) - HasClosure fields -> - renamedFields = List.map fields \{ name, id, accessors } -> { name: "f$(name)", id, accessors } - HasClosure renamedFields + HasClosure(fields) -> + renamed_fields = List.map(fields, \{ name, id, accessors } -> { name: "f$(name)", id, accessors }) + HasClosure(renamed_fields) -generateEnumeration = \buf, types, enumType, name, tags, tagBytes -> - escapedName = escapeKW name +generate_enumeration = \buf, types, enum_type, name, tags, tag_bytes -> + escaped_name = escape_kw(name) - reprBits = tagBytes * 8 |> Num.toStr + repr_bits = tag_bytes * 8 |> Num.to_str buf - |> generateDeriveStr types enumType ExcludeDebug - |> Str.concat "#[repr(u$(reprBits))]\npub enum $(escapedName) {\n" - |> \b -> List.walkWithIndex tags b generateEnumTags + |> generate_derive_str(types, enum_type, ExcludeDebug) + |> Str.concat("#[repr(u$(repr_bits))]\npub enum $(escaped_name) {\n") + |> \b -> List.walk_with_index(tags, b, generate_enum_tags) |> # Enums require a custom debug impl to ensure naming is identical on all platforms. - Str.concat + Str.concat( """ } - impl core::fmt::Debug for $(escapedName) { + impl core::fmt::Debug for $(escaped_name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - """ - |> \b -> List.walk tags b (generateEnumTagsDebug name) - |> Str.concat "$(indent)$(indent)}\n$(indent)}\n}\n\n" - |> generateRocRefcounted types enumType escapedName + """, + ) + |> \b -> List.walk(tags, b, generate_enum_tags_debug(name)) + |> Str.concat("$(indent)$(indent)}\n$(indent)}\n}\n\n") + |> generate_roc_refcounted(types, enum_type, escaped_name) -generateEnumTags = \accum, name, index -> - indexStr = Num.toStr index +generate_enum_tags = \accum, name, index -> + index_str = Num.to_str(index) - Str.concat accum "$(indent)$(name) = $(indexStr),\n" + Str.concat(accum, "$(indent)$(name) = $(index_str),\n") -generateEnumTagsDebug = \name -> - \accum, tagName -> - Str.concat accum "$(indent)$(indent)$(indent)Self::$(tagName) => f.write_str(\"$(name)::$(tagName)\"),\n" +generate_enum_tags_debug = \name -> + \accum, tag_name -> + Str.concat(accum, "$(indent)$(indent)$(indent)Self::$(tag_name) => f.write_str(\"$(name)::$(tag_name)\"),\n") -deriveCloneTagUnion : Str, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -deriveCloneTagUnion = \buf, tagUnionType, tags -> +derive_clone_tag_union : Str, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +derive_clone_tag_union = \buf, tag_union_type, tags -> clones = - List.walk tags "" \accum, { name: tagName } -> + List.walk(tags, "", \accum, { name: tag_name } -> """ $(accum) - $(tagName) => union_$(tagUnionType) { - $(tagName): self.payload.$(tagName).clone(), + $(tag_name) => union_$(tag_union_type) { + $(tag_name): self.payload.$(tag_name).clone(), }, - """ + """) """ $(buf) - impl Clone for $(tagUnionType) { + impl Clone for $(tag_union_type) { fn clone(&self) -> Self { - use discriminant_$(tagUnionType)::*; + use discriminant_$(tag_union_type)::*; let payload = unsafe { match self.discriminant {$(clones) @@ -418,29 +420,29 @@ deriveCloneTagUnion = \buf, tagUnionType, tags -> } """ -deriveDebugTagUnion : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -deriveDebugTagUnion = \buf, types, tagUnionType, tags -> +derive_debug_tag_union : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +derive_debug_tag_union = \buf, types, tag_union_type, tags -> checks = - List.walk tags "" \accum, { name: tagName, payload } -> + List.walk(tags, "", \accum, { name: tag_name, payload } -> type = when payload is - Some id -> typeName types id + Some(id) -> type_name(types, id) None -> "()" """ $(accum) - $(tagName) => { - let field: &$(type) = &self.payload.$(tagName); - f.debug_tuple("$(tagUnionType)::$(tagName)").field(field).finish() + $(tag_name) => { + let field: &$(type) = &self.payload.$(tag_name); + f.debug_tuple("$(tag_union_type)::$(tag_name)").field(field).finish() }, - """ + """) """ $(buf) - impl core::fmt::Debug for $(tagUnionType) { + impl core::fmt::Debug for $(tag_union_type) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - use discriminant_$(tagUnionType)::*; + use discriminant_$(tag_union_type)::*; unsafe { match self.discriminant {$(checks) @@ -450,33 +452,33 @@ deriveDebugTagUnion = \buf, types, tagUnionType, tags -> } """ -deriveEqTagUnion : Str, Types, Shape, Str -> Str -deriveEqTagUnion = \buf, types, shape, tagUnionType -> - if canSupportEqHashOrd types shape then +derive_eq_tag_union : Str, Types, Shape, Str -> Str +derive_eq_tag_union = \buf, types, shape, tag_union_type -> + if can_support_eq_hash_ord(types, shape) then """ $(buf) - impl Eq for $(tagUnionType) {} + impl Eq for $(tag_union_type) {} """ else buf -derivePartialEqTagUnion : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -derivePartialEqTagUnion = \buf, types, shape, tagUnionType, tags -> - if canSupportPartialEqOrd types shape then +derive_partial_eq_tag_union : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +derive_partial_eq_tag_union = \buf, types, shape, tag_union_type, tags -> + if can_support_partial_eq_ord(types, shape) then checks = - List.walk tags "" \accum, { name: tagName } -> + List.walk(tags, "", \accum, { name: tag_name } -> """ $(accum) - $(tagName) => self.payload.$(tagName) == other.payload.$(tagName), - """ + $(tag_name) => self.payload.$(tag_name) == other.payload.$(tag_name), + """) """ $(buf) - impl PartialEq for $(tagUnionType) { + impl PartialEq for $(tag_union_type) { fn eq(&self, other: &Self) -> bool { - use discriminant_$(tagUnionType)::*; + use discriminant_$(tag_union_type)::*; if self.discriminant != other.discriminant { return false; @@ -492,13 +494,13 @@ derivePartialEqTagUnion = \buf, types, shape, tagUnionType, tags -> else buf -deriveOrdTagUnion : Str, Types, Shape, Str -> Str -deriveOrdTagUnion = \buf, types, shape, tagUnionType -> - if canSupportEqHashOrd types shape then +derive_ord_tag_union : Str, Types, Shape, Str -> Str +derive_ord_tag_union = \buf, types, shape, tag_union_type -> + if can_support_eq_hash_ord(types, shape) then """ $(buf) - impl Ord for $(tagUnionType) { + impl Ord for $(tag_union_type) { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.partial_cmp(other).unwrap() } @@ -507,22 +509,22 @@ deriveOrdTagUnion = \buf, types, shape, tagUnionType -> else buf -derivePartialOrdTagUnion : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -derivePartialOrdTagUnion = \buf, types, shape, tagUnionType, tags -> - if canSupportPartialEqOrd types shape then +derive_partial_ord_tag_union : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +derive_partial_ord_tag_union = \buf, types, shape, tag_union_type, tags -> + if can_support_partial_eq_ord(types, shape) then checks = - List.walk tags "" \accum, { name: tagName } -> + List.walk(tags, "", \accum, { name: tag_name } -> """ $(accum) - $(tagName) => self.payload.$(tagName).partial_cmp(&other.payload.$(tagName)), - """ + $(tag_name) => self.payload.$(tag_name).partial_cmp(&other.payload.$(tag_name)), + """) """ $(buf) - impl PartialOrd for $(tagUnionType) { + impl PartialOrd for $(tag_union_type) { fn partial_cmp(&self, other: &Self) -> Option { - use discriminant_$(tagUnionType)::*; + use discriminant_$(tag_union_type)::*; use std::cmp::Ordering::*; @@ -540,22 +542,22 @@ derivePartialOrdTagUnion = \buf, types, shape, tagUnionType, tags -> else buf -deriveHashTagUnion : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -deriveHashTagUnion = \buf, types, shape, tagUnionType, tags -> - if canSupportEqHashOrd types shape then +derive_hash_tag_union : Str, Types, Shape, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +derive_hash_tag_union = \buf, types, shape, tag_union_type, tags -> + if can_support_eq_hash_ord(types, shape) then checks = - List.walk tags "" \accum, { name: tagName } -> + List.walk(tags, "", \accum, { name: tag_name } -> """ $(accum) - $(tagName) => self.payload.$(tagName).hash(state), - """ + $(tag_name) => self.payload.$(tag_name).hash(state), + """) """ $(buf) - impl core::hash::Hash for $(tagUnionType) { + impl core::hash::Hash for $(tag_union_type) { fn hash(&self, state: &mut H) { - use discriminant_$(tagUnionType)::*; + use discriminant_$(tag_union_type)::*; unsafe { match self.discriminant {$(checks) @@ -567,36 +569,36 @@ deriveHashTagUnion = \buf, types, shape, tagUnionType, tags -> else buf -generateConstructorFunctions : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -generateConstructorFunctions = \buf, types, tagUnionType, tags -> +generate_constructor_functions : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +generate_constructor_functions = \buf, types, tag_union_type, tags -> buf - |> Str.concat "\n\nimpl $(tagUnionType) {" - |> \b -> List.walk tags b \accum, r -> generateConstructorFunction accum types tagUnionType r.name r.payload - |> Str.concat "\n}\n\n" + |> Str.concat("\n\nimpl $(tag_union_type) {") + |> \b -> List.walk(tags, b, \accum, r -> generate_constructor_function(accum, types, tag_union_type, r.name, r.payload)) + |> Str.concat("\n}\n\n") -generateConstructorFunction : Str, Types, Str, Str, [Some TypeId, None] -> Str -generateConstructorFunction = \buf, types, tagUnionType, name, optPayload -> - when optPayload is +generate_constructor_function : Str, Types, Str, Str, [Some TypeId, None] -> Str +generate_constructor_function = \buf, types, tag_union_type, name, opt_payload -> + when opt_payload is None -> """ $(buf) pub fn $(name)() -> Self { Self { - discriminant: discriminant_$(tagUnionType)::$(name), - payload: union_$(tagUnionType) { + discriminant: discriminant_$(tag_union_type)::$(name), + payload: union_$(tag_union_type) { $(name): (), } } } """ - Some payloadId -> - payloadType = typeName types payloadId - shape = Types.shape types payloadId + Some(payload_id) -> + payload_type = type_name(types, payload_id) + shape = Types.shape(types, payload_id) new = - if canDeriveCopy types shape then + if can_derive_copy(types, shape) then "payload" else "core::mem::ManuallyDrop::new(payload)" @@ -604,288 +606,292 @@ generateConstructorFunction = \buf, types, tagUnionType, name, optPayload -> """ $(buf) - pub fn $(name)(payload: $(payloadType)) -> Self { + pub fn $(name)(payload: $(payload_type)) -> Self { Self { - discriminant: discriminant_$(tagUnionType)::$(name), - payload: union_$(tagUnionType) { + discriminant: discriminant_$(tag_union_type)::$(name), + payload: union_$(tag_union_type) { $(name): $(new), } } } """ -generateDestructorFunctions : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str -generateDestructorFunctions = \buf, types, tagUnionType, tags -> +generate_destructor_functions : Str, Types, Str, List { name : Str, payload : [Some TypeId, None] } -> Str +generate_destructor_functions = \buf, types, tag_union_type, tags -> buf - |> Str.concat "\n\nimpl $(tagUnionType) {" - |> \b -> List.walk tags b \accum, r -> generateDestructorFunction accum types tagUnionType r.name r.payload - |> Str.concat "\n}\n\n" + |> Str.concat("\n\nimpl $(tag_union_type) {") + |> \b -> List.walk(tags, b, \accum, r -> generate_destructor_function(accum, types, tag_union_type, r.name, r.payload)) + |> Str.concat("\n}\n\n") -generateDestructorFunction : Str, Types, Str, Str, [Some TypeId, None] -> Str -generateDestructorFunction = \buf, types, tagUnionType, name, optPayload -> - when optPayload is +generate_destructor_function : Str, Types, Str, Str, [Some TypeId, None] -> Str +generate_destructor_function = \buf, types, tag_union_type, name, opt_payload -> + when opt_payload is None -> """ $(buf) pub fn is_$(name)(&self) -> bool { - matches!(self.discriminant, discriminant_$(tagUnionType)::$(name)) + matches!(self.discriminant, discriminant_$(tag_union_type)::$(name)) } """ - Some payloadId -> - payloadType = typeName types payloadId - shape = Types.shape types payloadId + Some(payload_id) -> + payload_type = type_name(types, payload_id) + shape = Types.shape(types, payload_id) take = - if canDeriveCopy types shape then + if can_derive_copy(types, shape) then "unsafe { self.payload.$(name) }" else "unsafe { core::mem::ManuallyDrop::take(&mut self.payload.$(name)) }" - (borrow, borrowType) = - if canDeriveCopy types shape then - ("unsafe { self.payload.$(name) }", payloadType) + (borrow, borrow_type) = + if can_derive_copy(types, shape) then + ("unsafe { self.payload.$(name) }", payload_type) else ( """ use core::borrow::Borrow; unsafe { self.payload.$(name).borrow() } """, - "&$(payloadType)", + "&$(payload_type)", ) - (borrowMut, borrowMutType) = - if canDeriveCopy types shape then - ("unsafe { &mut self.payload.$(name) }", "&mut $(payloadType)") + (borrow_mut, borrow_mut_type) = + if can_derive_copy(types, shape) then + ("unsafe { &mut self.payload.$(name) }", "&mut $(payload_type)") else ( """ use core::borrow::BorrowMut; unsafe { self.payload.$(name).borrow_mut() } """, - "&mut $(payloadType)", + "&mut $(payload_type)", ) """ $(buf) - pub fn unwrap_$(name)(mut self) -> $(payloadType) { - debug_assert_eq!(self.discriminant, discriminant_$(tagUnionType)::$(name)); + pub fn unwrap_$(name)(mut self) -> $(payload_type) { + debug_assert_eq!(self.discriminant, discriminant_$(tag_union_type)::$(name)); $(take) } - pub fn borrow_$(name)(&self) -> $(borrowType) { - debug_assert_eq!(self.discriminant, discriminant_$(tagUnionType)::$(name)); + pub fn borrow_$(name)(&self) -> $(borrow_type) { + debug_assert_eq!(self.discriminant, discriminant_$(tag_union_type)::$(name)); $(borrow) } - pub fn borrow_mut_$(name)(&mut self) -> $(borrowMutType) { - debug_assert_eq!(self.discriminant, discriminant_$(tagUnionType)::$(name)); - $(borrowMut) + pub fn borrow_mut_$(name)(&mut self) -> $(borrow_mut_type) { + debug_assert_eq!(self.discriminant, discriminant_$(tag_union_type)::$(name)); + $(borrow_mut) } pub fn is_$(name)(&self) -> bool { - matches!(self.discriminant, discriminant_$(tagUnionType)::$(name)) + matches!(self.discriminant, discriminant_$(tag_union_type)::$(name)) } """ -generateNonRecursiveTagUnion : Str, Types, TypeId, Str, List { name : Str, payload : [Some TypeId, None] }, U32, U32 -> Str -generateNonRecursiveTagUnion = \buf, types, id, name, tags, discriminantSize, discriminantOffset -> - escapedName = escapeKW name - discriminantName = "discriminant_$(escapedName)" - unionName = "union_$(escapedName)" - discriminantOffsetStr = Num.toStr discriminantOffset - tagNames = List.map tags \{ name: n } -> n - selfMut = "self" +generate_non_recursive_tag_union : Str, Types, TypeId, Str, List { name : Str, payload : [Some TypeId, None] }, U32, U32 -> Str +generate_non_recursive_tag_union = \buf, types, id, name, tags, discriminant_size, discriminant_offset -> + escaped_name = escape_kw(name) + discriminant_name = "discriminant_$(escaped_name)" + union_name = "union_$(escaped_name)" + discriminant_offset_str = Num.to_str(discriminant_offset) + tag_names = List.map(tags, \{ name: n } -> n) + self_mut = "self" max = \a, b -> if a >= b then a else b - alignOfUnion = - List.walk tags 1 \accum, { payload } -> + align_of_union = + List.walk(tags, 1, \accum, { payload } -> when payload is - Some payloadId -> max accum (Types.alignment types payloadId) - None -> accum + Some(payload_id) -> max(accum, Types.alignment(types, payload_id)) + None -> accum) - alignOfUnionStr = Num.toStr alignOfUnion + align_of_union_str = Num.to_str(align_of_union) - sizeOfUnionStr = - List.walk tags 1 \accum, { payload } -> + size_of_union_str = + List.walk(tags, 1, \accum, { payload } -> when payload is - Some payloadId -> max accum (Types.size types payloadId) - None -> accum - |> nextMultipleOf alignOfUnion - |> Num.toStr + Some(payload_id) -> max(accum, Types.size(types, payload_id)) + None -> accum) + |> next_multiple_of(align_of_union) + |> Num.to_str - sizeOfSelf = Num.toStr (Types.size types id) - alignOfSelf = Num.toStr (Types.alignment types id) - shape = Types.shape types id + size_of_self = Num.to_str(Types.size(types, id)) + align_of_self = Num.to_str(Types.alignment(types, id)) + shape = Types.shape(types, id) # TODO: this value can be different than the alignment of `id` align = - List.walk tags 1 \accum, { payload } -> + List.walk(tags, 1, \accum, { payload } -> when payload is - Some payloadId -> max accum (Types.alignment types payloadId) - None -> accum - |> Num.toStr + Some(payload_id) -> max(accum, Types.alignment(types, payload_id)) + None -> accum) + |> Num.to_str - unionType = Types.shape types id + union_type = Types.shape(types, id) buf - |> generateDiscriminant types discriminantName tagNames discriminantSize - |> Str.concat "#[repr(C, align($(align)))]\npub union $(unionName) {\n" - |> \b -> List.walk tags b (generateUnionField types) - |> Str.concat + |> generate_discriminant(types, discriminant_name, tag_names, discriminant_size) + |> Str.concat("#[repr(C, align($(align)))]\npub union $(union_name) {\n") + |> \b -> List.walk(tags, b, generate_union_field(types)) + |> Str.concat( """ } // TODO(@roc-lang): See https://github.com/roc-lang/roc/issues/6012 - // const _SIZE_CHECK_$(unionName): () = assert!(core::mem::size_of::<$(unionName)>() == $(sizeOfUnionStr)); - const _ALIGN_CHECK_$(unionName): () = assert!(core::mem::align_of::<$(unionName)>() == $(alignOfUnionStr)); + // const _SIZE_CHECK_$(union_name): () = assert!(core::mem::size_of::<$(union_name)>() == $(size_of_union_str)); + const _ALIGN_CHECK_$(union_name): () = assert!(core::mem::align_of::<$(union_name)>() == $(align_of_union_str)); - const _SIZE_CHECK_$(escapedName): () = assert!(core::mem::size_of::<$(escapedName)>() == $(sizeOfSelf)); - const _ALIGN_CHECK_$(escapedName): () = assert!(core::mem::align_of::<$(escapedName)>() == $(alignOfSelf)); + const _SIZE_CHECK_$(escaped_name): () = assert!(core::mem::size_of::<$(escaped_name)>() == $(size_of_self)); + const _ALIGN_CHECK_$(escaped_name): () = assert!(core::mem::align_of::<$(escaped_name)>() == $(align_of_self)); - impl $(escapedName) { - $(discriminantDocComment) - pub fn discriminant(&self) -> $(discriminantName) { + impl $(escaped_name) { + $(discriminant_doc_comment) + pub fn discriminant(&self) -> $(discriminant_name) { unsafe { let bytes = core::mem::transmute::<&Self, &[u8; core::mem::size_of::()]>(self); - core::mem::transmute::(*bytes.as_ptr().add($(discriminantOffsetStr))) + core::mem::transmute::(*bytes.as_ptr().add($(discriminant_offset_str))) } } /// Internal helper - fn set_discriminant(&mut self, discriminant: $(discriminantName)) { - let discriminant_ptr: *mut $(discriminantName) = (self as *mut $(escapedName)).cast(); + fn set_discriminant(&mut self, discriminant: $(discriminant_name)) { + let discriminant_ptr: *mut $(discriminant_name) = (self as *mut $(escaped_name)).cast(); unsafe { - *(discriminant_ptr.add($(discriminantOffsetStr))) = discriminant; + *(discriminant_ptr.add($(discriminant_offset_str))) = discriminant; } } } - """ - |> Str.concat + """, + ) + |> Str.concat( """ #[repr(C)] - pub struct $(escapedName) { - payload: union_$(escapedName), - discriminant: discriminant_$(escapedName), + pub struct $(escaped_name) { + payload: union_$(escaped_name), + discriminant: discriminant_$(escaped_name), } - """ - |> deriveCloneTagUnion escapedName tags - |> deriveDebugTagUnion types escapedName tags - |> deriveEqTagUnion types shape escapedName - |> derivePartialEqTagUnion types shape escapedName tags - |> deriveOrdTagUnion types shape escapedName - |> derivePartialOrdTagUnion types shape escapedName tags - |> deriveHashTagUnion types shape escapedName tags - |> generateDestructorFunctions types escapedName tags - |> generateConstructorFunctions types escapedName tags + """, + ) + |> derive_clone_tag_union(escaped_name, tags) + |> derive_debug_tag_union(types, escaped_name, tags) + |> derive_eq_tag_union(types, shape, escaped_name) + |> derive_partial_eq_tag_union(types, shape, escaped_name, tags) + |> derive_ord_tag_union(types, shape, escaped_name) + |> derive_partial_ord_tag_union(types, shape, escaped_name, tags) + |> derive_hash_tag_union(types, shape, escaped_name, tags) + |> generate_destructor_functions(types, escaped_name, tags) + |> generate_constructor_functions(types, escaped_name, tags) |> \b -> - if cannotSupportCopy types unionType then + if cannot_support_copy(types, union_type) then # A custom drop impl is only needed when we can't derive copy. b - |> Str.concat + |> Str.concat( """ - impl Drop for $(escapedName) { + impl Drop for $(escaped_name) { fn drop(&mut self) { // Drop the payloads - """ - |> generateTagUnionDropPayload types selfMut tags discriminantName discriminantSize 2 - |> Str.concat + """, + ) + |> generate_tag_union_drop_payload(types, self_mut, tags, discriminant_name, discriminant_size, 2) + |> Str.concat( """ } } - """ + """, + ) else b - |> generateRocRefcounted types unionType escapedName + |> generate_roc_refcounted(types, union_type, escaped_name) -generateNonNullableUnwrapped = \buf, types, name, tagName, payload, discriminantSize, _discriminantOffset, _nullTagIndex -> - escapedName = escapeKW name - discriminantName = "discriminant_$(escapedName)" +generate_non_nullable_unwrapped = \buf, types, name, tag_name, payload, discriminant_size, _discriminant_offset, _null_tagIndex -> + escaped_name = escape_kw(name) + discriminant_name = "discriminant_$(escaped_name)" - payloadFields = - when Types.shape types payload is - TagUnionPayload { fields } -> + payload_fields = + when Types.shape(types, payload) is + TagUnionPayload({ fields }) -> when fields is - HasNoClosure xs -> List.map xs .id - HasClosure xs -> List.map xs .id + HasNoClosure(xs) -> List.map(xs, .id) + HasClosure(xs) -> List.map(xs, .id) _ -> [] - payloadFieldNames = - commaSeparated "" payloadFields \_, i -> - n = Num.toStr i - "f$(n)" + payload_field_names = + comma_separated("", payload_fields, \_, i -> + n = Num.to_str(i) + "f$(n)") - constructorArguments = - commaSeparated "" payloadFields \id, i -> - n = Num.toStr i - type = typeName types id - "f$(n): $(type)" + constructor_arguments = + comma_separated("", payload_fields, \id, i -> + n = Num.to_str(i) + type = type_name(types, id) + "f$(n): $(type)") - debugFields = - payloadFields - |> List.mapWithIndex \_, i -> - n = Num.toStr i - ".field(&node.f$(n))" - |> Str.joinWith "" + debug_fields = + payload_fields + |> List.map_with_index(\_, i -> + n = Num.to_str(i) + ".field(&node.f$(n))") + |> Str.join_with("") - buf1 = buf |> generateDiscriminant types discriminantName [tagName] discriminantSize + buf1 = buf |> generate_discriminant(types, discriminant_name, [tag_name], discriminant_size) - unionType = TagUnion (NonNullableUnwrapped { name, tagName, payload }) + union_type = TagUnion(NonNullableUnwrapped({ name, tag_name, payload })) """ $(buf1) #[repr(transparent)] #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] - pub struct $(escapedName)(roc_std::RocBox<$(name)_$(tagName)>); + pub struct $(escaped_name)(roc_std::RocBox<$(name)_$(tag_name)>); - impl $(escapedName) { - pub fn $(tagName)($(constructorArguments)) -> Self { - let payload = $(name)_$(tagName) { $(payloadFieldNames) }; + impl $(escaped_name) { + pub fn $(tag_name)($(constructor_arguments)) -> Self { + let payload = $(name)_$(tag_name) { $(payload_field_names) }; Self(roc_std::RocBox::new(payload)) } } - impl core::fmt::Debug for $(escapedName) { + impl core::fmt::Debug for $(escaped_name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let node = &self.0; - f.debug_tuple("$(escapedName)::$(tagName)")$(debugFields).finish() + f.debug_tuple("$(escaped_name)::$(tag_name)")$(debug_fields).finish() } } """ - |> generateRocRefcounted types unionType escapedName + |> generate_roc_refcounted(types, union_type, escaped_name) -generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSize, _discriminantOffset, nullTagIndex -> - escapedName = escapeKW tagUnionName - discriminantName = "discriminant_$(escapedName)" - tagNames = List.map tags \{ name: n } -> n +generate_recursive_tag_union = \buf, types, id, tag_union_name, tags, discriminant_size, _discriminant_offset, null_tag_index -> + escaped_name = escape_kw(tag_union_name) + discriminant_name = "discriminant_$(escaped_name)" + tag_names = List.map(tags, \{ name: n } -> n) # self = "(&*self.union_pointer())" # selfMut = "(&mut *self.union_pointer())" # other = "(&*other.union_pointer())" - unionName = "union_$(escapedName)" + union_name = "union_$(escaped_name)" discriminants = - tagNames - |> Str.joinWith ", " + tag_names + |> Str.join_with(", ") |> \b -> "[ $(b) ]" - nullTagId = - when nullTagIndex is - Some index -> - n = Num.toStr index + null_tag_id = + when null_tag_index is + Some(index) -> + n = Num.to_str(index) "discriminants[$(n)]" None -> @@ -893,15 +899,15 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz unreachable!("this pointer cannot be NULL") """ - isFunction = \{ name: tagName, payload: optPayload }, index -> - payloadFields = - when optPayload is - Some payload -> - when Types.shape types payload is - TagUnionPayload { fields } -> + is_function = \{ name: tag_name, payload: opt_payload }, index -> + payload_fields = + when opt_payload is + Some(payload) -> + when Types.shape(types, payload) is + TagUnionPayload({ fields }) -> when fields is - HasNoClosure xs -> List.map xs .id - HasClosure xs -> List.map xs .id + HasNoClosure(xs) -> List.map(xs, .id) + HasClosure(xs) -> List.map(xs, .id) _ -> [] @@ -909,49 +915,49 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz None -> [] - fieldGetters = - List.walk payloadFields { i: 0, accum: "" } \{ i, accum }, fieldTypeId -> - fieldTypeName = typeName types fieldTypeId - fieldIndex = Num.toStr i + field_getters = + List.walk(payload_fields, { i: 0, accum: "" }, \{ i, accum }, field_type_id -> + field_type_name = type_name(types, field_type_id) + field_index = Num.to_str(i) { i: i + 1, accum: """ $(accum) - pub fn get_$(tagName)_f$(fieldIndex)(&self) -> &$(fieldTypeName) { - debug_assert!(self.is_$(tagName)()); + pub fn get_$(tag_name)_f$(field_index)(&self) -> &$(field_type_name) { + debug_assert!(self.is_$(tag_name)()); // extern "C" { // fn foobar(tag_id: u16, field_index: usize) -> usize; // } - // let offset = unsafe { foobar($(fieldIndex)) }; + // let offset = unsafe { foobar($(field_index)) }; let offset = 0; unsafe { &*self.unmasked_pointer().add(offset).cast() } } """, - } + }) |> .accum - payloadFieldNames = - commaSeparated "" payloadFields \_, i -> - n = Num.toStr i - "f$(n)" + payload_field_names = + comma_separated("", payload_fields, \_, i -> + n = Num.to_str(i) + "f$(n)") - constructorArguments = - commaSeparated "" payloadFields \payloadId, i -> - n = Num.toStr i - type = typeName types payloadId - "f$(n): $(type)" + constructor_arguments = + comma_separated("", payload_fields, \payload_id, i -> + n = Num.to_str(i) + type = type_name(types, payload_id) + "f$(n): $(type)") - fixManuallyDrop = - when optPayload is - Some payload -> - shape = Types.shape types payload + fix_manually_drop = + when opt_payload is + Some(payload) -> + shape = Types.shape(types, payload) - if canDeriveCopy types shape then + if can_derive_copy(types, shape) then "payload" else "core::mem::ManuallyDrop::new(payload)" @@ -959,60 +965,60 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz None -> "payload" - if Some (Num.intCast index) == nullTagIndex then + if Some(Num.int_cast(index)) == null_tag_index then """ - pub fn is_$(tagName)(&self) -> bool { - matches!(self.discriminant(), discriminant_$(escapedName)::$(tagName)) + pub fn is_$(tag_name)(&self) -> bool { + matches!(self.discriminant(), discriminant_$(escaped_name)::$(tag_name)) } - pub fn $(tagName)($(constructorArguments)) -> Self { + pub fn $(tag_name)($(constructor_arguments)) -> Self { Self(std::ptr::null_mut()) } """ else """ - pub fn is_$(tagName)(&self) -> bool { - matches!(self.discriminant(), discriminant_$(escapedName)::$(tagName)) + pub fn is_$(tag_name)(&self) -> bool { + matches!(self.discriminant(), discriminant_$(escaped_name)::$(tag_name)) } - pub fn $(tagName)($(constructorArguments)) -> Self { - let tag_id = discriminant_$(escapedName)::$(tagName); + pub fn $(tag_name)($(constructor_arguments)) -> Self { + let tag_id = discriminant_$(escaped_name)::$(tag_name); - let payload = $(escapedName)_$(tagName) { $(payloadFieldNames) } ; + let payload = $(escaped_name)_$(tag_name) { $(payload_field_names) } ; - let union_payload = union_$(escapedName) { $(tagName): $(fixManuallyDrop) }; + let union_payload = union_$(escaped_name) { $(tag_name): $(fix_manually_drop) }; let ptr = unsafe { roc_std::RocBox::leak(roc_std::RocBox::new(union_payload)) }; Self((ptr as usize | tag_id as usize) as *mut _) } - $(fieldGetters) + $(field_getters) - pub fn get_$(tagName)(mut self) -> $(escapedName)_$(tagName) { - debug_assert!(self.is_$(tagName)()); + pub fn get_$(tag_name)(mut self) -> $(escaped_name)_$(tag_name) { + debug_assert!(self.is_$(tag_name)()); - unsafe { core::mem::ManuallyDrop::take(&mut self.ptr_read_union().$(tagName)) } + unsafe { core::mem::ManuallyDrop::take(&mut self.ptr_read_union().$(tag_name)) } } """ constructors = tags - |> List.mapWithIndex isFunction - |> Str.joinWith "\n\n" + |> List.map_with_index(is_function) + |> Str.join_with("\n\n") - cloneCase = \{ name: tagName }, index -> - if Some (Num.intCast index) == nullTagIndex then + clone_case = \{ name: tag_name }, index -> + if Some(Num.int_cast(index)) == null_tag_index then """ - $(tagName) => Self::$(tagName)(), + $(tag_name) => Self::$(tag_name)(), """ else """ - $(tagName) => { - let tag_id = discriminant_$(escapedName)::$(tagName); + $(tag_name) => { + let tag_id = discriminant_$(escaped_name)::$(tag_name); let payload_union = unsafe { self.ptr_read_union() }; - let payload = union_$(escapedName) { - $(tagName): unsafe { payload_union.$(tagName).clone() }, + let payload = union_$(escaped_name) { + $(tag_name): unsafe { payload_union.$(tag_name).clone() }, }; let ptr = unsafe { roc_std::RocBox::leak(roc_std::RocBox::new(payload)) }; @@ -1021,69 +1027,69 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz }, """ - cloneCases = + clone_cases = tags - |> List.mapWithIndex cloneCase - |> Str.joinWith "\n" + |> List.map_with_index(clone_case) + |> Str.join_with("\n") - partialEqCase = \{ name: tagName }, index -> - if Some (Num.intCast index) == nullTagIndex then + partial_eq_case = \{ name: tag_name }, index -> + if Some(Num.int_cast(index)) == null_tag_index then """ - $(tagName) => true, + $(tag_name) => true, """ else """ - $(tagName) => { + $(tag_name) => { let payload_union1 = unsafe { self.ptr_read_union() }; let payload_union2 = unsafe { other.ptr_read_union() }; unsafe { - payload_union1.$(tagName) == payload_union2.$(tagName) + payload_union1.$(tag_name) == payload_union2.$(tag_name) } }, """ - partialEqCases = + partial_eq_cases = tags - |> List.mapWithIndex partialEqCase - |> Str.joinWith "\n" + |> List.map_with_index(partial_eq_case) + |> Str.join_with("\n") - partialEqImpl = - if canSupportPartialEqOrd types (Types.shape types id) then + partial_eq_impl = + if can_support_partial_eq_ord(types, Types.shape(types, id)) then """ - impl PartialEq for $(escapedName) { + impl PartialEq for $(escaped_name) { fn eq(&self, other: &Self) -> bool { - use discriminant_$(escapedName)::*; + use discriminant_$(escaped_name)::*; if self.discriminant() != other.discriminant() { return false; } match self.discriminant() { - $(partialEqCases) + $(partial_eq_cases) } } } - impl Eq for $(escapedName) {} + impl Eq for $(escaped_name) {} """ else "" - debugCase = \{ name: tagName, payload: optPayload }, index -> - if Some (Num.intCast index) == nullTagIndex then + debug_case = \{ name: tag_name, payload: opt_payload }, index -> + if Some(Num.int_cast(index)) == null_tag_index then """ - $(tagName) => f.debug_tuple("$(escapedName)::$(tagName)").finish(), + $(tag_name) => f.debug_tuple("$(escaped_name)::$(tag_name)").finish(), """ else - payloadFields = - when optPayload is - Some payload -> - when Types.shape types payload is - TagUnionPayload { fields } -> + payload_fields = + when opt_payload is + Some(payload) -> + when Types.shape(types, payload) is + TagUnionPayload({ fields }) -> when fields is - HasNoClosure xs -> List.map xs .id - HasClosure xs -> List.map xs .id + HasNoClosure(xs) -> List.map(xs, .id) + HasClosure(xs) -> List.map(xs, .id) _ -> [] @@ -1091,58 +1097,58 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz None -> [] - debugFields = - payloadFields - |> List.mapWithIndex \_, i -> - n = Num.toStr i - ".field(&payload_union.$(tagName).f$(n))" - |> Str.joinWith "" + debug_fields = + payload_fields + |> List.map_with_index(\_, i -> + n = Num.to_str(i) + ".field(&payload_union.$(tag_name).f$(n))") + |> Str.join_with("") """ - $(tagName) => { + $(tag_name) => { let payload_union = unsafe { self.ptr_read_union() }; unsafe { - f.debug_tuple("$(escapedName)::$(tagName)")$(debugFields).finish() + f.debug_tuple("$(escaped_name)::$(tag_name)")$(debug_fields).finish() } }, """ - debugCases = + debug_cases = tags - |> List.mapWithIndex debugCase - |> Str.joinWith "\n" + |> List.map_with_index(debug_case) + |> Str.join_with("\n") - hashCase = \{ name: tagName }, index -> - if Some (Num.intCast index) == nullTagIndex then + hash_case = \{ name: tag_name }, index -> + if Some(Num.int_cast(index)) == null_tag_index then """ - $(tagName) => {} + $(tag_name) => {} """ else """ - $(tagName) => { + $(tag_name) => { let payload_union = unsafe { self.ptr_read_union() }; - unsafe { payload_union.$(tagName).hash(state) }; + unsafe { payload_union.$(tag_name).hash(state) }; }, """ - hashCases = + hash_cases = tags - |> List.mapWithIndex hashCase - |> Str.joinWith "\n" + |> List.map_with_index(hash_case) + |> Str.join_with("\n") - unionType = Types.shape types id - hashImpl = - if canSupportPartialEqOrd types unionType then + union_type = Types.shape(types, id) + hash_impl = + if can_support_partial_eq_ord(types, union_type) then """ - impl core::hash::Hash for $(escapedName) { + impl core::hash::Hash for $(escaped_name) { fn hash(&self, state: &mut H) { - use discriminant_$(escapedName)::*; + use discriminant_$(escaped_name)::*; self.discriminant().hash(state); match self.discriminant() { - $(hashCases) + $(hash_cases) } } } @@ -1150,40 +1156,40 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz else "" - partialOrdCase = \{ name: tagName }, index -> - if Some (Num.intCast index) == nullTagIndex then + partial_ord_case = \{ name: tag_name }, index -> + if Some(Num.int_cast(index)) == null_tag_index then """ - $(tagName) => std::cmp::Ordering::Equal, + $(tag_name) => std::cmp::Ordering::Equal, """ else """ - $(tagName) => { + $(tag_name) => { let payload_union1 = unsafe { self.ptr_read_union() }; let payload_union2 = unsafe { other.ptr_read_union() }; unsafe { - payload_union1.$(tagName).cmp(&payload_union2.$(tagName)) + payload_union1.$(tag_name).cmp(&payload_union2.$(tag_name)) } }, """ - partialOrdCases = + partial_ord_cases = tags - |> List.mapWithIndex partialOrdCase - |> Str.joinWith "\n" + |> List.map_with_index(partial_ord_case) + |> Str.join_with("\n") - partialOrdImpl = - if canSupportPartialEqOrd types (Types.shape types id) then + partial_ord_impl = + if can_support_partial_eq_ord(types, Types.shape(types, id)) then """ - impl PartialOrd for $(escapedName) { + impl PartialOrd for $(escaped_name) { fn partial_cmp(&self, other: &Self) -> Option { Some(::cmp(self, other)) } } - impl Ord for $(escapedName) { + impl Ord for $(escaped_name) { fn cmp(&self, other: &Self) -> std::cmp::Ordering { - use discriminant_$(escapedName)::*; + use discriminant_$(escaped_name)::*; use std::cmp::Ordering::*; @@ -1192,7 +1198,7 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz Greater => Greater, Equal => unsafe { match self.discriminant() { - $(partialOrdCases) + $(partial_ord_cases) } }, } @@ -1202,29 +1208,29 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz else "" - sizeOfSelf = Num.toStr (Types.size types id) - alignOfSelf = Num.toStr (Types.alignment types id) + size_of_self = Num.to_str(Types.size(types, id)) + align_of_self = Num.to_str(Types.alignment(types, id)) buf - |> generateDiscriminant types discriminantName tagNames discriminantSize - |> Str.concat + |> generate_discriminant(types, discriminant_name, tag_names, discriminant_size) + |> Str.concat( """ #[repr(transparent)] - pub struct $(escapedName)(*mut $(unionName)); + pub struct $(escaped_name)(*mut $(union_name)); - const _SIZE_CHECK_$(escapedName): () = assert!(core::mem::size_of::<$(escapedName)>() == $(sizeOfSelf)); - const _ALIGN_CHECK_$(escapedName): () = assert!(core::mem::align_of::<$(escapedName)>() == $(alignOfSelf)); + const _SIZE_CHECK_$(escaped_name): () = assert!(core::mem::size_of::<$(escaped_name)>() == $(size_of_self)); + const _ALIGN_CHECK_$(escaped_name): () = assert!(core::mem::align_of::<$(escaped_name)>() == $(align_of_self)); - impl $(escapedName) { - pub fn discriminant(&self) -> discriminant_$(escapedName) { + impl $(escaped_name) { + pub fn discriminant(&self) -> discriminant_$(escaped_name) { let discriminants = { - use $(discriminantName)::*; + use $(discriminant_name)::*; $(discriminants) }; if self.0.is_null() { - $(nullTagId) + $(null_tag_id) } else { match std::mem::size_of::() { 4 => discriminants[self.0 as usize & 0b011], @@ -1234,7 +1240,7 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz } } - fn unmasked_pointer(&self) -> *mut union_$(escapedName) { + fn unmasked_pointer(&self) -> *mut union_$(escaped_name) { debug_assert!(!self.0.is_null()); let mask = match std::mem::size_of::() { @@ -1243,10 +1249,10 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz _ => unreachable!(), }; - ((self.0 as usize) & mask) as *mut union_$(escapedName) + ((self.0 as usize) & mask) as *mut union_$(escaped_name) } - unsafe fn ptr_read_union(&self) -> core::mem::ManuallyDrop { + unsafe fn ptr_read_union(&self) -> core::mem::ManuallyDrop { let ptr = self.unmasked_pointer(); core::mem::ManuallyDrop::new(unsafe { std::ptr::read(ptr) }) @@ -1255,184 +1261,185 @@ generateRecursiveTagUnion = \buf, types, id, tagUnionName, tags, discriminantSiz $(constructors) } - impl Clone for $(escapedName) { + impl Clone for $(escaped_name) { fn clone(&self) -> Self { - use discriminant_$(escapedName)::*; + use discriminant_$(escaped_name)::*; let discriminant = self.discriminant(); match discriminant { - $(cloneCases) + $(clone_cases) } } } - $(partialEqImpl) + $(partial_eq_impl) - $(hashImpl) + $(hash_impl) - $(partialOrdImpl) + $(partial_ord_impl) - impl core::fmt::Debug for $(escapedName) { + impl core::fmt::Debug for $(escaped_name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - use discriminant_$(escapedName)::*; + use discriminant_$(escaped_name)::*; match self.discriminant() { - $(debugCases) + $(debug_cases) } } } #[repr(C)] - union $(unionName) { - """ - |> \b -> List.walk tags b (generateUnionField types) - |> Str.concat "}\n\n" - |> generateRocRefcounted types unionType escapedName - -generateTagUnionDropPayload = \buf, types, selfMut, tags, discriminantName, discriminantSize, indents -> - if discriminantSize == 0 then - when List.first tags is - Ok { name } -> + union $(union_name) { + """, + ) + |> \b -> List.walk(tags, b, generate_union_field(types)) + |> Str.concat("}\n\n") + |> generate_roc_refcounted(types, union_type, escaped_name) + +generate_tag_union_drop_payload = \buf, types, self_mut, tags, discriminant_name, discriminant_size, indents -> + if discriminant_size == 0 then + when List.first(tags) is + Ok({ name }) -> # There's only one tag, so there's no discriminant and no need to match; # just drop the pointer. buf - |> writeIndents indents - |> Str.concat "unsafe { core::mem::ManuallyDrop::drop(&mut core::ptr::read(self.pointer).$(name)); }" + |> write_indents(indents) + |> Str.concat("unsafe { core::mem::ManuallyDrop::drop(&mut core::ptr::read(self.pointer).$(name)); }") - Err ListWasEmpty -> - crash "unreachable" + Err(ListWasEmpty) -> + crash("unreachable") else buf - |> writeTagImpls tags discriminantName indents \name, payload -> + |> write_tag_impls(tags, discriminant_name, indents, \name, payload -> when payload is - Some id if cannotSupportCopy types (Types.shape types id) -> - "unsafe { core::mem::ManuallyDrop::drop(&mut $(selfMut).payload.$(name)) }," + Some(id) if cannot_support_copy(types, Types.shape(types, id)) -> + "unsafe { core::mem::ManuallyDrop::drop(&mut $(self_mut).payload.$(name)) }," _ -> # If it had no payload, or if the payload had no pointers, # there's nothing to clean up, so do `=> {}` for the branch. - "{}" + "{}") -writeIndents = \buf, indents -> +write_indents = \buf, indents -> if indents <= 0 then buf else buf - |> Str.concat indent - |> writeIndents (indents - 1) + |> Str.concat(indent) + |> write_indents((indents - 1)) -writeTagImpls : Str, List { name : Str, payload : [Some TypeId, None] }, Str, U64, (Str, [Some TypeId, None] -> Str) -> Str -writeTagImpls = \buf, tags, discriminantName, indents, f -> +write_tag_impls : Str, List { name : Str, payload : [Some TypeId, None] }, Str, U64, (Str, [Some TypeId, None] -> Str) -> Str +write_tag_impls = \buf, tags, discriminant_name, indents, f -> buf - |> writeIndents indents - |> Str.concat "match self.discriminant() {\n" - |> \b -> List.walk tags b \accum, { name, payload } -> - branchStr = f name payload + |> write_indents(indents) + |> Str.concat("match self.discriminant() {\n") + |> \b -> + List.walk(tags, b, \accum, { name, payload } -> + branch_str = f(name, payload) accum - |> writeIndents (indents + 1) - |> Str.concat "$(discriminantName)::$(name) => $(branchStr)\n" - |> writeIndents indents - |> Str.concat "}\n" + |> write_indents((indents + 1)) + |> Str.concat("$(discriminant_name)::$(name) => $(branch_str)\n")) + |> write_indents(indents) + |> Str.concat("}\n") -generateDiscriminant = \buf, types, name, tags, size -> +generate_discriminant = \buf, types, name, tags, size -> if size > 0 then - enumType = - TagUnion - ( - Enumeration { - name, - tags, - size, - } - ) + enum_type = + TagUnion( + Enumeration({ + name, + tags, + size, + }), + ) buf - |> generateEnumeration types enumType name tags size + |> generate_enumeration(types, enum_type, name, tags, size) else buf -generateUnionField = \types -> - \accum, { name: fieldName, payload } -> - escapedFieldName = escapeKW fieldName +generate_union_field = \types -> + \accum, { name: field_name, payload } -> + escaped_field_name = escape_kw(field_name) when payload is - Some id -> - typeStr = typeName types id + Some(id) -> + type_str = type_name(types, id) - type = Types.shape types id - fullTypeStr = - if cannotSupportCopy types type then + type = Types.shape(types, id) + full_type_str = + if cannot_support_copy(types, type) then # types with pointers need ManuallyDrop # because rust unions don't (and can't) # know how to drop them automatically! - "core::mem::ManuallyDrop<$(typeStr)>" + "core::mem::ManuallyDrop<$(type_str)>" else - typeStr + type_str - Str.concat accum "$(indent)$(escapedFieldName): $(fullTypeStr),\n" + Str.concat(accum, "$(indent)$(escaped_field_name): $(full_type_str),\n") None -> # use unit as the payload - Str.concat accum "$(indent)$(escapedFieldName): (),\n" + Str.concat(accum, "$(indent)$(escaped_field_name): (),\n") -commaSeparated : Str, List a, (a, U64 -> Str) -> Str -commaSeparated = \buf, items, step -> +comma_separated : Str, List a, (a, U64 -> Str) -> Str +comma_separated = \buf, items, step -> - length = List.len items |> Num.intCast + length = List.len(items) |> Num.int_cast help : { buf : Str, count : U64 }, a -> { buf : Str, count : U64 } help = \accum, item -> if accum.count + 1 == length then - { buf: Str.concat accum.buf (step item accum.count), count: length } + { buf: Str.concat(accum.buf, step(item, accum.count)), count: length } else - { buf: Str.concat accum.buf (step item accum.count) |> Str.concat ", ", count: accum.count + 1 } + { buf: Str.concat(accum.buf, step(item, accum.count)) |> Str.concat(", "), count: accum.count + 1 } items - |> List.walk { buf, count: 0 } help + |> List.walk({ buf, count: 0 }, help) |> .buf -generateNullableUnwrapped : Str, Types, TypeId, Str, Str, Str, TypeId, [FirstTagIsNull, SecondTagIsNull] -> Str -generateNullableUnwrapped = \buf, types, tagUnionid, name, nullTag, nonNullTag, nonNullPayload, whichTagIsNull -> - payloadFields = - when Types.shape types nonNullPayload is - TagUnionPayload { fields } -> +generate_nullable_unwrapped : Str, Types, TypeId, Str, Str, Str, TypeId, [FirstTagIsNull, SecondTagIsNull] -> Str +generate_nullable_unwrapped = \buf, types, tag_unionid, name, null_tag, non_null_tag, non_null_payload, which_tag_is_null -> + payload_fields = + when Types.shape(types, non_null_payload) is + TagUnionPayload({ fields }) -> when fields is - HasNoClosure xs -> List.map xs .id - HasClosure xs -> List.map xs .id + HasNoClosure(xs) -> List.map(xs, .id) + HasClosure(xs) -> List.map(xs, .id) _ -> [] - payloadFieldNames = - commaSeparated "" payloadFields \_, i -> - n = Num.toStr i - "f$(n)" - - constructorArguments = - commaSeparated "" payloadFields \id, i -> - n = Num.toStr i - type = typeName types id - "f$(n): $(type)" - - debugFields = - payloadFields - |> List.mapWithIndex \_, i -> - n = Num.toStr i - ".field(&node.f$(n))" - |> Str.joinWith "" - - unionType = TagUnion (NullableUnwrapped { name, nullTag, nonNullTag, nonNullPayload, whichTagIsNull }) + payload_field_names = + comma_separated("", payload_fields, \_, i -> + n = Num.to_str(i) + "f$(n)") + + constructor_arguments = + comma_separated("", payload_fields, \id, i -> + n = Num.to_str(i) + type = type_name(types, id) + "f$(n): $(type)") + + debug_fields = + payload_fields + |> List.map_with_index(\_, i -> + n = Num.to_str(i) + ".field(&node.f$(n))") + |> Str.join_with("") + + union_type = TagUnion(NullableUnwrapped({ name, null_tag, non_null_tag, non_null_payload, which_tag_is_null })) discriminant = - when whichTagIsNull is + when which_tag_is_null is FirstTagIsNull -> """ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum discriminant_$(name) { - $(nullTag) = 0, - $(nonNullTag) = 1, + $(null_tag) = 0, + $(non_null_tag) = 1, } """ @@ -1440,33 +1447,33 @@ generateNullableUnwrapped = \buf, types, tagUnionid, name, nullTag, nonNullTag, """ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum discriminant_$(name) { - $(nonNullTag) = 0, - $(nullTag) = 1, + $(non_null_tag) = 0, + $(null_tag) = 1, } """ - sizeOfSelf = Num.toStr (Types.size types tagUnionid) - alignOfSelf = Num.toStr (Types.alignment types tagUnionid) + size_of_self = Num.to_str(Types.size(types, tag_unionid)) + align_of_self = Num.to_str(Types.alignment(types, tag_unionid)) """ $(buf) #[derive(PartialOrd, Ord)] #[repr(C)] - pub struct $(name)(*mut $(name)_$(nonNullTag)); + pub struct $(name)(*mut $(name)_$(non_null_tag)); $(discriminant) - const _SIZE_CHECK_$(name): () = assert!(core::mem::size_of::<$(name)>() == $(sizeOfSelf)); - const _ALIGN_CHECK_$(name): () = assert!(core::mem::align_of::<$(name)>() == $(alignOfSelf)); + const _SIZE_CHECK_$(name): () = assert!(core::mem::size_of::<$(name)>() == $(size_of_self)); + const _ALIGN_CHECK_$(name): () = assert!(core::mem::align_of::<$(name)>() == $(align_of_self)); impl $(name) { - pub fn $(nullTag)() -> Self { + pub fn $(null_tag)() -> Self { Self(core::ptr::null_mut()) } - pub fn $(nonNullTag)($(constructorArguments)) -> Self { - let payload = $(name)_$(nonNullTag) { $(payloadFieldNames) }; + pub fn $(non_null_tag)($(constructor_arguments)) -> Self { + let payload = $(name)_$(non_null_tag) { $(payload_field_names) }; let ptr = unsafe { roc_std::RocBox::leak(roc_std::RocBox::new(payload)) }; @@ -1474,42 +1481,42 @@ generateNullableUnwrapped = \buf, types, tagUnionid, name, nullTag, nonNullTag, } pub fn discriminant(&self) -> discriminant_$(name) { - if self.is_$(nullTag)() { - discriminant_$(name)::$(nullTag) + if self.is_$(null_tag)() { + discriminant_$(name)::$(null_tag) } else { - discriminant_$(name)::$(nonNullTag) + discriminant_$(name)::$(non_null_tag) } } - pub fn is_$(nullTag)(&self) -> bool { + pub fn is_$(null_tag)(&self) -> bool { self.0.is_null() } - pub fn is_$(nonNullTag)(&self) -> bool { + pub fn is_$(non_null_tag)(&self) -> bool { !self.0.is_null() } } impl core::fmt::Debug for $(name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - if self.is_$(nullTag)() { - f.debug_tuple("$(name)::$(nullTag)").finish() + if self.is_$(null_tag)() { + f.debug_tuple("$(name)::$(null_tag)").finish() } else { let node = core::mem::ManuallyDrop::new(unsafe { std::ptr::read(self.0) }); - f.debug_tuple("$(name)::$(nonNullTag)")$(debugFields).finish() + f.debug_tuple("$(name)::$(non_null_tag)")$(debug_fields).finish() } } } impl Clone for $(name) { fn clone(&self) -> Self { - if self.is_$(nullTag)() { - Self::$(nullTag)() + if self.is_$(null_tag)() { + Self::$(null_tag)() } else { use std::ops::Deref; let node_ref = core::mem::ManuallyDrop::new(unsafe { std::ptr::read(self.0) }); - let payload : $(name)_$(nonNullTag) = (node_ref.deref()).clone(); + let payload : $(name)_$(non_null_tag) = (node_ref.deref()).clone(); let ptr = unsafe { roc_std::RocBox::leak(roc_std::RocBox::new(payload)) }; @@ -1524,7 +1531,7 @@ generateNullableUnwrapped = \buf, types, tagUnionid, name, nullTag, nonNullTag, return false; } - if self.is_$(nullTag)() { + if self.is_$(null_tag)() { return true; } @@ -1541,448 +1548,455 @@ generateNullableUnwrapped = \buf, types, tagUnionid, name, nullTag, nonNullTag, fn hash(&self, state: &mut H) { self.discriminant().hash(state); - if self.is_$(nonNullTag)() { + if self.is_$(non_null_tag)() { let payload = core::mem::ManuallyDrop::new(unsafe { std::ptr::read(self.0) }); payload.hash(state); } } } """ - |> generateRocRefcounted types unionType name + |> generate_roc_refcounted(types, union_type, name) -generateSingleTagStruct = \buf, types, name, tagName, payload -> +generate_single_tag_struct = \buf, types, name, tag_name, payload -> # Store single-tag unions as structs rather than enums, # because they have only one alternative. However, still # offer the usual tag union APIs. - escapedName = escapeKW name + escaped_name = escape_kw(name) repr = length = when payload is - HasClosure fields -> List.len fields - HasNoClosure fields -> List.len fields + HasClosure(fields) -> List.len(fields) + HasNoClosure(fields) -> List.len(fields) if length <= 1 then "transparent" else "C" when payload is - HasNoClosure fields -> - asStructFields = - List.mapWithIndex fields \{ id }, index -> - indexStr = Num.toStr index + HasNoClosure(fields) -> + as_struct_fields = + List.map_with_index(fields, \{ id }, index -> + index_str = Num.to_str(index) - { name: "f$(indexStr)", id } + { name: "f$(index_str)", id }) |> HasNoClosure - asStructType = - Struct { + as_struct_type = + Struct({ name, - fields: asStructFields, - } + fields: as_struct_fields, + }) buf - |> generateDeriveStr types asStructType ExcludeDebug - |> Str.concat "#[repr($(repr))]\npub struct $(escapedName) " + |> generate_derive_str(types, as_struct_type, ExcludeDebug) + |> Str.concat("#[repr($(repr))]\npub struct $(escaped_name) ") |> \b -> - if List.isEmpty fields then - generateZeroElementSingleTagStruct b escapedName tagName + if List.is_empty(fields) then + generate_zero_element_single_tag_struct(b, escaped_name, tag_name) else - generateMultiElementSingleTagStruct b types escapedName tagName fields asStructFields - |> generateRocRefcounted types (TagUnion (SingleTagStruct { name, tagName, payload })) escapedName + generate_multi_element_single_tag_struct(b, types, escaped_name, tag_name, fields, as_struct_fields) + |> generate_roc_refcounted(types, TagUnion(SingleTagStruct({ name, tag_name, payload })), escaped_name) - HasClosure _ -> - Str.concat buf "\\TODO: SingleTagStruct with closures" + HasClosure(_) -> + Str.concat(buf, "\\TODO: SingleTagStruct with closures") -generateMultiElementSingleTagStruct = \buf, types, name, tagName, payloadFields, asStructFields -> +generate_multi_element_single_tag_struct = \buf, types, name, tag_name, payload_fields, as_struct_fields -> buf - |> Str.concat "{\n" - |> generateStructFields types Private asStructFields - |> Str.concat "}\n\n" - |> Str.concat + |> Str.concat("{\n") + |> generate_struct_fields(types, Private, as_struct_fields) + |> Str.concat("}\n\n") + |> Str.concat( """ impl $(name) { - """ + """, + ) |> \b -> - fieldTypes = - payloadFields - |> List.map \{ id } -> - typeName types id + field_types = + payload_fields + |> List.map(\{ id } -> + type_name(types, id)) args = - fieldTypes - |> List.mapWithIndex \fieldTypeName, index -> - indexStr = Num.toStr index + field_types + |> List.map_with_index(\field_type_name, index -> + index_str = Num.to_str(index) - "f$(indexStr): $(fieldTypeName)" + "f$(index_str): $(field_type_name)") fields = - payloadFields - |> List.mapWithIndex \_, index -> - indexStr = Num.toStr index + payload_fields + |> List.map_with_index(\_, index -> + index_str = Num.to_str(index) - "f$(indexStr)" + "f$(index_str)") - fieldAccesses = + field_accesses = fields - |> List.map \field -> - "self.$(field)" + |> List.map(\field -> + "self.$(field)") { b, args, fields, - fieldTypes, - fieldAccesses, + field_types, + field_accesses, } - |> \{ b, args, fields, fieldTypes, fieldAccesses } -> - argsStr = Str.joinWith args ", " - fieldsStr = Str.joinWith fields ",\n$(indent)$(indent)$(indent)" + |> \{ b, args, fields, field_types, field_accesses } -> + args_str = Str.join_with(args, ", ") + fields_str = Str.join_with(fields, ",\n$(indent)$(indent)$(indent)") { - b: Str.concat - b + b: Str.concat( + b, """ - $(indent)/// A tag named ``$(tagName)``, with the given payload. - $(indent)pub fn $(tagName)($(argsStr)) -> Self { + $(indent)/// A tag named ``$(tag_name)``, with the given payload. + $(indent)pub fn $(tag_name)($(args_str)) -> Self { $(indent) Self { - $(indent) $(fieldsStr) + $(indent) $(fields_str) $(indent) } $(indent)} """, - fieldTypes, - fieldAccesses, + ), + field_types, + field_accesses, } - |> \{ b, fieldTypes, fieldAccesses } -> - retType = asRustTuple fieldTypes - retExpr = asRustTuple fieldAccesses + |> \{ b, field_types, field_accesses } -> + ret_type = as_rust_tuple(field_types) + ret_expr = as_rust_tuple(field_accesses) { - b: Str.concat - b + b: Str.concat( + b, """ - $(indent)/// Since `$(name)` only has one tag (namely, `$(tagName)`), - $(indent)/// convert it to `$(tagName)`'s payload. - $(indent)pub fn into_$(tagName)(self) -> $(retType) { - $(indent) $(retExpr) + $(indent)/// Since `$(name)` only has one tag (namely, `$(tag_name)`), + $(indent)/// convert it to `$(tag_name)`'s payload. + $(indent)pub fn into_$(tag_name)(self) -> $(ret_type) { + $(indent) $(ret_expr) $(indent)} """, - fieldTypes, - fieldAccesses, + ), + field_types, + field_accesses, } - |> \{ b, fieldTypes, fieldAccesses } -> - retType = - fieldTypes - |> List.map \ft -> "&$(ft)" - |> asRustTuple - retExpr = - fieldAccesses - |> List.map \fa -> "&$(fa)" - |> asRustTuple - - Str.concat - b + |> \{ b, field_types, field_accesses } -> + ret_type = + field_types + |> List.map(\ft -> "&$(ft)") + |> as_rust_tuple + ret_expr = + field_accesses + |> List.map(\fa -> "&$(fa)") + |> as_rust_tuple + + Str.concat( + b, """ - $(indent)/// Since `$(name)` only has one tag (namely, `$(tagName)`), - $(indent)/// convert it to `$(tagName)`'s payload. - $(indent)pub fn as_$(tagName)(&self) -> $(retType) { - $(indent) $(retExpr) + $(indent)/// Since `$(name)` only has one tag (namely, `$(tag_name)`), + $(indent)/// convert it to `$(tag_name)`'s payload. + $(indent)pub fn as_$(tag_name)(&self) -> $(ret_type) { + $(indent) $(ret_expr) $(indent)} - """ - |> Str.concat + """, + ) + |> Str.concat( """ } impl core::fmt::Debug for $(name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_tuple("$(name)::$(tagName)") + f.debug_tuple("$(name)::$(tag_name)") - """ + """, + ) |> \b -> - payloadFields - |> List.mapWithIndex \_, index -> - indexStr = Num.toStr index + payload_fields + |> List.map_with_index(\_, index -> + index_str = Num.to_str(index) - "$(indent)$(indent)$(indent)$(indent).field(&self.f$(indexStr))\n" - |> List.walk b Str.concat - |> Str.concat + "$(indent)$(indent)$(indent)$(indent).field(&self.f$(index_str))\n") + |> List.walk(b, Str.concat) + |> Str.concat( """ .finish() } } - """ + """, + ) -asRustTuple = \list -> +as_rust_tuple = \list -> # If there is 1 element in the list we just return it # Otherwise, we make a proper tuple string. - joined = Str.joinWith list ", " + joined = Str.join_with(list, ", ") - if List.len list == 1 then + if List.len(list) == 1 then joined else "($(joined))" -generateZeroElementSingleTagStruct = \buf, name, tagName -> +generate_zero_element_single_tag_struct = \buf, name, tag_name -> # A single tag with no payload is a zero-sized unit type, so # represent it as a zero-sized struct (e.g. "struct Foo()"). buf - |> Str.concat "();\n\n" - |> Str.concat + |> Str.concat("();\n\n") + |> Str.concat( """ impl $(name) { - /// A tag named $(tagName), which has no payload. - pub const $(tagName): Self = Self(); + /// A tag named $(tag_name), which has no payload. + pub const $(tag_name): Self = Self(); - /// Other `into_` methods return a payload, but since $(tagName) tag + /// Other `into_` methods return a payload, but since $(tag_name) tag /// has no payload, this does nothing and is only here for completeness. - pub fn into_$(tagName)(self) { + pub fn into_$(tag_name)(self) { () } - /// Other `as_` methods return a payload, but since $(tagName) tag + /// Other `as_` methods return a payload, but since $(tag_name) tag /// has no payload, this does nothing and is only here for completeness. - pub fn as_$(tagName)(&self) { + pub fn as_$(tag_name)(&self) { () } } impl core::fmt::Debug for $(name) { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("$(name)::$(tagName)") + f.write_str("$(name)::$(tag_name)") } } - """ + """, + ) -generateDeriveStr = \buf, types, type, includeDebug -> - condWrite = \b, cond, str -> +generate_derive_str = \buf, types, type, include_debug -> + cond_write = \b, cond, str -> if cond then - Str.concat b str + Str.concat(b, str) else b - deriveDebug = - when includeDebug is + derive_debug = + when include_debug is IncludeDebug -> Bool.true ExcludeDebug -> Bool.false buf - |> Str.concat "#[derive(Clone, " - |> condWrite (!(cannotSupportCopy types type)) "Copy, " - |> condWrite (!(cannotSupportDefault types type)) "Default, " - |> condWrite deriveDebug "Debug, " - |> condWrite (canSupportPartialEqOrd types type) "PartialEq, PartialOrd, " - |> condWrite (canSupportEqHashOrd types type) "Eq, Ord, Hash, " - |> Str.concat ")]\n" - -canSupportEqHashOrd : Types, Shape -> Bool -canSupportEqHashOrd = \types, type -> - !(hasFloat types type) && (canSupportPartialEqOrd types type) - -canSupportPartialEqOrd : Types, Shape -> Bool -canSupportPartialEqOrd = \types, type -> + |> Str.concat("#[derive(Clone, ") + |> cond_write(!(cannot_support_copy(types, type)), "Copy, ") + |> cond_write(!(cannot_support_default(types, type)), "Default, ") + |> cond_write(derive_debug, "Debug, ") + |> cond_write(can_support_partial_eq_ord(types, type), "PartialEq, PartialOrd, ") + |> cond_write(can_support_eq_hash_ord(types, type), "Eq, Ord, Hash, ") + |> Str.concat(")]\n") + +can_support_eq_hash_ord : Types, Shape -> Bool +can_support_eq_hash_ord = \types, type -> + !(has_float(types, type)) && (can_support_partial_eq_ord(types, type)) + +can_support_partial_eq_ord : Types, Shape -> Bool +can_support_partial_eq_ord = \types, type -> when type is - Function rocFn -> - runtimeRepresentation = Types.shape types rocFn.lambdaSet - canSupportPartialEqOrd types runtimeRepresentation + Function(roc_fn) -> + runtime_representation = Types.shape(types, roc_fn.lambda_set) + can_support_partial_eq_ord(types, runtime_representation) Unsized -> Bool.false - Unit | EmptyTagUnion | Bool | Num _ | TagUnion (Enumeration _) -> Bool.true + Unit | EmptyTagUnion | Bool | Num(_) | TagUnion(Enumeration(_)) -> Bool.true RocStr -> Bool.true - RocList inner | RocSet inner | RocBox inner -> - innerType = Types.shape types inner - canSupportPartialEqOrd types innerType + RocList(inner) | RocSet(inner) | RocBox(inner) -> + inner_type = Types.shape(types, inner) + can_support_partial_eq_ord(types, inner_type) - RocDict k v -> - kType = Types.shape types k - vType = Types.shape types v + RocDict(k, v) -> + k_type = Types.shape(types, k) + v_type = Types.shape(types, v) - canSupportPartialEqOrd types kType && canSupportPartialEqOrd types vType + can_support_partial_eq_ord(types, k_type) && can_support_partial_eq_ord(types, v_type) - TagUnion (Recursive { tags }) -> - List.all tags \{ payload } -> + TagUnion(Recursive({ tags })) -> + List.all(tags, \{ payload } -> when payload is None -> Bool.true - Some id -> canSupportPartialEqOrd types (Types.shape types id) + Some(id) -> can_support_partial_eq_ord(types, Types.shape(types, id))) - TagUnion (NullableWrapped { tags }) -> - List.all tags \{ payload } -> + TagUnion(NullableWrapped({ tags })) -> + List.all(tags, \{ payload } -> when payload is None -> Bool.true - Some id -> canSupportPartialEqOrd types (Types.shape types id) + Some(id) -> can_support_partial_eq_ord(types, Types.shape(types, id))) - TagUnion (NonNullableUnwrapped { payload }) -> - canSupportPartialEqOrd types (Types.shape types payload) + TagUnion(NonNullableUnwrapped({ payload })) -> + can_support_partial_eq_ord(types, Types.shape(types, payload)) - TagUnion (NullableUnwrapped { nonNullPayload }) -> - canSupportPartialEqOrd types (Types.shape types nonNullPayload) + TagUnion(NullableUnwrapped({ non_null_payload })) -> + can_support_partial_eq_ord(types, Types.shape(types, non_null_payload)) - RecursivePointer _ -> Bool.true - TagUnion (SingleTagStruct { payload: HasNoClosure fields }) -> - List.all fields \{ id } -> canSupportPartialEqOrd types (Types.shape types id) + RecursivePointer(_) -> Bool.true + TagUnion(SingleTagStruct({ payload: HasNoClosure(fields) })) -> + List.all(fields, \{ id } -> can_support_partial_eq_ord(types, Types.shape(types, id))) - TagUnion (SingleTagStruct { payload: HasClosure _ }) -> + TagUnion(SingleTagStruct({ payload: HasClosure(_) })) -> Bool.false - TagUnion (NonRecursive { tags }) -> - List.all tags \{ payload } -> + TagUnion(NonRecursive({ tags })) -> + List.all(tags, \{ payload } -> when payload is - Some id -> canSupportPartialEqOrd types (Types.shape types id) - None -> Bool.true + Some(id) -> can_support_partial_eq_ord(types, Types.shape(types, id)) + None -> Bool.true) - RocResult okId errId -> - okShape = Types.shape types okId - errShape = Types.shape types errId + RocResult(ok_id, err_id) -> + ok_shape = Types.shape(types, ok_id) + err_shape = Types.shape(types, err_id) - canSupportPartialEqOrd types okShape && canSupportPartialEqOrd types errShape + can_support_partial_eq_ord(types, ok_shape) && can_support_partial_eq_ord(types, err_shape) - Struct { fields: HasNoClosure fields } | TagUnionPayload { fields: HasNoClosure fields } -> - List.all fields \{ id } -> canSupportPartialEqOrd types (Types.shape types id) + Struct({ fields: HasNoClosure(fields) }) | TagUnionPayload({ fields: HasNoClosure(fields) }) -> + List.all(fields, \{ id } -> can_support_partial_eq_ord(types, Types.shape(types, id))) - Struct { fields: HasClosure fields } | TagUnionPayload { fields: HasClosure fields } -> - List.all fields \{ id } -> canSupportPartialEqOrd types (Types.shape types id) + Struct({ fields: HasClosure(fields) }) | TagUnionPayload({ fields: HasClosure(fields) }) -> + List.all(fields, \{ id } -> can_support_partial_eq_ord(types, Types.shape(types, id))) -cannotSupportCopy : Types, Shape -> Bool -cannotSupportCopy = \types, type -> - !(canDeriveCopy types type) +cannot_support_copy : Types, Shape -> Bool +cannot_support_copy = \types, type -> + !(can_derive_copy(types, type)) -canDeriveCopy : Types, Shape -> Bool -canDeriveCopy = \types, type -> +can_derive_copy : Types, Shape -> Bool +can_derive_copy = \types, type -> when type is - Function rocFn -> - runtimeRepresentation = Types.shape types rocFn.lambdaSet - canDeriveCopy types runtimeRepresentation + Function(roc_fn) -> + runtime_representation = Types.shape(types, roc_fn.lambda_set) + can_derive_copy(types, runtime_representation) # unsized values are heap-allocated Unsized -> Bool.false - Unit | EmptyTagUnion | Bool | Num _ | TagUnion (Enumeration _) -> Bool.true - RocStr | RocList _ | RocDict _ _ | RocSet _ | RocBox _ | TagUnion (NullableUnwrapped _) | TagUnion (NullableWrapped _) | TagUnion (Recursive _) | TagUnion (NonNullableUnwrapped _) | RecursivePointer _ -> Bool.false - TagUnion (SingleTagStruct { payload: HasNoClosure fields }) -> - List.all fields \{ id } -> canDeriveCopy types (Types.shape types id) + Unit | EmptyTagUnion | Bool | Num(_) | TagUnion(Enumeration(_)) -> Bool.true + RocStr | RocList(_) | RocDict(_, _) | RocSet(_) | RocBox(_) | TagUnion(NullableUnwrapped(_)) | TagUnion(NullableWrapped(_)) | TagUnion(Recursive(_)) | TagUnion(NonNullableUnwrapped(_)) | RecursivePointer(_) -> Bool.false + TagUnion(SingleTagStruct({ payload: HasNoClosure(fields) })) -> + List.all(fields, \{ id } -> can_derive_copy(types, Types.shape(types, id))) - TagUnion (SingleTagStruct { payload: HasClosure fields }) -> - List.all fields \{ id } -> canDeriveCopy types (Types.shape types id) + TagUnion(SingleTagStruct({ payload: HasClosure(fields) })) -> + List.all(fields, \{ id } -> can_derive_copy(types, Types.shape(types, id))) - TagUnion (NonRecursive { tags }) -> - List.all tags \{ payload } -> + TagUnion(NonRecursive({ tags })) -> + List.all(tags, \{ payload } -> when payload is - Some id -> canDeriveCopy types (Types.shape types id) - None -> Bool.true + Some(id) -> can_derive_copy(types, Types.shape(types, id)) + None -> Bool.true) - RocResult okId errId -> - canDeriveCopy types (Types.shape types okId) - && canDeriveCopy types (Types.shape types errId) + RocResult(ok_id, err_id) -> + can_derive_copy(types, Types.shape(types, ok_id)) + && can_derive_copy(types, Types.shape(types, err_id)) - Struct { fields: HasNoClosure fields } | TagUnionPayload { fields: HasNoClosure fields } -> - List.all fields \{ id } -> canDeriveCopy types (Types.shape types id) + Struct({ fields: HasNoClosure(fields) }) | TagUnionPayload({ fields: HasNoClosure(fields) }) -> + List.all(fields, \{ id } -> can_derive_copy(types, Types.shape(types, id))) - Struct { fields: HasClosure fields } | TagUnionPayload { fields: HasClosure fields } -> - List.all fields \{ id } -> canDeriveCopy types (Types.shape types id) + Struct({ fields: HasClosure(fields) }) | TagUnionPayload({ fields: HasClosure(fields) }) -> + List.all(fields, \{ id } -> can_derive_copy(types, Types.shape(types, id))) -cannotSupportDefault = \types, type -> +cannot_support_default = \types, type -> when type is - Unit | Unsized | EmptyTagUnion | TagUnion _ | RocResult _ _ | RecursivePointer _ | Function _ -> Bool.true - RocStr | Bool | Num _ -> Bool.false - RocList id | RocSet id | RocBox id -> - cannotSupportDefault types (Types.shape types id) + Unit | Unsized | EmptyTagUnion | TagUnion(_) | RocResult(_, _) | RecursivePointer(_) | Function(_) -> Bool.true + RocStr | Bool | Num(_) -> Bool.false + RocList(id) | RocSet(id) | RocBox(id) -> + cannot_support_default(types, Types.shape(types, id)) - TagUnionPayload { fields: HasClosure _ } -> Bool.true - RocDict keyId valId -> - cannotSupportCopy types (Types.shape types keyId) - || cannotSupportCopy types (Types.shape types valId) + TagUnionPayload({ fields: HasClosure(_) }) -> Bool.true + RocDict(key_id, val_id) -> + cannot_support_copy(types, Types.shape(types, key_id)) + || cannot_support_copy(types, Types.shape(types, val_id)) - Struct { fields: HasClosure _ } -> Bool.true - Struct { fields: HasNoClosure fields } | TagUnionPayload { fields: HasNoClosure fields } -> - List.any fields \{ id } -> cannotSupportDefault types (Types.shape types id) + Struct({ fields: HasClosure(_) }) -> Bool.true + Struct({ fields: HasNoClosure(fields) }) | TagUnionPayload({ fields: HasNoClosure(fields) }) -> + List.any(fields, \{ id } -> cannot_support_default(types, Types.shape(types, id))) -hasFloat = \types, type -> - hasFloatHelp types type (Set.empty {}) +has_float = \types, type -> + has_float_help(types, type, Set.empty({})) -hasFloatHelp = \types, type, doNotRecurse -> +has_float_help = \types, type, do_not_recurse -> # TODO: is doNotRecurse problematic? Do we need an updated doNotRecurse for calls up the tree? # I think there is a change it really only matters for RecursivePointer, so it may be fine. # Otherwise we need to deal with threading through updates to doNotRecurse when type is - Num kind -> + Num(kind) -> when kind is F32 | F64 -> Bool.true _ -> Bool.false - Unit | Unsized | EmptyTagUnion | RocStr | Bool | TagUnion (Enumeration _) | Function _ -> Bool.false - RocList id | RocSet id | RocBox id -> - hasFloatHelp types (Types.shape types id) doNotRecurse + Unit | Unsized | EmptyTagUnion | RocStr | Bool | TagUnion(Enumeration(_)) | Function(_) -> Bool.false + RocList(id) | RocSet(id) | RocBox(id) -> + has_float_help(types, Types.shape(types, id), do_not_recurse) - RocDict id0 id1 | RocResult id0 id1 -> - hasFloatHelp types (Types.shape types id0) doNotRecurse - || hasFloatHelp types (Types.shape types id1) doNotRecurse + RocDict(id0, id1) | RocResult(id0, id1) -> + has_float_help(types, Types.shape(types, id0), do_not_recurse) + || has_float_help(types, Types.shape(types, id1), do_not_recurse) - Struct { fields: HasNoClosure fields } | TagUnionPayload { fields: HasNoClosure fields } -> - List.any fields \{ id } -> hasFloatHelp types (Types.shape types id) doNotRecurse + Struct({ fields: HasNoClosure(fields) }) | TagUnionPayload({ fields: HasNoClosure(fields) }) -> + List.any(fields, \{ id } -> has_float_help(types, Types.shape(types, id), do_not_recurse)) - Struct { fields: HasClosure fields } | TagUnionPayload { fields: HasClosure fields } -> - List.any fields \{ id } -> hasFloatHelp types (Types.shape types id) doNotRecurse + Struct({ fields: HasClosure(fields) }) | TagUnionPayload({ fields: HasClosure(fields) }) -> + List.any(fields, \{ id } -> has_float_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (SingleTagStruct { payload: HasNoClosure fields }) -> - List.any fields \{ id } -> hasFloatHelp types (Types.shape types id) doNotRecurse + TagUnion(SingleTagStruct({ payload: HasNoClosure(fields) })) -> + List.any(fields, \{ id } -> has_float_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (SingleTagStruct { payload: HasClosure fields }) -> - List.any fields \{ id } -> hasFloatHelp types (Types.shape types id) doNotRecurse + TagUnion(SingleTagStruct({ payload: HasClosure(fields) })) -> + List.any(fields, \{ id } -> has_float_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (Recursive { tags }) -> - List.any tags \{ payload } -> + TagUnion(Recursive({ tags })) -> + List.any(tags, \{ payload } -> when payload is - Some id -> hasFloatHelp types (Types.shape types id) doNotRecurse - None -> Bool.false + Some(id) -> has_float_help(types, Types.shape(types, id), do_not_recurse) + None -> Bool.false) - TagUnion (NonRecursive { tags }) -> - List.any tags \{ payload } -> + TagUnion(NonRecursive({ tags })) -> + List.any(tags, \{ payload } -> when payload is - Some id -> hasFloatHelp types (Types.shape types id) doNotRecurse - None -> Bool.false + Some(id) -> has_float_help(types, Types.shape(types, id), do_not_recurse) + None -> Bool.false) - TagUnion (NullableWrapped { tags }) -> - List.any tags \{ payload } -> + TagUnion(NullableWrapped({ tags })) -> + List.any(tags, \{ payload } -> when payload is - Some id -> hasFloatHelp types (Types.shape types id) doNotRecurse - None -> Bool.false + Some(id) -> has_float_help(types, Types.shape(types, id), do_not_recurse) + None -> Bool.false) - TagUnion (NonNullableUnwrapped { payload }) -> - if Set.contains doNotRecurse payload then + TagUnion(NonNullableUnwrapped({ payload })) -> + if Set.contains(do_not_recurse, payload) then Bool.false else - nextDoNotRecurse = Set.insert doNotRecurse payload + next_do_not_recurse = Set.insert(do_not_recurse, payload) - hasFloatHelp types (Types.shape types payload) nextDoNotRecurse + has_float_help(types, Types.shape(types, payload), next_do_not_recurse) - TagUnion (NullableUnwrapped { nonNullPayload }) -> - if Set.contains doNotRecurse nonNullPayload then + TagUnion(NullableUnwrapped({ non_null_payload })) -> + if Set.contains(do_not_recurse, non_null_payload) then Bool.false else - nextDoNotRecurse = Set.insert doNotRecurse nonNullPayload + next_do_not_recurse = Set.insert(do_not_recurse, non_null_payload) - hasFloatHelp types (Types.shape types nonNullPayload) nextDoNotRecurse + has_float_help(types, Types.shape(types, non_null_payload), next_do_not_recurse) - RecursivePointer payload -> - if Set.contains doNotRecurse payload then + RecursivePointer(payload) -> + if Set.contains(do_not_recurse, payload) then Bool.false else - nextDoNotRecurse = Set.insert doNotRecurse payload + next_do_not_recurse = Set.insert(do_not_recurse, payload) - hasFloatHelp types (Types.shape types payload) nextDoNotRecurse + has_float_help(types, Types.shape(types, payload), next_do_not_recurse) -generateRocRefcounted = \buf, types, type, escapedName -> - if containsRefcounted types type then +generate_roc_refcounted = \buf, types, type, escaped_name -> + if contains_refcounted(types, type) then impl = when type is - TagUnion (NonNullableUnwrapped _) -> + TagUnion(NonNullableUnwrapped(_)) -> """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { self.0.inc(); } @@ -1995,9 +2009,9 @@ generateRocRefcounted = \buf, types, type, escapedName -> }\n\n """ - TagUnion (Recursive _) -> + TagUnion(Recursive(_)) -> """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { unimplemented!(); } @@ -2008,7 +2022,7 @@ generateRocRefcounted = \buf, types, type, escapedName -> true } }\n\n - impl roc_std::RocRefcounted for union_$(escapedName) { + impl roc_std::RocRefcounted for union_$(escaped_name) { fn inc(&mut self) { unimplemented!(); } @@ -2021,9 +2035,9 @@ generateRocRefcounted = \buf, types, type, escapedName -> }\n\n """ - TagUnion (NullableWrapped _) -> + TagUnion(NullableWrapped(_)) -> """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { unimplemented!(); } @@ -2034,7 +2048,7 @@ generateRocRefcounted = \buf, types, type, escapedName -> true } }\n\n - impl roc_std::RocRefcounted for union_$(escapedName) { + impl roc_std::RocRefcounted for union_$(escaped_name) { fn inc(&mut self) { unimplemented!(); } @@ -2047,16 +2061,16 @@ generateRocRefcounted = \buf, types, type, escapedName -> }\n\n """ - Struct { fields: HasNoClosure fields } -> - incFields = generateRocRefcountedNamedFields types fields Inc Struct - decFields = generateRocRefcountedNamedFields types fields Dec Struct + Struct({ fields: HasNoClosure(fields) }) -> + inc_fields = generate_roc_refcounted_named_fields(types, fields, Inc, Struct) + dec_fields = generate_roc_refcounted_named_fields(types, fields, Dec, Struct) """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { - $(incFields) + $(inc_fields) } fn dec(&mut self) { - $(decFields) + $(dec_fields) } fn is_refcounted() -> bool { true @@ -2064,16 +2078,16 @@ generateRocRefcounted = \buf, types, type, escapedName -> }\n\n """ - TagUnionPayload { fields: HasNoClosure fields } -> - incFields = generateRocRefcountedNamedFields types fields Inc Tag - decFields = generateRocRefcountedNamedFields types fields Dec Tag + TagUnionPayload({ fields: HasNoClosure(fields) }) -> + inc_fields = generate_roc_refcounted_named_fields(types, fields, Inc, Tag) + dec_fields = generate_roc_refcounted_named_fields(types, fields, Dec, Tag) """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { - $(incFields) + $(inc_fields) } fn dec(&mut self) { - $(decFields) + $(dec_fields) } fn is_refcounted() -> bool { true @@ -2083,7 +2097,7 @@ generateRocRefcounted = \buf, types, type, escapedName -> _ -> """ - impl roc_std::RocRefcounted for $(escapedName) { + impl roc_std::RocRefcounted for $(escaped_name) { fn inc(&mut self) { unimplemented!(); } @@ -2095,141 +2109,143 @@ generateRocRefcounted = \buf, types, type, escapedName -> } }\n\n """ - Str.concat - buf - impl + Str.concat( + buf, + impl, + ) else - Str.concat buf "roc_refcounted_noop_impl!($(escapedName));\n\n" + Str.concat(buf, "roc_refcounted_noop_impl!($(escaped_name));\n\n") -generateRocRefcountedNamedFields = \types, fields, mode, wrapper -> - fieldName = \name -> - escapedName = escapeKW name +generate_roc_refcounted_named_fields = \types, fields, mode, wrapper -> + field_name = \name -> + escaped_name = escape_kw(name) when wrapper is - Struct -> escapedName - Tag -> "f$(escapedName)" + Struct -> escaped_name + Tag -> "f$(escaped_name)" - methodName = + method_name = when mode is Inc -> "inc" Dec -> "dec" walker = \accum, { name, id } -> - if containsRefcounted types (Types.shape types id) then - Str.concat - accum - "$(indent) self.$(fieldName name).$(methodName)();\n" + if contains_refcounted(types, Types.shape(types, id)) then + Str.concat( + accum, + "$(indent) self.$(field_name(name)).$(method_name)();\n", + ) else accum - List.walk fields "" walker + List.walk(fields, "", walker) # If a value or any data in it must be refcounted. -containsRefcounted = \types, type -> - containsRefcountedHelp types type (Set.empty {}) +contains_refcounted = \types, type -> + contains_refcounted_help(types, type, Set.empty({})) -containsRefcountedHelp = \types, type, doNotRecurse -> +contains_refcounted_help = \types, type, do_not_recurse -> # TODO: is doNotRecurse problematic? Do we need an updated doNotRecurse for calls up the tree? # I think there is a change it really only matters for RecursivePointer, so it may be fine. # Otherwise we need to deal with threading through updates to doNotRecurse when type is - RocStr | RocList _ | RocSet _ | RocDict _ _ | RocBox _ | RecursivePointer _ -> + RocStr | RocList(_) | RocSet(_) | RocDict(_, _) | RocBox(_) | RecursivePointer(_) -> Bool.true - Unit | Unsized | EmptyTagUnion | Num _ | Bool | TagUnion (Enumeration _) -> + Unit | Unsized | EmptyTagUnion | Num(_) | Bool | TagUnion(Enumeration(_)) -> Bool.false - Function { lambdaSet: id } -> - containsRefcountedHelp types (Types.shape types id) doNotRecurse + Function({ lambda_set: id }) -> + contains_refcounted_help(types, Types.shape(types, id), do_not_recurse) - RocResult id0 id1 -> - containsRefcountedHelp types (Types.shape types id0) doNotRecurse - || containsRefcountedHelp types (Types.shape types id1) doNotRecurse + RocResult(id0, id1) -> + contains_refcounted_help(types, Types.shape(types, id0), do_not_recurse) + || contains_refcounted_help(types, Types.shape(types, id1), do_not_recurse) - Struct { fields: HasNoClosure fields } | TagUnionPayload { fields: HasNoClosure fields } -> - List.any fields \{ id } -> containsRefcountedHelp types (Types.shape types id) doNotRecurse + Struct({ fields: HasNoClosure(fields) }) | TagUnionPayload({ fields: HasNoClosure(fields) }) -> + List.any(fields, \{ id } -> contains_refcounted_help(types, Types.shape(types, id), do_not_recurse)) - Struct { fields: HasClosure fields } | TagUnionPayload { fields: HasClosure fields } -> - List.any fields \{ id } -> containsRefcountedHelp types (Types.shape types id) doNotRecurse + Struct({ fields: HasClosure(fields) }) | TagUnionPayload({ fields: HasClosure(fields) }) -> + List.any(fields, \{ id } -> contains_refcounted_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (SingleTagStruct { payload: HasNoClosure fields }) -> - List.any fields \{ id } -> containsRefcountedHelp types (Types.shape types id) doNotRecurse + TagUnion(SingleTagStruct({ payload: HasNoClosure(fields) })) -> + List.any(fields, \{ id } -> contains_refcounted_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (SingleTagStruct { payload: HasClosure fields }) -> - List.any fields \{ id } -> containsRefcountedHelp types (Types.shape types id) doNotRecurse + TagUnion(SingleTagStruct({ payload: HasClosure(fields) })) -> + List.any(fields, \{ id } -> contains_refcounted_help(types, Types.shape(types, id), do_not_recurse)) - TagUnion (Recursive _) -> Bool.true - TagUnion (NullableWrapped _) -> Bool.true - TagUnion (NonNullableUnwrapped _) -> Bool.true - TagUnion (NullableUnwrapped _) -> Bool.true - TagUnion (NonRecursive { tags }) -> - List.any tags \{ payload } -> + TagUnion(Recursive(_)) -> Bool.true + TagUnion(NullableWrapped(_)) -> Bool.true + TagUnion(NonNullableUnwrapped(_)) -> Bool.true + TagUnion(NullableUnwrapped(_)) -> Bool.true + TagUnion(NonRecursive({ tags })) -> + List.any(tags, \{ payload } -> when payload is - Some id -> containsRefcountedHelp types (Types.shape types id) doNotRecurse - None -> Bool.false + Some(id) -> contains_refcounted_help(types, Types.shape(types, id), do_not_recurse) + None -> Bool.false) -typeName = \types, id -> - when Types.shape types id is +type_name = \types, id -> + when Types.shape(types, id) is Unit -> "()" Unsized -> "roc_std::RocList" EmptyTagUnion -> "std::convert::Infallible" RocStr -> "roc_std::RocStr" Bool -> "bool" - Num U8 -> "u8" - Num U16 -> "u16" - Num U32 -> "u32" - Num U64 -> "u64" - Num U128 -> "u128" - Num I8 -> "i8" - Num I16 -> "i16" - Num I32 -> "i32" - Num I64 -> "i64" - Num I128 -> "i128" - Num F32 -> "f32" - Num F64 -> "f64" - Num Dec -> "roc_std:RocDec" - RocDict _key _value -> - # keyName = typeName types key - # valueName = typeName types value - # "roc_std::RocDict<$(keyName), $(valueName)>" - crash "RocDict is not yet supported in rust" - - RocSet _elem -> - # elemName = typeName types elem - # "roc_std::RocSet<$(elemName)>" - crash "RocSet is not yet supported in rust" - - RocList elem -> - elemName = typeName types elem - - "roc_std::RocList<$(elemName)>" - - RocBox elem -> - elemName = typeName types elem - - "roc_std::RocBox<$(elemName)>" - - RocResult ok err -> - okName = typeName types ok - errName = typeName types err - - "roc_std::RocResult<$(okName), $(errName)>" - - RecursivePointer content -> - typeName types content - - Struct { name } -> escapeKW name - TagUnionPayload { name } -> escapeKW name - TagUnion (NonRecursive { name }) -> escapeKW name - TagUnion (Recursive { name }) -> escapeKW name - TagUnion (Enumeration { name }) -> escapeKW name - TagUnion (NullableWrapped { name }) -> escapeKW name - TagUnion (NullableUnwrapped { name }) -> escapeKW name - TagUnion (NonNullableUnwrapped { name }) -> escapeKW name - TagUnion (SingleTagStruct { name }) -> escapeKW name - Function { functionName } -> escapeKW functionName - -archName = \arch -> + Num(U8) -> "u8" + Num(U16) -> "u16" + Num(U32) -> "u32" + Num(U64) -> "u64" + Num(U128) -> "u128" + Num(I8) -> "i8" + Num(I16) -> "i16" + Num(I32) -> "i32" + Num(I64) -> "i64" + Num(I128) -> "i128" + Num(F32) -> "f32" + Num(F64) -> "f64" + Num(Dec) -> "roc_std:RocDec" + RocDict(_key, _value) -> + # key_name = type_name(types, key) + # value_name = type_name(types, value) + # "roc_std::RocDict<$(key_name), $(value_name)>" + crash("RocDict is not yet supported in rust") + + RocSet(_elem) -> + # elem_name = type_name(types, elem) + # "roc_std::RocSet<$(elem_name)>" + crash("RocSet is not yet supported in rust") + + RocList(elem) -> + elem_name = type_name(types, elem) + + "roc_std::RocList<$(elem_name)>" + + RocBox(elem) -> + elem_name = type_name(types, elem) + + "roc_std::RocBox<$(elem_name)>" + + RocResult(ok, err) -> + ok_name = type_name(types, ok) + err_name = type_name(types, err) + + "roc_std::RocResult<$(ok_name), $(err_name)>" + + RecursivePointer(content) -> + type_name(types, content) + + Struct({ name }) -> escape_kw(name) + TagUnionPayload({ name }) -> escape_kw(name) + TagUnion(NonRecursive({ name })) -> escape_kw(name) + TagUnion(Recursive({ name })) -> escape_kw(name) + TagUnion(Enumeration({ name })) -> escape_kw(name) + TagUnion(NullableWrapped({ name })) -> escape_kw(name) + TagUnion(NullableUnwrapped({ name })) -> escape_kw(name) + TagUnion(NonNullableUnwrapped({ name })) -> escape_kw(name) + TagUnion(SingleTagStruct({ name })) -> escape_kw(name) + Function({ function_name }) -> escape_kw(function_name) + +arch_name = \arch -> when arch is Aarch32 -> "arm" @@ -2246,7 +2262,7 @@ archName = \arch -> X86x64 -> "x86_64" -fileHeader = +file_header = """ // ⚠️ GENERATED CODE ⚠️ - this entire file was generated by the `roc glue` CLI command @@ -2274,9 +2290,9 @@ fileHeader = """ indent = " " -discriminantDocComment = "/// Returns which variant this tag union holds. Note that this never includes a payload!" +discriminant_doc_comment = "/// Returns which variant this tag union holds. Note that this never includes a payload!" -reservedKeywords = Set.fromList [ +reserved_keywords = Set.from_list([ "try", "abstract", "become", @@ -2328,42 +2344,42 @@ reservedKeywords = Set.fromList [ "use", "where", "while", -] +]) -escapeKW = \input -> +escape_kw = \input -> # use a raw identifier for this, to prevent a syntax error due to using a reserved keyword. # https://doc.rust-lang.org/rust-by-example/compatibility/raw_identifiers.html # another design would be to add an underscore after it; this is an experiment! - if Set.contains reservedKeywords input then + if Set.contains(reserved_keywords, input) then "r#$(input)" else input -nextMultipleOf = \lhs, rhs -> +next_multiple_of = \lhs, rhs -> when lhs % rhs is 0 -> lhs r -> lhs + (rhs - r) -isUnit : Shape -> Bool -isUnit = \shape -> +is_unit : Shape -> Bool +is_unit = \shape -> when shape is Unit -> Bool.true _ -> Bool.false -toArgStr : List TypeId, Types, (TypeId, Shape, U64 -> Str) -> Str -toArgStr = \args, types, fmt -> - List.walkWithIndex args "" \state, argId, index -> - shape = Types.shape types argId +to_arg_str : List TypeId, Types, (TypeId, Shape, U64 -> Str) -> Str +to_arg_str = \args, types, fmt -> + List.walk_with_index(args, "", \state, arg_id, index -> + shape = Types.shape(types, arg_id) # Drop `()` args; they aren't FFI-safe, and nothing will get passed anyway. - if isUnit shape then + if is_unit(shape) then state else - argStr = fmt argId shape index + arg_str = fmt(arg_id, shape, index) - if Str.isEmpty state then - argStr # Don't prepend a comma if this is the first one + if Str.is_empty(state) then + arg_str # Don't prepend a comma if this is the first one else state - |> Str.concat ", " - |> Str.concat argStr + |> Str.concat(", ") + |> Str.concat(arg_str)) diff --git a/crates/glue/src/ZigGlue.roc b/crates/glue/src/ZigGlue.roc index bf5dc23cb91..ef85ebece37 100644 --- a/crates/glue/src/ZigGlue.roc +++ b/crates/glue/src/ZigGlue.roc @@ -1,28 +1,28 @@ -app [makeGlue] { pf: platform "../platform/main.roc" } +app [make_glue] { pf: platform "../platform/main.roc" } import pf.Types exposing [Types] import pf.File exposing [File] -import "../../compiler/builtins/bitcode/src/list.zig" as rocStdList : Str -import "../../compiler/builtins/bitcode/src/str.zig" as rocStdStr : Str -import "../../compiler/builtins/bitcode/src/utils.zig" as rocStdUtils : Str +import "../../compiler/builtins/bitcode/src/list.zig" as roc_std_list : Str +import "../../compiler/builtins/bitcode/src/str.zig" as roc_std_str : Str +import "../../compiler/builtins/bitcode/src/utils.zig" as roc_std_utils : Str -makeGlue : List Types -> Result (List File) Str -makeGlue = \typesByArch -> - typesByArch - |> List.map convertTypesToFile - |> List.concat staticFiles +make_glue : List Types -> Result (List File) Str +make_glue = \types_by_arch -> + types_by_arch + |> List.map(convert_types_to_file) + |> List.concat(static_files) |> Ok ## These are always included, and don't depend on the specifics of the app. -staticFiles : List File -staticFiles = [ - { name: "list.zig", content: rocStdList }, - { name: "str.zig", content: rocStdStr }, - { name: "utils.zig", content: rocStdUtils }, +static_files : List File +static_files = [ + { name: "list.zig", content: roc_std_list }, + { name: "str.zig", content: roc_std_str }, + { name: "utils.zig", content: roc_std_utils }, ] -convertTypesToFile : Types -> File -convertTypesToFile = \_ -> { name: "main.zig", content } +convert_types_to_file : Types -> File +convert_types_to_file = \_ -> { name: "main.zig", content } content = """ diff --git a/crates/glue/src/glue.rs b/crates/glue/src/glue.rs index 34a1f2d8855..e64e2dc054f 100644 --- a/crates/glue/src/glue.rs +++ b/crates/glue/src/glue.rs @@ -24,7 +24,7 @@ pub struct Types { pub deps: roc_std::RocDict>, pub sizes: roc_std::RocList, pub types: roc_std::RocList, - pub typesByName: roc_std::RocDict, + pub types_by_name: roc_std::RocDict, pub target: Target, } @@ -163,7 +163,7 @@ pub struct R3 { #[repr(C)] pub struct Target { pub architecture: Architecture, - pub operatingSystem: OperatingSystem, + pub operating_system: OperatingSystem, } #[cfg(any( @@ -289,16 +289,16 @@ pub union RocTagUnion { #[repr(C)] pub struct R13 { pub name: roc_std::RocStr, - pub payloadFields: roc_std::RocList, - pub tagName: roc_std::RocStr, + pub payload_fields: roc_std::RocList, + pub tag_name: roc_std::RocStr, } #[cfg(any(target_arch = "arm", target_arch = "wasm32", target_arch = "x86"))] #[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)] #[repr(C)] pub struct R11 { - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, pub name: roc_std::RocStr, pub tags: roc_std::RocList, } @@ -337,11 +337,11 @@ pub union U4 { #[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)] #[repr(C)] pub struct R9 { - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub indexOfNullTag: u16, + pub index_of_null_tag: u16, } #[cfg(any( @@ -379,10 +379,10 @@ pub union U3 { #[repr(C)] pub struct R8 { pub name: roc_std::RocStr, - pub nonNullPayload: u32, - pub nonNullTag: roc_std::RocStr, - pub nullTag: roc_std::RocStr, - pub whichTagIsNull: U2, + pub non_null_payload: u32, + pub non_null_tag: roc_std::RocStr, + pub null_tag: roc_std::RocStr, + pub which_tag_is_null: U2, } #[cfg(any( @@ -412,8 +412,8 @@ impl core::fmt::Debug for U2 { #[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)] #[repr(C)] pub struct R6 { - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, pub name: roc_std::RocStr, pub tags: roc_std::RocList, } @@ -454,7 +454,7 @@ pub union U1 { pub struct R5 { pub name: roc_std::RocStr, pub payload: u32, - pub tagName: roc_std::RocStr, + pub tag_name: roc_std::RocStr, } #[cfg(any(target_arch = "arm", target_arch = "wasm32", target_arch = "x86"))] @@ -558,7 +558,7 @@ pub struct Types { pub deps: roc_std::RocDict>, pub sizes: roc_std::RocList, pub types: roc_std::RocList, - pub typesByName: roc_std::RocDict, + pub types_by_name: roc_std::RocDict, pub target: Target, } @@ -613,8 +613,8 @@ pub union RocTagUnion { #[repr(C)] pub struct R13 { pub name: roc_std::RocStr, - pub payloadFields: roc_std::RocList, - pub tagName: roc_std::RocStr, + pub payload_fields: roc_std::RocList, + pub tag_name: roc_std::RocStr, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] @@ -623,8 +623,8 @@ pub struct R13 { pub struct R11 { pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] @@ -640,9 +640,9 @@ pub union U4 { pub struct R9 { pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub discriminantOffset: u32, - pub discriminantSize: u32, - pub indexOfNullTag: u16, + pub discriminant_offset: u32, + pub discriminant_size: u32, + pub index_of_null_tag: u16, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] @@ -657,10 +657,10 @@ pub union U3 { #[repr(C)] pub struct R8 { pub name: roc_std::RocStr, - pub nonNullPayload: u64, - pub nonNullTag: roc_std::RocStr, - pub nullTag: roc_std::RocStr, - pub whichTagIsNull: U2, + pub non_null_payload: u64, + pub non_null_tag: roc_std::RocStr, + pub null_tag: roc_std::RocStr, + pub which_tag_is_null: U2, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] @@ -669,8 +669,8 @@ pub struct R8 { pub struct R6 { pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] @@ -686,7 +686,7 @@ pub union U1 { pub struct R5 { pub name: roc_std::RocStr, pub payload: u64, - pub tagName: roc_std::RocStr, + pub tag_name: roc_std::RocStr, } #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))] diff --git a/crates/glue/src/load.rs b/crates/glue/src/load.rs index 8891e31ef25..4401a04b75d 100644 --- a/crates/glue/src/load.rs +++ b/crates/glue/src/load.rs @@ -247,11 +247,11 @@ fn call_roc_make_glue( &roc_std::RocList, ); - let name_of_main = "roc__makeGlueForHost_1_exposed_generic"; + let name_of_main = "roc__make_glue_for_host_1_exposed_generic"; let make_glue: libloading::Symbol = unsafe { lib.get(name_of_main.as_bytes()) - .unwrap_or_else(|_| panic!("Unable to load glue function")) + .unwrap_or_else(|_| panic!("Unable to load glue function: {lib:?}")) }; let mut files = RocCallResult::new(roc_std::RocResult::err(roc_std::RocStr::empty())); unsafe { make_glue(&mut files, &roc_types) }; diff --git a/crates/glue/src/roc_type/mod.rs b/crates/glue/src/roc_type/mod.rs index 96deeb18891..02b45efa36a 100644 --- a/crates/glue/src/roc_type/mod.rs +++ b/crates/glue/src/roc_type/mod.rs @@ -65,7 +65,7 @@ pub struct Types { pub entrypoints: roc_std::RocList, pub sizes: roc_std::RocList, pub types: roc_std::RocList, - pub typesByName: roc_std::RocList, + pub types_by_name: roc_std::RocList, pub target: Target, } @@ -76,7 +76,7 @@ impl RocRefcounted for Types { self.entrypoints.inc(); self.sizes.inc(); self.types.inc(); - self.typesByName.inc(); + self.types_by_name.inc(); self.target.inc(); } @@ -86,7 +86,7 @@ impl RocRefcounted for Types { self.entrypoints.dec(); self.sizes.dec(); self.types.dec(); - self.typesByName.dec(); + self.types_by_name.dec(); self.target.dec(); } @@ -242,7 +242,7 @@ pub struct Tuple2 { #[repr(C)] pub struct Target { pub architecture: Architecture, - pub operatingSystem: OperatingSystem, + pub operating_system: OperatingSystem, } roc_refcounted_noop_impl!(Target); @@ -364,20 +364,20 @@ pub union RocTagUnion { pub struct R14 { pub name: roc_std::RocStr, pub payload: RocSingleTagPayload, - pub tagName: roc_std::RocStr, + pub tag_name: roc_std::RocStr, } impl RocRefcounted for R14 { fn inc(&mut self) { self.name.inc(); self.payload.inc(); - self.tagName.inc(); + self.tag_name.inc(); } fn dec(&mut self) { self.name.dec(); self.payload.dec(); - self.tagName.dec(); + self.tag_name.dec(); } fn is_refcounted() -> bool { @@ -454,11 +454,11 @@ impl RocRefcounted for RocSingleTagPayload { #[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)] #[repr(C)] pub struct R10 { - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub indexOfNullTag: u16, + pub index_of_null_tag: u16, } #[cfg(any(target_arch = "arm", target_arch = "wasm32", target_arch = "x86"))] @@ -466,10 +466,10 @@ pub struct R10 { #[repr(C)] pub struct R9 { pub name: roc_std::RocStr, - pub nonNullPayload: u32, - pub nonNullTag: roc_std::RocStr, - pub nullTag: roc_std::RocStr, - pub whichTagIsNull: U2, + pub non_null_payload: u32, + pub non_null_tag: roc_std::RocStr, + pub null_tag: roc_std::RocStr, + pub which_tag_is_null: U2, } #[cfg(any( @@ -499,8 +499,8 @@ impl core::fmt::Debug for U2 { #[derive(Clone, Debug, Eq, Ord, Hash, PartialEq, PartialOrd)] #[repr(C)] pub struct R7 { - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, pub name: roc_std::RocStr, pub tags: roc_std::RocList, } @@ -541,7 +541,7 @@ pub union U1 { pub struct R6 { pub name: roc_std::RocStr, pub payload: u32, - pub tagName: roc_std::RocStr, + pub tag_name: roc_std::RocStr, } #[cfg(any(target_arch = "arm", target_arch = "wasm32", target_arch = "x86"))] @@ -730,9 +730,9 @@ impl core::fmt::Debug for RocNum { #[repr(C)] pub struct RocFn { pub args: roc_std::RocList, - pub externName: roc_std::RocStr, - pub functionName: roc_std::RocStr, - pub lambdaSet: u32, + pub extern_name: roc_std::RocStr, + pub function_name: roc_std::RocStr, + pub lambda_set: u32, pub ret: u32, pub is_toplevel: bool, } @@ -967,9 +967,9 @@ impl RocRefcounted for RocTagUnion { pub struct R10 { pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub discriminantOffset: u32, - pub discriminantSize: u32, - pub indexOfNullTag: u16, + pub discriminant_offset: u32, + pub discriminant_size: u32, + pub index_of_null_tag: u16, } impl RocRefcounted for R10 { @@ -993,23 +993,23 @@ impl RocRefcounted for R10 { #[repr(C)] pub struct R9 { pub name: roc_std::RocStr, - pub nonNullPayload: u64, - pub nonNullTag: roc_std::RocStr, - pub nullTag: roc_std::RocStr, - pub whichTagIsNull: U2, + pub non_null_payload: u64, + pub non_null_tag: roc_std::RocStr, + pub null_tag: roc_std::RocStr, + pub which_tag_is_null: U2, } impl RocRefcounted for R9 { fn inc(&mut self) { self.name.inc(); - self.nonNullTag.inc(); - self.nullTag.inc(); + self.non_null_tag.inc(); + self.null_tag.inc(); } fn dec(&mut self) { self.name.dec(); - self.nonNullTag.dec(); - self.nullTag.dec(); + self.non_null_tag.dec(); + self.null_tag.dec(); } fn is_refcounted() -> bool { @@ -1023,8 +1023,8 @@ impl RocRefcounted for R9 { pub struct R7 { pub name: roc_std::RocStr, pub tags: roc_std::RocList, - pub discriminantOffset: u32, - pub discriminantSize: u32, + pub discriminant_offset: u32, + pub discriminant_size: u32, } impl RocRefcounted for R7 { @@ -1056,18 +1056,18 @@ pub union U1 { pub struct R6 { pub name: roc_std::RocStr, pub payload: u64, - pub tagName: roc_std::RocStr, + pub tag_name: roc_std::RocStr, } impl RocRefcounted for R6 { fn inc(&mut self) { self.name.inc(); - self.tagName.inc(); + self.tag_name.inc(); } fn dec(&mut self) { self.name.dec(); - self.tagName.dec(); + self.tag_name.dec(); } fn is_refcounted() -> bool { @@ -1114,24 +1114,24 @@ roc_refcounted_noop_impl!(RocType_RocDict); #[repr(C)] pub struct RocFn { pub args: roc_std::RocList, - pub externName: roc_std::RocStr, - pub functionName: roc_std::RocStr, - pub lambdaSet: u64, + pub extern_name: roc_std::RocStr, + pub function_name: roc_std::RocStr, + pub lambda_set: u64, pub ret: u64, - pub isToplevel: bool, + pub is_toplevel: bool, } impl RocRefcounted for RocFn { fn inc(&mut self) { self.args.inc(); - self.externName.inc(); - self.functionName.inc(); + self.extern_name.inc(); + self.function_name.inc(); } fn dec(&mut self) { self.args.dec(); - self.externName.dec(); - self.functionName.dec(); + self.extern_name.dec(); + self.function_name.dec(); } fn is_refcounted() -> bool { diff --git a/crates/glue/src/types.rs b/crates/glue/src/types.rs index 2ec9b13d521..1ad014ad18d 100644 --- a/crates/glue/src/types.rs +++ b/crates/glue/src/types.rs @@ -669,7 +669,7 @@ impl From<&Types> for roc_type::Types { entrypoints, sizes: types.sizes.as_slice().into(), types: types.types.iter().map(roc_type::RocType::from).collect(), - typesByName: types_by_name, + types_by_name, target: types.target.into(), } } @@ -708,11 +708,11 @@ impl From<&RocType> for roc_type::RocType { is_toplevel, }) => roc_type::RocType::Function(roc_type::RocFn { args: args.iter().map(|arg| arg.0 as _).collect(), - functionName: function_name.as_str().into(), - externName: extern_name.as_str().into(), + function_name: function_name.as_str().into(), + extern_name: extern_name.as_str().into(), ret: ret.0 as _, - lambdaSet: lambda_set.0 as _, - isToplevel: *is_toplevel, + lambda_set: lambda_set.0 as _, + is_toplevel: *is_toplevel, }), RocType::Unit => roc_type::RocType::Unit, RocType::Unsized => roc_type::RocType::Unsized, @@ -764,8 +764,8 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { payload: payload.into(), }) .collect(), - discriminantSize: *discriminant_size, - discriminantOffset: *discriminant_offset, + discriminant_size: *discriminant_size, + discriminant_offset: *discriminant_offset, }), RocTagUnion::Recursive { name, @@ -781,8 +781,8 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { payload: payload.into(), }) .collect(), - discriminantSize: *discriminant_size, - discriminantOffset: *discriminant_offset, + discriminant_size: *discriminant_size, + discriminant_offset: *discriminant_offset, }), RocTagUnion::NonNullableUnwrapped { name, @@ -790,7 +790,7 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { payload, } => roc_type::RocTagUnion::NonNullableUnwrapped(roc_type::R6 { name: name.as_str().into(), - tagName: tag_name.as_str().into(), + tag_name: tag_name.as_str().into(), payload: payload.0 as _, }), RocTagUnion::SingleTagStruct { @@ -799,7 +799,7 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { payload, } => roc_type::RocTagUnion::SingleTagStruct(roc_type::R14 { name: name.as_str().into(), - tagName: tag_name.as_str().into(), + tag_name: tag_name.as_str().into(), payload: payload.into(), }), RocTagUnion::NullableWrapped { @@ -810,7 +810,7 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { discriminant_offset, } => roc_type::RocTagUnion::NullableWrapped(roc_type::R10 { name: name.as_str().into(), - indexOfNullTag: *index_of_null_tag, + index_of_null_tag: *index_of_null_tag, tags: tags .iter() .map(|(name, payload)| roc_type::R8 { @@ -818,8 +818,8 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { payload: payload.into(), }) .collect(), - discriminantSize: *discriminant_size, - discriminantOffset: *discriminant_offset, + discriminant_size: *discriminant_size, + discriminant_offset: *discriminant_offset, }), RocTagUnion::NullableUnwrapped { name, @@ -829,10 +829,10 @@ impl From<&RocTagUnion> for roc_type::RocTagUnion { null_represents_first_tag, } => roc_type::RocTagUnion::NullableUnwrapped(roc_type::R9 { name: name.as_str().into(), - nonNullPayload: non_null_payload.0 as _, - nonNullTag: non_null_tag.as_str().into(), - nullTag: null_tag.as_str().into(), - whichTagIsNull: if *null_represents_first_tag { + non_null_payload: non_null_payload.0 as _, + non_null_tag: non_null_tag.as_str().into(), + null_tag: null_tag.as_str().into(), + which_tag_is_null: if *null_represents_first_tag { roc_type::U2::FirstTagIsNull } else { roc_type::U2::SecondTagIsNull @@ -909,7 +909,7 @@ impl From for roc_type::Target { fn from(target: Target) -> Self { roc_type::Target { architecture: target.architecture().into(), - operatingSystem: target.operating_system().into(), + operating_system: target.operating_system().into(), } } } @@ -1269,7 +1269,7 @@ fn add_function_type<'a>( let name = format!("RocFunction_{closure_var:?}"); let extern_name = match env.lambda_set_ids.get(&closure_var) { - Some(id) => format!("roc__mainForHost_{}_caller", id.0), + Some(id) => format!("roc__main_for_host_{}_caller", id.0), None => { debug_assert!(is_toplevel); String::from("this_extern_should_not_be_used_this_is_a_bug") diff --git a/crates/glue/tests/fixtures/c/hello-world/host.c b/crates/glue/tests/fixtures/c/hello-world/host.c index cc2343ef47f..6d070f9532c 100644 --- a/crates/glue/tests/fixtures/c/hello-world/host.c +++ b/crates/glue/tests/fixtures/c/hello-world/host.c @@ -6,9 +6,9 @@ int main(void) { - uint8_t mainForHost = roc_mainForHost(); + uint8_t main_for_host = roc_main_for_host(); - printf("mainForHost = %i\n", mainForHost); + printf("main_for_host = %i\n", main_for_host); - assert(mainForHost == 42); + assert(main_for_host == 42); } \ No newline at end of file diff --git a/crates/glue/tests/fixtures/c/hello-world/platform.roc b/crates/glue/tests/fixtures/c/hello-world/platform.roc index bfc3a5bad49..db519c12ba3 100644 --- a/crates/glue/tests/fixtures/c/hello-world/platform.roc +++ b/crates/glue/tests/fixtures/c/hello-world/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : U8 -mainForHost = main +main_for_host : U8 +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/advanced-recursive-union/app.roc b/crates/glue/tests/fixtures/rust/advanced-recursive-union/app.roc index 9ba7529b68d..f1e9137f313 100644 --- a/crates/glue/tests/fixtures/rust/advanced-recursive-union/app.roc +++ b/crates/glue/tests/fixtures/rust/advanced-recursive-union/app.roc @@ -1,11 +1,11 @@ app [main] { pf: platform "platform.roc" } main = { - default: Job { - command: Command { - tool: SystemTool { name: "test", num: 42 }, - }, - inputFiles: ["foo"], - }, + default: Job({ + command: Command({ + tool: SystemTool({ name: "test", num: 42 }), + }), + input_files: ["foo"], + }), } diff --git a/crates/glue/tests/fixtures/rust/advanced-recursive-union/platform.roc b/crates/glue/tests/fixtures/rust/advanced-recursive-union/platform.roc index 06b43a6dc9d..f957fee1c82 100644 --- a/crates/glue/tests/fixtures/rust/advanced-recursive-union/platform.roc +++ b/crates/glue/tests/fixtures/rust/advanced-recursive-union/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] Tool : [ SystemTool { name : Str, num : U32 }, @@ -13,7 +13,7 @@ Tool : [ Command : [Command { tool : Tool }] Job : [ - Job { command : Command, inputFiles : List Str }, + Job { command : Command, input_files : List Str }, Foo Str, # TODO make a recursive tag union test that doesn't try to do mutual recursion, # just so I can get a PR up. @@ -22,5 +22,5 @@ Job : [ Rbt : { default : Job } -mainForHost : {} -> Rbt -mainForHost = \{} -> main +main_for_host : {} -> Rbt +main_for_host = \{} -> main diff --git a/crates/glue/tests/fixtures/rust/advanced-recursive-union/src/lib.rs b/crates/glue/tests/fixtures/rust/advanced-recursive-union/src/lib.rs index bb9660783e9..ee089a004a4 100644 --- a/crates/glue/tests/fixtures/rust/advanced-recursive-union/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/advanced-recursive-union/src/lib.rs @@ -10,7 +10,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/arguments/platform.roc b/crates/glue/tests/fixtures/rust/arguments/platform.roc index b4cfc05570b..ca036a7878f 100644 --- a/crates/glue/tests/fixtures/rust/arguments/platform.roc +++ b/crates/glue/tests/fixtures/rust/arguments/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : I64 -> I64 -mainForHost = \x -> main x +main_for_host : I64 -> I64 +main_for_host = \x -> main(x) diff --git a/crates/glue/tests/fixtures/rust/arguments/src/lib.rs b/crates/glue/tests/fixtures/rust/arguments/src/lib.rs index 3f8b31edd29..e3206a26854 100644 --- a/crates/glue/tests/fixtures/rust/arguments/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/arguments/src/lib.rs @@ -3,7 +3,7 @@ use roc_std::RocStr; #[no_mangle] pub extern "C" fn rust_main() { - let answer = roc_app::mainForHost(42i64); + let answer = roc_app::main_for_host(42i64); init(); diff --git a/crates/glue/tests/fixtures/rust/basic-record/platform.roc b/crates/glue/tests/fixtures/rust/basic-record/platform.roc index 12466b50bca..2291914615d 100644 --- a/crates/glue/tests/fixtures/rust/basic-record/platform.roc +++ b/crates/glue/tests/fixtures/rust/basic-record/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] MyRcd : { a : U64, b : U128 } -mainForHost : MyRcd -mainForHost = main +main_for_host : MyRcd +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/basic-record/src/lib.rs b/crates/glue/tests/fixtures/rust/basic-record/src/lib.rs index 9ed84a80485..de04edaafba 100644 --- a/crates/glue/tests/fixtures/rust/basic-record/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/basic-record/src/lib.rs @@ -8,7 +8,7 @@ pub extern "C" fn rust_main() { init(); - let record = roc_app::mainForHost(); + let record = roc_app::main_for_host(); // Verify that the record has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/basic-recursive-union/app.roc b/crates/glue/tests/fixtures/rust/basic-recursive-union/app.roc index bf26d2ec032..7451fbabe02 100644 --- a/crates/glue/tests/fixtures/rust/basic-recursive-union/app.roc +++ b/crates/glue/tests/fixtures/rust/basic-recursive-union/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = Concat (String "Hello, ") (String "World!") +main = Concat(String("Hello, "), String("World!")) diff --git a/crates/glue/tests/fixtures/rust/basic-recursive-union/platform.roc b/crates/glue/tests/fixtures/rust/basic-recursive-union/platform.roc index 2816c4ba72e..861e6b4b96c 100644 --- a/crates/glue/tests/fixtures/rust/basic-recursive-union/platform.roc +++ b/crates/glue/tests/fixtures/rust/basic-recursive-union/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] Expr : [String Str, Concat Expr Expr] -mainForHost : {} -> Expr -mainForHost = \{} -> main +main_for_host : {} -> Expr +main_for_host = \{} -> main diff --git a/crates/glue/tests/fixtures/rust/basic-recursive-union/src/lib.rs b/crates/glue/tests/fixtures/rust/basic-recursive-union/src/lib.rs index 2492ef4213a..44d84939da0 100644 --- a/crates/glue/tests/fixtures/rust/basic-recursive-union/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/basic-recursive-union/src/lib.rs @@ -9,7 +9,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/closures/platform.roc b/crates/glue/tests/fixtures/rust/closures/platform.roc index d00c64de206..9d74d98bbdd 100644 --- a/crates/glue/tests/fixtures/rust/closures/platform.roc +++ b/crates/glue/tests/fixtures/rust/closures/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : I64 -> ({} -> I64) -mainForHost = \x -> main x +main_for_host : I64 -> ({} -> I64) +main_for_host = \x -> main(x) diff --git a/crates/glue/tests/fixtures/rust/closures/src/lib.rs b/crates/glue/tests/fixtures/rust/closures/src/lib.rs index 7dc784be364..08c00197661 100644 --- a/crates/glue/tests/fixtures/rust/closures/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/closures/src/lib.rs @@ -3,7 +3,7 @@ use roc_std::RocStr; #[no_mangle] pub extern "C" fn rust_main() { - let closure = roc_app::mainForHost(42i64); + let closure = roc_app::main_for_host(42i64); init(); diff --git a/crates/glue/tests/fixtures/rust/enumeration/platform.roc b/crates/glue/tests/fixtures/rust/enumeration/platform.roc index ba4b90b610f..1f7b8e58884 100644 --- a/crates/glue/tests/fixtures/rust/enumeration/platform.roc +++ b/crates/glue/tests/fixtures/rust/enumeration/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] MyEnum : [Foo, Bar, Baz] -mainForHost : MyEnum -mainForHost = main +main_for_host : MyEnum +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/enumeration/src/lib.rs b/crates/glue/tests/fixtures/rust/enumeration/src/lib.rs index aee5f45e497..78f4e93663d 100644 --- a/crates/glue/tests/fixtures/rust/enumeration/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/enumeration/src/lib.rs @@ -8,7 +8,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/list-recursive-union/app.roc b/crates/glue/tests/fixtures/rust/list-recursive-union/app.roc index baa81e8172c..b9c4446d82f 100644 --- a/crates/glue/tests/fixtures/rust/list-recursive-union/app.roc +++ b/crates/glue/tests/fixtures/rust/list-recursive-union/app.roc @@ -1,13 +1,13 @@ app [main] { pf: platform "platform.roc" } main = { - default: Job { - command: Command { - tool: SystemTool { name: "test" }, + default: Job({ + command: Command({ + tool: SystemTool({ name: "test" }), args: [], - }, + }), job: [], - inputFiles: ["foo"], - }, + input_files: ["foo"], + }), } diff --git a/crates/glue/tests/fixtures/rust/list-recursive-union/platform.roc b/crates/glue/tests/fixtures/rust/list-recursive-union/platform.roc index b248ccc6f11..3de676309d1 100644 --- a/crates/glue/tests/fixtures/rust/list-recursive-union/platform.roc +++ b/crates/glue/tests/fixtures/rust/list-recursive-union/platform.roc @@ -3,15 +3,15 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] Tool : [SystemTool { name : Str }] Command : [Command { tool : Tool, args : List Str }] -Job : [Job { command : Command, job : List Job, inputFiles : List Str }, Blah Str] +Job : [Job { command : Command, job : List Job, input_files : List Str }, Blah Str] Rbt : { default : Job } -mainForHost : Rbt -mainForHost = main +main_for_host : Rbt +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/list-recursive-union/src/lib.rs b/crates/glue/tests/fixtures/rust/list-recursive-union/src/lib.rs index e18174bfb93..a1b2ed4ac1c 100644 --- a/crates/glue/tests/fixtures/rust/list-recursive-union/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/list-recursive-union/src/lib.rs @@ -11,7 +11,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/multiple-modules/Dep1.roc b/crates/glue/tests/fixtures/rust/multiple-modules/Dep1.roc index 291dfd66ac7..4f9e98832da 100644 --- a/crates/glue/tests/fixtures/rust/multiple-modules/Dep1.roc +++ b/crates/glue/tests/fixtures/rust/multiple-modules/Dep1.roc @@ -1,5 +1,5 @@ -interface Dep1 exposes [DepStr1, string] imports [] +module [DepStr1, string] DepStr1 := [S Str] -string = \s -> @DepStr1 (S s) +string = \s -> @DepStr1(S(s)) diff --git a/crates/glue/tests/fixtures/rust/multiple-modules/Dep2.roc b/crates/glue/tests/fixtures/rust/multiple-modules/Dep2.roc index 99f00e08c16..2b5d5deee05 100644 --- a/crates/glue/tests/fixtures/rust/multiple-modules/Dep2.roc +++ b/crates/glue/tests/fixtures/rust/multiple-modules/Dep2.roc @@ -1,5 +1,5 @@ -interface Dep2 exposes [DepStr2, string] imports [] +module [DepStr2, string] DepStr2 := [R Str] -string = \s -> @DepStr2 (R s) +string = \s -> @DepStr2(R(s)) diff --git a/crates/glue/tests/fixtures/rust/multiple-modules/app.roc b/crates/glue/tests/fixtures/rust/multiple-modules/app.roc index 50b7b6ee703..e83bf8bfc10 100644 --- a/crates/glue/tests/fixtures/rust/multiple-modules/app.roc +++ b/crates/glue/tests/fixtures/rust/multiple-modules/app.roc @@ -3,4 +3,4 @@ app [main] { pf: platform "platform.roc" } import pf.Dep1 import pf.Dep2 -main = { s1: Dep1.string "hello", s2: Dep2.string "world" } +main = { s1: Dep1.string("hello"), s2: Dep2.string("world") } diff --git a/crates/glue/tests/fixtures/rust/multiple-modules/platform.roc b/crates/glue/tests/fixtures/rust/multiple-modules/platform.roc index 016bb3fc138..bb0bc187f51 100644 --- a/crates/glue/tests/fixtures/rust/multiple-modules/platform.roc +++ b/crates/glue/tests/fixtures/rust/multiple-modules/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [Dep1, Dep2] - provides [mainForHost] + provides [main_for_host] Combined : { s1 : Dep1.DepStr1, s2 : Dep2.DepStr2 } -mainForHost : Combined -mainForHost = main +main_for_host : Combined +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/multiple-modules/src/lib.rs b/crates/glue/tests/fixtures/rust/multiple-modules/src/lib.rs index 89273a00d81..195299f98e3 100644 --- a/crates/glue/tests/fixtures/rust/multiple-modules/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/multiple-modules/src/lib.rs @@ -9,7 +9,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/nested-record/platform.roc b/crates/glue/tests/fixtures/rust/nested-record/platform.roc index 90c0b2b769b..ce4e869a819 100644 --- a/crates/glue/tests/fixtures/rust/nested-record/platform.roc +++ b/crates/glue/tests/fixtures/rust/nested-record/platform.roc @@ -3,11 +3,11 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] Outer : { x : Inner, y : Str, z : List U8 } Inner : { a : U16, b : F32 } -mainForHost : Outer -mainForHost = main +main_for_host : Outer +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/nested-record/src/lib.rs b/crates/glue/tests/fixtures/rust/nested-record/src/lib.rs index d92c175ce22..b84eff83d53 100644 --- a/crates/glue/tests/fixtures/rust/nested-record/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/nested-record/src/lib.rs @@ -7,7 +7,7 @@ pub extern "C" fn rust_main() { init(); - let outer = roc_app::mainForHost(); + let outer = roc_app::main_for_host(); // Verify that `inner` has all the expected traits. { diff --git a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/app.roc b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/app.roc index 530d8799107..66cdea1f119 100644 --- a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/app.roc +++ b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = Tree "root" [Tree "leaf1" [], Tree "leaf2" []] +main = Tree("root", [Tree("leaf1", []), Tree("leaf2", [])]) diff --git a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/platform.roc b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/platform.roc index 6765fbf5258..cd9f595951f 100644 --- a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/platform.roc +++ b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] StrRoseTree : [Tree Str (List StrRoseTree)] -mainForHost : StrRoseTree -mainForHost = main +main_for_host : StrRoseTree +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/src/lib.rs b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/src/lib.rs index a84fb47ae3f..9a89c165878 100644 --- a/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/nonnullable-unwrapped/src/lib.rs @@ -5,7 +5,7 @@ use roc_app::StrRoseTree; use roc_std::{RocList, RocStr}; extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(_: *mut StrRoseTree); } diff --git a/crates/glue/tests/fixtures/rust/nullable-unwrapped/app.roc b/crates/glue/tests/fixtures/rust/nullable-unwrapped/app.roc index b76da9e4f50..5a12077575f 100644 --- a/crates/glue/tests/fixtures/rust/nullable-unwrapped/app.roc +++ b/crates/glue/tests/fixtures/rust/nullable-unwrapped/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = Cons "World!" (Cons "Hello " Nil) +main = Cons("World!", Cons("Hello ", Nil)) diff --git a/crates/glue/tests/fixtures/rust/nullable-unwrapped/platform.roc b/crates/glue/tests/fixtures/rust/nullable-unwrapped/platform.roc index 13992876507..2bb373dbe7e 100644 --- a/crates/glue/tests/fixtures/rust/nullable-unwrapped/platform.roc +++ b/crates/glue/tests/fixtures/rust/nullable-unwrapped/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] StrConsList : [Nil, Cons Str StrConsList] -mainForHost : StrConsList -mainForHost = main +main_for_host : StrConsList +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/nullable-unwrapped/src/lib.rs b/crates/glue/tests/fixtures/rust/nullable-unwrapped/src/lib.rs index 93adb3146b9..9b049c31973 100644 --- a/crates/glue/tests/fixtures/rust/nullable-unwrapped/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/nullable-unwrapped/src/lib.rs @@ -11,7 +11,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/nullable-wrapped/app.roc b/crates/glue/tests/fixtures/rust/nullable-wrapped/app.roc index a240679aaec..561fd952b27 100644 --- a/crates/glue/tests/fixtures/rust/nullable-wrapped/app.roc +++ b/crates/glue/tests/fixtures/rust/nullable-wrapped/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = More "foo" (More "bar" Empty) +main = More("foo", More("bar", Empty)) diff --git a/crates/glue/tests/fixtures/rust/nullable-wrapped/platform.roc b/crates/glue/tests/fixtures/rust/nullable-wrapped/platform.roc index dc3d2283c30..a689b0c1c47 100644 --- a/crates/glue/tests/fixtures/rust/nullable-wrapped/platform.roc +++ b/crates/glue/tests/fixtures/rust/nullable-wrapped/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] StrFingerTree : [Empty, Single Str, More Str StrFingerTree] -mainForHost : {} -> StrFingerTree -mainForHost = \{} -> main +main_for_host : {} -> StrFingerTree +main_for_host = \{} -> main diff --git a/crates/glue/tests/fixtures/rust/nullable-wrapped/src/lib.rs b/crates/glue/tests/fixtures/rust/nullable-wrapped/src/lib.rs index f69df0a4e09..13657d67657 100644 --- a/crates/glue/tests/fixtures/rust/nullable-wrapped/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/nullable-wrapped/src/lib.rs @@ -5,7 +5,7 @@ use roc_app::StrFingerTree; use roc_std::RocStr; extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(_: *mut StrFingerTree); } @@ -16,7 +16,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Eq assert!(StrFingerTree::Empty() == StrFingerTree::Empty()); diff --git a/crates/glue/tests/fixtures/rust/option/app.roc b/crates/glue/tests/fixtures/rust/option/app.roc index 82b21e996dc..34278512943 100644 --- a/crates/glue/tests/fixtures/rust/option/app.roc +++ b/crates/glue/tests/fixtures/rust/option/app.roc @@ -1,8 +1,8 @@ app [main] { pf: platform "platform.roc" } main : Bool -> [Some Str, None] -main = \returnStr -> - if returnStr then - Some "Hello World!" +main = \return_str -> + if return_str then + Some("Hello World!") else None diff --git a/crates/glue/tests/fixtures/rust/option/platform.roc b/crates/glue/tests/fixtures/rust/option/platform.roc index bfa9a5f9f87..b42ca7bf4b5 100644 --- a/crates/glue/tests/fixtures/rust/option/platform.roc +++ b/crates/glue/tests/fixtures/rust/option/platform.roc @@ -1,9 +1,9 @@ platform "test-platform" - requires {} { main : Bool -> [ Some Str, None ] } + requires {} { main : Bool -> [Some Str, None] } exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Bool -> [ Some Str, None ] -mainForHost = \u -> main u +main_for_host : Bool -> [Some Str, None] +main_for_host = \u -> main(u) diff --git a/crates/glue/tests/fixtures/rust/option/src/lib.rs b/crates/glue/tests/fixtures/rust/option/src/lib.rs index 788cd675705..2a7f79cf60f 100644 --- a/crates/glue/tests/fixtures/rust/option/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/option/src/lib.rs @@ -5,10 +5,10 @@ use roc_std::RocStr; pub extern "C" fn rust_main() { init(); - let string = roc_app::mainForHost(true); + let string = roc_app::main_for_host(true); println!("Answer was: {:?}", string.unwrap_Some()); // Debug // - let integer = roc_app::mainForHost(false); + let integer = roc_app::main_for_host(false); println!("Answer was: {:?}", integer.discriminant()); // Debug } diff --git a/crates/glue/tests/fixtures/rust/rocresult/app.roc b/crates/glue/tests/fixtures/rust/rocresult/app.roc index 0bcc926bee5..19f984a7033 100644 --- a/crates/glue/tests/fixtures/rust/rocresult/app.roc +++ b/crates/glue/tests/fixtures/rust/rocresult/app.roc @@ -1,8 +1,8 @@ app [main] { pf: platform "platform.roc" } main : Bool -> Result Str I32 -main = \returnStr -> - if returnStr then - Ok "Hello World!" +main = \return_str -> + if return_str then + Ok("Hello World!") else - Err 42 + Err(42) diff --git a/crates/glue/tests/fixtures/rust/rocresult/platform.roc b/crates/glue/tests/fixtures/rust/rocresult/platform.roc index bdb6635c382..c1d59fddafb 100644 --- a/crates/glue/tests/fixtures/rust/rocresult/platform.roc +++ b/crates/glue/tests/fixtures/rust/rocresult/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Bool -> Result Str I32 -mainForHost = \u -> main u +main_for_host : Bool -> Result Str I32 +main_for_host = \u -> main(u) diff --git a/crates/glue/tests/fixtures/rust/rocresult/src/lib.rs b/crates/glue/tests/fixtures/rust/rocresult/src/lib.rs index c5eb7d0b919..dcd37f38fae 100644 --- a/crates/glue/tests/fixtures/rust/rocresult/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/rocresult/src/lib.rs @@ -5,10 +5,10 @@ use roc_std::RocStr; pub extern "C" fn rust_main() { init(); - let string = roc_app::mainForHost(true); + let string = roc_app::main_for_host(true); println!("Answer was: {:?}", string); // Debug // - let integer = roc_app::mainForHost(false); + let integer = roc_app::main_for_host(false); println!("Answer was: {:?}", integer); // Debug } diff --git a/crates/glue/tests/fixtures/rust/single-tag-union/platform.roc b/crates/glue/tests/fixtures/rust/single-tag-union/platform.roc index c6c13c5e586..bf335e4e238 100644 --- a/crates/glue/tests/fixtures/rust/single-tag-union/platform.roc +++ b/crates/glue/tests/fixtures/rust/single-tag-union/platform.roc @@ -3,9 +3,9 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] SingleTagUnion : [OneTag] -mainForHost : SingleTagUnion -mainForHost = main +main_for_host : SingleTagUnion +main_for_host = main diff --git a/crates/glue/tests/fixtures/rust/single-tag-union/src/lib.rs b/crates/glue/tests/fixtures/rust/single-tag-union/src/lib.rs index 8d41e9a9ce6..edea3ad0134 100644 --- a/crates/glue/tests/fixtures/rust/single-tag-union/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/single-tag-union/src/lib.rs @@ -11,7 +11,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/union-with-padding/app.roc b/crates/glue/tests/fixtures/rust/union-with-padding/app.roc index 5ad22410b13..1a71f224be6 100644 --- a/crates/glue/tests/fixtures/rust/union-with-padding/app.roc +++ b/crates/glue/tests/fixtures/rust/union-with-padding/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = Foo "This is a test" +main = Foo("This is a test") diff --git a/crates/glue/tests/fixtures/rust/union-with-padding/platform.roc b/crates/glue/tests/fixtures/rust/union-with-padding/platform.roc index ba923679cb4..a55b581e6b1 100644 --- a/crates/glue/tests/fixtures/rust/union-with-padding/platform.roc +++ b/crates/glue/tests/fixtures/rust/union-with-padding/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] # This case is important to test because the U128 # gives the whole struct an alignment of 16, but the @@ -13,5 +13,5 @@ platform "test-platform" # that all variants have. NonRecursive : [Foo Str, Bar U128, Blah I32, Baz] -mainForHost : {} -> NonRecursive -mainForHost = \{} -> main +main_for_host : {} -> NonRecursive +main_for_host = \{} -> main diff --git a/crates/glue/tests/fixtures/rust/union-with-padding/src/lib.rs b/crates/glue/tests/fixtures/rust/union-with-padding/src/lib.rs index 9b04972c17a..6db7f76ade5 100644 --- a/crates/glue/tests/fixtures/rust/union-with-padding/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/union-with-padding/src/lib.rs @@ -4,7 +4,7 @@ use roc_app::NonRecursive; use roc_std::RocStr; extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(_: *mut NonRecursive); } @@ -15,7 +15,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/fixtures/rust/union-without-padding/app.roc b/crates/glue/tests/fixtures/rust/union-without-padding/app.roc index 5ad22410b13..1a71f224be6 100644 --- a/crates/glue/tests/fixtures/rust/union-without-padding/app.roc +++ b/crates/glue/tests/fixtures/rust/union-without-padding/app.roc @@ -1,3 +1,3 @@ app [main] { pf: platform "platform.roc" } -main = Foo "This is a test" +main = Foo("This is a test") diff --git a/crates/glue/tests/fixtures/rust/union-without-padding/platform.roc b/crates/glue/tests/fixtures/rust/union-without-padding/platform.roc index 35ff29794e2..a490cb82a3c 100644 --- a/crates/glue/tests/fixtures/rust/union-without-padding/platform.roc +++ b/crates/glue/tests/fixtures/rust/union-without-padding/platform.roc @@ -3,7 +3,7 @@ platform "test-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] # This case is important to test because there's no padding # after the largest variant, so the compiler adds an extra u8 @@ -11,5 +11,5 @@ platform "test-platform" # to store the discriminant. We have to generate glue code accordingly! NonRecursive : [Foo Str, Bar I64, Blah I32, Baz] -mainForHost : {} -> NonRecursive -mainForHost = \{} -> main +main_for_host : {} -> NonRecursive +main_for_host = \{} -> main diff --git a/crates/glue/tests/fixtures/rust/union-without-padding/src/lib.rs b/crates/glue/tests/fixtures/rust/union-without-padding/src/lib.rs index 2c49645bcba..ef5d3fdef8f 100644 --- a/crates/glue/tests/fixtures/rust/union-without-padding/src/lib.rs +++ b/crates/glue/tests/fixtures/rust/union-without-padding/src/lib.rs @@ -2,7 +2,7 @@ use roc_app; use roc_std::RocStr; extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(_: *mut roc_app::NonRecursive); } @@ -13,7 +13,7 @@ pub extern "C" fn rust_main() { init(); - let tag_union = roc_app::mainForHost(); + let tag_union = roc_app::main_for_host(); // Verify that it has all the expected traits. diff --git a/crates/glue/tests/test_glue_cli.rs b/crates/glue/tests/test_glue_cli.rs index 63823ad43e6..3925ebfa91f 100644 --- a/crates/glue/tests/test_glue_cli.rs +++ b/crates/glue/tests/test_glue_cli.rs @@ -167,7 +167,7 @@ mod glue_cli_tests { Answer was: discriminant_U1::None "#), c_hello_world:"c/hello-world" => indoc!(r#" - mainForHost = 42 + main_for_host = 42 "#), } @@ -233,6 +233,7 @@ mod glue_cli_tests { if glue_dir.exists() { std::fs::remove_dir_all(&glue_dir) .expect("Unable to remove test_glue dir in order to regenerate it in the test"); + // std::fs::create_dir(&glue_dir) } let glue_spec_filename = match fixtures_subfolder_name.to_str().unwrap() { @@ -242,6 +243,8 @@ mod glue_cli_tests { unknown_subfolder => panic!("I don't know which glue file to use for tests in the `{}` subfolder! Please add one here!", unknown_subfolder), }; + println!("here"); + let rust_glue_spec = tests_dir .parent() .unwrap() diff --git a/crates/linker/dynhost_benchmarks_elf64 b/crates/linker/dynhost_benchmarks_elf64 index b51fc7f9327dd2d9acfef472c5218029e6c092a0..65c3fdf538f51c3be299eff0c758633bf6cc6b2e 100755 GIT binary patch delta 214 zcmaEGR{z6U{SDR}Z1HLNMe!Na4Q_MG+d@a4hNArB`1st!%sjAk9fuTHUGqGS y_IVtPK+FWh%s|Wn#H>Kf2E^<@43g&rVy^A;IJl=>BFXg0^Ekw|uf5If%nblmls4M{ diff --git a/crates/linker/dynhost_benchmarks_windows.exe b/crates/linker/dynhost_benchmarks_windows.exe index 4f8c9e8ed534c6be0390bee79b9b021c9c3b9958..67678fa30d426ad5f45d93ca6120f98f93a1ad0b 100755 GIT binary patch delta 100 zcmZpeqt`Jicx=#3v`_, /// Symbols that the host exports, like roc_alloc @@ -625,7 +625,7 @@ impl DynamicRelocationsPe { Ok(None) } - /// Append metadata for the functions (e.g. mainForHost) that the host needs from the app + /// Append metadata for the functions (e.g. main_for_host) that the host needs from the app fn append_roc_imports( &mut self, import_table: &ImportTable, @@ -1462,25 +1462,25 @@ mod test { // // DynamicRelocationsPe { // name_by_virtual_address: { - // 0xaf4e0: "roc__mainForHost_size", - // 0xaf4c8: "roc__mainForHost_1__Fx_caller", - // 0xaf4d0: "roc__mainForHost_1__Fx_result_size", - // 0xaf4d8: "roc__mainForHost_1_exposed_generic", + // 0xaf4e0: "roc__main_for_host_size", + // 0xaf4c8: "roc__main_for_host_1__Fx_caller", + // 0xaf4d0: "roc__main_for_host_1__Fx_result_size", + // 0xaf4d8: "roc__main_for_host_1_exposed_generic", // }, // address_and_offset: { - // "roc__mainForHost_1__Fx_result_size": ( + // "roc__main_for_host_1__Fx_result_size": ( // 0xaf4d0, // 0xae4d0, // ), - // "roc__mainForHost_1__Fx_caller": ( + // "roc__main_for_host_1__Fx_caller": ( // 0xaf4c8, // 0xae4c8, // ), - // "roc__mainForHost_1_exposed_generic": ( + // "roc__main_for_host_1_exposed_generic": ( // 0xaf4d8, // 0xae4d8, // ), - // "roc__mainForHost_size": ( + // "roc__main_for_host_size": ( // 0xaf4e0, // 0xae4e0, // ), @@ -1564,10 +1564,10 @@ mod test { assert_eq!( [ - "roc__mainForHost_1__Fx_caller", - "roc__mainForHost_1__Fx_result_size", - "roc__mainForHost_1_exposed_generic", - "roc__mainForHost_size" + "roc__main_for_host_1__Fx_caller", + "roc__main_for_host_1__Fx_result_size", + "roc__main_for_host_1_exposed_generic", + "roc__main_for_host_size" ], imports.as_slice(), ) diff --git a/crates/test_utils/src/TagLenEncoderFmt.roc b/crates/test_utils/src/TagLenEncoderFmt.roc index 75f2fb39dd5..bd156b578d6 100644 --- a/crates/test_utils/src/TagLenEncoderFmt.roc +++ b/crates/test_utils/src/TagLenEncoderFmt.roc @@ -9,252 +9,252 @@ # # module [ # TagLenFmt, -# tagLenFmt, +# tag_len_fmt, # ] TagLenFmt := {} implements [ EncoderFormatting { - u8: encodeU8, - u16: encodeU16, - u32: encodeU32, - u64: encodeU64, - u128: encodeU128, - i8: encodeI8, - i16: encodeI16, - i32: encodeI32, - i64: encodeI64, - i128: encodeI128, - f32: encodeF32, - f64: encodeF64, - dec: encodeDec, - bool: encodeBool, - string: encodeString, - list: encodeList, - record: encodeRecord, - tuple: encodeTuple, - tag: encodeTag, + u8: encode_u8, + u16: encode_u16, + u32: encode_u32, + u64: encode_u64, + u128: encode_u128, + i8: encode_i8, + i16: encode_i16, + i32: encode_i32, + i64: encode_i64, + i128: encode_i128, + f32: encode_f32, + f64: encode_f64, + dec: encode_dec, + bool: encode_bool, + string: encode_string, + list: encode_list, + record: encode_record, + tuple: encode_tuple, + tag: encode_tag, }, DecoderFormatting { - u8: decodeU8, - u16: decodeU16, - u32: decodeU32, - u64: decodeU64, - u128: decodeU128, - i8: decodeI8, - i16: decodeI16, - i32: decodeI32, - i64: decodeI64, - i128: decodeI128, - f32: decodeF32, - f64: decodeF64, - dec: decodeDec, - bool: decodeBool, - string: decodeString, - list: decodeList, - record: decodeRecord, - tuple: decodeTuple, + u8: decode_u8, + u16: decode_u16, + u32: decode_u32, + u64: decode_u64, + u128: decode_u128, + i8: decode_i8, + i16: decode_i16, + i32: decode_i32, + i64: decode_i64, + i128: decode_i128, + f32: decode_f32, + f64: decode_f64, + dec: decode_dec, + bool: decode_bool, + string: decode_string, + list: decode_list, + record: decode_record, + tuple: decode_tuple, }, ] -tagLenFmt = @TagLenFmt {} +tag_len_fmt = @TagLenFmt {} # ENCODE -appendPreLen = \bytes, pre, len -> - List.append bytes (Num.toU8 pre) - |> List.concat (Num.toStr len |> Str.toUtf8) +append_pre_len = \bytes, pre, len -> + List.append bytes (Num.to_u8 pre) + |> List.concat (Num.to_str len |> Str.to_utf8) |> List.append ' ' -encodeNum = \n -> Encode.custom \bytes, @TagLenFmt {} -> appendPreLen bytes 'n' n - -encodeU8 = encodeNum -encodeU16 = encodeNum -encodeU32 = encodeNum -encodeU64 = encodeNum -encodeU128 = encodeNum -encodeI8 = encodeNum -encodeI16 = encodeNum -encodeI32 = encodeNum -encodeI64 = encodeNum -encodeI128 = encodeNum -encodeF32 = encodeNum -encodeF64 = encodeNum -encodeDec = encodeNum -encodeBool = \b -> encodeU8 (if b then 1 else 0) +encode_num = \n -> Encode.custom \bytes, @TagLenFmt {} -> append_pre_len bytes 'n' n + +encode_u8 = encode_num +encode_u16 = encode_num +encode_u32 = encode_num +encode_u64 = encode_num +encode_u128 = encode_num +encode_i8 = encode_num +encode_i16 = encode_num +encode_i32 = encode_num +encode_i64 = encode_num +encode_i128 = encode_num +encode_f32 = encode_num +encode_f64 = encode_num +encode_dec = encode_num +encode_bool = \b -> encode_u8 (if b then 1 else 0) expect - actual = Encode.toBytes 1 tagLenFmt - actual == (Str.toUtf8 "n1 ") + actual = Encode.to_bytes 1 tag_len_fmt + actual == (Str.to_utf8 "n1 ") expect - actual = Encode.toBytes 1.3dec tagLenFmt - actual == (Str.toUtf8 "n1.3 ") + actual = Encode.to_bytes 1.3dec tag_len_fmt + actual == (Str.to_utf8 "n1.3 ") expect - actual = Encode.toBytes Bool.true tagLenFmt - actual == (Str.toUtf8 "n1 ") + actual = Encode.to_bytes Bool.true tag_len_fmt + actual == (Str.to_utf8 "n1 ") -encodeString = \str -> Encode.custom \bytes, @TagLenFmt {} -> - appendPreLen bytes 's' (Str.countUtf8Bytes str) - |> List.concat (Str.toUtf8 str) +encode_string = \str -> Encode.custom \bytes, @TagLenFmt {} -> + append_pre_len bytes 's' (Str.count_utf8_bytes str) + |> List.concat (Str.to_utf8 str) |> List.append ' ' expect - actual = Encode.toBytes "hey" tagLenFmt - actual == (Str.toUtf8 "s3 hey ") + actual = Encode.to_bytes "hey" tag_len_fmt + actual == (Str.to_utf8 "s3 hey ") -encodeList = \lst, encodeElem -> Encode.custom \bytes, @TagLenFmt {} -> - bytesPre = appendPreLen bytes 'l' (List.len lst) - List.walk lst bytesPre \buf, elem -> - Encode.appendWith buf (encodeElem elem) (@TagLenFmt {}) +encode_list = \lst, encode_elem -> Encode.custom \bytes, @TagLenFmt {} -> + bytes_pre = append_pre_len bytes 'l' (List.len lst) + List.walk lst bytes_pre \buf, elem -> + Encode.append_with buf (encode_elem elem) (@TagLenFmt {}) expect - actual = Encode.toBytes [1, 2, 3] tagLenFmt - actual == (Str.toUtf8 "l3 n1 n2 n3 ") + actual = Encode.to_bytes [1, 2, 3] tag_len_fmt + actual == (Str.to_utf8 "l3 n1 n2 n3 ") -encodeRecord = \fields -> Encode.custom \bytes, @TagLenFmt {} -> - bytesPre = - appendPreLen bytes 'r' (List.len fields) - List.walk fields bytesPre \buf, { key, value } -> - Encode.appendWith buf (encodeString key) (@TagLenFmt {}) - |> Encode.appendWith value (@TagLenFmt {}) +encode_record = \fields -> Encode.custom \bytes, @TagLenFmt {} -> + bytes_pre = + append_pre_len bytes 'r' (List.len fields) + List.walk fields bytes_pre \buf, { key, value } -> + Encode.append_with buf (encode_string key) (@TagLenFmt {}) + |> Encode.append_with value (@TagLenFmt {}) expect - actual = Encode.toBytes { foo: "foo", bar: Bool.true } tagLenFmt - actual == Str.toUtf8 "r2 s3 bar n1 s3 foo s3 foo " + actual = Encode.to_bytes { foo: "foo", bar: Bool.true } tag_len_fmt + actual == Str.to_utf8 "r2 s3 bar n1 s3 foo s3 foo " -encodeTuple = \elems -> encodeList elems (\e -> e) -encodeTag = \name, payload -> encodeTuple (List.prepend payload (encodeString name)) +encode_tuple = \elems -> encode_list elems (\e -> e) +encode_tag = \name, payload -> encode_tuple (List.prepend payload (encode_string name)) expect - actual = Encode.toBytes (1, "foo", {}) tagLenFmt - actual == (Str.toUtf8 "l3 n1 s3 foo r0 ") + actual = Encode.to_bytes (1, "foo", {}) tag_len_fmt + actual == (Str.to_utf8 "l3 n1 s3 foo r0 ") # DECODE -splitAtSpace = \bytes -> - when List.splitFirst bytes ' ' is +split_at_space = \bytes -> + when List.split_first bytes ' ' is Ok { before, after } -> { taken: before, rest: after } Err _ -> { taken: [], rest: bytes } -decodeNumPre = \bytes, pre, toNum -> - when List.splitAt bytes 1 is +decode_num_pre = \bytes, pre, to_num -> + when List.split_at bytes 1 is { before: [b], others } if b == pre -> - { taken, rest } = splitAtSpace others - str = taken |> Str.fromUtf8 |> Result.mapErr \_ -> TooShort - result = Result.try str \s -> (toNum s |> Result.mapErr \_ -> TooShort) + { taken, rest } = split_at_space others + str = taken |> Str.from_utf8 |> Result.map_err \_ -> TooShort + result = Result.try str \s -> (to_num s |> Result.map_err \_ -> TooShort) when result is Ok _ -> { result, rest } Err _ -> { result, rest: others } _ -> { result: Err TooShort, rest: bytes } -decodeNum = \toNum -> Decode.custom \bytes, @TagLenFmt {} -> decodeNumPre bytes 'n' toNum - -decodeU8 = decodeNum Str.toU8 -decodeU16 = decodeNum Str.toU16 -decodeU32 = decodeNum Str.toU32 -decodeU64 = decodeNum Str.toU64 -decodeU128 = decodeNum Str.toU128 -decodeI8 = decodeNum Str.toI8 -decodeI16 = decodeNum Str.toI16 -decodeI32 = decodeNum Str.toI32 -decodeI64 = decodeNum Str.toI64 -decodeI128 = decodeNum Str.toI128 -decodeF32 = decodeNum Str.toF32 -decodeF64 = decodeNum Str.toF64 -decodeDec = decodeNum Str.toDec -decodeBool = Decode.custom \bytes, @TagLenFmt {} -> - { result: numResult, rest } = Decode.decodeWith bytes decodeU8 (@TagLenFmt {}) - when numResult is +decode_num = \to_num -> Decode.custom \bytes, @TagLenFmt {} -> decode_num_pre bytes 'n' to_num + +decode_u8 = decode_num Str.to_u8 +decode_u16 = decode_num Str.to_u16 +decode_u32 = decode_num Str.to_u32 +decode_u64 = decode_num Str.to_u64 +decode_u128 = decode_num Str.to_u128 +decode_i8 = decode_num Str.to_i8 +decode_i16 = decode_num Str.to_i16 +decode_i32 = decode_num Str.to_i32 +decode_i64 = decode_num Str.to_i64 +decode_i128 = decode_num Str.to_i128 +decode_f32 = decode_num Str.to_f32 +decode_f64 = decode_num Str.to_f64 +decode_dec = decode_num Str.to_dec +decode_bool = Decode.custom \bytes, @TagLenFmt {} -> + { result: num_result, rest } = Decode.decode_with bytes decode_u8 (@TagLenFmt {}) + when num_result is Ok 1 -> { result: Ok Bool.true, rest } Ok 0 -> { result: Ok Bool.false, rest } _ -> { result: Err TooShort, rest: bytes } expect - actual = Decode.fromBytes (Str.toUtf8 "n1 ") tagLenFmt - actual == Ok (Num.toU8 1) + actual = Decode.from_bytes (Str.to_utf8 "n1 ") tag_len_fmt + actual == Ok (Num.to_u8 1) expect - actual = Decode.fromBytes (Str.toUtf8 "n1 ") tagLenFmt + actual = Decode.from_bytes (Str.to_utf8 "n1 ") tag_len_fmt actual == Ok Bool.true -decodeLenPre = \bytes, pre -> decodeNumPre bytes pre Str.toU64 +decode_len_pre = \bytes, pre -> decode_num_pre bytes pre Str.to_u64 -decodeTry = \{ result, rest }, map -> +decode_try = \{ result, rest }, map -> when result is Ok a -> map a rest Err e -> { result: Err e, rest } -decodeString = Decode.custom \bytes, @TagLenFmt {} -> - decodeLenPre bytes 's' - |> decodeTry \len, lenRest -> - { before, others } = List.splitAt lenRest len - result = Str.fromUtf8 before |> Result.mapErr \_ -> TooShort - when List.splitAt others 1 is +decode_string = Decode.custom \bytes, @TagLenFmt {} -> + decode_len_pre bytes 's' + |> decode_try \len, len_rest -> + { before, others } = List.split_at len_rest len + result = Str.from_utf8 before |> Result.map_err \_ -> TooShort + when List.split_at others 1 is { before: [' '], others: rest } -> { result, rest } _ -> { result: Err TooShort, rest: others } expect - actual = Decode.fromBytes (Str.toUtf8 "s3 foo ") tagLenFmt + actual = Decode.from_bytes (Str.to_utf8 "s3 foo ") tag_len_fmt actual == Ok "foo" -repeatDecode : U8, List U8, state, (state -> Decode.Decoder state TagLenFmt) -> DecodeResult state -repeatDecode = \pre, bytes, state, stepState -> +repeat_decode : U8, List U8, state, (state -> Decode.Decoder state TagLenFmt) -> DecodeResult state +repeat_decode = \pre, bytes, state, step_state -> run = \end, bs -> List.range { start: At 0, end: Before end } |> List.walk { result: Ok state, rest: bs } \res, _i -> - decodeTry res \s, rest -> - Decode.decodeWith rest (stepState s) (@TagLenFmt {}) + decode_try res \s, rest -> + Decode.decode_with rest (step_state s) (@TagLenFmt {}) - decodeLenPre bytes pre |> decodeTry run + decode_len_pre bytes pre |> decode_try run -decodeList = \elemDecoder -> Decode.custom \bytes, @TagLenFmt {} -> +decode_list = \elem_decoder -> Decode.custom \bytes, @TagLenFmt {} -> step = \lst -> Decode.custom \sbytes, @TagLenFmt {} -> - Decode.decodeWith sbytes elemDecoder (@TagLenFmt {}) - |> Decode.mapResult \elem -> List.append lst elem - repeatDecode 'l' bytes [] step + Decode.decode_with sbytes elem_decoder (@TagLenFmt {}) + |> Decode.map_result \elem -> List.append lst elem + repeat_decode 'l' bytes [] step expect - actual = Decode.fromBytes (Str.toUtf8 "l3 n1 n2 n3 ") tagLenFmt + actual = Decode.from_bytes (Str.to_utf8 "l3 n1 n2 n3 ") tag_len_fmt actual == Ok [1, 2, 3] -decodeRecord = \initState, stepField, finalizer -> Decode.custom \bytes, @TagLenFmt {} -> - flattenFieldRes = \next, rest -> +decode_record = \init_state, step_field, finalizer -> Decode.custom \bytes, @TagLenFmt {} -> + flatten_field_res = \next, rest -> when next is - Keep valueDecoder -> { result: Ok valueDecoder, rest } + Keep value_decoder -> { result: Ok value_decoder, rest } Skip -> { result: Err TooShort, rest } step = \state -> Decode.custom \sbytes, @TagLenFmt {} -> - Decode.decodeWith sbytes decodeString (@TagLenFmt {}) - |> decodeTry \key, bs -> - flattenFieldRes (stepField state key) bs - |> decodeTry \valueDecoder, bs -> - Decode.decodeWith bs valueDecoder (@TagLenFmt {}) + Decode.decode_with sbytes decode_string (@TagLenFmt {}) + |> decode_try \key, bs -> + flatten_field_res (step_field state key) bs + |> decode_try \value_decoder, bs -> + Decode.decode_with bs value_decoder (@TagLenFmt {}) - repeatDecode 'r' bytes initState step - |> decodeTry \state, rest -> { result: finalizer state (@TagLenFmt {}), rest } + repeat_decode 'r' bytes init_state step + |> decode_try \state, rest -> { result: finalizer state (@TagLenFmt {}), rest } expect - actual = Decode.fromBytes (Str.toUtf8 "r2 s3 bar n1 s3 foo s3 foo ") tagLenFmt + actual = Decode.from_bytes (Str.to_utf8 "r2 s3 bar n1 s3 foo s3 foo ") tag_len_fmt actual == Ok ({ foo: "foo", bar: Bool.true }) -decodeTuple = \initialState, stepElem, finalizer -> Decode.custom \bytes, @TagLenFmt {} -> - flattenFieldRes = \next, rest -> +decode_tuple = \initial_state, step_elem, finalizer -> Decode.custom \bytes, @TagLenFmt {} -> + flatten_field_res = \next, rest -> when next is Next dec -> { result: Ok dec, rest } TooLong -> { result: Err TooShort, rest } step = \{ state, i } -> Decode.custom \sbytes, @TagLenFmt {} -> - flattenFieldRes (stepElem state i) sbytes - |> decodeTry \dec, rest -> Decode.decodeWith rest dec (@TagLenFmt {}) - |> Decode.mapResult \s -> { state: s, i: i + 1 } + flatten_field_res (step_elem state i) sbytes + |> decode_try \dec, rest -> Decode.decode_with rest dec (@TagLenFmt {}) + |> Decode.map_result \s -> { state: s, i: i + 1 } - repeatDecode 'l' bytes { state: initialState, i: 0 } step - |> decodeTry \s, rest -> { result: finalizer s.state, rest } + repeat_decode 'l' bytes { state: initial_state, i: 0 } step + |> decode_try \s, rest -> { result: finalizer s.state, rest } expect - actual = Decode.fromBytes (Str.toUtf8 "l3 n1 s3 abc l1 n0 ") tagLenFmt + actual = Decode.from_bytes (Str.to_utf8 "l3 n1 s3 abc l1 n0 ") tag_len_fmt actual == Ok (1, "abc", [Bool.false]) expect input = { foo: (1, "abc", [Bool.false, Bool.true]), bar: { baz: 0.32 } } - encoded = Encode.toBytes input tagLenFmt - decoded = Decode.fromBytes encoded tagLenFmt + encoded = Encode.to_bytes input tag_len_fmt + decoded = Decode.from_bytes encoded tag_len_fmt decoded == Ok input diff --git a/crates/valgrind_tests/src/lib.rs b/crates/valgrind_tests/src/lib.rs index 75a481234a8..b1221bc0e49 100644 --- a/crates/valgrind_tests/src/lib.rs +++ b/crates/valgrind_tests/src/lib.rs @@ -24,7 +24,7 @@ fn build_host() { } let stub_dll_symbols = roc_linker::ExposedSymbols { - top_level_values: vec![String::from("mainForHost")], + top_level_values: vec![String::from("main_for_host")], exported_closure_types: vec![], } .stub_dll_symbols(); diff --git a/crates/valgrind_tests/zig-platform/host.zig b/crates/valgrind_tests/zig-platform/host.zig index 26d432aa997..1bec2f024f7 100644 --- a/crates/valgrind_tests/zig-platform/host.zig +++ b/crates/valgrind_tests/zig-platform/host.zig @@ -102,7 +102,7 @@ comptime { const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic(*RocStr) void; +extern fn roc__main_for_host_1_exposed_generic(*RocStr) void; const Unit = extern struct {}; @@ -114,7 +114,7 @@ pub export fn main() u8 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed_generic(&callresult); + roc__main_for_host_1_exposed_generic(&callresult); const nanos = timer.read(); const seconds = (@as(f64, @floatFromInt(nanos)) / 1_000_000_000.0); diff --git a/crates/valgrind_tests/zig-platform/main.roc b/crates/valgrind_tests/zig-platform/main.roc index a52fe9a4801..f42048abe8c 100644 --- a/crates/valgrind_tests/zig-platform/main.roc +++ b/crates/valgrind_tests/zig-platform/main.roc @@ -3,7 +3,7 @@ platform "echo-in-zig" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/crates/wasm_module/src/lib.rs b/crates/wasm_module/src/lib.rs index f29f413e539..3e662c1c7e5 100644 --- a/crates/wasm_module/src/lib.rs +++ b/crates/wasm_module/src/lib.rs @@ -513,7 +513,7 @@ impl<'a> WasmModule<'a> { }) } - /// Linking steps for host-to-app functions like `roc__mainForHost_1_exposed` + /// Linking steps for host-to-app functions like `roc__main_for_host_1_exposed` /// (See further explanation in the gen_wasm README) /// - Remove the target function from the ImportSection. It's not a JS import but the host declared it as one. /// - Update all of its call sites to the new index in the app diff --git a/examples/glue/glue.roc b/examples/glue/glue.roc index c988fa87e23..912853e350e 100644 --- a/examples/glue/glue.roc +++ b/examples/glue/glue.roc @@ -2,6 +2,6 @@ app [main] { pf: platform "rust-platform/main.roc" } main = msg = "Roc <3 Rust, also on stderr!\n" - StdoutWrite "Roc <3 Rust!\n" \{} -> - StderrWrite msg \{} -> - Done + StdoutWrite("Roc <3 Rust!\n", \{} -> + StderrWrite(msg, \{} -> + Done)) diff --git a/examples/glue/rust-platform/main.roc b/examples/glue/rust-platform/main.roc index 47017d926ca..657653f7e2e 100644 --- a/examples/glue/rust-platform/main.roc +++ b/examples/glue/rust-platform/main.roc @@ -3,14 +3,14 @@ platform "echo-in-rust" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -# mainForHost : [StdoutWrite Str (({} -> Op) as Fx0), StderrWrite Str (({} -> Op) as Fx1), Done] as Op -mainForHost : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op -mainForHost = main +# main_for_host : [StdoutWrite Str (({} -> Op) as Fx0), StderrWrite Str (({} -> Op) as Fx1), Done] as Op +main_for_host : [StdoutWrite Str ({} -> Op), StderrWrite Str ({} -> Op), Done] as Op +main_for_host = main -# mainForHost : { x: Str, y: {} -> Str } -# mainForHost = +# main_for_host : { x: Str, y: {} -> Str } +# main_for_host = # y = "foo" # # when main is diff --git a/examples/glue/rust-platform/src/glue.rs b/examples/glue/rust-platform/src/glue.rs index e3e2e524b7e..b0787246928 100644 --- a/examples/glue/rust-platform/src/glue.rs +++ b/examples/glue/rust-platform/src/glue.rs @@ -101,12 +101,12 @@ pub struct RocFunction_66 { impl RocFunction_66 { pub fn force_thunk(mut self, arg_0: ()) -> Op { extern "C" { - fn roc__mainForHost_0_caller(arg_0: &(), closure_data: *mut u8, output: *mut Op); + fn roc__main_for_host_0_caller(arg_0: &(), closure_data: *mut u8, output: *mut Op); } let mut output = std::mem::MaybeUninit::uninit(); let ptr = self.closure_data.as_mut_ptr(); - unsafe { roc__mainForHost_0_caller(&arg_0, ptr, output.as_mut_ptr()) }; + unsafe { roc__main_for_host_0_caller(&arg_0, ptr, output.as_mut_ptr()) }; unsafe { output.assume_init() } } } @@ -126,12 +126,12 @@ pub struct RocFunction_67 { impl RocFunction_67 { pub fn force_thunk(mut self, arg_0: ()) -> Op { extern "C" { - fn roc__mainForHost_1_caller(arg_0: &(), closure_data: *mut u8, output: *mut Op); + fn roc__main_for_host_1_caller(arg_0: &(), closure_data: *mut u8, output: *mut Op); } let mut output = std::mem::MaybeUninit::uninit(); let ptr = self.closure_data.as_mut_ptr(); - unsafe { roc__mainForHost_1_caller(&arg_0, ptr, output.as_mut_ptr()) }; + unsafe { roc__main_for_host_1_caller(&arg_0, ptr, output.as_mut_ptr()) }; unsafe { output.assume_init() } } } diff --git a/examples/glue/rust-platform/src/lib.rs b/examples/glue/rust-platform/src/lib.rs index 022ea94a18e..64bf071a65f 100644 --- a/examples/glue/rust-platform/src/lib.rs +++ b/examples/glue/rust-platform/src/lib.rs @@ -7,7 +7,7 @@ use std::ffi::CStr; use std::io::Write; use std::os::raw::c_char; -use roc_app::mainForHost as roc_main; +use roc_app::main_for_host as roc_main; #[no_mangle] pub unsafe extern "C" fn roc_alloc(size: usize, _alignment: u32) -> *mut c_void { diff --git a/examples/jvm-interop/bridge.c b/examples/jvm-interop/bridge.c index 4bd4aafc278..0e2a9827532 100644 --- a/examples/jvm-interop/bridge.c +++ b/examples/jvm-interop/bridge.c @@ -282,11 +282,11 @@ void roc_dbg(struct RocStr *loc, struct RocStr *msg, struct RocStr *src) { fprintf(stderr, "[%s] %s = %s\n", loc_bytes, src_bytes, msg_bytes); } -extern void roc__programForHost_1__InterpolateString_caller(struct RocStr *name, char *closure_data, struct RocStr *ret); +extern void roc__program_for_host_1__InterpolateString_caller(struct RocStr *name, char *closure_data, struct RocStr *ret); -extern void roc__programForHost_1__MulArrByScalar_caller(struct RocListI32 *arr, int32_t *scalar, char *closure_data, struct RocListI32 *ret); +extern void roc__program_for_host_1__MulArrByScalar_caller(struct RocListI32 *arr, int32_t *scalar, char *closure_data, struct RocListI32 *ret); -extern void roc__programForHost_1__Factorial_caller(int64_t *scalar, char *closure_data, int64_t *ret); +extern void roc__program_for_host_1__Factorial_caller(int64_t *scalar, char *closure_data, int64_t *ret); JNIEXPORT jstring JNICALL Java_javaSource_Demo_sayHello @@ -303,7 +303,7 @@ JNIEXPORT jstring JNICALL Java_javaSource_Demo_sayHello struct RocStr ret = {0}; // Call the Roc function to populate `ret`'s bytes. - roc__programForHost_1__InterpolateString_caller(&rocName, 0, &ret); + roc__program_for_host_1__InterpolateString_caller(&rocName, 0, &ret); jbyte *bytes = (jbyte*)(is_small_str(ret) ? (uint8_t*)&ret : ret.bytes); // java being java making this a lot harder than it needs to be @@ -346,7 +346,7 @@ JNIEXPORT jintArray JNICALL Java_javaSource_Demo_mulArrByScalar incref((void *)&originalArray, alignof(int32_t*)); struct RocListI32 ret = {0}; - roc__programForHost_1__MulArrByScalar_caller(&originalArray, &scalar, 0, &ret); + roc__program_for_host_1__MulArrByScalar_caller(&originalArray, &scalar, 0, &ret); // create jvm constructs jintArray multiplied = (*env)->NewIntArray(env, ret.len); @@ -378,7 +378,7 @@ JNIEXPORT jlong JNICALL Java_javaSource_Demo_factorial } else { int64_t n = (int64_t)num; - roc__programForHost_1__Factorial_caller(&n, 0, &ret); + roc__program_for_host_1__Factorial_caller(&n, 0, &ret); return ret; } } diff --git a/examples/jvm-interop/impl.roc b/examples/jvm-interop/impl.roc index 137525a97b5..5b72fc724fa 100644 --- a/examples/jvm-interop/impl.roc +++ b/examples/jvm-interop/impl.roc @@ -1,23 +1,23 @@ app [program] { pf: platform "platform.roc" } -interpolateString : Str -> Str -interpolateString = \name -> +interpolate_string : Str -> Str +interpolate_string = \name -> "Hello from Roc $(name)!!!🤘🤘🤘" # jint is i32 -mulArrByScalar : List I32, I32 -> List I32 -mulArrByScalar = \arr, scalar -> - List.map arr \x -> x * scalar +mul_arr_by_scalar : List I32, I32 -> List I32 +mul_arr_by_scalar = \arr, scalar -> + List.map(arr, \x -> x * scalar) # java doesn't have unsigned numbers so we cope with long # factorial : I64 -> I64 factorial = \n -> if n < 0 then # while we get the chance, exemplify a roc panic in an interop - crash "No negatives here!!!" + crash("No negatives here!!!") else if n == 0 then 1 else - n * (factorial (n - 1)) + n * (factorial((n - 1))) -program = { interpolateString, factorial, mulArrByScalar } +program = { interpolate_string, factorial, mul_arr_by_scalar } diff --git a/examples/jvm-interop/platform.roc b/examples/jvm-interop/platform.roc index 8931752ff03..933b0243e16 100644 --- a/examples/jvm-interop/platform.roc +++ b/examples/jvm-interop/platform.roc @@ -3,11 +3,11 @@ platform "jvm-interop" exposes [] packages {} imports [] - provides [programForHost] + provides [program_for_host] -programForHost : { - interpolateString : (Str -> Str) as InterpolateString, - mulArrByScalar : (List I32, I32 -> List I32) as MulArrByScalar, +program_for_host : { + interpolate_string : (Str -> Str) as InterpolateString, + mul_arr_by_scalar : (List I32, I32 -> List I32) as MulArrByScalar, factorial : (I64 -> I64) as Factorial, } -programForHost = program +program_for_host = program diff --git a/examples/nodejs-interop/native-c-api/demo.c b/examples/nodejs-interop/native-c-api/demo.c index 5d20082fcbf..a46462dbde4 100644 --- a/examples/nodejs-interop/native-c-api/demo.c +++ b/examples/nodejs-interop/native-c-api/demo.c @@ -347,7 +347,7 @@ napi_value roc_str_as_node_string(napi_env env, struct RocStr roc_str) { return answer; } -extern void roc__mainForHost_1_exposed_generic(struct RocStr *ret, struct RocStr *arg); +extern void roc__main_for_host_1_exposed_generic(struct RocStr *ret, struct RocStr *arg); // Receive a string value from Node and pass it to Roc as a RocStr, then get a RocStr // back from Roc and convert it into a Node string. @@ -388,7 +388,7 @@ napi_value call_roc(napi_env env, napi_callback_info info) { struct RocStr roc_ret; // Call the Roc function to populate `roc_ret`'s bytes. - roc__mainForHost_1_exposed_generic(&roc_ret, &roc_arg); + roc__main_for_host_1_exposed_generic(&roc_ret, &roc_arg); // Consume the RocStr to create the Node string. return roc_str_into_node_string(env, roc_ret); diff --git a/examples/nodejs-interop/native-c-api/platform/main.roc b/examples/nodejs-interop/native-c-api/platform/main.roc index 43294c9d6d7..b633421669d 100644 --- a/examples/nodejs-interop/native-c-api/platform/main.roc +++ b/examples/nodejs-interop/native-c-api/platform/main.roc @@ -3,8 +3,8 @@ platform "nodejs-interop" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -> Str -mainForHost = \message -> - main message +main_for_host : Str -> Str +main_for_host = \message -> + main(message) diff --git a/examples/nodejs-interop/wasm/platform/host.zig b/examples/nodejs-interop/wasm/platform/host.zig index 5f830fabdd9..2eeab845b03 100644 --- a/examples/nodejs-interop/wasm/platform/host.zig +++ b/examples/nodejs-interop/wasm/platform/host.zig @@ -35,14 +35,14 @@ export fn roc_dealloc(c_ptr: *anyopaque, alignment: u32) callconv(.C) void { // NOTE roc_panic and roc_dbg is provided in the JS file, so it can throw an exception -extern fn roc__mainForHost_1_exposed(*RocStr) void; +extern fn roc__main_for_host_1_exposed(*RocStr) void; extern fn js_display_roc_string(str_bytes: ?[*]u8, str_len: usize) void; pub export fn main() u8 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed(&callresult); + roc__main_for_host_1_exposed(&callresult); // display the result using JavaScript js_display_roc_string(callresult.asU8ptrMut(), callresult.len()); diff --git a/examples/nodejs-interop/wasm/platform/main.roc b/examples/nodejs-interop/wasm/platform/main.roc index 231cfb4fecb..d8d7292582e 100644 --- a/examples/nodejs-interop/wasm/platform/main.roc +++ b/examples/nodejs-interop/wasm/platform/main.roc @@ -3,7 +3,7 @@ platform "wasm-nodejs-example-platform" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/examples/platform-switching/c-platform/host.c b/examples/platform-switching/c-platform/host.c index 2b0baf8e15c..021d20c974f 100644 --- a/examples/platform-switching/c-platform/host.c +++ b/examples/platform-switching/c-platform/host.c @@ -85,12 +85,12 @@ size_t roc_str_len(struct RocStr str) { } } -extern void roc__mainForHost_1_exposed_generic(struct RocStr *string); +extern void roc__main_for_host_1_exposed_generic(struct RocStr *string); int main() { struct RocStr str; - roc__mainForHost_1_exposed_generic(&str); + roc__main_for_host_1_exposed_generic(&str); // Determine str_len and the str_bytes pointer, // taking into account the small string optimization. diff --git a/examples/platform-switching/c-platform/main.roc b/examples/platform-switching/c-platform/main.roc index 35c286a30ef..7687aa43d39 100644 --- a/examples/platform-switching/c-platform/main.roc +++ b/examples/platform-switching/c-platform/main.roc @@ -3,7 +3,7 @@ platform "echo-in-c" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/examples/platform-switching/rust-platform/build.rs b/examples/platform-switching/rust-platform/build.rs index fdb4c2891f2..32b0e6cadab 100644 --- a/examples/platform-switching/rust-platform/build.rs +++ b/examples/platform-switching/rust-platform/build.rs @@ -2,7 +2,7 @@ // // ``` // = note: Undefined symbols for architecture arm64: -// "_roc__mainForHost_1_exposed_generic", referenced from: +// "_roc__main_for_host_1_exposed_generic", referenced from: // _main in rustplatform-df9e357e0cc989a6.rustplatform.863be87f3956573-cgu.0.rcgu.o // ld: symbol(s) not found for architecture arm64 // clang-16: error: linker command failed with exit code 1 (use -v to see invocation) diff --git a/examples/platform-switching/rust-platform/main.roc b/examples/platform-switching/rust-platform/main.roc index 13dd322d6b9..0fe1dd7353d 100644 --- a/examples/platform-switching/rust-platform/main.roc +++ b/examples/platform-switching/rust-platform/main.roc @@ -3,7 +3,7 @@ platform "echo-in-rust" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/examples/platform-switching/rust-platform/src/lib.rs b/examples/platform-switching/rust-platform/src/lib.rs index 1f910821130..55ed67ba974 100644 --- a/examples/platform-switching/rust-platform/src/lib.rs +++ b/examples/platform-switching/rust-platform/src/lib.rs @@ -6,7 +6,7 @@ use roc_std::RocStr; use std::io::Write; extern "C" { - #[link_name = "roc__mainForHost_1_exposed_generic"] + #[link_name = "roc__main_for_host_1_exposed_generic"] fn roc_main(_: &mut RocStr); } diff --git a/examples/platform-switching/web-assembly-platform/host.zig b/examples/platform-switching/web-assembly-platform/host.zig index 04c8eb716b8..c8a54aff9e1 100644 --- a/examples/platform-switching/web-assembly-platform/host.zig +++ b/examples/platform-switching/web-assembly-platform/host.zig @@ -35,14 +35,14 @@ export fn roc_dealloc(c_ptr: *anyopaque, alignment: u32) callconv(.C) void { // NOTE roc_panic and roc_dbg is provided in the JS file, so it can throw an exception -extern fn roc__mainForHost_1_exposed(*RocStr) void; +extern fn roc__main_for_host_1_exposed(*RocStr) void; extern fn js_display_roc_string(str_bytes: ?[*]u8, str_len: usize) void; pub export fn main() u8 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed(&callresult); + roc__main_for_host_1_exposed(&callresult); // display the result using JavaScript js_display_roc_string(callresult.asU8ptrMut(), callresult.len()); diff --git a/examples/platform-switching/web-assembly-platform/main.roc b/examples/platform-switching/web-assembly-platform/main.roc index 08830392cda..ad7de7c8986 100644 --- a/examples/platform-switching/web-assembly-platform/main.roc +++ b/examples/platform-switching/web-assembly-platform/main.roc @@ -3,7 +3,7 @@ platform "echo-in-web-assembly" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/examples/platform-switching/zig-platform/host.zig b/examples/platform-switching/zig-platform/host.zig index ce8fdd1e2b5..37a1298119d 100644 --- a/examples/platform-switching/zig-platform/host.zig +++ b/examples/platform-switching/zig-platform/host.zig @@ -102,7 +102,7 @@ comptime { const mem = std.mem; const Allocator = mem.Allocator; -extern fn roc__mainForHost_1_exposed_generic(*RocStr) void; +extern fn roc__main_for_host_1_exposed_generic(*RocStr) void; const Unit = extern struct {}; @@ -111,7 +111,7 @@ pub export fn main() u8 { // actually call roc to populate the callresult var callresult = RocStr.empty(); - roc__mainForHost_1_exposed_generic(&callresult); + roc__main_for_host_1_exposed_generic(&callresult); // stdout the result stdout.print("{s}", .{callresult.asSlice()}) catch unreachable; diff --git a/examples/platform-switching/zig-platform/main.roc b/examples/platform-switching/zig-platform/main.roc index a52fe9a4801..f42048abe8c 100644 --- a/examples/platform-switching/zig-platform/main.roc +++ b/examples/platform-switching/zig-platform/main.roc @@ -3,7 +3,7 @@ platform "echo-in-zig" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : Str -mainForHost = main +main_for_host : Str +main_for_host = main diff --git a/examples/python-interop/README.md b/examples/python-interop/README.md index 4dbbed8f3e5..b58779c94dc 100644 --- a/examples/python-interop/README.md +++ b/examples/python-interop/README.md @@ -76,7 +76,7 @@ We have: The first three are basically the backbone of any C-API extension.\ In addition, a couple more functions and notes you may want to pay attention to: - [`void roc_panic`] - When creating such interpreter-dependent code, it is reasonable to make the implementation of this function fire up an interpreter Exception (e.g `RuntimeError` or whatever suits). -- When I first came across another implementation, I was a bit confused about `extern void roc__mainForHost_1_exposed_generic`, so let me clarify - this is an external function, implemented by the application, that goes (on the application side-) by the name `mainForHost`. +- When I first came across another implementation, I was a bit confused about `extern void roc__main_for_host_1_exposed_generic`, so let me clarify - this is an external function, implemented by the application, that goes (on the application side-) by the name `main_for_host`. And one last thing - - When writing such the C glue (here, `demo.c`), you need to pay attention to not only Python's reference counting, but also Roc's, so remember to wear seatbelts and decrement your ref counts. diff --git a/examples/python-interop/demo.c b/examples/python-interop/demo.c index 566d43dcd83..99ba3902b8b 100644 --- a/examples/python-interop/demo.c +++ b/examples/python-interop/demo.c @@ -196,7 +196,7 @@ size_t roc_str_len(struct RocStr str) } } -extern void roc__mainForHost_1_exposed_generic(struct RocBytes *ret, struct RocBytes *arg); +extern void roc__main_for_host_1_exposed_generic(struct RocBytes *ret, struct RocBytes *arg); // Receive a value from Python, JSON serialized it and pass it to Roc as a List U8 // (at which point the Roc platform will decode it and crash if it's invalid, @@ -224,7 +224,7 @@ PyObject * call_roc(PyObject *self, PyObject *args) struct RocBytes ret; // Call the Roc function to populate `ret`'s bytes. - roc__mainForHost_1_exposed_generic(&ret, &arg); + roc__main_for_host_1_exposed_generic(&ret, &arg); // Create a Python string from the heap-allocated JSON bytes the Roc function returned. PyObject* py_obj = PyUnicode_FromStringAndSize((char*)ret.bytes, ret.len); diff --git a/examples/python-interop/libhello.roc b/examples/python-interop/libhello.roc index a804afad7ab..1ee460ee2a6 100644 --- a/examples/python-interop/libhello.roc +++ b/examples/python-interop/libhello.roc @@ -5,6 +5,6 @@ main = \num -> if num == 0 then "I need a positive number here!" else - str = Num.toStr num + str = Num.to_str(num) "The number was $(str), OH YEAH!!! 🤘🤘" diff --git a/examples/python-interop/platform/host.c b/examples/python-interop/platform/host.c index 8d3ab3c39f4..393790bf4d5 100644 --- a/examples/python-interop/platform/host.c +++ b/examples/python-interop/platform/host.c @@ -80,12 +80,12 @@ size_t roc_str_len(struct RocStr str) { } } -extern void roc__mainForHost_1_exposed_generic(struct RocStr *string); +extern void roc__main_for_host_1_exposed_generic(struct RocStr *string); int main() { struct RocStr str; - roc__mainForHost_1_exposed_generic(&str); + roc__main_for_host_1_exposed_generic(&str); // Determine str_len and the str_bytes pointer, // taking into account the small string optimization. diff --git a/examples/python-interop/platform/main.roc b/examples/python-interop/platform/main.roc index 7162c931fc3..e81dd52fb7a 100644 --- a/examples/python-interop/platform/main.roc +++ b/examples/python-interop/platform/main.roc @@ -3,14 +3,14 @@ platform "python-interop" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : List U8 -> List U8 -mainForHost = \input -> - when Str.fromUtf8 input is - Ok arg -> - when Str.toU64 arg is - Ok num -> main num |> Str.toUtf8 - Err _ -> [] +main_for_host : List U8 -> List U8 +main_for_host = \input -> + when Str.from_utf8(input) is + Ok(arg) -> + when Str.to_u64(arg) is + Ok(num) -> main(num) |> Str.to_utf8 + Err(_) -> [] - Err _ -> [] + Err(_) -> [] diff --git a/examples/ruby-interop/demo.c b/examples/ruby-interop/demo.c index 5e76d3377e3..f3a73f30fd8 100644 --- a/examples/ruby-interop/demo.c +++ b/examples/ruby-interop/demo.c @@ -192,7 +192,7 @@ size_t roc_str_len(struct RocStr str) } } -extern void roc__mainForHost_1_exposed_generic(struct RocBytes *ret, struct RocBytes *arg); +extern void roc__main_for_host_1_exposed_generic(struct RocBytes *ret, struct RocBytes *arg); // Receive a value from Ruby, serialize it and pass it to Roc as a List U8 // (at which point the Roc platform will decode it and crash if it's invalid, @@ -207,7 +207,7 @@ VALUE call_roc(VALUE self, VALUE rb_arg) struct RocBytes ret; // Call the Roc function to populate `ret`'s bytes. - roc__mainForHost_1_exposed_generic(&ret, &arg); + roc__main_for_host_1_exposed_generic(&ret, &arg); // Create a rb_utf8_str from the heap-allocated utf-8 bytes the Roc function returned. VALUE returned_str = rb_utf8_str_new((char *)ret.bytes, ret.len); diff --git a/examples/ruby-interop/libhello.roc b/examples/ruby-interop/libhello.roc index a804afad7ab..1ee460ee2a6 100644 --- a/examples/ruby-interop/libhello.roc +++ b/examples/ruby-interop/libhello.roc @@ -5,6 +5,6 @@ main = \num -> if num == 0 then "I need a positive number here!" else - str = Num.toStr num + str = Num.to_str(num) "The number was $(str), OH YEAH!!! 🤘🤘" diff --git a/examples/ruby-interop/platform/host.c b/examples/ruby-interop/platform/host.c index 10267c6eaac..f27aaefd991 100644 --- a/examples/ruby-interop/platform/host.c +++ b/examples/ruby-interop/platform/host.c @@ -84,12 +84,12 @@ size_t roc_str_len(struct RocStr str) { } } -extern void roc__mainForHost_1_exposed_generic(struct RocStr *string); +extern void roc__main_for_host_1_exposed_generic(struct RocStr *string); int main() { struct RocStr str; - roc__mainForHost_1_exposed_generic(&str); + roc__main_for_host_1_exposed_generic(&str); // Determine str_len and the str_bytes pointer, // taking into account the small string optimization. diff --git a/examples/ruby-interop/platform/main.roc b/examples/ruby-interop/platform/main.roc index c4a7379a3a9..33ad40d532f 100644 --- a/examples/ruby-interop/platform/main.roc +++ b/examples/ruby-interop/platform/main.roc @@ -3,14 +3,14 @@ platform "ruby-interop" exposes [] packages {} imports [] - provides [mainForHost] + provides [main_for_host] -mainForHost : List U8 -> List U8 -mainForHost = \input -> - when Str.fromUtf8 input is - Ok arg -> - when Str.toU64 arg is - Ok num -> main num |> Str.toUtf8 - Err _ -> [] +main_for_host : List U8 -> List U8 +main_for_host = \input -> + when Str.from_utf8(input) is + Ok(arg) -> + when Str.to_u64(arg) is + Ok(num) -> main(num) |> Str.to_utf8 + Err(_) -> [] - Err _ -> [] # TODO panic so that Ruby raises an exception + Err(_) -> [] # TODO panic so that Ruby raises an exception diff --git a/examples/virtual-dom-wip/ExampleApp.roc b/examples/virtual-dom-wip/ExampleApp.roc index acfad07efa7..9b08414bdbc 100644 --- a/examples/virtual-dom-wip/ExampleApp.roc +++ b/examples/virtual-dom-wip/ExampleApp.roc @@ -1,4 +1,4 @@ -module [exampleApp, State] +module [example_app, State] import pf.Html exposing [App, Html, html, head, body, div, text, h1] @@ -6,31 +6,31 @@ State : { answer : U32, } -exampleApp : App State State -exampleApp = { +example_app : App State State +example_app = { init, render, - wasmUrl: "assets/example-client.wasm", + wasm_url: "assets/example-client.wasm", } init = \result -> when result is - Ok state -> state - Err _ -> { answer: 0 } + Ok(state) -> state + Err(_) -> { answer: 0 } render : State -> Html State render = \state -> - num = Num.toStr state.answer + num = Num.to_str(state.answer) - html [] [ - head [] [], - body [] [ - h1 [] [text "The app"], - div [] [text "The answer is $(num)"], - ], - ] + html([], [ + head([], []), + body([], [ + h1([], [text("The app")]), + div([], [text("The answer is $(num)")]), + ]), + ]) expect - Html.renderStatic (Html.translateStatic (render { answer: 42 })) + Html.render_static(Html.translate_static(render({ answer: 42 }))) == "

The app

The answer is 42
" diff --git a/examples/virtual-dom-wip/example-client.roc b/examples/virtual-dom-wip/example-client.roc index 947930620a0..9799c2185e8 100644 --- a/examples/virtual-dom-wip/example-client.roc +++ b/examples/virtual-dom-wip/example-client.roc @@ -1,5 +1,5 @@ app [app] { pf: platform "platform/client-side.roc" } -import ExampleApp exposing [exampleApp] +import ExampleApp exposing [example_app] -app = exampleApp +app = example_app diff --git a/examples/virtual-dom-wip/example-server.roc b/examples/virtual-dom-wip/example-server.roc index 23e98bd4874..e2c3a14c1a1 100644 --- a/examples/virtual-dom-wip/example-server.roc +++ b/examples/virtual-dom-wip/example-server.roc @@ -1,5 +1,5 @@ app [app] { pf: platform "platform/server-side.roc" } -import ExampleApp exposing [exampleApp] +import ExampleApp exposing [example_app] -app = exampleApp +app = example_app diff --git a/examples/virtual-dom-wip/platform/Action.roc b/examples/virtual-dom-wip/platform/Action.roc index 073c517f589..87d03160b54 100644 --- a/examples/virtual-dom-wip/platform/Action.roc +++ b/examples/virtual-dom-wip/platform/Action.roc @@ -12,4 +12,4 @@ map : Action a, (a -> b) -> Action b map = \action, transform -> when action is None -> None - Update state -> Update (transform state) + Update(state) -> Update(transform(state)) diff --git a/examples/virtual-dom-wip/platform/Html.roc b/examples/virtual-dom-wip/platform/Html.roc index f06da92d3b4..6a11dc1a3a8 100644 --- a/examples/virtual-dom-wip/platform/Html.roc +++ b/examples/virtual-dom-wip/platform/Html.roc @@ -2,10 +2,10 @@ module [ App, Html, Attribute, - renderStatic, - renderStaticWithoutDocType, + render_static, + render_static_without_doc_type, translate, - translateStatic, + translate_static, text, none, html, @@ -126,7 +126,7 @@ module [ import Html.Internal.Shared import Html.Internal.Server -App state initData : Html.Internal.Shared.App state initData +App state init_data : Html.Internal.Shared.App state init_data Html state : Html.Internal.Shared.Html state Attribute state : Html.Internal.Shared.Attribute state @@ -135,7 +135,7 @@ text = Html.Internal.Shared.text none = Html.Internal.Shared.none translate = Html.Internal.Shared.translate -translateStatic = Html.Internal.Shared.translateStatic +translate_static = Html.Internal.Shared.translate_static ## Render a static Html node to a string, for saving to disk or sending over a network ## @@ -143,129 +143,129 @@ translateStatic = Html.Internal.Shared.translateStatic ## This is intended for generating full HTML documents, so it ## automatically adds `` to the start of the string. ## See also `renderStaticWithoutDocType`. -renderStatic : Html [] -> Str -renderStatic = \node -> - buffer = Str.reserve "" (Html.Internal.Shared.nodeSize node) +render_static : Html [] -> Str +render_static = \node -> + buffer = Str.reserve("", Html.Internal.Shared.node_size(node)) - Html.Internal.Server.appendRenderedStatic buffer node + Html.Internal.Server.append_rendered_static(buffer, node) ## Render a Html node to a static string, without a DOCTYPE -renderStaticWithoutDocType : Html [] -> Str -renderStaticWithoutDocType = \node -> - buffer = Str.reserve "" (Html.Internal.Shared.nodeSize node) +render_static_without_doc_type : Html [] -> Str +render_static_without_doc_type = \node -> + buffer = Str.reserve("", Html.Internal.Shared.node_size(node)) - Html.Internal.Server.appendRenderedStatic buffer node + Html.Internal.Server.append_rendered_static(buffer, node) -html = element "html" -base = element "base" -head = element "head" -link = element "link" -meta = element "meta" -style = element "style" -title = element "title" -body = element "body" -address = element "address" -article = element "article" -aside = element "aside" -footer = element "footer" -header = element "header" -h1 = element "h1" -h2 = element "h2" -h3 = element "h3" -h4 = element "h4" -h5 = element "h5" -h6 = element "h6" -main = element "main" -nav = element "nav" -section = element "section" -blockquote = element "blockquote" -dd = element "dd" -div = element "div" -dl = element "dl" -dt = element "dt" -figcaption = element "figcaption" -figure = element "figure" -hr = element "hr" -li = element "li" -menu = element "menu" -ol = element "ol" -p = element "p" -pre = element "pre" -ul = element "ul" -a = element "a" -abbr = element "abbr" -b = element "b" -bdi = element "bdi" -bdo = element "bdo" -br = element "br" -cite = element "cite" -code = element "code" -data = element "data" -dfn = element "dfn" -em = element "em" -i = element "i" -kbd = element "kbd" -mark = element "mark" -q = element "q" -rp = element "rp" -rt = element "rt" -ruby = element "ruby" -s = element "s" -samp = element "samp" -small = element "small" -span = element "span" -strong = element "strong" -sub = element "sub" -sup = element "sup" -time = element "time" -u = element "u" -var = element "var" -wbr = element "wbr" -area = element "area" -audio = element "audio" -img = element "img" -map = element "map" -track = element "track" -video = element "video" -embed = element "embed" -iframe = element "iframe" -object = element "object" -picture = element "picture" -portal = element "portal" -source = element "source" -svg = element "svg" -math = element "math" -canvas = element "canvas" -noscript = element "noscript" -script = element "script" -del = element "del" -ins = element "ins" -caption = element "caption" -col = element "col" -colgroup = element "colgroup" -table = element "table" -tbody = element "tbody" -td = element "td" -tfoot = element "tfoot" -th = element "th" -thead = element "thead" -tr = element "tr" -button = element "button" -datalist = element "datalist" -fieldset = element "fieldset" -form = element "form" -input = element "input" -label = element "label" -legend = element "legend" -meter = element "meter" -optgroup = element "optgroup" -option = element "option" -output = element "output" -progress = element "progress" -select = element "select" -textarea = element "textarea" -details = element "details" -dialog = element "dialog" -summary = element "summary" -slot = element "slot" -template = element "template" +html = element("html") +base = element("base") +head = element("head") +link = element("link") +meta = element("meta") +style = element("style") +title = element("title") +body = element("body") +address = element("address") +article = element("article") +aside = element("aside") +footer = element("footer") +header = element("header") +h1 = element("h1") +h2 = element("h2") +h3 = element("h3") +h4 = element("h4") +h5 = element("h5") +h6 = element("h6") +main = element("main") +nav = element("nav") +section = element("section") +blockquote = element("blockquote") +dd = element("dd") +div = element("div") +dl = element("dl") +dt = element("dt") +figcaption = element("figcaption") +figure = element("figure") +hr = element("hr") +li = element("li") +menu = element("menu") +ol = element("ol") +p = element("p") +pre = element("pre") +ul = element("ul") +a = element("a") +abbr = element("abbr") +b = element("b") +bdi = element("bdi") +bdo = element("bdo") +br = element("br") +cite = element("cite") +code = element("code") +data = element("data") +dfn = element("dfn") +em = element("em") +i = element("i") +kbd = element("kbd") +mark = element("mark") +q = element("q") +rp = element("rp") +rt = element("rt") +ruby = element("ruby") +s = element("s") +samp = element("samp") +small = element("small") +span = element("span") +strong = element("strong") +sub = element("sub") +sup = element("sup") +time = element("time") +u = element("u") +var = element("var") +wbr = element("wbr") +area = element("area") +audio = element("audio") +img = element("img") +map = element("map") +track = element("track") +video = element("video") +embed = element("embed") +iframe = element("iframe") +object = element("object") +picture = element("picture") +portal = element("portal") +source = element("source") +svg = element("svg") +math = element("math") +canvas = element("canvas") +noscript = element("noscript") +script = element("script") +del = element("del") +ins = element("ins") +caption = element("caption") +col = element("col") +colgroup = element("colgroup") +table = element("table") +tbody = element("tbody") +td = element("td") +tfoot = element("tfoot") +th = element("th") +thead = element("thead") +tr = element("tr") +button = element("button") +datalist = element("datalist") +fieldset = element("fieldset") +form = element("form") +input = element("input") +label = element("label") +legend = element("legend") +meter = element("meter") +optgroup = element("optgroup") +option = element("option") +output = element("output") +progress = element("progress") +select = element("select") +textarea = element("textarea") +details = element("details") +dialog = element("dialog") +summary = element("summary") +slot = element("slot") +template = element("template") diff --git a/examples/virtual-dom-wip/platform/Html/Attributes.roc b/examples/virtual-dom-wip/platform/Html/Attributes.roc index 0d9cda74cb9..8dd510ef035 100644 --- a/examples/virtual-dom-wip/platform/Html/Attributes.roc +++ b/examples/virtual-dom-wip/platform/Html/Attributes.roc @@ -1,7 +1,7 @@ module [ attribute, accept, - acceptCharset, + accept_charset, accesskey, action, align, @@ -60,7 +60,7 @@ module [ high, href, hreflang, - httpEquiv, + http_equiv, icon, id, importance, @@ -137,137 +137,137 @@ module [ import Html.Internal.Shared exposing [Attribute] attribute : Str -> (Str -> Attribute state) -attribute = \attrType -> - \attrValue -> HtmlAttr attrType attrValue +attribute = \attr_type -> + \attr_value -> HtmlAttr(attr_type, attr_value) -accept = attribute "accept" -acceptCharset = attribute "acceptCharset" -accesskey = attribute "accesskey" -action = attribute "action" -align = attribute "align" -allow = attribute "allow" -alt = attribute "alt" -async = attribute "async" -autocapitalize = attribute "autocapitalize" -autocomplete = attribute "autocomplete" -autofocus = attribute "autofocus" -autoplay = attribute "autoplay" -background = attribute "background" -bgcolor = attribute "bgcolor" -border = attribute "border" -buffered = attribute "buffered" -capture = attribute "capture" -challenge = attribute "challenge" -charset = attribute "charset" -checked = attribute "checked" -cite = attribute "cite" -class = attribute "class" -code = attribute "code" -codebase = attribute "codebase" -color = attribute "color" -cols = attribute "cols" -colspan = attribute "colspan" -content = attribute "content" -contenteditable = attribute "contenteditable" -contextmenu = attribute "contextmenu" -controls = attribute "controls" -coords = attribute "coords" -crossorigin = attribute "crossorigin" -csp = attribute "csp" -data = attribute "data" -datetime = attribute "datetime" -decoding = attribute "decoding" -default = attribute "default" -defer = attribute "defer" -dir = attribute "dir" -dirname = attribute "dirname" -disabled = attribute "disabled" -download = attribute "download" -draggable = attribute "draggable" -enctype = attribute "enctype" -enterkeyhint = attribute "enterkeyhint" -for = attribute "for" -form = attribute "form" -formaction = attribute "formaction" -formenctype = attribute "formenctype" -formmethod = attribute "formmethod" -formnovalidate = attribute "formnovalidate" -formtarget = attribute "formtarget" -headers = attribute "headers" -height = attribute "height" -hidden = attribute "hidden" -high = attribute "high" -href = attribute "href" -hreflang = attribute "hreflang" -httpEquiv = attribute "httpEquiv" -icon = attribute "icon" -id = attribute "id" -importance = attribute "importance" -integrity = attribute "integrity" -intrinsicsize = attribute "intrinsicsize" -inputmode = attribute "inputmode" -ismap = attribute "ismap" -itemprop = attribute "itemprop" -keytype = attribute "keytype" -kind = attribute "kind" -label = attribute "label" -lang = attribute "lang" -language = attribute "language" -loading = attribute "loading" -list = attribute "list" -loop = attribute "loop" -low = attribute "low" -manifest = attribute "manifest" -max = attribute "max" -maxlength = attribute "maxlength" -minlength = attribute "minlength" -media = attribute "media" -method = attribute "method" -min = attribute "min" -multiple = attribute "multiple" -muted = attribute "muted" -name = attribute "name" -novalidate = attribute "novalidate" -open = attribute "open" -optimum = attribute "optimum" -pattern = attribute "pattern" -ping = attribute "ping" -placeholder = attribute "placeholder" -poster = attribute "poster" -preload = attribute "preload" -radiogroup = attribute "radiogroup" -readonly = attribute "readonly" -referrerpolicy = attribute "referrerpolicy" -rel = attribute "rel" -required = attribute "required" -reversed = attribute "reversed" -role = attribute "role" -rows = attribute "rows" -rowspan = attribute "rowspan" -sandbox = attribute "sandbox" -scope = attribute "scope" -scoped = attribute "scoped" -selected = attribute "selected" -shape = attribute "shape" -size = attribute "size" -sizes = attribute "sizes" -slot = attribute "slot" -span = attribute "span" -spellcheck = attribute "spellcheck" -src = attribute "src" -srcdoc = attribute "srcdoc" -srclang = attribute "srclang" -srcset = attribute "srcset" -start = attribute "start" -step = attribute "step" -style = attribute "style" -summary = attribute "summary" -tabindex = attribute "tabindex" -target = attribute "target" -title = attribute "title" -translate = attribute "translate" -type = attribute "type" -usemap = attribute "usemap" -value = attribute "value" -width = attribute "width" -wrap = attribute "wrap" +accept = attribute("accept") +accept_charset = attribute("acceptCharset") +accesskey = attribute("accesskey") +action = attribute("action") +align = attribute("align") +allow = attribute("allow") +alt = attribute("alt") +async = attribute("async") +autocapitalize = attribute("autocapitalize") +autocomplete = attribute("autocomplete") +autofocus = attribute("autofocus") +autoplay = attribute("autoplay") +background = attribute("background") +bgcolor = attribute("bgcolor") +border = attribute("border") +buffered = attribute("buffered") +capture = attribute("capture") +challenge = attribute("challenge") +charset = attribute("charset") +checked = attribute("checked") +cite = attribute("cite") +class = attribute("class") +code = attribute("code") +codebase = attribute("codebase") +color = attribute("color") +cols = attribute("cols") +colspan = attribute("colspan") +content = attribute("content") +contenteditable = attribute("contenteditable") +contextmenu = attribute("contextmenu") +controls = attribute("controls") +coords = attribute("coords") +crossorigin = attribute("crossorigin") +csp = attribute("csp") +data = attribute("data") +datetime = attribute("datetime") +decoding = attribute("decoding") +default = attribute("default") +defer = attribute("defer") +dir = attribute("dir") +dirname = attribute("dirname") +disabled = attribute("disabled") +download = attribute("download") +draggable = attribute("draggable") +enctype = attribute("enctype") +enterkeyhint = attribute("enterkeyhint") +for = attribute("for") +form = attribute("form") +formaction = attribute("formaction") +formenctype = attribute("formenctype") +formmethod = attribute("formmethod") +formnovalidate = attribute("formnovalidate") +formtarget = attribute("formtarget") +headers = attribute("headers") +height = attribute("height") +hidden = attribute("hidden") +high = attribute("high") +href = attribute("href") +hreflang = attribute("hreflang") +http_equiv = attribute("httpEquiv") +icon = attribute("icon") +id = attribute("id") +importance = attribute("importance") +integrity = attribute("integrity") +intrinsicsize = attribute("intrinsicsize") +inputmode = attribute("inputmode") +ismap = attribute("ismap") +itemprop = attribute("itemprop") +keytype = attribute("keytype") +kind = attribute("kind") +label = attribute("label") +lang = attribute("lang") +language = attribute("language") +loading = attribute("loading") +list = attribute("list") +loop = attribute("loop") +low = attribute("low") +manifest = attribute("manifest") +max = attribute("max") +maxlength = attribute("maxlength") +minlength = attribute("minlength") +media = attribute("media") +method = attribute("method") +min = attribute("min") +multiple = attribute("multiple") +muted = attribute("muted") +name = attribute("name") +novalidate = attribute("novalidate") +open = attribute("open") +optimum = attribute("optimum") +pattern = attribute("pattern") +ping = attribute("ping") +placeholder = attribute("placeholder") +poster = attribute("poster") +preload = attribute("preload") +radiogroup = attribute("radiogroup") +readonly = attribute("readonly") +referrerpolicy = attribute("referrerpolicy") +rel = attribute("rel") +required = attribute("required") +reversed = attribute("reversed") +role = attribute("role") +rows = attribute("rows") +rowspan = attribute("rowspan") +sandbox = attribute("sandbox") +scope = attribute("scope") +scoped = attribute("scoped") +selected = attribute("selected") +shape = attribute("shape") +size = attribute("size") +sizes = attribute("sizes") +slot = attribute("slot") +span = attribute("span") +spellcheck = attribute("spellcheck") +src = attribute("src") +srcdoc = attribute("srcdoc") +srclang = attribute("srclang") +srcset = attribute("srcset") +start = attribute("start") +step = attribute("step") +style = attribute("style") +summary = attribute("summary") +tabindex = attribute("tabindex") +target = attribute("target") +title = attribute("title") +translate = attribute("translate") +type = attribute("type") +usemap = attribute("usemap") +value = attribute("value") +width = attribute("width") +wrap = attribute("wrap") diff --git a/examples/virtual-dom-wip/platform/Html/Event.roc b/examples/virtual-dom-wip/platform/Html/Event.roc index 513e0499344..a16c7afabb8 100644 --- a/examples/virtual-dom-wip/platform/Html/Event.roc +++ b/examples/virtual-dom-wip/platform/Html/Event.roc @@ -3,19 +3,19 @@ module [ CyclicStructureAccessor, on, custom, - onClick, - onDoubleClick, - onMouseDown, - onMouseUp, - onMouseEnter, - onMouseLeave, - onMouseOver, - onMouseOut, - onCheck, - onBlur, - onFocus, - onInput, - onSubmit, + on_click, + on_double_click, + on_mouse_down, + on_mouse_up, + on_mouse_enter, + on_mouse_leave, + on_mouse_over, + on_mouse_out, + on_check, + on_blur, + on_focus, + on_input, + on_submit, ] import Action exposing [Action] @@ -24,52 +24,52 @@ import Html.Internal.Shared exposing [Attribute] Handler state : Html.Internal.Shared.Handler state CyclicStructureAccessor : Html.Internal.Shared.CyclicStructureAccessor -custom : Str, List CyclicStructureAccessor, (state, List (List U8) -> { action : Action state, stopPropagation : Bool, preventDefault : Bool }) -> Attribute state -custom = \eventName, accessors, callback -> - EventListener eventName accessors (Custom callback) +custom : Str, List CyclicStructureAccessor, (state, List (List U8) -> { action : Action state, stop_propagation : Bool, prevent_default : Bool }) -> Attribute state +custom = \event_name, accessors, callback -> + EventListener(event_name, accessors, Custom(callback)) on : Str, List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state -on = \eventName, accessors, callback -> - EventListener eventName accessors (Normal callback) +on = \event_name, accessors, callback -> + EventListener(event_name, accessors, Normal(callback)) # Internal helper -curriedOn : Str -> (List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state) -curriedOn = \eventName -> +curried_on : Str -> (List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state) +curried_on = \event_name -> \accessors, callback -> - EventListener eventName accessors (Normal callback) + EventListener(event_name, accessors, Normal(callback)) -onClick = curriedOn "click" -onDoubleClick = curriedOn "dblclick" -onMouseDown = curriedOn "mousedown" -onMouseUp = curriedOn "mouseup" -onMouseEnter = curriedOn "mouseenter" -onMouseLeave = curriedOn "mouseleave" -onMouseOver = curriedOn "mouseover" -onMouseOut = curriedOn "mouseout" -onCheck = curriedOn "check" -onBlur = curriedOn "blur" -onFocus = curriedOn "focus" +on_click = curried_on("click") +on_double_click = curried_on("dblclick") +on_mouse_down = curried_on("mousedown") +on_mouse_up = curried_on("mouseup") +on_mouse_enter = curried_on("mouseenter") +on_mouse_leave = curried_on("mouseleave") +on_mouse_over = curried_on("mouseover") +on_mouse_out = curried_on("mouseout") +on_check = curried_on("check") +on_blur = curried_on("blur") +on_focus = curried_on("focus") -onInput : List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state -onInput = \accessors, callback -> - customCallback : state, List (List U8) -> { action : Action state, stopPropagation : Bool, preventDefault : Bool } - customCallback = \state, jsons -> { - action: callback state jsons, - stopPropagation: Bool.true, - preventDefault: Bool.false, +on_input : List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state +on_input = \accessors, callback -> + custom_callback : state, List (List U8) -> { action : Action state, stop_propagation : Bool, prevent_default : Bool } + custom_callback = \state, jsons -> { + action: callback(state, jsons), + stop_propagation: Bool.true, + prevent_default: Bool.false, } - EventListener "input" accessors (Custom customCallback) + EventListener("input", accessors, Custom(custom_callback)) -onSubmit : List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state -onSubmit = \accessors, callback -> - customCallback = \state, jsons -> { - action: callback state jsons, - stopPropagation: Bool.false, - preventDefault: Bool.true, +on_submit : List CyclicStructureAccessor, (state, List (List U8) -> Action state) -> Attribute state +on_submit = \accessors, callback -> + custom_callback = \state, jsons -> { + action: callback(state, jsons), + stop_propagation: Bool.false, + prevent_default: Bool.true, } - EventListener "submit" accessors (Custom customCallback) + EventListener("submit", accessors, Custom(custom_callback)) # Notes from Elm: # - stopPropagation causes immediate view update, without waiting for animationFrame, diff --git a/examples/virtual-dom-wip/platform/Html/Internal/Client.roc b/examples/virtual-dom-wip/platform/Html/Internal/Client.roc index 36b566a6f90..24edce4f79d 100644 --- a/examples/virtual-dom-wip/platform/Html/Internal/Client.roc +++ b/examples/virtual-dom-wip/platform/Html/Internal/Client.roc @@ -1,7 +1,7 @@ module [ PlatformState, - initClientApp, - dispatchEvent, + init_client_app, + dispatch_event, ] import PlatformTasks exposing [ @@ -17,13 +17,13 @@ import Html.Internal.Shared exposing [ Attribute, CyclicStructureAccessor, Handler, - translateStatic, + translate_static, ] import Json import Action -PlatformState state initData : { - app : App state initData, +PlatformState state init_data : { + app : App state init_data, state, rendered : RenderedTree state, } @@ -34,9 +34,9 @@ PlatformState state initData : { RenderedTree state : { root : NodeId, nodes : List (Result RenderedNode [DeletedNode]), - deletedNodeCache : List NodeId, + deleted_node_cache : List NodeId, handlers : List (Result (Handler state) [DeletedHandler]), - deletedHandlerCache : List HandlerId, + deleted_handler_cache : List HandlerId, } RenderedNode : [ @@ -46,17 +46,17 @@ RenderedNode : [ ] RenderedAttributes : { - eventListeners : Dict Str { accessors : List CyclicStructureAccessor, handlerId : HandlerId }, - htmlAttrs : Dict Str Str, - domProps : Dict Str (List U8), + event_listeners : Dict Str { accessors : List CyclicStructureAccessor, handler_id : HandlerId }, + html_attrs : Dict Str Str, + dom_props : Dict Str (List U8), styles : Dict Str Str, } -emptyRenderedAttrs = { - eventListeners: Dict.empty {}, - htmlAttrs: Dict.empty {}, - domProps: Dict.empty {}, - styles: Dict.empty {}, +empty_rendered_attrs = { + event_listeners: Dict.empty({}), + html_attrs: Dict.empty({}), + dom_props: Dict.empty({}), + styles: Dict.empty({}), } Patch : [ @@ -80,45 +80,45 @@ DiffState state : { rendered : RenderedTree state, patches : List Patch } # ------------------------------- # INITIALISATION # ------------------------------- -initClientApp : List U8, App state initData -> Task (PlatformState state initData) * where initData implements Decoding -initClientApp = \json, app -> +init_client_app : List U8, App state init_data -> Task (PlatformState state init_data) * where init_data implements Decoding +init_client_app = \json, app -> # Initialise the Roc representation of the rendered DOM, and calculate patches (for event listeners) { state, rendered, patches } = - initClientAppHelp json app + init_client_app_help(json, app) # Call out to JS to patch the DOM, attaching the event listeners - applyPatches! patches + apply_patches!(patches) - Task.ok { + Task.ok({ app, state, rendered, - } + }) # Testable helper function to initialise the app -initClientAppHelp : List U8, App state initData -> { state, rendered : RenderedTree state, patches : List Patch } where initData implements Decoding -initClientAppHelp = \json, app -> +init_client_app_help : List U8, App state init_data -> { state, rendered : RenderedTree state, patches : List Patch } where init_data implements Decoding +init_client_app_help = \json, app -> state = json - |> Decode.fromBytes Json.json + |> Decode.from_bytes(Json.json) |> app.init - dynamicView = - app.render state - staticUnindexed = - translateStatic dynamicView - { nodes: staticNodes } = - indexNodes { nodes: [], siblingIds: [] } staticUnindexed - staticRendered = { - root: List.len staticNodes - 1, - nodes: List.map staticNodes Ok, - deletedNodeCache: [], + dynamic_view = + app.render(state) + static_unindexed = + translate_static(dynamic_view) + { nodes: static_nodes } = + index_nodes({ nodes: [], sibling_ids: [] }, static_unindexed) + static_rendered = { + root: List.len(static_nodes) - 1, + nodes: List.map(static_nodes, Ok), + deleted_node_cache: [], handlers: [], - deletedHandlerCache: [], + deleted_handler_cache: [], } # Run our first diff. The only differences will be event listeners, so we will generate patches to attach those. { rendered, patches } = - diff { rendered: staticRendered, patches: [] } dynamicView + diff({ rendered: static_rendered, patches: [] }, dynamic_view) { state, rendered, patches } @@ -127,610 +127,614 @@ initClientAppHelp = \json, app -> # In Roc, we maintain a matching List of virtual DOM nodes with the same indices. # They are both initialised separately, but use the same indexing algorithm. # (We *could* pass this data in as JSON from the HTML file, but it would roughly double the size of that HTML file!) -indexNodes : { nodes : List RenderedNode, siblingIds : List U64 }, Html state -> { nodes : List RenderedNode, siblingIds : List U64 } -indexNodes = \{ nodes, siblingIds }, unrendered -> +index_nodes : { nodes : List RenderedNode, sibling_ids : List U64 }, Html state -> { nodes : List RenderedNode, sibling_ids : List U64 } +index_nodes = \{ nodes, sibling_ids }, unrendered -> when unrendered is - Text content -> + Text(content) -> { - nodes: List.append nodes (RenderedText content), - siblingIds: List.append siblingIds (List.len nodes), + nodes: List.append(nodes, RenderedText(content)), + sibling_ids: List.append(sibling_ids, List.len(nodes)), } - Element name _ attrs children -> - { nodes: listWithChildren, siblingIds: childIds } = - List.walk children { nodes, siblingIds: [] } indexNodes - renderedAttrs = - List.walk attrs emptyRenderedAttrs \walkedAttrs, attr -> + Element(name, _, attrs, children) -> + { nodes: list_with_children, sibling_ids: child_ids } = + List.walk(children, { nodes, sibling_ids: [] }, index_nodes) + rendered_attrs = + List.walk(attrs, empty_rendered_attrs, \walked_attrs, attr -> when attr is - EventListener _ _ _ -> walkedAttrs # Dropped! Server-rendered HTML has no listeners - HtmlAttr k v -> { walkedAttrs & htmlAttrs: Dict.insert walkedAttrs.htmlAttrs k v } - DomProp k v -> { walkedAttrs & domProps: Dict.insert walkedAttrs.domProps k v } - Style k v -> { walkedAttrs & styles: Dict.insert walkedAttrs.styles k v } + EventListener(_, _, _) -> walked_attrs # Dropped! Server-rendered HTML has no listeners + HtmlAttr(k, v) -> { walked_attrs & html_attrs: Dict.insert(walked_attrs.html_attrs, k, v) } + DomProp(k, v) -> { walked_attrs & dom_props: Dict.insert(walked_attrs.dom_props, k, v) } + Style(k, v) -> { walked_attrs & styles: Dict.insert(walked_attrs.styles, k, v) }) { - nodes: List.append listWithChildren (RenderedElement name renderedAttrs childIds), - siblingIds: List.append siblingIds (List.len listWithChildren), + nodes: List.append(list_with_children, RenderedElement(name, rendered_attrs, child_ids)), + sibling_ids: List.append(sibling_ids, List.len(list_with_children)), } None -> { - nodes: List.append nodes RenderedNone, - siblingIds: List.append siblingIds (List.len nodes), + nodes: List.append(nodes, RenderedNone), + sibling_ids: List.append(sibling_ids, List.len(nodes)), } # ------------------------------- # Patches # ------------------------------- -applyPatch : Patch -> Task {} * -applyPatch = \patch -> +apply_patch : Patch -> Task {} * +apply_patch = \patch -> when patch is - CreateElement nodeId tagName -> PlatformTasks.createElement nodeId tagName - CreateTextNode nodeId content -> PlatformTasks.createTextNode nodeId content - UpdateTextNode nodeId content -> PlatformTasks.updateTextNode nodeId content - AppendChild parentId childId -> PlatformTasks.appendChild parentId childId - RemoveNode id -> PlatformTasks.removeNode id - ReplaceNode oldId newId -> PlatformTasks.replaceNode oldId newId - SetAttribute nodeId attrName value -> PlatformTasks.setAttribute nodeId attrName value - RemoveAttribute nodeId attrName -> PlatformTasks.removeAttribute nodeId attrName - SetProperty nodeId propName json -> PlatformTasks.setProperty nodeId propName json - RemoveProperty nodeId propName -> PlatformTasks.removeProperty nodeId propName - SetStyle nodeId key value -> PlatformTasks.setStyle nodeId key value - SetListener nodeId eventType accessorsJson handlerId -> PlatformTasks.setListener nodeId eventType accessorsJson handlerId - RemoveListener nodeId handlerId -> PlatformTasks.removeListener nodeId handlerId - -applyPatches : List Patch -> Task {} * -applyPatches = \patches -> - List.walk patches (Task.ok {}) \previousEffects, patch -> - previousEffects! - applyPatch patch + CreateElement(node_id, tag_name) -> PlatformTasks.create_element(node_id, tag_name) + CreateTextNode(node_id, content) -> PlatformTasks.create_text_node(node_id, content) + UpdateTextNode(node_id, content) -> PlatformTasks.update_text_node(node_id, content) + AppendChild(parent_id, child_id) -> PlatformTasks.append_child(parent_id, child_id) + RemoveNode(id) -> PlatformTasks.remove_node(id) + ReplaceNode(old_id, new_id) -> PlatformTasks.replace_node(old_id, new_id) + SetAttribute(node_id, attr_name, value) -> PlatformTasks.set_attribute(node_id, attr_name, value) + RemoveAttribute(node_id, attr_name) -> PlatformTasks.remove_attribute(node_id, attr_name) + SetProperty(node_id, prop_name, json) -> PlatformTasks.set_property(node_id, prop_name, json) + RemoveProperty(node_id, prop_name) -> PlatformTasks.remove_property(node_id, prop_name) + SetStyle(node_id, key, value) -> PlatformTasks.set_style(node_id, key, value) + SetListener(node_id, event_type, accessors_json, handler_id) -> PlatformTasks.set_listener(node_id, event_type, accessors_json, handler_id) + RemoveListener(node_id, handler_id) -> PlatformTasks.remove_listener(node_id, handler_id) + +apply_patches : List Patch -> Task {} * +apply_patches = \patches -> + List.walk(patches, Task.ok({}), \previous_effects, patch -> + previous_effects! + apply_patch(patch)) # ------------------------------- # EVENT HANDLING # ------------------------------- -JsEventResult state initData : { - platformState : PlatformState state initData, - stopPropagation : Bool, - preventDefault : Bool, +JsEventResult state init_data : { + platform_state : PlatformState state init_data, + stop_propagation : Bool, + prevent_default : Bool, } ## Dispatch a JavaScript event to a Roc handler, given the handler ID and some JSON event data. -dispatchEvent : PlatformState state initData, List (List U8), HandlerId -> Task (JsEventResult state initData) * where initData implements Decoding -dispatchEvent = \platformState, eventData, handlerId -> +dispatch_event : PlatformState state init_data, List (List U8), HandlerId -> Task (JsEventResult state init_data) * where init_data implements Decoding +dispatch_event = \platform_state, event_data, handler_id -> { app, state, rendered } = - platformState - maybeHandler = - List.get rendered.handlers handlerId - |> Result.withDefault (Err DeletedHandler) - { action, stopPropagation, preventDefault } = - when maybeHandler is - Err DeletedHandler -> - { action: Action.none, stopPropagation: Bool.false, preventDefault: Bool.false } + platform_state + maybe_handler = + List.get(rendered.handlers, handler_id) + |> Result.with_default(Err(DeletedHandler)) + { action, stop_propagation, prevent_default } = + when maybe_handler is + Err(DeletedHandler) -> + { action: Action.none, stop_propagation: Bool.false, prevent_default: Bool.false } - Ok (Normal handler) -> - { action: handler state eventData, stopPropagation: Bool.false, preventDefault: Bool.false } + Ok(Normal(handler)) -> + { action: handler(state, event_data), stop_propagation: Bool.false, prevent_default: Bool.false } - Ok (Custom handler) -> - handler state eventData + Ok(Custom(handler)) -> + handler(state, event_data) when action is - Update newState -> - newViewUnrendered = - app.render newState - { rendered: newRendered, patches } = - diff { rendered, patches: [] } newViewUnrendered - - applyPatches! patches - Task.ok { - platformState: { + Update(new_state) -> + new_view_unrendered = + app.render(new_state) + { rendered: new_rendered, patches } = + diff({ rendered, patches: [] }, new_view_unrendered) + + apply_patches!(patches) + Task.ok({ + platform_state: { app, - state: newState, - rendered: newRendered, + state: new_state, + rendered: new_rendered, }, - stopPropagation, - preventDefault, - } + stop_propagation, + prevent_default, + }) None -> - Task.ok { platformState, stopPropagation, preventDefault } + Task.ok({ platform_state, stop_propagation, prevent_default }) # ------------------------------- # DIFF # ------------------------------- diff : DiffState state, Html state -> DiffState state -diff = \{ rendered, patches }, newNode -> +diff = \{ rendered, patches }, new_node -> root = rendered.root - oldNode = - List.get rendered.nodes root - |> Result.withDefault (Ok RenderedNone) - |> Result.withDefault (RenderedNone) + old_node = + List.get(rendered.nodes, root) + |> Result.with_default(Ok(RenderedNone)) + |> Result.with_default(RenderedNone) - when { oldNode, newNode } is - { oldNode: RenderedText oldContent, newNode: Text newContent } -> - if newContent != oldContent then - newNodes = - List.set rendered.nodes rendered.root (Ok (RenderedText newContent)) + when { old_node, new_node } is + { old_node: RenderedText(old_content), new_node: Text(new_content) } -> + if new_content != old_content then + new_nodes = + List.set(rendered.nodes, rendered.root, Ok(RenderedText(new_content))) { rendered: { rendered & - nodes: newNodes, + nodes: new_nodes, }, - patches: List.append patches (UpdateTextNode rendered.root newContent), + patches: List.append(patches, UpdateTextNode(rendered.root, new_content)), } else { rendered, patches } - { oldNode: RenderedElement oldName oldAttrs oldChildren, newNode: Element newName _ newAttrs newChildren } -> - if newName != oldName then - replaceNode { rendered, patches } root newNode + { old_node: RenderedElement(old_name, old_attrs, old_children), new_node: Element(new_name, _, new_attrs, new_children) } -> + if new_name != old_name then + replace_node({ rendered, patches }, root, new_node) else - stateAttrs = - diffAttrs { rendered, patches } root oldAttrs newAttrs - stateChildPairs = - List.map2 oldChildren newChildren (\oldChildId, newChild -> { oldChildId, newChild }) - |> List.walk stateAttrs \childWalkState, { oldChildId, newChild } -> - { rendered: childWalkRendered, patches: childWalkPatches } = childWalkState - diff { rendered: { childWalkRendered & root: oldChildId }, patches: childWalkPatches } newChild - { rendered: renderedLeftOverChildren, patches: patchesLeftOverChildren } = - if List.len oldChildren > List.len newChildren then - List.walkFrom oldChildren (List.len newChildren) stateChildPairs deleteNode - else if List.len oldChildren < List.len newChildren then - stateBeforeCreate = { - rendered: stateChildPairs.rendered, - patches: stateChildPairs.patches, + state_attrs = + diff_attrs({ rendered, patches }, root, old_attrs, new_attrs) + state_child_pairs = + List.map2(old_children, new_children, \old_child_id, new_child -> { old_child_id, new_child }) + |> List.walk(state_attrs, \child_walk_state, { old_child_id, new_child } -> + { rendered: child_walk_rendered, patches: child_walk_patches } = child_walk_state + diff({ rendered: { child_walk_rendered & root: old_child_id }, patches: child_walk_patches }, new_child)) + { rendered: rendered_left_over_children, patches: patches_left_over_children } = + if List.len(old_children) > List.len(new_children) then + List.walk_from(old_children, List.len(new_children), state_child_pairs, delete_node) + else if List.len(old_children) < List.len(new_children) then + state_before_create = { + rendered: state_child_pairs.rendered, + patches: state_child_pairs.patches, ids: [], } - { rendered: renderedAfterCreate, patches: patchesAfterCreate, ids: createdIds } = - List.walkFrom newChildren (List.len oldChildren) stateBeforeCreate createChildNode + { rendered: rendered_after_create, patches: patches_after_create, ids: created_ids } = + List.walk_from(new_children, List.len(old_children), state_before_create, create_child_node) # Look up the children again since they might have new node IDs! - nodeWithUpdatedChildren = - when List.get renderedAfterCreate.nodes root is - Ok (Ok (RenderedElement n a c)) -> RenderedElement n a (List.concat c createdIds) - _ -> crash "Bug in virtual-dom framework: nodeWithUpdatedChildren not found" - updatedNodes = - List.set renderedAfterCreate.nodes root (Ok nodeWithUpdatedChildren) + node_with_updated_children = + when List.get(rendered_after_create.nodes, root) is + Ok(Ok(RenderedElement(n, a, c))) -> RenderedElement(n, a, List.concat(c, created_ids)) + _ -> crash("Bug in virtual-dom framework: nodeWithUpdatedChildren not found") + updated_nodes = + List.set(rendered_after_create.nodes, root, Ok(node_with_updated_children)) { - rendered: { renderedAfterCreate & nodes: updatedNodes }, - patches: List.walk createdIds patchesAfterCreate \p, id -> List.append p (AppendChild root id), + rendered: { rendered_after_create & nodes: updated_nodes }, + patches: List.walk(created_ids, patches_after_create, \p, id -> List.append(p, AppendChild(root, id))), } else - stateChildPairs + state_child_pairs { - rendered: { renderedLeftOverChildren & root }, - patches: patchesLeftOverChildren, + rendered: { rendered_left_over_children & root }, + patches: patches_left_over_children, } - { oldNode: RenderedNone, newNode: None } -> + { old_node: RenderedNone, new_node: None } -> { rendered, patches } _ -> # old node has been replaced with a totally different variant. There's no point in diffing, just replace. - replaceNode { rendered, patches } rendered.root newNode - -replaceNode : DiffState state, NodeId, Html state -> DiffState state -replaceNode = \diffState, oldNodeId, newNode -> - { rendered: createRendered, patches: createPatches, id: createNodeId } = - createNode diffState newNode - preDeleteState = { - rendered: createRendered, - patches: List.append createPatches (ReplaceNode oldNodeId createNodeId), + replace_node({ rendered, patches }, rendered.root, new_node) + +replace_node : DiffState state, NodeId, Html state -> DiffState state +replace_node = \diff_state, old_node_id, new_node -> + { rendered: create_rendered, patches: create_patches, id: create_node_id } = + create_node(diff_state, new_node) + pre_delete_state = { + rendered: create_rendered, + patches: List.append(create_patches, ReplaceNode(old_node_id, create_node_id)), } - deleteNode preDeleteState oldNodeId + delete_node(pre_delete_state, old_node_id) # Delete a node, and drop any JS references to its children and event listeners # TODO: see if it would speed things up to leave this junk lying around until the slot is reused. # Any danger of spurious events being sent to the wrong handler? # Otherwise, can we sweep everything at once at the end of the diff? # Let's be conservative on things like this until we have more test cases working. -deleteNode : DiffState state, NodeId -> DiffState state -deleteNode = \diffState, id -> +delete_node : DiffState state, NodeId -> DiffState state +delete_node = \diff_state, id -> { rendered, patches } = - when List.get diffState.rendered.nodes id is - Ok node -> + when List.get(diff_state.rendered.nodes, id) is + Ok(node) -> when node is - Ok (RenderedElement _ _ children) -> - List.walk children diffState deleteNode + Ok(RenderedElement(_, _, children)) -> + List.walk(children, diff_state, delete_node) - _ -> diffState + _ -> diff_state - _ -> diffState + _ -> diff_state - patchesRemoveListeners = - when List.get rendered.nodes id is - Ok (Ok (RenderedElement _ attrs _)) -> - Dict.walk attrs.eventListeners patches \p, _, { handlerId } -> - List.append p (RemoveListener id handlerId) + patches_remove_listeners = + when List.get(rendered.nodes, id) is + Ok(Ok(RenderedElement(_, attrs, _))) -> + Dict.walk(attrs.event_listeners, patches, \p, _, { handler_id } -> + List.append(p, RemoveListener(id, handler_id))) _ -> patches - newNodes = - List.set rendered.nodes id (Err DeletedNode) - newDeletedNodeCache = - List.append rendered.deletedNodeCache id - newPatches = - List.append patchesRemoveListeners (RemoveNode id) + new_nodes = + List.set(rendered.nodes, id, Err(DeletedNode)) + new_deleted_node_cache = + List.append(rendered.deleted_node_cache, id) + new_patches = + List.append(patches_remove_listeners, RemoveNode(id)) { rendered: { rendered & - nodes: newNodes, - deletedNodeCache: newDeletedNodeCache, + nodes: new_nodes, + deleted_node_cache: new_deleted_node_cache, }, - patches: newPatches, + patches: new_patches, } -createNode : DiffState state, Html state -> { rendered : RenderedTree state, patches : List Patch, id : NodeId } -createNode = \{ rendered, patches }, newNode -> - when newNode is - Text content -> - { rendered: newRendered, id } = - insertNode rendered (RenderedText content) +create_node : DiffState state, Html state -> { rendered : RenderedTree state, patches : List Patch, id : NodeId } +create_node = \{ rendered, patches }, new_node -> + when new_node is + Text(content) -> + { rendered: new_rendered, id } = + insert_node(rendered, RenderedText(content)) { - rendered: newRendered, - patches: List.append patches (CreateTextNode id content), + rendered: new_rendered, + patches: List.append(patches, CreateTextNode(id, content)), id, } None -> - { rendered: newRendered, id } = - insertNode rendered RenderedNone - - { rendered: newRendered, patches, id } - - Element tagName _ attrs children -> - { rendered: renderedWithChildren, patches: patchesWithChildren, ids: childIds } = - List.walk children { rendered, patches, ids: [] } createChildNode - nodeId = - nextNodeId renderedWithChildren - patchesWithElem = - List.append patchesWithChildren (CreateElement nodeId tagName) - { renderedAttrs, rendered: renderedWithAttrs, patches: patchesWithAttrs } = - renderAttrs attrs renderedWithChildren patchesWithElem nodeId - { rendered: renderedWithNode } = - insertNode renderedWithAttrs (RenderedElement tagName renderedAttrs childIds) + { rendered: new_rendered, id } = + insert_node(rendered, RenderedNone) + + { rendered: new_rendered, patches, id } + + Element(tag_name, _, attrs, children) -> + { rendered: rendered_with_children, patches: patches_with_children, ids: child_ids } = + List.walk(children, { rendered, patches, ids: [] }, create_child_node) + node_id = + next_node_id(rendered_with_children) + patches_with_elem = + List.append(patches_with_children, CreateElement(node_id, tag_name)) + { rendered_attrs, rendered: rendered_with_attrs, patches: patches_with_attrs } = + render_attrs(attrs, rendered_with_children, patches_with_elem, node_id) + { rendered: rendered_with_node } = + insert_node(rendered_with_attrs, RenderedElement(tag_name, rendered_attrs, child_ids)) { - rendered: renderedWithNode, - patches: patchesWithAttrs, - id: nodeId, + rendered: rendered_with_node, + patches: patches_with_attrs, + id: node_id, } AttrDiffState state : { - nodeId : NodeId, + node_id : NodeId, attrs : RenderedAttributes, patches : List Patch, handlers : List (Result (Handler state) [DeletedHandler]), - deletedHandlerCache : List HandlerId, + deleted_handler_cache : List HandlerId, } -diffAttrs : DiffState state, NodeId, RenderedAttributes, List (Attribute state) -> DiffState state -diffAttrs = \{ rendered, patches }, nodeId, attrs, newAttrs -> - initState = { - nodeId, +diff_attrs : DiffState state, NodeId, RenderedAttributes, List (Attribute state) -> DiffState state +diff_attrs = \{ rendered, patches }, node_id, attrs, new_attrs -> + init_state = { + node_id, attrs, patches, handlers: rendered.handlers, - deletedHandlerCache: rendered.deletedHandlerCache, + deleted_handler_cache: rendered.deleted_handler_cache, } - finalState = - List.walk newAttrs initState diffAttr - newRendered = + final_state = + List.walk(new_attrs, init_state, diff_attr) + new_rendered = { rendered & - handlers: finalState.handlers, - deletedHandlerCache: finalState.deletedHandlerCache, + handlers: final_state.handlers, + deleted_handler_cache: final_state.deleted_handler_cache, } { - rendered: newRendered, - patches: finalState.patches, + rendered: new_rendered, + patches: final_state.patches, } -diffAttr : AttrDiffState state, Attribute state -> AttrDiffState state -diffAttr = \{ nodeId, attrs, patches, handlers, deletedHandlerCache }, attr -> +diff_attr : AttrDiffState state, Attribute state -> AttrDiffState state +diff_attr = \{ node_id, attrs, patches, handlers, deleted_handler_cache }, attr -> when attr is - EventListener eventName newAccessors newHandler -> - when Dict.get attrs.eventListeners eventName is - Ok { accessors, handlerId } -> - (Tuple newAttrs newPatches) = - if accessors == newAccessors then - Tuple attrs patches + EventListener(event_name, new_accessors, new_handler) -> + when Dict.get(attrs.event_listeners, event_name) is + Ok({ accessors, handler_id }) -> + Tuple(new_attrs, new_patches) = + if accessors == new_accessors then + Tuple(attrs, patches) else - json = newAccessors |> Encode.toBytes Json.json + json = new_accessors |> Encode.to_bytes(Json.json) - Tuple - { attrs & eventListeners: Dict.insert attrs.eventListeners eventName { accessors, handlerId } } + Tuple( + { attrs & event_listeners: Dict.insert(attrs.event_listeners, event_name, { accessors, handler_id }) }, ( patches - |> List.append (RemoveListener nodeId handlerId) - |> List.append (SetListener nodeId eventName json handlerId) - ) + |> List.append(RemoveListener(node_id, handler_id)) + |> List.append(SetListener(node_id, event_name, json, handler_id)) + ), + ) { - nodeId, - attrs: newAttrs, - patches: newPatches, - handlers: List.set handlers handlerId (Ok newHandler), - deletedHandlerCache, + node_id, + attrs: new_attrs, + patches: new_patches, + handlers: List.set(handlers, handler_id, Ok(new_handler)), + deleted_handler_cache, } - Err KeyNotFound -> - renderAttr { nodeId, attrs, patches, handlers, deletedHandlerCache } attr + Err(KeyNotFound) -> + render_attr({ node_id, attrs, patches, handlers, deleted_handler_cache }, attr) - HtmlAttr k v -> - when Dict.get attrs.htmlAttrs k is - Ok oldVal -> - (Tuple newAttrs newPatches) = - if oldVal == v then - Tuple attrs patches + HtmlAttr(k, v) -> + when Dict.get(attrs.html_attrs, k) is + Ok(old_val) -> + Tuple(new_attrs, new_patches) = + if old_val == v then + Tuple(attrs, patches) else - Tuple - { attrs & htmlAttrs: Dict.insert attrs.htmlAttrs k v } - (patches |> List.append (SetAttribute nodeId k v)) + Tuple( + { attrs & html_attrs: Dict.insert(attrs.html_attrs, k, v) }, + (patches |> List.append(SetAttribute(node_id, k, v))), + ) { - nodeId, - attrs: newAttrs, - patches: newPatches, + node_id, + attrs: new_attrs, + patches: new_patches, handlers, - deletedHandlerCache, + deleted_handler_cache, } - Err KeyNotFound -> - renderAttr { nodeId, attrs, patches, handlers, deletedHandlerCache } attr + Err(KeyNotFound) -> + render_attr({ node_id, attrs, patches, handlers, deleted_handler_cache }, attr) - DomProp k v -> - when Dict.get attrs.domProps k is - Ok oldVal -> - (Tuple newAttrs newPatches) = - if oldVal == v then - Tuple attrs patches + DomProp(k, v) -> + when Dict.get(attrs.dom_props, k) is + Ok(old_val) -> + Tuple(new_attrs, new_patches) = + if old_val == v then + Tuple(attrs, patches) else - Tuple - { attrs & domProps: Dict.insert attrs.domProps k v } - (patches |> List.append (SetProperty nodeId k v)) + Tuple( + { attrs & dom_props: Dict.insert(attrs.dom_props, k, v) }, + (patches |> List.append(SetProperty(node_id, k, v))), + ) { - nodeId, - attrs: newAttrs, - patches: newPatches, + node_id, + attrs: new_attrs, + patches: new_patches, handlers, - deletedHandlerCache, + deleted_handler_cache, } - Err KeyNotFound -> - renderAttr { nodeId, attrs, patches, handlers, deletedHandlerCache } attr + Err(KeyNotFound) -> + render_attr({ node_id, attrs, patches, handlers, deleted_handler_cache }, attr) - Style k v -> - when Dict.get attrs.styles k is - Ok oldVal -> - (Tuple newAttrs newPatches) = - if oldVal == v then - Tuple attrs patches + Style(k, v) -> + when Dict.get(attrs.styles, k) is + Ok(old_val) -> + Tuple(new_attrs, new_patches) = + if old_val == v then + Tuple(attrs, patches) else - Tuple - { attrs & styles: Dict.insert attrs.styles k v } - (patches |> List.append (SetStyle nodeId k v)) + Tuple( + { attrs & styles: Dict.insert(attrs.styles, k, v) }, + (patches |> List.append(SetStyle(node_id, k, v))), + ) { - nodeId, - attrs: newAttrs, - patches: newPatches, + node_id, + attrs: new_attrs, + patches: new_patches, handlers, - deletedHandlerCache, + deleted_handler_cache, } - Err KeyNotFound -> - renderAttr { nodeId, attrs, patches, handlers, deletedHandlerCache } attr + Err(KeyNotFound) -> + render_attr({ node_id, attrs, patches, handlers, deleted_handler_cache }, attr) -renderAttrs : List (Attribute state), RenderedTree state, List Patch, NodeId -> { renderedAttrs : RenderedAttributes, rendered : RenderedTree state, patches : List Patch } -renderAttrs = \attrs, rendered, patches, nodeId -> - initState = { - nodeId, - attrs: emptyRenderedAttrs, +render_attrs : List (Attribute state), RenderedTree state, List Patch, NodeId -> { rendered_attrs : RenderedAttributes, rendered : RenderedTree state, patches : List Patch } +render_attrs = \attrs, rendered, patches, node_id -> + init_state = { + node_id, + attrs: empty_rendered_attrs, patches, handlers: rendered.handlers, - deletedHandlerCache: rendered.deletedHandlerCache, + deleted_handler_cache: rendered.deleted_handler_cache, } - finalState = - List.walk attrs initState renderAttr + final_state = + List.walk(attrs, init_state, render_attr) { - renderedAttrs: finalState.attrs, + rendered_attrs: final_state.attrs, rendered: { rendered & - handlers: finalState.handlers, - deletedHandlerCache: finalState.deletedHandlerCache, + handlers: final_state.handlers, + deleted_handler_cache: final_state.deleted_handler_cache, }, - patches: finalState.patches, + patches: final_state.patches, } -renderAttr : AttrDiffState state, Attribute state -> AttrDiffState state -renderAttr = \{ nodeId, attrs, patches, handlers, deletedHandlerCache }, attr -> +render_attr : AttrDiffState state, Attribute state -> AttrDiffState state +render_attr = \{ node_id, attrs, patches, handlers, deleted_handler_cache }, attr -> when attr is - HtmlAttr k v -> + HtmlAttr(k, v) -> { - nodeId, + node_id, handlers, - deletedHandlerCache, - attrs: { attrs & htmlAttrs: Dict.insert attrs.htmlAttrs k v }, - patches: List.append patches (SetAttribute nodeId k v), + deleted_handler_cache, + attrs: { attrs & html_attrs: Dict.insert(attrs.html_attrs, k, v) }, + patches: List.append(patches, SetAttribute(node_id, k, v)), } - DomProp k v -> + DomProp(k, v) -> { - nodeId, + node_id, handlers, - deletedHandlerCache, - attrs: { attrs & domProps: Dict.insert attrs.domProps k v }, - patches: List.append patches (SetProperty nodeId k v), + deleted_handler_cache, + attrs: { attrs & dom_props: Dict.insert(attrs.dom_props, k, v) }, + patches: List.append(patches, SetProperty(node_id, k, v)), } - Style k v -> + Style(k, v) -> { - nodeId, + node_id, handlers, - deletedHandlerCache, - attrs: { attrs & styles: Dict.insert attrs.styles k v }, - patches: List.append patches (SetStyle nodeId k v), + deleted_handler_cache, + attrs: { attrs & styles: Dict.insert(attrs.styles, k, v) }, + patches: List.append(patches, SetStyle(node_id, k, v)), } - EventListener eventType accessors handler -> - { handlerId, newHandlers, newDeletedHandlerCache } = - when List.last deletedHandlerCache is - Ok id -> + EventListener(event_type, accessors, handler) -> + { handler_id, new_handlers, new_deleted_handler_cache } = + when List.last(deleted_handler_cache) is + Ok(id) -> { - handlerId: id, - newHandlers: List.set handlers id (Ok handler), - newDeletedHandlerCache: List.dropLast deletedHandlerCache 1, + handler_id: id, + new_handlers: List.set(handlers, id, Ok(handler)), + new_deleted_handler_cache: List.drop_last(deleted_handler_cache, 1), } - Err _ -> + Err(_) -> { - handlerId: List.len handlers, - newHandlers: List.append handlers (Ok handler), - newDeletedHandlerCache: deletedHandlerCache, + handler_id: List.len(handlers), + new_handlers: List.append(handlers, Ok(handler)), + new_deleted_handler_cache: deleted_handler_cache, } - accessorsJson = - accessors |> Encode.toBytes Json.json + accessors_json = + accessors |> Encode.to_bytes(Json.json) patch = - SetListener nodeId eventType accessorsJson handlerId + SetListener(node_id, event_type, accessors_json, handler_id) { - nodeId, - attrs: { attrs & eventListeners: Dict.insert attrs.eventListeners eventType { accessors, handlerId } }, - handlers: newHandlers, - deletedHandlerCache: newDeletedHandlerCache, - patches: List.append patches patch, + node_id, + attrs: { attrs & event_listeners: Dict.insert(attrs.event_listeners, event_type, { accessors, handler_id }) }, + handlers: new_handlers, + deleted_handler_cache: new_deleted_handler_cache, + patches: List.append(patches, patch), } -createChildNode : +create_child_node : { rendered : RenderedTree state, patches : List Patch, ids : List NodeId }, Html state -> { rendered : RenderedTree state, patches : List Patch, ids : List NodeId } -createChildNode = \{ rendered, patches, ids }, childHtml -> - { rendered: renderedChild, patches: childPatches, id } = - createNode { rendered, patches } childHtml +create_child_node = \{ rendered, patches, ids }, child_html -> + { rendered: rendered_child, patches: child_patches, id } = + create_node({ rendered, patches }, child_html) { - rendered: renderedChild, - patches: childPatches, - ids: List.append ids id, + rendered: rendered_child, + patches: child_patches, + ids: List.append(ids, id), } # insert a node into the nodes list, assigning it a NodeId -insertNode : RenderedTree state, RenderedNode -> { rendered : RenderedTree state, id : NodeId } -insertNode = \rendered, node -> - when List.last rendered.deletedNodeCache is - Ok id -> - newRendered = +insert_node : RenderedTree state, RenderedNode -> { rendered : RenderedTree state, id : NodeId } +insert_node = \rendered, node -> + when List.last(rendered.deleted_node_cache) is + Ok(id) -> + new_rendered = { rendered & - nodes: List.set rendered.nodes id (Ok node), - deletedNodeCache: List.dropLast rendered.deletedNodeCache 1, + nodes: List.set(rendered.nodes, id, Ok(node)), + deleted_node_cache: List.drop_last(rendered.deleted_node_cache, 1), } - { rendered: newRendered, id } + { rendered: new_rendered, id } - Err _ -> - newRendered = + Err(_) -> + new_rendered = { rendered & - nodes: List.append rendered.nodes (Ok node), + nodes: List.append(rendered.nodes, Ok(node)), } - { rendered: newRendered, id: List.len rendered.nodes } + { rendered: new_rendered, id: List.len(rendered.nodes) } # Predict what NodeId will be assigned next, without actually assigning it -nextNodeId : RenderedTree state -> NodeId -nextNodeId = \rendered -> - when List.last rendered.deletedNodeCache is - Ok id -> id - Err _ -> List.len rendered.nodes +next_node_id : RenderedTree state -> NodeId +next_node_id = \rendered -> + when List.last(rendered.deleted_node_cache) is + Ok(id) -> id + Err(_) -> List.len(rendered.nodes) # ------------------------------- # TESTS # ------------------------------- -eqRenderedTree : RenderedTree state, RenderedTree state -> Bool -eqRenderedTree = \a, b -> +eq_rendered_tree : RenderedTree state, RenderedTree state -> Bool +eq_rendered_tree = \a, b -> (a.root == b.root) && (a.nodes == b.nodes) - && (List.len a.handlers == List.len b.handlers) - && (a.deletedNodeCache == b.deletedNodeCache) - && (a.deletedHandlerCache == b.deletedHandlerCache) + && (List.len(a.handlers) == List.len(b.handlers)) + && (a.deleted_node_cache == b.deleted_node_cache) + && (a.deleted_handler_cache == b.deleted_handler_cache) # indexNodes expect html : Html {} html = - Element "a" 43 [HtmlAttr "href" "https://www.roc-lang.org/"] [Text "Roc"] + Element("a", 43, [HtmlAttr("href", "https://www.roc-lang.org/")], [Text("Roc")]) - actual : { nodes : List RenderedNode, siblingIds : List U64 } + actual : { nodes : List RenderedNode, sibling_ids : List U64 } actual = - indexNodes { nodes: [], siblingIds: [] } html + index_nodes({ nodes: [], sibling_ids: [] }, html) - expected : { nodes : List RenderedNode, siblingIds : List U64 } + expected : { nodes : List RenderedNode, sibling_ids : List U64 } expected = { nodes: [ - RenderedText "Roc", - RenderedElement "a" { emptyRenderedAttrs & htmlAttrs: Dict.fromList [("href", "https://www.roc-lang.org/")] } [0], + RenderedText("Roc"), + RenderedElement("a", { empty_rendered_attrs & html_attrs: Dict.from_list([("href", "https://www.roc-lang.org/")]) }, [0]), ], - siblingIds: [1], + sibling_ids: [1], } (actual.nodes == expected.nodes) - && (actual.siblingIds == expected.siblingIds) + && (actual.sibling_ids == expected.sibling_ids) # diff expect State : { answer : U32 } - diffStateBefore : DiffState State - diffStateBefore = { + diff_state_before : DiffState State + diff_state_before = { rendered: { root: 4, nodes: [ - Ok (RenderedText "The app"), - Ok (RenderedElement "h1" emptyRenderedAttrs [0]), - Ok (RenderedText "The answer is 42"), - Ok (RenderedElement "div" emptyRenderedAttrs [2]), - Ok (RenderedElement "body" emptyRenderedAttrs [1, 3]), + Ok(RenderedText("The app")), + Ok(RenderedElement("h1", empty_rendered_attrs, [0])), + Ok(RenderedText("The answer is 42")), + Ok(RenderedElement("div", empty_rendered_attrs, [2])), + Ok(RenderedElement("body", empty_rendered_attrs, [1, 3])), ], - deletedNodeCache: [], + deleted_node_cache: [], handlers: [], - deletedHandlerCache: [], + deleted_handler_cache: [], }, patches: [], } # Sizes don't matter, use zero. We are not creating a HTML string so we don't care what size it would be. - newNode : Html State - newNode = - Element "body" 0 [] [ - Element "h1" 0 [] [Text "The app"], - Element "div" 0 [] [Text "The answer is 111"], - ] + new_node : Html State + new_node = + Element("body", 0, [], [ + Element("h1", 0, [], [Text("The app")]), + Element("div", 0, [], [Text("The answer is 111")]), + ]) expected : DiffState State expected = { rendered: { root: 4, nodes: [ - Ok (RenderedText "The app"), - Ok (RenderedElement "h1" emptyRenderedAttrs [0]), - Ok (RenderedText "The answer is 111"), - Ok (RenderedElement "div" emptyRenderedAttrs [2]), - Ok (RenderedElement "body" emptyRenderedAttrs [1, 3]), + Ok(RenderedText("The app")), + Ok(RenderedElement("h1", empty_rendered_attrs, [0])), + Ok(RenderedText("The answer is 111")), + Ok(RenderedElement("div", empty_rendered_attrs, [2])), + Ok(RenderedElement("body", empty_rendered_attrs, [1, 3])), ], - deletedNodeCache: [], + deleted_node_cache: [], handlers: [], - deletedHandlerCache: [], + deleted_handler_cache: [], }, - patches: [UpdateTextNode 2 "The answer is 111"], + patches: [UpdateTextNode(2, "The answer is 111")], } actual : DiffState State actual = - diff diffStateBefore newNode + diff(diff_state_before, new_node) (actual.patches == expected.patches) - && eqRenderedTree actual.rendered expected.rendered + && eq_rendered_tree(actual.rendered, expected.rendered) # initClientAppHelp expect @@ -738,60 +742,60 @@ expect init = \result -> when result is - Ok state -> state - Err _ -> { answer: 0 } + Ok(state) -> state + Err(_) -> { answer: 0 } - onClickHandler : Handler State - onClickHandler = - Normal \state, _ -> Action.update { answer: state.answer + 1 } + on_click_handler : Handler State + on_click_handler = + Normal(\state, _ -> Action.update({ answer: state.answer + 1 })) render : State -> Html State render = \state -> - num = Num.toStr state.answer + num = Num.to_str(state.answer) - onClickAttr : Attribute State - onClickAttr = - EventListener "click" [] onClickHandler + on_click_attr : Attribute State + on_click_attr = + EventListener("click", [], on_click_handler) # Sizes don't matter, use zero. We are not creating a HTML string so we don't care what size it would be. - Element "body" 0 [] [ - Element "h1" 0 [] [Text "The app"], - Element "div" 0 [onClickAttr] [Text "The answer is $(num)"], - ] + Element("body", 0, [], [ + Element("h1", 0, [], [Text("The app")]), + Element("div", 0, [on_click_attr], [Text("The answer is $(num)")]), + ]) app : App State State app = { init, render, - wasmUrl: "assets/test.wasm", + wasm_url: "assets/test.wasm", } - initJson : List U8 - initJson = - { answer: 42 } |> Encode.toBytes Json.json # panics at mono/src/ir.rs:5739:56 + init_json : List U8 + init_json = + { answer: 42 } |> Encode.to_bytes(Json.json) # panics at mono/src/ir.rs:5739:56 expected : { state : State, rendered : RenderedTree State, patches : List Patch } expected = { state: { answer: 42 }, rendered: { root: 4, nodes: [ - Ok (RenderedText "The app"), - Ok (RenderedElement "h1" emptyRenderedAttrs [0]), - Ok (RenderedText "The answer is 42"), - Ok (RenderedElement "div" { emptyRenderedAttrs & eventListeners: Dict.fromList [("click", { accessors: [], handlerId: 0 })] } [2]), - Ok (RenderedElement "body" emptyRenderedAttrs [1, 3]), + Ok(RenderedText("The app")), + Ok(RenderedElement("h1", empty_rendered_attrs, [0])), + Ok(RenderedText("The answer is 42")), + Ok(RenderedElement("div", { empty_rendered_attrs & event_listeners: Dict.from_list([("click", { accessors: [], handler_id: 0 })]) }, [2])), + Ok(RenderedElement("body", empty_rendered_attrs, [1, 3])), ], - deletedNodeCache: [], - handlers: [Ok onClickHandler], - deletedHandlerCache: [], + deleted_node_cache: [], + handlers: [Ok(on_click_handler)], + deleted_handler_cache: [], }, - patches: [SetListener 3 "click" [] 0], + patches: [SetListener(3, "click", [], 0)], } actual : { state : State, rendered : RenderedTree State, patches : List Patch } actual = - initClientAppHelp initJson app + init_client_app_help(init_json, app) (actual.state == expected.state) - && eqRenderedTree actual.rendered expected.rendered + && eq_rendered_tree(actual.rendered, expected.rendered) && (actual.patches == expected.patches) diff --git a/examples/virtual-dom-wip/platform/Html/Internal/Server.roc b/examples/virtual-dom-wip/platform/Html/Internal/Server.roc index 9c20390f8c7..51ebc096506 100644 --- a/examples/virtual-dom-wip/platform/Html/Internal/Server.roc +++ b/examples/virtual-dom-wip/platform/Html/Internal/Server.roc @@ -1,121 +1,122 @@ module [ - appendRenderedStatic, - initServerApp, + append_rendered_static, + init_server_app, ] -import Html.Internal.Shared exposing [Html, Attribute, App, translateStatic, text, element] +import Html.Internal.Shared exposing [Html, Attribute, App, translate_static, text, element] import Json # ------------------------------- # STATIC HTML # ------------------------------- -appendRenderedStatic : Str, Html [] -> Str -appendRenderedStatic = \buffer, node -> +append_rendered_static : Str, Html [] -> Str +append_rendered_static = \buffer, node -> when node is - Text content -> - Str.concat buffer content - - Element name _ attrs children -> - withTagName = "$(buffer)<$(name)" - withAttrs = - if List.isEmpty attrs then - withTagName + Text(content) -> + Str.concat(buffer, content) + + Element(name, _, attrs, children) -> + with_tag_name = "$(buffer)<$(name)" + with_attrs = + if List.is_empty(attrs) then + with_tag_name else - init = { buffer: Str.concat withTagName " ", styles: "" } - { buffer: attrBuffer, styles } = - List.walk attrs init appendRenderedStaticAttr + init = { buffer: Str.concat(with_tag_name, " "), styles: "" } + { buffer: attr_buffer, styles } = + List.walk(attrs, init, append_rendered_static_attr) - if Str.isEmpty styles then - attrBuffer + if Str.is_empty(styles) then + attr_buffer else - "$(attrBuffer) style=\"$(styles)\"" + "$(attr_buffer) style=\"$(styles)\"" - withTag = Str.concat withAttrs ">" - withChildren = List.walk children withTag appendRenderedStatic + with_tag = Str.concat(with_attrs, ">") + with_children = List.walk(children, with_tag, append_rendered_static) - "$(withChildren)" + "$(with_children)" None -> buffer -appendRenderedStaticAttr : { buffer : Str, styles : Str }, Attribute [] -> { buffer : Str, styles : Str } -appendRenderedStaticAttr = \{ buffer, styles }, attr -> +append_rendered_static_attr : { buffer : Str, styles : Str }, Attribute [] -> { buffer : Str, styles : Str } +append_rendered_static_attr = \{ buffer, styles }, attr -> when attr is - HtmlAttr key value -> - newBuffer = "$(buffer) $(key)=\"$(value)\"" + HtmlAttr(key, value) -> + new_buffer = "$(buffer) $(key)=\"$(value)\"" - { buffer: newBuffer, styles } + { buffer: new_buffer, styles } - Style key value -> - newStyles = "$(styles) $(key): $(value);" + Style(key, value) -> + new_styles = "$(styles) $(key): $(value);" - { buffer, styles: newStyles } + { buffer, styles: new_styles } - DomProp _ _ -> { buffer, styles } + DomProp(_, _) -> { buffer, styles } # ------------------------------- # INITIALISATION # ------------------------------- -initServerApp : App state initData, initData, Str -> Result (Html []) [InvalidDocument] where initData implements Encoding -initServerApp = \app, initData, hostJavaScript -> - initData +init_server_app : App state init_data, init_data, Str -> Result (Html []) [InvalidDocument] where init_data implements Encoding +init_server_app = \app, init_data, host_java_script -> + init_data |> Ok |> app.init |> app.render - |> translateStatic - |> insertRocScript initData app.wasmUrl hostJavaScript + |> translate_static + |> insert_roc_script(init_data, app.wasm_url, host_java_script) -insertRocScript : Html [], initData, Str, Str -> Result (Html []) [InvalidDocument] where initData implements Encoding -insertRocScript = \document, initData, wasmUrl, hostJavaScript -> +insert_roc_script : Html [], init_data, Str, Str -> Result (Html []) [InvalidDocument] where init_data implements Encoding +insert_roc_script = \document, init_data, wasm_url, host_java_script -> encode = \value -> value - |> Encode.toBytes Json.json - |> Str.fromUtf8 - |> Result.withDefault "" + |> Encode.to_bytes(Json.json) + |> Str.from_utf8 + |> Result.with_default("") # Convert initData to JSON as a Roc Str, then convert the Roc Str to a JS string. # JSON won't have invalid UTF-8 in it, since it would be escaped as part of JSON encoding. - jsInitData = - initData |> encode |> encode + js_init_data = + init_data |> encode |> encode - jsWasmUrl = - encode wasmUrl + js_wasm_url = + encode(wasm_url) script : Html [] - script = (element "script") [] [ - text + script = element("script")([], [ + text( """ - $(hostJavaScript) + $(host_java_script) (function(){ - const initData = $(jsInitData); - const wasmUrl = $(jsWasmUrl); + const initData = $(js_init_data); + const wasmUrl = $(js_wasm_url); window.roc = roc_init(initData, wasmUrl); })(); """, - ] + ), + ]) # append the